/// <summary>
 /// Initializes a new instance of the <see cref="RedisCache"/> class.
 /// </summary>
 /// <param name="configuration">The configuration.</param>
 public RedisCache(ConfigurationOptions configuration)
 {
     if (RedisCache.connection == null)
     {
         try
         {
             connectionTask = ConnectionMultiplexer.ConnectAsync(configuration);
             connectionTask.ContinueWith(t =>
                 {
                     lock (syncronizationObject)
                     {
                         if (RedisCache.connection == null)
                             RedisCache.connection = t.Result;
                     }
                     this.cache = RedisCache.connection.GetDatabase();
                     Trace.TraceInformation("Redis Cache Provider connection complete - Correlation Id = {0}", Trace.CorrelationManager.ActivityId);
                 });
         }
         catch (AggregateException age)
         {
             age.Handle(e =>
             {
                 Trace.TraceError("Redis Cache Provider error - Correlation Id = {0}\n {1}\n {2}", Trace.CorrelationManager.ActivityId, e.Message, e.StackTrace);
                 return true;
             });
         }
         catch (Exception ex)
         {
             Trace.TraceError("Redis Cache Provider exception - Correlation Id = {0}\n {1}\n {2}", Trace.CorrelationManager.ActivityId, ex.Message, ex.StackTrace);
         }
     }
 }
Ejemplo n.º 2
0
        private static ConnectionMultiplexer GetRedisConnection()
        {
            ConnectionMultiplexer connection;
            string isLocal = ConfigurationManager.AppSettings["IsLocal"];

            if (isLocal == "1")
            {
                connection = ConnectionMultiplexer.Connect(ConfigurationManager.AppSettings["RedisServer"]);
            }
            else
            {
                var options = new ConfigurationOptions();

                options.EndPoints.Add(ConfigurationManager.AppSettings["RedisKeyDns"], 6380);
                options.Ssl = true;

                options.Password = ConfigurationManager.AppSettings["RedisPassword"];
                options.AllowAdmin = true;

                // necessary?
                options.KeepAlive = 30;
                options.ConnectTimeout = 15000;
                options.SyncTimeout = 15000;

                connection = ConnectionMultiplexer.Connect(options);
            }

            return connection;
        }
        public static void Init(string sHost, int iPort, string sPassword)
        {
            CacheDatabase._Host = sHost;
            CacheDatabase._Port = iPort;
            CacheDatabase._Password = sPassword;
            if (CacheDatabase._Password.Length > 0)
            {
                CacheDatabase._AuthRequired = true;
            }
            else
            {
                CacheDatabase._AuthRequired = false;
            }

            _oConectionOptions = new ConfigurationOptions();
            if (CacheDatabase._AuthRequired)
            {
                CacheDatabase._oConectionOptions.Password = CacheDatabase._Password;
            }

            CacheDatabase._oConectionOptions.EndPoints.Add(CacheDatabase._Host + ":" + CacheDatabase._Port.ToString());
            CacheDatabase._oCacheConnection = ConnectionMultiplexer.Connect(CacheDatabase._oConectionOptions);
            CacheDatabase._oCommand = CacheDatabase._oCacheConnection.GetDatabase();
            //Check to make sure the Key Exists and if not then set it to 0
            if (!_oCommand.KeyExists(CacheDatabase._ObjectCounterKeyName))
            {
                CacheDatabase._oCommand.StringSet(CacheDatabase._ObjectCounterKeyName, 0);
            }
        }
