Пример #1
0
        //1043 //不支持异常回滚
        static void RedisInsertStringWithTran()
        {
            var redis = StackExchange.Redis.ConnectionMultiplexer.Connect("localhost:6379");

            StackExchange.Redis.IDatabase db = redis.GetDatabase();

            var sw = new System.Diagnostics.Stopwatch();

            sw.Start();

            var tran = db.CreateTransaction();

            Enumerable.Range(0, 100000).ToList().ForEach(a => {
                tran.StringSetAsync($"strKey{a.ToString().PadLeft(7, '0')}", $"strValue{a.ToString().PadLeft(7, '0')}");
                if (a % 1000 == 0)
                {
                    string key1 = "key1";
                    tran.SetAddAsync(key1, "key1");
                    tran.SetAddAsync(key1, "key2");
                    tran.SetAddAsync("key1", "key1");
                    if (!tran.Execute())
                    {
                        Console.WriteLine("false");
                    }
                    tran = db.CreateTransaction();
                    Console.WriteLine($"it takes {sw.Elapsed.TotalMilliseconds}mm");
                }
            });

            tran.Execute();
            sw.Stop();

            Console.WriteLine($"total takes {sw.Elapsed.TotalMilliseconds}mm");
        }
Пример #2
0
        static void SetRedisList()
        {
            var list = GetDatabaseList();

            var redis = StackExchange.Redis.ConnectionMultiplexer.Connect("localhost:6379");

            StackExchange.Redis.IDatabase db = redis.GetDatabase();

            var sw = new System.Diagnostics.Stopwatch();

            sw.Start();

            var tran  = db.CreateTransaction();
            var index = 0;

            list.ForEach(item =>
            {
                index++;
                var dic = ToDic(item).Select(a => new StackExchange.Redis.HashEntry(a.Key, a.Value ?? "")).ToArray();
                tran.HashSetAsync("database_student_" + item.Id, dic);

                if (index % 10000 == 0)
                {
                    tran.Execute();
                    Console.WriteLine($"SetRedisList {index} {sw.Elapsed.TotalMilliseconds}mm");
                }
            });

            tran.Execute();
            sw.Stop();
            Console.WriteLine($"SetRedisList save complete {sw.Elapsed.TotalMilliseconds}mm");
        }
Пример #3
0
 public EventHandlers(IServiceScopeFactory scopeFactory, DiscordSocketClient client, IRedisCache cache, ICurrencyService currency, IConfigurationService config)
 {
     _scopeFactory = scopeFactory;
     _client       = client;
     _currency     = currency;
     _config       = config;
     _cache        = cache.Redis.GetDatabase();
 }
Пример #4
0
        /// <summary>
        /// 监听
        /// </summary>
        /// <param name="methodName"></param>
        private static void MonitorResult(Func <ILogger, ISerializer, ResponseCommon> methodName)
        {
            while (true)
            {
                Thread.Sleep(sleepTime);
                Stopwatch watch = new Stopwatch();

                ResponseCommon result = new ResponseCommon();
                try
                {
                    watch.Start();

                    string redisContent = string.Empty;
                    result = methodName(m_ilogger, m_serializer);
                    ConsoleColor msgColor = ConsoleColor.White;
                    if (!result.IsSuccess)
                    {
                        msgColor = ConsoleColor.White;
                    }
                    else
                    {
                        msgColor = ConsoleColor.Green;
                    }

                    watch.Stop();

                    messageQueue.Enqueue(new WriteMessage()
                    {
                        ShowColor = msgColor, ShowText = $"[{result.MsgType}]-[耗时:{ watch.Elapsed.TotalMilliseconds}]{result.MessageContent}"
                    });


                    //==========压力测试代码==========
                    if (result.IsSuccess)
                    {
                        StackExchange.Redis.IDatabase db = BaseConnect.RedisHelper.GetDatabase(8);
                        db.ListRightPush("test:" + result.MessageContent.Substring(0, 7), "[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "]处理" + result.MsgType + "业务:" + result.MessageContent);

                        if (result.MsgType == MsgType.InParking)
                        {
                            //入场成功后,再记录数据到出场车牌列表(以便执行出场业务)
                            db.ListRightPush("ExitDataList", result.RedisContent);
                        }
                    }

                    //==========压力测试代码==========
                }
                catch (Exception ex)
                {
                    m_ilogger.LogFatal(LoggerLogicEnum.Tools, "", "", "", "Fujica.com.cn.MonitorServiceClient.MonitorResult", $"执行{result.MsgType}数据发生异常;参数:{result.RedisContent}", ex.ToString());

                    messageQueue.Enqueue(new WriteMessage()
                    {
                        ShowColor = ConsoleColor.Yellow, ShowText = $"[{result.MsgType}]-[{DateTime.Now}]系统发生异常,redis数据:{result.RedisContent};系统异常:{ex.ToString()}"
                    });
                }
            }
        }
