天天看點

.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