/// <summary>
        /// Register RedisKeySpaceNotification's dependencies.
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddRedisKeySpaceNotification(this IServiceCollection services, Action <IRedisConfiguration> configuration)
        {
            var redisConfiguration = new RedisConfiguration();

            configuration.Invoke(redisConfiguration);

            services.AddSingleton(typeof(IRedisConfiguration), redisConfiguration);

            services.AddSingleton <IRedisServer, RedisServer>();
            services.AddSingleton <IKeySpaceNotificationService, KeySpaceNotificationService>();

            return(services);
        }
Exemple #2
0
        public ServiceSettings GetServiceSettings()
        {
            var uri = GetEndpointAddress("WSHttpBinding_PosServerDbSyncService");

            return(new ServiceSettings()
            {
                Redis = RedisConfiguration.GetConfig().ConnectionString,
                SocketIp = SocketClientConfig.GetConfig().Ip,
                SocketPort = SocketClientConfig.GetConfig().Port,
                WCFIp = (uri == default(Uri) ? "192.168.10.122" : uri.Host),
                WCFPort = (uri == default(Uri) ? 808 : uri.Port)
            });
        }
 public LockingConnectionPool(RedisConfiguration configuration, IConnectionFactory connectionFactory)
 {
     AvailableLock        = new ReaderWriterLockSlim();
     ReservedLock         = new ReaderWriterLockSlim();
     Configuration        = configuration;
     ConnectionFactory    = connectionFactory;
     AvailableConnections = new Queue <IConnection>();
     ReservedConnections  = new HashSet <IConnection>();
     while (AvailableConnections.Count < Configuration.ConnectionLimit)
     {
         AvailableConnections.Enqueue(ConnectionFactory.GetConnection());
     }
 }
 public RedisAttributeBindingProvider(RedisConfiguration config, TraceWriter trace)
 {
     if (config == null)
     {
         throw new ArgumentNullException("config");
     }
     if (trace == null)
     {
         throw new ArgumentNullException("trace");
     }
     _config = config;
     _trace  = trace;
 }
Exemple #5
0
        public static StackExchangeRedisCacheClient GetClient()
        {
            if (config == null)
            {
                config = RedisCachingSectionHandler.GetConfig();
            }



            client = new StackExchangeRedisCacheClient(new NewtonsoftSerializer(), config);

            return(client);
        }
Exemple #6
0
        public static void AddRedisCaching(this IServiceCollection services, IConfiguration configuration)
        {
            var redisConfig = new RedisConfiguration();
            var redisConfigurationSection = configuration.GetSection("JediCacheSettings:RedisConfiguration");

            redisConfigurationSection.Bind(redisConfig);

            services.AddSingleton <IDistributedCacheService>(
                CacheBuilder.Builder()
                .WithRedisConfiguration(redisConfig)
                .BuildDistributedCache()
                );
        }
Exemple #7
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;
 }
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        /// <summary>
        ///
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <IConfiguration>(Configuration);

            services.AddSignalR();//和ws相关

            //这里就是填写数据库的连接字符串
            services.AddDbContext <MyDbContext>(options => options.UseMySql(Configuration.GetConnectionString("DefaultConnection")));

            #region 配置Swagger
            var basepath = Path.GetDirectoryName(typeof(Program).Assembly.Location);//获取应用程序所在目录(绝对,不受工作目录影响,建议采用此方法获取路径)
            var xmlpath  = Path.Combine(basepath, Assembly.GetEntryAssembly().GetName().Name + ".xml");
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "My API", Version = "v1"
                });

                /*
                 * // Enable Swagger examples
                 * c.OperationFilter<ExamplesOperationFilter>();
                 *
                 * // Enable swagger descriptions
                 * c.OperationFilter<DescriptionOperationFilter>();
                 *
                 * // Enable swagger response headers
                 * c.OperationFilter<AddResponseHeadersFilter>();
                 *
                 * // Add (Auth) to action summary
                 * c.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();
                 * // */
                c.IncludeXmlComments(xmlpath);
            });
            #endregion

            #region 配置Redis
            var redisconfiguration = new RedisConfiguration();
            Configuration.Bind("Redis", redisconfiguration);
            services.AddSingleton(redisconfiguration);
            services.AddSingleton <IRedisCacheClient, RedisCacheClient>();
            services.AddSingleton <IRedisCacheConnectionPoolManager, RedisCacheConnectionPoolManager>();
            services.AddSingleton <IRedisDefaultCacheClient, RedisDefaultCacheClient>();
            services.AddSingleton <ISerializer, NewtonsoftSerializer>();

            #endregion

            services.AddTransient <Helpers.ITaskQueue, Helpers.TaskQueue>();

            services.AddMvc();
        }
 public async Task Setup()
 {
     defaultSerialiser         = new Mock <IDataSerializer>();
     configuration             = new RedisConfiguration("Test");
     resilience                = new Mock <IResilience>();
     configuration.ServiceName = "Redis";
     database    = new Mock <IDatabase>();
     multiplexer = new Mock <IRedisMultiplexer>();
     multiplexer.Setup(item => item.Database).Returns(database.Object);
     multiplexer.Setup(item => item.Configuration).Returns(configuration);
     entitySubscriber = new Mock <IEntitySubscriber>();
     redisLink        = new RedisLink(new NullLoggerFactory(), configuration, multiplexer.Object, resilience.Object, entitySubscriber.Object, defaultSerialiser.Object);
     await redisLink.Open().ConfigureAwait(false);
 }