Пример #5
0
        static void GetRedisList()
        {
            var redis = StackExchange.Redis.ConnectionMultiplexer.Connect("localhost:6379");

            StackExchange.Redis.IDatabase db = redis.GetDatabase();

            var keys   = db.HashKeys("database_student_100003");
            var values = db.HashValues("database_student_100003");
        }
		protected RedisObjectBase(string name, StackExchange.Redis.IDatabase database)
		{
			if(string.IsNullOrWhiteSpace(name))
				throw new ArgumentNullException(nameof(name));

			if(database == null)
				throw new ArgumentNullException(nameof(database));

			_name = name.Trim();
			_database = database;
		}
 /// <summary>
 /// Initializes a new instance of the <see cref="RedisCacheProvider"/> class
 /// </summary>
 /// <param name="cache">The redis database cache</param>
 public RedisCacheProvider(StackExchange.Redis.IDatabase cache)
 {
     RedisCache = new RedisCache(cache, new JsonSerializerSettings
     {
         DateTimeZoneHandling   = DateTimeZoneHandling.Unspecified,
         NullValueHandling      = NullValueHandling.Ignore,
         ObjectCreationHandling = ObjectCreationHandling.Replace,
         ReferenceLoopHandling  = ReferenceLoopHandling.Ignore,
         TypeNameHandling       = TypeNameHandling.Objects,
         Converters             = new List <JsonConverter> {
             new ReportPartContentConverter()
         }
     });
 }
Пример #8
0
        private async Task DoExecuteAsync(StackExchange.Redis.IDatabase db)
        {
            //AllGroupsName保存的是组的名字
            var groupNames = await db.SetMembersAsync("AllGroupsName");

            List <Task> tasks = new List <Task>();

            foreach (string groupName in groupNames)
            {
                var task = ProcessGroupMessageAsync(db, groupName);
                tasks.Add(task);
            }
            //Task.WaitAll(tasks.ToArray());
            await Task.WhenAll(tasks.ToArray());
        }
Пример #9
0
        //49704
        static void RedisInsertString()
        {
            var redis = StackExchange.Redis.ConnectionMultiplexer.Connect("localhost:6379");

            StackExchange.Redis.IDatabase db = redis.GetDatabase();

            var sw = new System.Diagnostics.Stopwatch();

            sw.Start();
            Enumerable.Range(0, 100000).ToList().ForEach(a => {
                db.StringSet($"strKey{a.ToString().PadLeft(7, '0')}", $"strValue{a.ToString().PadLeft(7, '0')}");
                if (a % 1000 == 0)
                {
                    Console.WriteLine($"it takes {sw.Elapsed.TotalMilliseconds}mm");
                }
            });
            sw.Stop();

            Console.WriteLine($"total takes {sw.Elapsed.TotalMilliseconds}mm");
        }
        /// <summary>
        /// Obtenir du cache partagé
        /// </summary>
        /// <param name="DirectInvoiceid"></param>
        /// <returns></returns>
        public DirectInvoice GetDirectInvoice(string iddirectinvoice)
        {
            DirectInvoice retour = null;

            try
            {
                // Obtien d'abord l'objet sur MemCached si Existe
                if (env != null)
                {
                    StackExchange.Redis.ConfigurationOptions redisconfig = new StackExchange.Redis.ConfigurationOptions();
                    redisconfig.EndPoints.Add("22ec9a54-2921-43af-a4e9-9b1e7aff2b9b.pdb.ovh.net", 21784);
                    redisconfig.Password = "******";

                    StackExchange.Redis.ConnectionMultiplexer redis   = StackExchange.Redis.ConnectionMultiplexer.Connect(redisconfig);
                    StackExchange.Redis.IDatabase             redisDb = redis.GetDatabase();


                    StackExchange.Redis.RedisKey key = iddirectinvoice;

                    StackExchange.Redis.RedisValue val = redisDb.StringGet(key, StackExchange.Redis.CommandFlags.None);
                    if (!string.IsNullOrWhiteSpace(val))
                    {
                        retour = new DirectInvoice();
                        retour.FromStringData(val);
                    }
                }

                // sinon regarde en base
                if (retour == null)
                {
                    Dictionary <string, object> ins = new Dictionary <string, object>();
                    ins.Add("iddirectinvoice", iddirectinvoice);
                    retour = this.GetOneDefault <DirectInvoice>(ins);
                }
                return(retour);
            }
            catch (Exception ex)
            {
                throw new Exception("GetDirectInvoice " + ex.Message, ex);
            }
        }
