예제 #1
0
        private void InitRedis()
        {
            redisConfiguration = new RedisConfiguration()
            {
                AbortOnConnectFail = false,
                AllowAdmin         = true,
                ConnectTimeout     = this.Settings.Server.Timeout,
                Database           = 0,
                Ssl      = false,
                Password = this.RedisNode.Password,
                ServerEnumerationStrategy = new ServerEnumerationStrategy()
                {
                    Mode       = ServerEnumerationStrategy.ModeOptions.All,
                    TargetRole = ServerEnumerationStrategy.TargetRoleOptions.Any,
                    UnreachableServerAction = ServerEnumerationStrategy.UnreachableServerActionOptions.IgnoreIfOtherAvailable
                },
            };

            var clusters = this.RedisNode.Clusters.ToList();

            redisConfiguration.Hosts = clusters
                                       .Select(m => new RedisHost {
                Host = m.Host, Port = m.Port
            })
                                       .ToArray();

            connection  = new RedisCacheConnectionPoolManager(redisConfiguration);
            this.Client = new Lazy <RedisCacheClient>(() => new RedisCacheClient(connection, new NewtonsoftSerializer(), redisConfiguration), true).Value;
        }
        internal CacheClientTestBase(ISerializer serializer)
        {
            redisConfiguration = new RedisConfiguration()
            {
                AbortOnConnectFail = true,
                KeyPrefix          = "MyPrefix__",
                Hosts = new RedisHost[]
                {
                    new RedisHost {
                        Host = "localhost", Port = 6379
                    }
                },
                AllowAdmin                = true,
                ConnectTimeout            = 3000,
                Database                  = 0,
                PoolSize                  = 5,
                ServerEnumerationStrategy = new ServerEnumerationStrategy()
                {
                    Mode       = ServerEnumerationStrategy.ModeOptions.All,
                    TargetRole = ServerEnumerationStrategy.TargetRoleOptions.Any,
                    UnreachableServerAction = ServerEnumerationStrategy.UnreachableServerActionOptions.Throw
                }
            };

            var moqLogger = new Mock <ILogger <RedisCacheConnectionPoolManager> >();

            this.serializer       = serializer;
            connectionPoolManager = new RedisCacheConnectionPoolManager(redisConfiguration, moqLogger.Object);
            sut = new RedisCacheClient(connectionPoolManager, this.serializer, redisConfiguration);
            db  = sut.GetDbFromConfiguration().Database;
        }
        public CacheObjectManager(IRedisCacheConnectionPoolManager redisCacheConnectionPool, ILogger<CacheObjectManager> logger, string keyPrefix = "")
        {
            _redisConnPool = redisCacheConnectionPool;

            _logger = logger;
            _binarySerializer = new BinarySerializer();
            _keyPrefix = keyPrefix;
        }
 public RedisCacheClient(
     IRedisCacheConnectionPoolManager connectionPoolManager,
     ISerializer serializer,
     RedisConfiguration redisConfiguration)
 {
     this.connectionPoolManager = connectionPoolManager;
     Serializer = serializer;
     this.redisConfiguration = redisConfiguration;
 }
예제 #5
0
 public RedisInformationMiddleware(
     RequestDelegate next,
     RedisMiddlewareAccessOptions options,
     ILogger <RedisInformationMiddleware> logger,
     IRedisCacheConnectionPoolManager connectionPoolManager,
     IRedisDatabase redisDatabase)
 {
     this.next    = next;
     this.options = options;
     this.logger  = logger;
     this.connectionPoolManager = connectionPoolManager;
     this.redisDatabase         = redisDatabase;
 }
