コード例 #1
0
        // 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
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSignalR()
            .AddStackExchangeRedis(o =>
            {
                o.ConnectionFactory = async writer =>
                {
                    var config = new ConfigurationOptions
                    {
                        AbortOnConnectFail = false,
                        ChannelPrefix      = "ChatApp"
                    };
                    config.EndPoints.Add("backplaneredis", 0);
                    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.");
                    }
                    else
                    {
                        Console.WriteLine("Connect to Redis.");
                    }

                    return(connection);
                };
            });

            services.AddMvc();
        }
コード例 #2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddSignalR(o =>
            {
                o.EnableDetailedErrors = true;
            })
            .AddMessagePackProtocol()
            .AddStackExchangeRedis(o =>
            {
                o.ConnectionFactory = async writer =>
                {
                    var config = new ConfigurationOptions
                    {
                        AbortOnConnectFail = false,
                    };
                    config.Password = "******";
                    config.EndPoints.Add("redis", 0);
                    config.SetDefaultPorts();
                    var connection = await ConnectionMultiplexer.ConnectAsync(config, writer);
                    connection.ConnectionFailed += (_, e) =>
                    {
                        Console.WriteLine("Connection to Redis failed.");
                    };

                    if (!connection.IsConnected)
                    {
                        Environment.Exit(-1);
                        Console.WriteLine("Did not connect to Redis. Restarting service");
                    }

                    return(connection);
                };
            });
        }
コード例 #3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var envVal = Environment.GetEnvironmentVariables();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddSignalR()
            .AddStackExchangeRedis(o =>
            {
                o.Configuration.ChannelPrefix = "CarParkApp";
                o.ConnectionFactory           = async writer =>
                {
                    var config = new ConfigurationOptions
                    {
                        AbortOnConnectFail = false
                    };
                    config.EndPoints.Add(envVal["REDIS_URL"].ToString(), 0);
                    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.AddHostedService <Worker>();
        }
コード例 #4
0
        /// <summary>
        /// 校验连接配置
        /// </summary>
        /// <param name="configOptions"></param>
        private static void CheckConfigurationOptions(ConfigurationOptions configOptions)
        {
            if (configOptions == null)
            {
                throw new ArgumentNullException(nameof(configOptions));
            }

            if (configOptions.EndPoints.Count == 0)
            {
                throw new ArgumentException("No endpoints specified", "configuration");
            }

            configOptions.SetDefaultPorts();
        }
コード例 #5
0
        static RedisConnectorHelper()
        {
            RedisConnectorHelper.lazyConnection = new Lazy <ConnectionMultiplexer>(() =>
            {
                ConfigurationOptions option = new ConfigurationOptions();
                option.AbortOnConnectFail   = false;
                option.EndPoints.Add("myname.redis.cache.windows.net");
                option.Ssl = true;
                option.SetDefaultPorts();


                return(ConnectionMultiplexer.Connect(option));
            });
        }
コード例 #6
0
        public void ConfigManualWithDefaultPorts(string host, int port, bool useSsl, int expectedPort)
        {
            var options = new ConfigurationOptions();
            if(port == 0)
            {
                options.EndPoints.Add(host);
            } else
            {
                options.EndPoints.Add(host, port);
            }
            if (useSsl) options.Ssl = true;

            options.SetDefaultPorts(); // normally it is the multiplexer that calls this, not us
            Assert.AreEqual(expectedPort, ((DnsEndPoint)options.EndPoints.Single()).Port);
        }
コード例 #7
0
ファイル: Startup.cs プロジェクト: extox/SignalRTest01
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();

            string redisConStr = Configuration.GetConnectionString("RedisConnectionStr");

            //services.AddSignalR();
            //services.AddSignalR().AddStackExchangeRedis("localhost:6379");
            //services.AddSignalR().AddStackExchangeRedis("172.16.0.4:6379");
            services.AddSignalR()
            .AddMessagePackProtocol()
            .AddStackExchangeRedis(o =>
            {
                o.ConnectionFactory = async writer =>
                {
                    var config = new ConfigurationOptions
                    {
                        AbortOnConnectFail = false
                    };
                    //config.EndPoints.Add(IPAddress.Loopback, 0);
                    //config.EndPoints.Add("172.16.0.4", 0);
                    //config.EndPoints.Add(redisConStr, 6379);
                    //config.EndPoints.Add("localhost", 6379);
                    config.EndPoints.Add("172.16.0.4", 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);
                };
            });

            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
        }
        internal async Task <IConnectionMultiplexer> ConnectAsync(ConfigurationOptions configuration, TextWriter log)
        {
            // Factory is publically settable. Assigning to a local variable before null check for thread safety.
            if (ConnectionFactory != null)
            {
                return(await ConnectionFactory(log));
            }

            // REVIEW: Should we do this?
            if (configuration.EndPoints.Count == 0)
            {
                configuration.EndPoints.Add(IPAddress.Loopback, 0);
                configuration.SetDefaultPorts();
            }

            return(await ConnectionMultiplexer.ConnectAsync(configuration, log));
        }
コード例 #9
0
        // 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
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddDefaultPolicy(
                    builder =>
                {
                    builder
                    .WithOrigins("http://localhost:8090")
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials();
                });
            });

            services.AddHostedService <RabbitConsumerService>();

            var redisAddress = "signalr-scaling-poc_redis_1";

            services
            .AddSignalR()
            .AddStackExchangeRedis(o =>
            {
                o.ConnectionFactory = async writer =>
                {
                    var config = new ConfigurationOptions
                    {
                        AbortOnConnectFail = false
                    };
                    config.EndPoints.Add(Dns.GetHostAddressesAsync(redisAddress).Result.FirstOrDefault().ToString(), 0);
                    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);
                };
            });
        }