Exemple #10
0
        static RedisBLFactory()
        {
            configuration = new RedisConfiguration();

            if (!IPAddress.TryParse(configuration.Host, out IPAddress ipAddress))
            {
                throw CreateException <BllException>(Constants.Errors.ConfigurationError);
            }
            var options = new ConfigurationOptions
            {
                EndPoints = { new IPEndPoint(ipAddress, configuration.Port) }
            };

            Connection = new Lazy <ConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(options));
        }
 public void Setup()
 {
     database = new Mock <IDatabase>();
     server   = new Mock <IServer>();
     connectionMultiplexer = new Mock <IConnectionMultiplexer>();
     connectionMultiplexer.Setup(item => item.GetServer(It.IsAny <EndPoint>(), null)).Returns(server.Object);
     server.Setup(item => item.Multiplexer).Returns(connectionMultiplexer.Object);
     connectionMultiplexer.Setup(item => item.GetDatabase(-1, null)).Returns(database.Object);
     multiplexerFactory = options => Task.FromResult(connectionMultiplexer.Object);
     option             = new RedisConfiguration("Test");
     option.Endpoints   = new[] { new RedisEndpoint {
                                      Host = "localhost", Port = 7000
                                  } };
     multiplexer = new RedisMultiplexer(new NullLogger <RedisMultiplexer>(), option, multiplexerFactory);
 }
Exemple #12
0
        public GeospatialTest()
        {
            _config = new ConfigurationBuilder()
                      .AddJsonFile("C:\\repos\\RedisApi\\RedisTest\\appsettings.Test.json")
                      .Build();

            var redisConfig = new RedisConfiguration();

            redisConfig.Host = _config.GetValue <string>("redis:host");
            redisConfig.Port = _config.GetValue <int>("redis:port");


            _options = Options.Create(redisConfig);
            _factory = new RedisConnectionFactory(_options);
        }
        public void Setup()
        {
            redis = new RedisInside.Redis(i => i.Port(6666).LogTo(message => log.Debug(message)));
            var config      = new RedisConfiguration("localhost", 6666);
            var jsonConvert = TweetinviContainer.Resolve <IJsonObjectConverter>();
            var jsons       = new FileLoader(new NullLogger <FileLoader>()).Load(Path.Combine(TestContext.CurrentContext.TestDirectory, @"data\data_20160311_1115.dat"));
            var tweetDto    = jsonConvert.DeserializeObject <TweetDTO>(jsons[0]);

            tweet = Tweet.GenerateTweetFromDTO(tweetDto);
            link  = new RedisLink("Trump", new RedisMultiplexer(config));
            link.Open();
            cache       = new MemoryCache(new MemoryCacheOptions());
            persistency = new RedisPersistency(new NullLogger <RedisPersistency>(), link, cache);
            persistency.ResolveRetweets = true;
        }