Ejemplo n.º 4
0
        public async Task Can_start_slave()
        {

            using (var redis = new Redis())
            using (var redis2 = new Redis())
            {
                ////Arrange
                // configure slave
                var config = new ConfigurationOptions { AllowAdmin = true };
                config.EndPoints.Add(redis.Endpoint);
                config.EndPoints.Add(redis2.Endpoint);
                using (var client = ConnectionMultiplexer.Connect(config))
                    await client.GetServer(redis.Endpoint).SlaveOfAsync(redis2.Endpoint);

                // new single-node client
                string actualValue;
                using (var client = ConnectionMultiplexer.Connect(redis2.Endpoint.ToString()))
                {

                    await client.GetDatabase().StringSetAsync("key", "value");

                    ////Act
                    actualValue = await client.GetDatabase().StringGetAsync("key");
                }

                ////Assert
                Assert.That(actualValue, Is.EqualTo("value"));
            }
        }
        static RedisCacheConfig()
        {
            string isLocal = WebConfigReader.Read("IsLocal");

            if (isLocal == "1")
            {
                connection = ConnectionMultiplexer.Connect(WebConfigReader.Read("RedisServer"));
            }
            else
            {
                var options = new ConfigurationOptions();

                options.EndPoints.Add(WebConfigReader.Read("RedisKeyDns"), 6380);
                options.Ssl = true;

                options.Password = WebConfigReader.Read("RedisPassword");
                options.AllowAdmin = true;

                // necessary?
                options.KeepAlive = 30;
                options.ConnectTimeout = 15000;
                options.SyncTimeout = 15000;

                connection = ConnectionMultiplexer.Connect(options);
            }
        }
		static RedisUtils()
		{
			connection = new Lazy<ConnectionMultiplexer>(() =>
				{
					ExceptionDispatchInfo lastError = null;
					ConfigurationOptions options = new ConfigurationOptions();
					options.EndPoints.Add(GetHostAndPort());
					options.AllowAdmin = true;
					for (int i = 0; i < 5; i++)
					{
						try
						{
							var cnn = ConnectionMultiplexer.Connect(options);
							if (cnn.IsConnected)
								return cnn;
						}
						catch (Exception ex)
						{
							lastError = ExceptionDispatchInfo.Capture(ex);
							Console.WriteLine(ex.Message);
							Thread.Sleep(10);
						}
					}
					lastError.Throw();
					return null;
				}
			);
		}
Ejemplo n.º 7
0
 public RedisCommon(string host="127.0.0.1", int port = 6379, string password = "") {
     options = new ConfigurationOptions {
         AllowAdmin = true,
         EndPoints = {new IPEndPoint(IPAddress.Parse(host), port)},
         Password = password
     };
 }
Ejemplo n.º 8
0
        public HttpResponseMessage Get(string deviceId)
        {
            if (String.IsNullOrEmpty(deviceId))
                return new HttpResponseMessage(HttpStatusCode.NoContent);

            ConfigurationOptions configurationOptions = new ConfigurationOptions();
            configurationOptions.EndPoints.Add("<< add your Redis cache name here >>.redis.cache.windows.net");
            configurationOptions.Ssl = true;
            configurationOptions.Password = "******";

            ConnectionMultiplexer connectionMultiplexer = ConnectionMultiplexer.Connect(configurationOptions);
            IDatabase commandQueue = connectionMultiplexer.GetDatabase();

            RedisValue redisValue = commandQueue.ListRightPop(deviceId);
            if (redisValue.HasValue)
                return new HttpResponseMessage()
                {
                    StatusCode = HttpStatusCode.OK,
                    Content = new StringContent(redisValue.ToString()),
                };
            else
                return new HttpResponseMessage()
                {
                    StatusCode = HttpStatusCode.NoContent,
                    Content = new StringContent(""),
                };
        }
Ejemplo n.º 9
0
        public WatcherManager(IEnumerable<WatchGroup> groups)
        {
            var groupList = groups.ToList();
            var config = new ConfigurationOptions()
            {
                AllowAdmin = true,
            };

            foreach (var group in groupList)
            {
                config.EndPoints.Add(group.Master.EndPoint);
            }

            muxerInstance = ConnectionMultiplexer.Connect(config);
            muxerInstance.ConnectionRestored += MuxerInstanceOnConnectionRestored;

            foreach (var group in groupList)
            {
                var server = muxerInstance.GetServer(group.Master.EndPoint);
                var epStr = server.EndPoint.ToString();

                group.Master.Server = server;
                group.Master.OnPing(TimeSpan.Zero);

                Program.zkAdaptor.Identity(group.Master.EndPoint.ToString());
                this.groups.Add(epStr, group);
                redisInstancesDict.Add(epStr, group.Master);
            }
        }