コード例 #10
0
ファイル: Startup.cs プロジェクト: ice02/SignalRNotif
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services
            .AddAuthorization(options =>
            {
                options.AddPolicy("DomainRestricted", policy =>
                {
                    policy.Requirements.Add(new DomainRestrictedRequirement());
                });
            });

            services.AddSignalR()
            //.AddMessagePackProtocol()
            .AddStackExchangeRedis(o =>
            {
                o.ConnectionFactory = async writer =>
                {
                    var config = new ConfigurationOptions
                    {
                        AbortOnConnectFail = false
                    };
                    config.EndPoints.Add(IPAddress.Loopback, 0);
                    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.");
                    }
                    else
                    {
                        Console.WriteLine("Connected to Redis.");
                    }

                    return(connection);
                };
            });
            services.AddControllers();

            services.AddSingleton <IUserIdProvider, NameUserIdProvider>();
        }
コード例 #11
0
        public void ConfigManualWithDefaultPorts(string host, int port, bool useSsl, int expectedPort)
        {
            var options = new ConfigurationOptions();

            if (port == 0)
            {
                options.EndPoints.Add(host);
            }
            else
            {
                options.EndPoints.Add(host, port);
            }
            if (useSsl)
            {
                options.Ssl = true;
            }

            options.SetDefaultPorts(); // normally it is the multiplexer that calls this, not us
            Assert.AreEqual(expectedPort, ((DnsEndPoint)options.EndPoints.Single()).Port);
        }
コード例 #12
0
        private static ConnectionMultiplexer ConnectToRedis(RedisOptions options, ILogger logger)
        {
            var loggerTextWriter = new LoggerTextWriter(logger);

            if (options.Factory != null)
            {
                return(options.Factory(loggerTextWriter));
            }

            if (options.Options.EndPoints.Any())
            {
                return(ConnectionMultiplexer.Connect(options.Options, loggerTextWriter));
            }

            var configurationOptions = new ConfigurationOptions();

            configurationOptions.EndPoints.Add(IPAddress.Loopback, 0);
            configurationOptions.SetDefaultPorts();

            return(ConnectionMultiplexer.Connect(configurationOptions, loggerTextWriter));
        }
コード例 #13
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHealthChecks()
            .AddCheck("self", () => running ? HealthCheckResult.Healthy() : HealthCheckResult.Unhealthy());
            services.AddApplicationInsightsTelemetry(Configuration["AppInsightsInstrumentationKey"]);
            services.AddControllers();
            services.AddRazorPages();
            services.AddSignalR();
            if (!string.IsNullOrEmpty(Configuration["REDIS_HOST"]))
            {
                services.AddSignalR().AddStackExchangeRedis(options =>
                {
                    options.ConnectionFactory = async writer =>
                    {
                        var config = new ConfigurationOptions
                        {
                            AbortOnConnectFail = false
                        };
                        var redisHost = Configuration["REDIS_HOST"] ?? "localhost";
                        var redisPort = int.Parse(Configuration["REDIS_PORT"] ?? "6379");
                        // config.EndPoints.Add(IPAddress.Loopback, 0);
                        config.EndPoints.Add(redisHost, redisPort);
                        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);
                    };
                });
            }
        }
