天天看点

.Net如何通过SSL连接Redis

最近在使用.Net SignalR Reids时一直出现无法连接的情况,所以记录一下遇到的坑。

因为用到的是Azure Reids服务器,开启了SSL(6380端口),同时禁用了TLS1.1和TLS1.2,

正常如果不使用SSL(6380端口)的话可以直接连接就可以了,但是如果是SSL就需要做一些修改才可以连接。

SignalR 需要Nuget引用如下包(使用StackExchangeRedis):

.Net如何通过SSL连接Redis

同时Startup中连接代码如下(ssl和sslprotocols为关键参数,用于连接开启ssl的redis服务器):

public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
      
            //使用Redis方式进行连接,用于负载均衡场景
            var connString = $"xxxxx:6380,password=xxxx,ssl=true,abortConnect=false,sslprotocols=tls12";
            GlobalHost.DependencyResolver.UseStackExchangeRedis(new RedisScaleoutConfiguration(connString, "ChatHub"));
        }
    }
           

另外如果使用ServiceStack.Redis工具包的话需要做如下调整(password需要进行url编码):

public IRedisClient GetClient()
        {
            var password = HttpUtility.UrlEncode("xxxxx");
            var connString = $"redis://xxxx:6380?ssl=true&sslprotocols=Tls12&password={password}";
            var redisManager = new RedisManagerPool(connString);
            return redisManager.GetClient();
        }
           

附ServiceStack.Redis和StackExchangeRedis使用说明连接:

https://github.com/ServiceStack/ServiceStack.Redis#servicestackredis-ssl-support

https://gist.github.com/JonCole/925630df72be1351b21440625ff2671f#file-redis-bestpractices-stackexchange-redis-md