Ejemplo n.º 10
0
		private static IList<RedisConnection> CreateRedisCaches(ICollection<RedisLockEndPoint> redisEndPoints)
		{
			var caches = new List<RedisConnection>(redisEndPoints.Count);

			foreach (var endPoint in redisEndPoints)
			{
                var configuration = new ConfigurationOptions
                {
                    AbortOnConnectFail = false,
                    ConnectTimeout = endPoint.ConnectionTimeout ?? DefaultConnectionTimeout,
                    Ssl = endPoint.Ssl,
                    Password = endPoint.Password,
				};

				configuration.EndPoints.Add(endPoint.EndPoint);

				caches.Add(new RedisConnection
				{
					ConnectionMultiplexer = ConnectionMultiplexer.Connect(configuration),
					RedisDatabase = endPoint.RedisDatabase ?? DefaultRedisDatabase,
					RedisKeyFormat = string.IsNullOrEmpty(endPoint.RedisKeyFormat) ? RedisLock.DefaultRedisKeyFormat : endPoint.RedisKeyFormat
				});
			}

			return caches;
		}
Ejemplo n.º 11
0
        public RedisAdaptor(List<EndPoint> endPoints)
        {
            var config = new ConfigurationOptions()
            {
                AllowAdmin = true,
            };

            foreach (var endPoint in endPoints)
            {
                config.EndPoints.Add(endPoint);
            }

            muxerInstance = ConnectionMultiplexer.Connect(config);

            Handle = muxerInstance.GetDatabase();

            var script = Load("update_multikeys_multifields.lua");

            //todo a hack way .. to be changed later
            foreach (var endPoint in muxerInstance.GetEndPoints())
            {
                var server = muxerInstance.GetServer(endPoint);

                updateScriptSha = server.ScriptLoad(script);
            }

            Handle.StringSet("test", "111");
        }
 protected RedisTest()
 {
     var config = new ConfigurationOptions() { AllowAdmin = true };
     config.EndPoints.Add(testHost, testPort);
     Multiplexer = ConnectionMultiplexer.Connect(config);
     Redis = GetFlushedRedis();
 }
 public static IGlobalConfiguration<RedisStorage> UseRedisStorage(this IGlobalConfiguration configuration, ConfigurationOptions Options, int db, string Prefix)
 {
     if (configuration == null) throw new ArgumentNullException("configuration");
     if (Options == null) throw new ArgumentNullException("Options");
     var storage = new RedisStorage(Options, db, Prefix);
     return configuration.UseStorage(storage);
 }
        public static void Connect()
        {
            ConfigurationOptions options = new ConfigurationOptions();
            options.EndPoints.Add("localhost:6379");

            Connection = ConnectionMultiplexer.Connect(options);
        }
Ejemplo n.º 15
0
        public static ConnectionMultiplexer RetrieveMultiplexer(ConfigurationOptions config)
        {
           if(_multiplexer != null) return _multiplexer;

            _multiplexer = ConnectionMultiplexer.Connect(config);
            return _multiplexer;
        }
Ejemplo n.º 16
0
        public MainForm()
        {
            InitializeComponent();
            var options = new ConfigurationOptions
            {
                ConnectTimeout = 5000,
                SyncTimeout = 2000,
                KeepAlive = 60,
                EndPoints =
                {
                    {Settings.Default.RedisHost, Settings.Default.RedisPort}
                }
            };

            _redis = ConnectionMultiplexer.Connect(options);
            var retries = 0;
            while (!_redis.IsConnected)
            {
                var config = _redis.Configuration;
                _redis.Dispose();
                if (retries > 10)
                {
                    MessageBox.Show(string.Format("Could not connect to the Redis server with configuration: {0}",
                        config));
                    Application.Exit();
                }

                _redis = ConnectionMultiplexer.Connect(options, Console.Out);
                retries++;

            }
            _red = new LightControlSet(button_RedOn, button_RedOff, button_RedFlash, textBox_RedOnDuty, textBox_RedOffDuty, textBox_RedOffset, textBox_RedPower, button_RedApply);
            _green = new LightControlSet(button_GreenOn, button_GreenOff, button_GreenFlash, textBox_GreenOnDuty, textBox_GreenOffDuty, textBox_GreenOffset, textBox_GreenPower, button_GreenApply);
            _blueYellow = new LightControlSet(button_BlueOn, button_BlueOff, button_BlueFlash, textBox_BlueOnDuty, textBox_BlueOffDuty, textBox_BlueOffset, textBox_BluePower, button_BlueApply);
        }