Exemple #14
0
        public void ConfigureServices(IServiceCollection services)
        {
            ClientConfiguration client = new ClientConfiguration
            {
                Url = Configuration.GetValue <string>("clientConfiguration:url")
            };

            services.AddCors(options =>
            {
                options.AddPolicy("ClientPermission", policy =>
                {
                    policy.AllowAnyHeader()
                    .AllowAnyMethod()
                    .SetIsOriginAllowed(origin => true)      // allow any origin
                                                             //.WithOrigins(client.Url)
                    .AllowCredentials();
                });
            });
            services.AddControllers();
            services.AddSignalR();

            RedisConfiguration redis = new RedisConfiguration
            {
                Configuration = Configuration.GetValue <string>("redisConfiguration:url"),
                InstanceName  = Configuration.GetValue <string>("redisConfiguration:instanceName")
            };

            services.AddDistributedRedisCache(option =>
            {
                option.Configuration = redis.Configuration;
                option.InstanceName  = redis.InstanceName;
            });

            services.Configure <MongoConfiguration>(
                Configuration.GetSection("mongoConfiguration"));
            services.AddSingleton <IMongoConfiguration>(sp =>
                                                        sp.GetRequiredService <IOptions <MongoConfiguration> >().Value);


            services.AddScoped <IChatService, ChatService>();
            services.AddSingleton <ILoginService, LoginService>();
            services.AddSingleton <IPlayerService, PlayerService>();
            services.AddSingleton <IBoardService, BoardService>();
            services.AddSingleton <IGameConfigService, GameConfigService>();
            services.AddSingleton <IGameService, GameService>();

            services.AddSingleton <ICommonService, CommonService>();
        }
        public RepositoryRedis()
        {
            key = "prueba";
            var redisConfig = new RedisConfiguration()
            {
                AbortOnConnectFail = true,
                KeyPrefix          = key,
                Hosts = new RedisHost[] { new RedisHost {
                                              Host = "127.0.0.1", Port = 6379
                                          } },
                ConnectTimeout = 4000,
                Database       = 0
            };

            redis = new StackExchangeRedisCacheClient(new NewtonsoftSerializer(), redisConfig);
        }
Exemple #16
0
 private static RedisConfiguration MergeConfiguration(RedisConfiguration redisConfiguration, IEnumerable <ScafellRedisHost> environmentVariableHosts, string environmentPassword)
 {
     return(new RedisConfiguration
     {
         AbortOnConnectFail = redisConfiguration.AbortOnConnectFail,
         KeyPrefix = redisConfiguration.KeyPrefix,
         Hosts = redisConfiguration.Hosts == null
             ? Map(environmentVariableHosts).ToArray()
             : Map(environmentVariableHosts).Concat(redisConfiguration.Hosts).ToArray(),
         AllowAdmin = redisConfiguration.AllowAdmin,
         ConnectTimeout = redisConfiguration.ConnectTimeout,
         Database = redisConfiguration.Database,
         ServerEnumerationStrategy = redisConfiguration.ServerEnumerationStrategy,
         Password = environmentPassword
     });
 }
Exemple #17
0
        private void ConfigureRedis(RedisSentinelOptions opt)
        {
            var redisConfig = new RedisConfiguration();

            _config.Bind("Redis", redisConfig);
            if (redisConfig.SentinelServers == null)
            {
                return;
            }

            opt.Hosts                 = redisConfig.SentinelServers.Select(s => $"{s.Host}:{s.Port}").ToArray();
            opt.AuthPass              = redisConfig.Password;
            opt.MasterGroup           = redisConfig.MasterName;
            opt.InstanceName          = "smart-pick";
            opt.ScanForOtherSentinels = false;
        }
        public static void AddCacheService(this IServiceCollection services, RedisConfiguration redisConfig)
        {
            services.AddDistributedRedisCache(options =>
            {
                options.Configuration = $"{redisConfig.Hosts[0].Host}:{redisConfig.Hosts[0].Port},Password={redisConfig.Password}";
                //options.ConfigurationOptions.ConnectTimeout = redisConfig.ConnectTimeout;
                //options.ConfigurationOptions.AbortOnConnectFail = redisConfig.AbortOnConnectFail;
                //options.ConfigurationOptions.SyncTimeout = redisConfig.SyncTimeout;
                //options.ConfigurationOptions.ConnectRetry = 4;
            });
            services.AddSingleton <ICacheService, CacheService>();

            services.AddSingleton(redisConfig);

            services.AddStackExchangeRedisExtensions <NewtonsoftSerializer>();
        }
Exemple #19
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            RedisConfiguration redisConfig = new RedisConfiguration()
            {
                ConnectTimeout = int.Parse(Environment.GetEnvironmentVariable("REDIS_TIMEOUT")),
                Ssl            = bool.Parse(Environment.GetEnvironmentVariable("REDIS_SSL")),
                Database       = int.Parse(Environment.GetEnvironmentVariable("REDIS_DB")),
                Hosts          = new RedisHost[] { new RedisHost()
                                                   {
                                                       Host = Environment.GetEnvironmentVariable("REDIS_HOST"), Port = int.Parse(Environment.GetEnvironmentVariable("REDIS_PORT"))
                                                   } }
            };
            var redisConfiguration = redisConfig;

            services.AddControllers();
            services.AddStackExchangeRedisExtensions <NewtonsoftSerializer>(redisConfiguration);
        }