Пример #11
0
        private async Task ProcessGroupMessageAsync(StackExchange.Redis.IDatabase db, string groupName)
        {
            List <GroupMessageResp> msgs = new List <GroupMessageResp>();
            Stopwatch stopwatch          = new Stopwatch();

            stopwatch.Start();
            //要么没有更多待发消息立即发给客户端
            //要么累积满1秒钟待发消息后发送给客户端
            while (true)
            {
                //弹出一条待发送消息
                string jsonStr = await db.ListRightPopAsync($"{groupName}_MessagesWaitToSent");

                if (jsonStr != null)
                {
                    //加入群发消息组
                    var msg = JsonConvert.DeserializeObject <GroupMessageResp>(jsonStr);
                    msgs.Add(msg);
                }
                else
                {
                    await Task.Delay(10);
                }
                //满一段时间的消息就向客户端发一组
                if (stopwatch.Elapsed > TimeSpan.FromSeconds(0.5))
                {
                    stopwatch.Stop();
                    //把积累的一组数据发给客户端
                    if (msgs.Any())
                    {
                        logger.LogWarning("过去了{0}准备向{1}发送一批消息,条数{2}", stopwatch.Elapsed, groupName, msgs.Count);
                        //如果一个周期内消息太多,则只发送一部分,其他的丢弃,以避免造成一次性发给客户端的消息太多
                        await this.hubContext.Clients.Group(groupName).SendAsync("OnGroupMessages", msgs.Take(20));

                        logger.LogWarning("完成向{0}发送一批消息,条数{1}", groupName, msgs.Count);
                    }
                    return;//本轮巡查完毕
                }
            }
        }
        /// <summary>
        /// enregistre en base et dans le cache partagé
        /// </summary>
        public void SaveDirectInvoice(DirectInvoice directinvoice)
        {
            try
            {
                // Enregistrement des clef (données persistantes) en bases
                System.Data.DataRowState rowstate = directinvoice.GetRow().RowState;
                if (rowstate == System.Data.DataRowState.Detached || rowstate == System.Data.DataRowState.Added)
                {
                    this.InsertBubble(directinvoice, true, false);
                }
                else
                {
                    this.SaveBubble(directinvoice);
                }

                // Enregistrement des données non persistantes sur MemCached
                if (env != null)
                {
                    StackExchange.Redis.ConnectionMultiplexer redis   = StackExchange.Redis.ConnectionMultiplexer.Connect(GetRedisConfig());
                    StackExchange.Redis.IDatabase             redisDb = redis.GetDatabase();

                    StackExchange.Redis.RedisValue val = directinvoice.ToStringData();
                    StackExchange.Redis.RedisKey   key = directinvoice.IdDirectInvoice;
                    redisDb.StringSet(key, val, null, StackExchange.Redis.When.Always, StackExchange.Redis.CommandFlags.None);



                    // redng75Oj82p

                    // !!! stocker dans memecached
                }
            }
            catch (Exception ex)
            {
                throw new Exception("SaveDirectInvoice " + ex.Message, ex);
            }
        }
Пример #13
0
 static SmsCacheProvider()
 {
     Cache = RedisConnectorHelper.Connection.GetDatabase();
 }
Пример #14
0
 public UserService(IOptions <AppSettings> appSettings, StackExchange.Redis.IDatabase database)
 {
     _appSettings = appSettings.Value;
     _database    = database;
 }
 public RedisDictionary(string name, StackExchange.Redis.IDatabase database) : base(name, database)
 {
 }
Пример #16
0
 public void Init()
 {
     database  = RedisConfig.RedisCache;
     usuarioBl = new UsuarioBlAsync(new RedisDao <Usuario>());
     controler = new UsuarioAsyncController(usuarioBl);
 }
Пример #17
0
 public TokenRepository()
 {
     IConnectionFactory connectionFactory = new ConnectionFactory(Infrastructure.Configuration.RedisConnectionAddress);
     _database = connectionFactory.GetDatabase();
 }
Пример #18
0
 public UtilRepository(CatDbContext context, StackExchange.Redis.IConnectionMultiplexer connection) : base(context)
 {
     _database = connection.GetDatabase();
 }
Пример #19
0
 public RedisDal()
 {
     _db = _cm.GetDatabase(Properties.Settings.Default.RedisDatabase);
 }