Ejemplo n.º 17
0
 private static ConnectionMultiplexer ConnectWithConfiguration()
 {
     ConnectionMultiplexer redisConnection;
         if (string.IsNullOrWhiteSpace(configuration.ConnectionString))
         {
             var options = new ConfigurationOptions
             {
                 ClientName = configuration.ApplicationName,
                 ConnectTimeout = configuration.ConnectionTimeoutInMilliSec,
                 SyncTimeout = configuration.OperationTimeoutInMilliSec,
                 ResolveDns = true,
                 AbortOnConnectFail = false // Important for shared usage
             };
             if (!string.IsNullOrWhiteSpace(configuration.AccessKey))
                 options.Password = configuration.AccessKey;
             if (configuration.RetryCount > 0)
                 options.ConnectRetry = configuration.RetryCount;
             if (configuration.UseSsl)
             {
                 options.Ssl = configuration.UseSsl;
                 options.SslHost = configuration.Host;
             }
             var hosts = configuration.Host.Split(new[] {SPLITTER}, StringSplitOptions.RemoveEmptyEntries);
             foreach (var host in hosts)
             {
                 options.EndPoints.Add(host);
             }
             redisConnection = ConnectionMultiplexer.Connect(options);
         }
         else
         {
             redisConnection = ConnectionMultiplexer.Connect(configuration.ConnectionString);
         }
         return redisConnection;
 }
Ejemplo n.º 18
0
        public RedisManager()
        {
            var configurationOptions = new ConfigurationOptions {Password = "******"};
            configurationOptions.EndPoints.Add(HostAndPort);

            _redisConn = ConnectionMultiplexer.Connect(configurationOptions);
        }
        public static void Init(string sHost, int iPort, string sPassword)
        {
            CacheDatabase._Host     = sHost;
            CacheDatabase._Port     = iPort;
            CacheDatabase._Password = sPassword;
            if (CacheDatabase._Password.Length > 0)
            {
                CacheDatabase._AuthRequired = true;
            }
            else
            {
                CacheDatabase._AuthRequired = false;
            }

            _oConectionOptions = new ConfigurationOptions();
            if (CacheDatabase._AuthRequired)
            {
                CacheDatabase._oConectionOptions.Password = CacheDatabase._Password;
            }

            CacheDatabase._oConectionOptions.EndPoints.Add(CacheDatabase._Host + ":" + CacheDatabase._Port.ToString());
            CacheDatabase._oCacheConnection = ConnectionMultiplexer.Connect(CacheDatabase._oConectionOptions);
            CacheDatabase._oCommand         = CacheDatabase._oCacheConnection.GetDatabase();
            //Check to make sure the Key Exists and if not then set it to 0
            if (!_oCommand.KeyExists(CacheDatabase._ObjectCounterKeyName))
            {
                CacheDatabase._oCommand.StringSet(CacheDatabase._ObjectCounterKeyName, 0);
            }
        }
Ejemplo n.º 20
0
 public RedisConnectionFactory(ConnectionMultiplexer conn, ConfigurationOptions configuration, JsonSerializerSettings jsonSerializerSettings)
 {
     _configurationOptions = configuration;
     _jsonSerializerSettings = jsonSerializerSettings;
     _conn = conn;
     if (!_conn.IsConnected)
         _conn = ConnectionMultiplexer.Connect(_configurationOptions); //TO DO - add other config options
 }
Ejemplo n.º 21
0
 public StackExchange.Redis.ConnectionMultiplexer GetClient()
 {
     StackExchange.Redis.ConfigurationOptions option = new StackExchange.Redis.ConfigurationOptions();
     option.EndPoints.Add(_redisOption.RedisIP, Int32.Parse(_redisOption.RedisPort));
     option.DefaultDatabase = 1;
     StackExchange.Redis.ConnectionMultiplexer conn = StackExchange.Redis.ConnectionMultiplexer.Connect(option);
     return(conn);
 }