コード例 #14
0
        private async Task ConnectAsync(CancellationToken token = default(CancellationToken))
        {
            token.ThrowIfCancellationRequested();

            if (_redis != null)
            {
                return;
            }

            await _connectionLock.WaitAsync(token);

            try
            {
                if (_redis == null)
                {
                    if (_options.ConfigurationOptions != null)
                    {
                        _redisConfig = _options.ConfigurationOptions;
                    }
                    else
                    {
                        _redisConfig = ConfigurationOptions.Parse(_options.Configuration);
                    }
                    _redisConfig.AllowAdmin = true;
                    _redisConfig.SetDefaultPorts();
                    _connection = await ConnectionMultiplexer.ConnectAsync(_redisConfig);

                    RegistenConnectionEvent(_connection);
                    _redis  = _connection.GetDatabase();
                    _server = _connection.GetServer(_redisConfig.EndPoints[0]);
                }
            }
            finally
            {
                _connectionLock.Release();
            }
        }
コード例 #15
0
        public void ConfigureServices(IServiceCollection services)
        {
            //加入JWT驗證
            services.AddAuthentication(
                opt =>
            {
                opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                opt.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
                opt.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(
                opt =>
            {
                opt.RequireHttpsMetadata      = false;
                opt.SaveToken                 = true;
                opt.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateAudience         = false,
                    ValidateIssuerSigningKey = false,
                    ValidateIssuer           = true,
                    ValidIssuer      = Configuration.GetValue <string>("Jwt:JwtIssuer"),
                    ValidAudience    = Configuration.GetValue <string>("Jwt:JwtAudience"),
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetValue <string>("Jwt:JwtKey"))),
                    ClockSkew        = TimeSpan.Zero  // remove delay of token when expire
                };
                opt.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];

                        // If the request is for our hub...
                        var path = context.HttpContext.Request.Path;
                        if (!string.IsNullOrEmpty(accessToken) &&
                            (path.StartsWithSegments("/chat")))
                        {
                            // Read the token out of the query string
                            context.Token = accessToken;
                        }
                        return(Task.CompletedTask);
                    }
                };
            });

            services.AddSignalR()
            //加入Redis Back plan
            .AddStackExchangeRedis(o =>
            {
                o.ConnectionFactory = async writer =>
                {
                    var config = new ConfigurationOptions
                    {
                        AbortOnConnectFail = false,
                        DefaultDatabase    = 0
                    };

                    config.EndPoints.Add(IPAddress.Loopback, 6379);
                    config.SetDefaultPorts();
                    var connection = await ConnectionMultiplexer.ConnectAsync(config, writer);
                    connection.ConnectionFailed += (_, e) =>
                    {
                        Console.WriteLine("Redis GG");
                    };

                    if (!connection.IsConnected)
                    {
                        Console.WriteLine("Redis Not Connected");
                    }

                    return(connection);
                };
            });


            services.AddSingleton <IConnectionMultiplexer>(s => ConnectionMultiplexer.Connect(Configuration.GetValue <string>("storage:redis:master")));


            services.AddSingleton <IUserManger, CacheUserManger>();
            services.AddSingleton <IChartEvent, BrocastAll>();
            services.AddSingleton <IChartEvent, GetOnlineUser>();
            services.AddSingleton <IChartEvent, Person>();


            services.AddCors(op =>
            {
                op.AddPolicy("CorsPolicy", set =>
                {
                    set.SetIsOriginAllowed(origin => true)
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials();
                });
            });
        }
コード例 #16
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy(Cors,
                                  builder =>
                {
                    builder
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowAnyOrigin();
                });
                options.AddPolicy("signalRCors",
                                  builder =>
                {
                    builder
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .WithOrigins("http://localhost:3000",
                                 "https://develop.delegate-market.nl",
                                 "https://delegate-market.nl")
                    .AllowCredentials();
                });
            });

            // configure strongly typed settings objects
            var jwtSettingsSection = Configuration.GetSection("JwtSettings");

            services.Configure <JwtSettings>(jwtSettingsSection);

            // configure jwt authentication
            var jwtSettings = jwtSettingsSection.Get <JwtSettings>();
            var key         = Encoding.ASCII.GetBytes(jwtSettings.SecretJWT);

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                    ValidateLifetime         = true,
                };
                x.Events = new JwtBearerEvents()
                {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];

                        var path = context.HttpContext.Request.Path;
                        if (!string.IsNullOrEmpty(accessToken) && (path.StartsWithSegments("/chathub")))
                        {
                            context.Token = accessToken;
                        }

                        return(Task.CompletedTask);
                    }
                };
            });

            services.AddCors();

            services.AddSingleton <ILiveChatService, LiveChatService>();
            services.AddSingleton <IUserIdProvider, UserIdProvider>();


            //jwt get id from token helper
            services.AddTransient <IJwtIdClaimReaderHelper, JwtIdClaimReaderHelper>();

            services.AddTransient <IChatService, ChatService>();

            services.AddTransient <IChatRepository, ChatRepository>();

            services.Configure <ChatDatabaseSettings>(
                Configuration.GetSection(nameof(ChatDatabaseSettings)));

            services.AddSingleton <IChatDatabaseSettings>(sp =>
                                                          sp.GetRequiredService <IOptions <ChatDatabaseSettings> >().Value);

            services.AddControllers();
            services.AddSignalR().AddStackExchangeRedis(o => o.ConnectionFactory = async writer =>
            {
                var config = new ConfigurationOptions
                {
                    AbortOnConnectFail = false
                };
                config.EndPoints.Add(Configuration["HubSettings:Url"]);
                config.SetDefaultPorts();
                var connection = await ConnectionMultiplexer.ConnectAsync(config, writer);
                return(connection);
            });

            services.AddHealthChecks().AddCheck("healthy", () => HealthCheckResult.Healthy());
        }