Exemple #20
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            MongoDBConfiguration mongoDBCfg = new MongoDBConfiguration();

            Configuration.GetSection("MongoDBConfiguration").Bind(mongoDBCfg);

            RedisConfiguration redisCfg = new RedisConfiguration();

            Configuration.GetSection("RedisConfiguration").Bind(mongoDBCfg);

            ServiceStartUp.StartUpMongoDB(mongoDBCfg);
            ServiceStartUp.StartUpRedis(redisCfg);

            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            app.UseMvc();
        }
Exemple #21
0
        public StudentDao()
        {
            var serializer = new NewtonsoftSerializer();

            var redisConfiguration = new RedisConfiguration()
            {
                AbortOnConnectFail = true,
                KeyPrefix          = "",
                Hosts = new RedisHost[] { new RedisHost()
                                          {
                                              Host = "192.168.99.100", Port = 6379
                                          } },
                ConnectTimeout = 3000,
                Database       = 0
            };

            cacheClient = new StackExchangeRedisCacheClient(serializer, redisConfiguration);
        }
 public RedisTriggerAttributeBindingProvider(RedisConfiguration config, INameResolver nameResolver, TraceWriter trace)
 {
     if (config == null)
     {
         throw new ArgumentNullException("config");
     }
     if (nameResolver == null)
     {
         throw new ArgumentNullException("nameResolver");
     }
     if (trace == null)
     {
         throw new ArgumentNullException("trace");
     }
     _config       = config;
     _nameResolver = nameResolver;
     _trace        = trace;
 }
Exemple #23
0
        public IEnumerable <Host> GetAll()
        {
            var config = new RedisConfiguration()
            {
                AbortOnConnectFail = false,
                KeyPrefix          = "MyApp",
                Hosts = new RedisHost[] {
                    new RedisHost()
                    {
                        Host = "redis", Port = 6379
                    }
                },
            };

            var cacheClient = new StackExchangeRedisCacheClient(new NewtonsoftSerializer(), config);

            return(cacheClient.Get <List <Host> >("myhost"));
        }
Exemple #24
0
        private static ICodeStorage GetRedisCacheStorage()
        {
            var redisConfig = new RedisConfiguration
            {
                Hosts = new RedisHost[] {
                    new RedisHost {
                        Host = "127.0.0.1",
                        Port = 6379
                    }
                }
            };
            var redisManager = new RedisCacheConnectionPoolManager(redisConfig);
            var redisClient  = new RedisCacheClient(redisManager,
                                                    new NewtonsoftSerializer(), redisConfig);//new ProtobufSerializer();
            var storage = new RedisCacheStorage(redisClient);

            return(storage);
        }
Exemple #25
0
        private static RedisConfiguration ConfigureRedis()
        {
            var uri = new Uri(Environment.GetEnvironmentVariable("REDIS_HOST"));
            var redisConfiguration = new RedisConfiguration()
            {
                AbortOnConnectFail = true,
                KeyPrefix          = "true_layer",
                Hosts = new RedisHost[] { new RedisHost()
                                          {
                                              Host = uri.Host, Port = uri.Port
                                          } },
                AllowAdmin     = true,
                ConnectTimeout = 3000,
                Database       = 0
            };

            return(redisConfiguration);
        }
Exemple #26
0
        private CacheManager()
        {
            //var serializer = new ProtobufSerializer();
            //var serializer = new BinarySerializer();
            var serializer         = new Utf8JsonSerializer();
            var redisConfiguration = new RedisConfiguration()
            {
                Hosts = new RedisHost[]
                {
                    new RedisHost()
                    {
                        Host = "127.0.0.1", Port = 6379
                    },
                },
            };

            cacheClient = new StackExchangeRedisCacheClient(serializer, redisConfiguration);
        }