Ejemplo n.º 22
0
        public void SetUp()
        {
            var config = new ConfigurationOptions() { EndPoints = { { _host, _port } }, Password = _password, DefaultDatabase = _database, AllowAdmin = true };
            _state = SchedulerFunc.Create(config, "Test", _database);

            var server = _state.Connection.GetServer(_state.Connection.GetEndPoints().First());
            server.FlushDatabase(_state.Database);
        }
Ejemplo n.º 23
0
        public RedisHelper(string host = "192.168.1.78", int port = 6379, string password = "") {
            options = new ConfigurationOptions {
                AllowAdmin = true,
                EndPoints = {new IPEndPoint(IPAddress.Parse(host), port)},
                Password = password
            };

            ServerEndPoint = options.EndPoints[0];
        }
        public static IGlobalConfiguration<RedisStorage> UseRedisStorage(this IGlobalConfiguration configuration, ConfigurationOptions Options, RedisStorageOptions HangfireOptions)
        {
            if (configuration == null) throw new ArgumentNullException("configuration");
            if (Options == null) throw new ArgumentNullException("Options");
            if (HangfireOptions == null) throw new ArgumentNullException("HangfireOptions");

            var storage = new RedisStorage(Options, HangfireOptions);
            return configuration.UseStorage(storage);
        }
Ejemplo n.º 25
0
        //string host = "192.168.1.78", int port = 6379, string password = ""
        static RedisHelper() {
            options = new ConfigurationOptions {
                AllowAdmin = true,
                EndPoints = { new IPEndPoint(IPAddress.Parse(host), port) },
                Password = password
            };

            ServerEndPoint = options.EndPoints[0];
        }
Ejemplo n.º 26
0
        public async static Task<IConnection> ConnectAsync(EndPoint[] endpoints)
        {
            var configuration = new ConfigurationOptions { ClientName = "ScarletLock" };

            foreach (var endpoint in endpoints)
                configuration.EndPoints.Add(endpoint);

            return new RedisConnection(await ConnectionMultiplexer.ConnectAsync(configuration));
        }
Ejemplo n.º 27
0
        static RedisStore()
        {
            var configurationOptions = new ConfigurationOptions
            {
                EndPoints = { ConfigurationManager.AppSettings["redis.connection"] }
            };

            LazyConnection = new Lazy<ConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(configurationOptions));
        }
Ejemplo n.º 28
0
        public RedisConnection(string host, int port = 6379, string password = null)
        {
            var options = new ConfigurationOptions();
            options.Password = password;
            options.EndPoints.Add(host, port);
            options.AbortOnConnectFail = false;

            this.connectionManager = ConnectionMultiplexer.Connect(options);
        }
        /// <summary>
        /// Initializes a new instance of the RedisConnectionWrapper class, which contains methods for accessing
        ///     a static concurrentdictionary of already created and open RedisConnection instances
        /// </summary>
        /// <param name="serverAddress">The ip address of the redis instance</param>
        /// <param name="serverPort">The port number of the redis instance</param>
        public RedisConnectionWrapper(string srvAddr, int srvPort)
        {
            this.connData = ConfigurationOptions.Parse(srvAddr + ":" + srvPort);

            this.ConnectionID = string.Format(
                    "{0}_%_{1}",
                    srvAddr,
                    srvPort);
        }
Ejemplo n.º 30
0
 public InvitationProvider()
 {
     var config = new ConfigurationOptions
     {
         Ssl = true,
         Password = "******",
         EndPoints = { { "bizexperiments.redis.cache.windows.net", 6380 } }
     };
     _connection = ConnectionMultiplexer.Connect(config);
 }