コード例 #17
0
ファイル: Startup.cs プロジェクト: sanglirong/SignalRChatDome
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddJwtBearerAuthentication();


            //services.AddAuthentication(auth =>
            //{
            //    auth.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            //    auth.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            //    auth.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            //})
            //.AddCookie(cookie =>
            //{
            //    cookie.LoginPath = "/Home";
            //    cookie.Cookie.Name = "ASPNETCORE_SESSION_ID";
            //    cookie.Cookie.Path = "/";
            //    //cookie.Cookie.HttpOnly = true;
            //    cookie.Cookie.Expiration = TimeSpan.FromMinutes(20);

            //});

            //数据库
            services.AddDbContext <WeChatContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Default")));


            //依赖注入
            services.AddScoped <IDAL_OnlineClient, DAL_OnlieClient>();

            services.AddSingleton <WeChatHub>();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddSignalR()
            .AddStackExchangeRedis(options =>
            {
                options.Configuration.ChannelPrefix = "MyApp";

                options.ConnectionFactory = async writer =>
                {
                    var config = new ConfigurationOptions
                    {
                        AbortOnConnectFail = false
                    };
                    config.EndPoints.Add("192.168.0.45");
                    // config.EndPoints.Add(IPAddress.Loopback, 0);

                    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);
                };
            });
            IocManager.Ic = services.BuildServiceProvider();
        }
コード例 #18
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <LiveShowDBContext>();
            services.AddAutoMapper();

            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version = "v1",
                    Title   = "LiveShow"
                });
                var xmlFilePaths = new List <string>()
                {
                    "LiveShow.MessageCenter.xml",
                    "LiveShow.Service.xml",
                    "LiveShow.Core.xml"
                };
                foreach (var filePath in xmlFilePaths)
                {
                    var xmlFilePath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, filePath);
                    if (File.Exists(xmlFilePath))
                    {
                        c.IncludeXmlComments(xmlFilePath);
                    }
                }
            });

            //注册Cors的策略
            services.AddCors(options => options.AddPolicy("CorsPolicy", policyBuilder => {
                policyBuilder.AllowAnyMethod()
                .AllowAnyHeader()
                .AllowAnyOrigin()
                .AllowCredentials();
            }));

            ///注册SignalR和Redis
            services.AddSignalR(option => option.EnableDetailedErrors = true)
            .AddMessagePackProtocol()
            .AddStackExchangeRedis(o =>
            {
                o.ConnectionFactory = async writer =>
                {
                    var config = new ConfigurationOptions
                    {
                        AbortOnConnectFail = false
                    };
                    config.EndPoints.Add(IPAddress.Loopback, 0);
                    config.SetDefaultPorts();
                    config.ChannelPrefix         = "SignalTest";
                    var connection               = await ConnectionMultiplexer.ConnectAsync(config, writer);
                    connection.ConnectionFailed += (_, e) =>
                    {
                        Console.WriteLine("Connection Redis failed.");
                    };
                    if (!connection.IsConnected)
                    {
                        Console.WriteLine("Connection did not connect.");
                    }
                    return(connection);
                };
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            var builder = new ContainerBuilder();

            builder.RegisterModule <CoreModule>();
            builder.RegisterModule <ServiceModule>();
            builder.Populate(services);
            ApplicationContainer = builder.Build();
            return(new AutofacServiceProvider(ApplicationContainer));
        }