Exemple #27
0
        /// <summary>
        /// Adds the services.
        /// </summary>
        /// <param name="services">The services.</param>
        private void AddServices(IServiceCollection services)
        {
            services.AddHttpContextAccessor();

            services.AddSingleton <ISerializer>(service => new NewtonsoftSerializer(new JsonSerializerSettings
            {
                TypeNameHandling  = TypeNameHandling.All,
                NullValueHandling = NullValueHandling.Include
            }));

            services.AddSingleton <IRedisCacheClient>(service =>
            {
                RedisConfiguration redisConfiguration = new RedisConfiguration()
                {
                    AbortOnConnectFail = true,
                    Hosts = new RedisHost[]
                    {
                        new RedisHost
                        {
                            Host = Configuration["KeyValueStore:host"],
                            Port = Convert.ToInt32(Configuration["KeyValueStore:port"])
                        }
                    },
                    AllowAdmin = true,
                    Database   = 0,
                    ServerEnumerationStrategy = new ServerEnumerationStrategy()
                    {
                        Mode       = ServerEnumerationStrategy.ModeOptions.All,
                        TargetRole = ServerEnumerationStrategy.TargetRoleOptions.Any,
                        UnreachableServerAction = ServerEnumerationStrategy.UnreachableServerActionOptions.Throw
                    },
                    PoolSize = 50
                };

                IRedisCacheConnectionPoolManager redisCacheConnectionPoolManager = new RedisCacheConnectionPoolManager(redisConfiguration);
                ISerializer serializer = service.GetRequiredService <ISerializer>();
                return(new RedisCacheClient(redisCacheConnectionPoolManager, serializer, redisConfiguration));
            });

            services.AddSingleton <IUrlService>(service => new UrlService(service.GetRequiredService <IKeyValueStore>(), service.GetRequiredService <IHttpContextAccessor>()));
            services.AddSingleton <IKeyValueStore>(service => new KeyValueStore(service.GetRequiredService <IRedisCacheClient>()));

            services.AddControllers(options => options.Filters.Add(new HttpResponseExceptionFilter()));
        }
        public void Setup()
        {
            mainIndexManager = new Mock <IMainIndexManager>();
            var configuration = new RedisConfiguration("Test");

            link = new Mock <IRedisLink>();
            link.Setup(item => item.Resilience).Returns(new ResilienceHandler(new NullLogger <ResilienceHandler>(), new ResilienceConfig()));
            var multiplexer = new Mock <IRedisMultiplexer>();

            multiplexer.Setup(item => item.Configuration).Returns(configuration);
            link.Setup(item => item.Multiplexer).Returns(multiplexer.Object);
            link.Setup(item => item.LinkId).Returns(0);
            link.Setup(item => item.State).Returns(ChannelState.Open);
            key       = new ObjectKey("Test");
            data      = new Identity();
            database  = new Mock <IDatabaseAsync>();
            objecMock = new Mock <IObjectSerialization <Identity> >();
            instance  = new SingleItemSerialization <Identity>(new NullLogger <SingleItemSerialization <Identity> >(), link.Object, objecMock.Object, mainIndexManager.Object);
        }
Exemple #29
0
        public RedisCacheStore(RedisConfiguration configuration, IRedisConnectionFactory connectionFactory, IJsonSerializer serializer)
        {
            // TODO: (core) Build versionStr from SmartstoreVersion class
            var versionStr = "5.0.0";

            // Don't try to deserialize values created with older app versions (could be incompatible)
            _cachePrefix = "cache." + versionStr + ":";
            _keyPrefix   = BuildCacheKey("");

            _configuration     = configuration;
            _connectionFactory = connectionFactory;
            _multiplexer       = _connectionFactory.GetConnection(configuration.ConnectionStrings.Cache ?? configuration.ConnectionStrings.Default);
            _messageBus        = _connectionFactory.GetMessageBus(configuration.ConnectionStrings.Bus ?? configuration.ConnectionStrings.Default);
            _serializer        = serializer;

            // Subscribe to key events triggered by Redis on item expiration
            _messageBus.SubscribeToKeyEvent("expired", OnRedisKeyEvent, false);
            _messageBus.SubscribeToKeyEvent("evicted", OnRedisKeyEvent, false);
        }
        public RedisService(IOptions <RedisConfiguration> config)
        {
            _config = config?.Value;

            if (_redis == null)
            {
                lock (syncRoot)
                {
                    if (_redis == null)
                    {
                        _redis = ConnectionMultiplexer.Connect(config?.Value?.ConnectionString);
                        if (config.Value.ClearCacheOnStartup)
                        {
                            ClearAllUserConnections().GetAwaiter().GetResult();
                        }
                    }
                }
            }
        }