Ejemplo n.º 31
0
        public static ConnectionMultiplexer Connect(RedisConfiguration configuration)
        {

            string connectionString = configuration.ConnectionString;
            if (string.IsNullOrWhiteSpace(configuration.ConnectionString))
            {
                Func<RedisConfiguration, string> createConfigurationOptions = (config) =>
                {
                    var configurationOptions = new ConfigurationOptions()
                    {
                        AllowAdmin = config.AllowAdmin,
                        ConnectTimeout = config.ConnectionTimeout,
                        Password = config.Password,
                        Ssl = config.IsSsl,
                        SslHost = config.SslHost,
                        ConnectRetry = 10,
                        AbortOnConnectFail = false
                    };
                    foreach (var endpoint in configuration.Endpoints)
                    {
                        configurationOptions.EndPoints.Add(endpoint.Host, endpoint.Port);
                    }

                    return configurationOptions.ToString();
                };
                connectionString = createConfigurationOptions(configuration);
            }
            ConnectionMultiplexer connection;
            lock (connectLock)
            {
                if (!connections.TryGetValue(connectionString, out connection))
                {
                    var builder = new StringBuilder();
                    using (var log = new StringWriter(builder, CultureInfo.InvariantCulture))
                    {
                        connection = ConnectionMultiplexer.Connect(connectionString, log);
                    }

                    connection.ConnectionFailed += (sender, args) =>
                    {
                        connections.Remove(connectionString);
                    };

                    if (!connection.IsConnected)
                    {
                        throw new InvalidOperationException("Connection failed.\n" + builder.ToString());
                    }

                    connection.PreserveAsyncOrder = false;
                    connections.Add(connectionString, connection);
                }
            }

            return connection;
        }
Ejemplo n.º 32
0
        public RedisSubscriber(RedisOptions configurationOptions)
        {
            _logger = Logger.CreateLogger <RedisSubscriber>();

            if (configurationOptions == null)
            {
                throw new ArgumentNullException(nameof(configurationOptions));
            }

            CreateConnection(configurationOptions);
        }
        public RedisSubscriber(string configuration)
        {
            _logger = Logger.CreateLogger <RedisSubscriber>();

            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            _options = RedisOptions.Parse(configuration);
        }
        public void OnBeforeTestExecute()
        {
            _redisConfigOpts = ConfigurationOptions.Parse(REDIS_SERVER);
            RedisConnectionConfig.GetSERedisServerConfigDbIndex = @base => new Tuple<string, int, ConfigurationOptions>(
                "SessionConnection", REDIS_DB, _redisConfigOpts);
            RedisSessionConfig.SessionTimeout = TIMEOUT;

            // StackExchange Redis client
            ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(REDIS_SERVER);
            db = redis.GetDatabase(REDIS_DB);
        }
Ejemplo n.º 35
0
        private void CreateConnection(RedisOptions configurationOptions)
        {
            using (var writer = new StringWriter())
            {
                _connection = ConnectionMultiplexer.Connect(configurationOptions, writer);

                _logger.LogDebug(writer.ToString());
            }

            _connection.ErrorMessage += (sender, args) => { _logger.LogError(args.Message); };

            _connection.ConnectionFailed += (sender, args) => { _logger.LogError(args.Exception, "Redis connection failed."); };

            _connection.ConnectionRestored += (sender, args) => { _logger.LogInformation("Redis connection restored."); };
        }
Ejemplo n.º 36
0
 public static ConnectionMultiplexer GetInstance(string host, int port)
 {
     if (conn == null)
     {
         var configOptions = new StackExchange.Redis.ConfigurationOptions
         {
             ConnectTimeout     = 5000,
             ConnectRetry       = 5,
             SyncTimeout        = 5000,
             AbortOnConnectFail = false,
         };
         configOptions.EndPoints.Add(host, port);
         conn = ConnectionMultiplexer.Connect(configOptions);
     }
     return(conn);
 }
Ejemplo n.º 37
0
        private static StackRedis.ConfigurationOptions CreateConfigurationOptions(RedisConfiguration configuration)
        {
            var configurationOptions = new StackRedis.ConfigurationOptions()
            {
                AllowAdmin         = configuration.AllowAdmin,
                ConnectTimeout     = configuration.ConnectionTimeout,
                Password           = configuration.Password,
                Ssl                = configuration.IsSsl,
                SslHost            = configuration.SslHost,
                ConnectRetry       = 10,
                AbortOnConnectFail = false
            };

            foreach (var endpoint in configuration.Endpoints)
            {
                configurationOptions.EndPoints.Add(endpoint.Host, endpoint.Port);
            }

            return(configurationOptions);
        }