예제 #6
0
 /// <summary>
 /// 初始化一个新的 <see cref="RedisCacheClient"/> 对象
 /// </summary>
 /// <param name="connectionPoolManager"> <see cref="IRedisCacheConnectionPoolManager" />.</param>
 /// <param name="serializer"> <see cref="ISerializer" />.</param>
 /// <param name="redisConfiguration"> <see cref="RedisConfiguration" />.</param>
 public RedisCacheClient(
     IRedisCacheConnectionPoolManager connectionPoolManager,
     ISerializer serializer,
     RedisConfiguration redisConfiguration,
     ILogger <RedisCacheClient> logger,
     IMemoryCache memorycache)
 {
     this.connectionPoolManager = connectionPoolManager;
     Serializer = serializer;
     this.redisConfiguration = redisConfiguration;
     _logger      = logger;
     _memorycache = memorycache;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="RedisDatabase"/> class.
 /// </summary>
 /// <param name="connectionPoolManager">The connection pool manager.</param>
 /// <param name="serializer">The serializer.</param>
 /// <param name="serverEnumerationStrategy">The server enumeration strategy.</param>
 /// <param name="dbNumber">The database to use.</param>
 /// <param name="maxvalueLength">The max lenght of the cache object.</param>
 /// <param name="keyPrefix">The key prefix.</param>
 public RedisDatabase(
     IRedisCacheConnectionPoolManager connectionPoolManager,
     ISerializer serializer,
     ServerEnumerationStrategy serverEnumerationStrategy,
     int dbNumber,
     uint maxvalueLength,
     string keyPrefix = null)
 {
     Serializer = serializer ?? throw new ArgumentNullException(nameof(serializer));
     this.serverEnumerationStrategy = serverEnumerationStrategy ?? new ServerEnumerationStrategy();
     this.connectionPoolManager     = connectionPoolManager ?? throw new ArgumentNullException(nameof(connectionPoolManager));
     this.dbNumber  = dbNumber;
     this.keyPrefix = keyPrefix;
     maxValueLength = maxvalueLength;
 }
예제 #8
0
 /// <summary>
 /// 对象的新实例初始化 <see cref="RedisDatabase"/> class.
 /// </summary>
 /// <param name="connectionPoolManager">连接池管理器。</param>
 /// <param name="serializer">序列化</param>
 /// <param name="serverEnumerationStrategy">服务器枚举策略</param>
 /// <param name="dbNumber">要使用的数据库序号.</param>
 /// <param name="maxvalueLength">缓存对象的最大长度</param>
 /// <param name="keyPrefix">key前缀</param>
 public RedisDatabase(
     IRedisCacheConnectionPoolManager connectionPoolManager,
     ISerializer serializer,
     ServerEnumerationStrategy serverEnumerationStrategy,
     int dbNumber,
     uint maxvalueLength,
     string keyPrefix         = null,
     ILogger logger           = null,
     IMemoryCache memorycache = null)
 {
     _logger    = logger ?? NullLogger <RedisDatabase> .Instance;
     Serializer = serializer ?? throw new ArgumentNullException(nameof(serializer));
     this.serverEnumerationStrategy = serverEnumerationStrategy ?? new ServerEnumerationStrategy();
     this.connectionPoolManager     = connectionPoolManager ?? throw new ArgumentNullException(nameof(connectionPoolManager));
     this.dbNumber  = dbNumber;
     this.keyPrefix = keyPrefix;
     maxValueLength = maxvalueLength;
     _memorycache   = memorycache;
 }
예제 #9
0
        public bool TalkToRedis()
        {
            NewtonsoftSerializer serializer  = new NewtonsoftSerializer();
            RedisConfiguration   redisConfig = new RedisConfiguration
            {
                Hosts = new[]
                {
                    new RedisHost {
                        Host = "192.168.1.71", Port = 6379
                    }
                },
                Password       = "******",
                ConnectTimeout = 1000,
                SyncTimeout    = 900,
                AllowAdmin     = true // Enable admin mode to allow flushing of the database
            };

            _connectionPoolManager = new RedisCacheConnectionPoolManager(redisConfig);
            _redisCacheClient      = new RedisCacheClient(_connectionPoolManager, serializer, redisConfig);

            return(true);
        }
        private void InitRedis()
        {
            var redisConfiguration = new RedisConfiguration()
            {
                AbortOnConnectFail = false,
                Hosts = new RedisHost[]
                {
                    new RedisHost()
                    {
                        Host = this.Settings.Host, Port = this.Settings.Port
                    },
                },
                AllowAdmin = true,
                Database   = 0,
                Ssl        = false,
                Password   = this.Settings.Password,
                ServerEnumerationStrategy = new ServerEnumerationStrategy()
                {
                    Mode       = ServerEnumerationStrategy.ModeOptions.All,
                    TargetRole = ServerEnumerationStrategy.TargetRoleOptions.Any,
                    UnreachableServerAction = ServerEnumerationStrategy.UnreachableServerActionOptions.IgnoreIfOtherAvailable
                },
            };

            this.Settings.Clusters?.ForEach(host =>
            {
                if (host.Host != null && host.Port > 0)
                {
                    redisConfiguration.Hosts.ToList().Add(new RedisHost {
                        Host = host.Host, Port = host.Port
                    });
                }
            });

            connection  = new RedisCacheConnectionPoolManager(redisConfiguration);
            this.Client = new Lazy <RedisCacheClient>(() => new RedisCacheClient(connection, new NewtonsoftSerializer(), redisConfiguration), true).Value;
        }
예제 #11
0
        static void PruebaStatusOrdenEvaluacion(string ordenId, int cantidadImagenes, IRedisCacheConnectionPoolManager _redisCacheConnectionPoolManager, IRedisCacheClient _redisClient)
        {
            const string TotalRegistros      = "tr";
            const string RegistrosProcesados = "rp";
            const string RegistrosValidos    = "rv";
            const string RegistrosObservados = "ro";
            //  ord:d7687efb-feb4-4a4a-a51e-b110434571a6:status
            //          TotalRegistros          :   100
            //          RegistrosProcesados     :   40
            //          RegistrosValidos        :   38
            //          RegistrosObservados     :    2



            var key = $"ord:{ordenId}:status";

            _redisClient.Db0.Database.HashSet(key,
                                              TotalRegistros,
                                              cantidadImagenes,
                                              When.NotExists);


            var connection = _redisCacheConnectionPoolManager.GetConnection();
            // get a publish client, or you can use connection.GetDatabase(), which won't open a new client.
            // GetSubscriber() will open a dedicated client which can only be used for Pub/Sub.
            var publisher = connection.GetSubscriber();

            _redisClient.Db0.Database.KeyDelete(key);
            for (int i = 1; i <= cantidadImagenes; i++)
            {
                Thread.Sleep(50);
                //Redundante se podria sacar al sumar RegistrosValidos y RegistrosObservados
                long valorActual = _redisClient.Db0.Database.HashIncrement(key,
                                                                           RegistrosProcesados,
                                                                           1, CommandFlags.None);

                if (i % 10 == 0)
                {
                    //Marcar como errores los multiplos de 10
                    _redisClient.Db0.Database.HashIncrement(key,
                                                            RegistrosObservados, 1, CommandFlags.FireAndForget);
                }
                else
                {
                    _redisClient.Db0.Database.HashIncrement(key,
                                                            RegistrosValidos, 1, CommandFlags.FireAndForget);
                }

                //var channelName = "Status:*";
                //// publish message to one channel
                //publisher.Publish(channelName, $"Publish a message to literal channel: {channelName}");
                // publish message to one channel

                var idEntidad = "1";
                publisher.Publish($"status:ord:{ordenId}", $"[{idEntidad},{valorActual}]");
            }
        }
예제 #12
0
        static void Main(string[] args)
        {
            //var builder = new ConfigurationBuilder()
            //    .SetBasePath(Directory.GetCurrentDirectory())
            //    .AddJsonFile("appsettings.json");

            IConfiguration config = new ConfigurationBuilder()
                                    .AddJsonFile("appsettings.json", true, true)
                                    .Build();


            IServiceCollection services = new ServiceCollection();

            services.AddRedis(config);

            var serviceProvider = services.BuildServiceProvider();

            IRedisCacheClient _redisClient = serviceProvider.GetService <IRedisCacheClient>();

            //Examplo
            var key = $"example:Eduardo:summary";

            _redisClient.Db0.Database.HashSet(key, "Valor:A", 1, When.NotExists);
            _redisClient.Db0.Database.HashSet(key, "Valor:B", 1, When.NotExists);
            _redisClient.Db0.Database.HashSet(key, "Valor:C", 1, When.NotExists);
            _redisClient.Db0.Database.HashSet(key, "Valor:A", 100, When.Always, CommandFlags.FireAndForget);
            _redisClient.Db0.Database.HashSet(key, "Valor:A", 200);


            // ******************EJEMPLO PARA ORDENES DE EVALUACION************************
            string OrdenId = Guid.NewGuid().ToString().ToLower();

            OrdenId = "f0cfdff6-194e-4351-8025-42697dc5f2ad";
            const int CANTIDAD_IMAGENES = 168;
            //Pub/Sub
            IRedisCacheConnectionPoolManager _redisCacheConnectionPoolManager = serviceProvider.GetService <IRedisCacheConnectionPoolManager>();
            var         connection = _redisCacheConnectionPoolManager.GetConnection();
            IDatabase   db         = connection.GetDatabase();
            ISubscriber subscriber = connection.GetSubscriber();

            subscriber.Subscribe("status:*", (channel, message) =>
            {
                if ((string)channel == $"status:ord:{OrdenId}")
                {
                    //Print Avance
                    Console.WriteLine($"{DateTime.Now.ToString("yyyyMMdd HH:mm:ss")}<Normal - {channel}><{message}>.");

                    //Print cuando termine
                    var procesados = GetStringBetween((string)message, "[", "]").Split(',')[2];
                    if (Convert.ToInt32(procesados) == CANTIDAD_IMAGENES)
                    {
                        Console.WriteLine($"{DateTime.Now.ToString("yyyyMMdd HH:mm:ss")}<Normal - {channel}><Se proceso todos las imagenes>.");
                    }
                }
            }
                                 );

            PruebaStatusOrdenEvaluacion(OrdenId, CANTIDAD_IMAGENES, _redisCacheConnectionPoolManager, _redisClient);

            Console.ReadKey();
        }
 public HomeController(IRedisDatabase redisDatabase, IRedisCacheConnectionPoolManager pool)
 {
     this.redisDatabase = redisDatabase;
     this.pool          = pool;
 }
예제 #14
0
 public HomeController(ILogger <HomeController> logger, IRedisDatabase redisDatabase, IRedisCacheConnectionPoolManager connectionPoolManager)
 {
     this.logger                = logger;
     this.redisDatabase         = redisDatabase;
     this.connectionPoolManager = connectionPoolManager;
 }
 /// <summary>
 /// Create a new instance of the locker
 /// </summary>
 /// <param name="redisConnectionPool">A connected instance of a redis muxer</param>
 public RedisDistributedAppLockProvider(IRedisCacheConnectionPoolManager redisConnectionPool)
 {
     _redisConnectionPool = redisConnectionPool;
     _rng = new Random();
 }