Ejemplo n.º 38
0
        public static void SignalRConfiguration(this IServiceCollection services, IConfiguration configuration)
        {
            services.AddSignalR()
            .AddJsonProtocol(x =>
            {
                x.PayloadSerializerOptions.IgnoreNullValues            = false;
                x.PayloadSerializerOptions.PropertyNameCaseInsensitive = false;
                x.PayloadSerializerOptions.WriteIndented = false;
            })
            .AddMessagePackProtocol()
            .AddStackExchangeRedis(o =>
            {
                o.ConnectionFactory = async writer =>
                {
                    var config = new StackExchange.Redis.ConfigurationOptions
                    {
                        AbortOnConnectFail = false,
                        ResolveDns         = true
                    };

                    config.EndPoints.Add(configuration.GetConnectionString("Redis"), 6379);
                    config.SetDefaultPorts();
                    var connection = await ConnectionMultiplexer.ConnectAsync(config, writer);
                    connection.ConnectionFailed += (_, e) =>
                    {
                        Console.WriteLine("Connection to Redis failed.");
                    };

                    if (!connection.IsConnected)
                    {
                        Console.WriteLine("Did not connect to Redis.");
                    }

                    return(connection);
                };
            });
        }
Ejemplo n.º 39
0
 partial void OnCreateReaderWriter(ConfigurationOptions configuration)
 {
     SocketManager = configuration.SocketManager ?? GetDefaultSocketManager();
 }
        public RedisSubscriber(RedisOptions configurationOptions)
        {
            _logger = Logger.CreateLogger <RedisSubscriber>();

            _options = configurationOptions ?? throw new ArgumentNullException(nameof(configurationOptions));
        }
Ejemplo n.º 41
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddOptions();

            services.AddControllers();

            services.AddMvc(config =>
            {
                config.Filters.Add(new ProducesAttribute("application/json"));
                //config.Filters.Add(new ConsumesAttribute("application/json"));
            })
            .AddFluentValidation()
            .AddJsonOptions(x =>
            {
                x.JsonSerializerOptions.WriteIndented = false;
                x.JsonSerializerOptions.PropertyNameCaseInsensitive = false;
                x.JsonSerializerOptions.IgnoreNullValues            = false;
            });

            services.Configure <GzipCompressionProviderOptions>(options => options.Level = CompressionLevel.Optimal);

            services.AddResponseCompression(options => options.Providers.Add <GzipCompressionProvider>());

            services.AddSignalR()
            .AddJsonProtocol(x =>
            {
                x.PayloadSerializerOptions.IgnoreNullValues            = false;
                x.PayloadSerializerOptions.PropertyNameCaseInsensitive = false;
                x.PayloadSerializerOptions.WriteIndented = false;
            })
            .AddMessagePackProtocol()
            .AddStackExchangeRedis(o =>
            {
                o.ConnectionFactory = async writer =>
                {
                    var config = new StackExchange.Redis.ConfigurationOptions
                    {
                        AbortOnConnectFail = false,
                        ResolveDns         = true
                    };

                    config.EndPoints.Add(Configuration.GetConnectionString("Redis"), 6379);
                    config.SetDefaultPorts();
                    var connection = await ConnectionMultiplexer.ConnectAsync(config, writer);
                    connection.ConnectionFailed += (_, e) =>
                    {
                        Console.WriteLine("Connection to Redis failed.");
                    };

                    if (!connection.IsConnected)
                    {
                        Console.WriteLine("Did not connect to Redis.");
                    }

                    return(connection);
                };
            });

            services.AddCors();

            services.AddEntityFrameworkSqlServer()
            .AddDbContext <ChatContext>((serviceProvider, options) =>
            {
                options.UseApplicationServiceProvider(serviceProvider);
                options.UseInternalServiceProvider(serviceProvider);
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
            });

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddScoped <ChatContext>();

            // Health Checks
            services.AddHealthChecks()
            .AddSqlServer(Configuration.GetConnectionString("DefaultConnection"), name: "MSSQL")
            .AddRedis(Configuration.GetConnectionString("Redis"), name: "REDIS");

            services
            .AddHealthChecksUI();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Chat API", Version = "v1"
                });
                c.EnableAnnotations();
            });
        }