問題描述

在Visual Studio 2019中,通過Cloud Service模板建立了一個Worker Role的角色,在角色中使用StackExchange.Redis來連線Redis。遇見了一系列的異常:

  • RedisConnectionException: No connection is available to service this operation: PING; It was not possible to connect to the redis server(s); ConnectTimeout; IOCP: (Busy=0,Free=1000,Min=8,Max=1000), WORKER: (Busy=2,Free=32765,Min=8,Max=32767), Local-CPU: n/a
  • RedisConnectionException: UnableToConnect on xxxxxx.redis.cache.chinacloudapi.cn:6380/Interactive, origin: ResetNonConnected, input-buffer: 0, outstanding: 0, last-read: 5s ago, last-write: 5s ago, unanswered-write: 524763s ago, keep-alive: 60s, pending: 0, state: Connecting, last-heartbeat: never, last-mbeat: -1s ago, global: 5s ago, mgr: Inactive, err: never
  • IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
  • SocketException: An existing connection was forcibly closed by the remote host

異常截圖:

問題分析

根據異常資訊 Socket Exception, 在建立連線的時候被Remote Host關閉,也就是Redis服務端強制關閉了此連線。那麼就需要進一步分析,為什麼Redis會強制關閉連線呢? 檢視Redis的連線字串:

  1. xxxxxx.redis.cache.chinacloudapi.cn:6380,password=<access key>,ssl=True,abortConnect=False

使用6380埠,建立SSL連線,在連線字串中已經啟用SSL。在建立Azure Redis的資源中,會發現一段提示:TLS1.0,1.1已不被支援。需要使用TLS1.2版本。

而當前的Cloud Service使用的是.NET Framework 4.5。 而恰巧,在 .NET Framework 4.5.2 或更低版本上,Redis .NET 客戶端預設使用最低的 TLS 版本;在 .NET Framework 4.6 或更高版本上,則使用最新的 TLS 版本。

所以如果使用的是較舊版本的 .NET Framework,需要手動啟用 TLS 1.2: StackExchange.Redis: 在連線字串中設定 ssl=true 和 sslprotocols=tls12

問題解決

在字串中新增 ssl=True,sslprotocols=tls12, 完整字串為:

  1. string cacheConnection = "xxxxxx.redis.cache.chinacloudapi.cn:6380,password=xxxxxxxxx+xxx+xxxxxxx=,ssl=True,sslprotocols=tls12, abortConnect=False";

在Visual Studio 2019程式碼中的效果如:

Could Service 與 Redis 使用的簡單程式碼片段為

WorkerRole:

  1. using Microsoft.WindowsAzure;
  2. using Microsoft.WindowsAzure.Diagnostics;
  3. using Microsoft.WindowsAzure.ServiceRuntime;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11.  
  12. namespace WorkerRole1
  13. {
  14. public class WorkerRole : RoleEntryPoint
  15. {
  16. private readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
  17. private readonly ManualResetEvent runCompleteEvent = new ManualResetEvent(false);
  18.  
  19. private RedisJob redisjob1 = new RedisJob();
  20.  
  21. public override void Run()
  22. {
  23. Trace.TraceInformation("WorkerRole1 is running");
  24.  
  25. try
  26. {
  27. this.RunAsync(this.cancellationTokenSource.Token).Wait();
  28. }
  29. finally
  30. {
  31. this.runCompleteEvent.Set();
  32. }
  33. }
  34.  
  35. public override bool OnStart()
  36. {
  37. // Set the maximum number of concurrent connections
  38. ServicePointManager.DefaultConnectionLimit = 12;
  39. //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
  40.  
  41. // For information on handling configuration changes
  42. // see the MSDN topic at https://go.microsoft.com/fwlink/?LinkId=166357.
  43.  
  44. bool result = base.OnStart();
  45.  
  46. Trace.TraceInformation("WorkerRole1 has been started");
  47.  
  48. return result;
  49. }
  50.  
  51. public override void OnStop()
  52. {
  53. Trace.TraceInformation("WorkerRole1 is stopping");
  54.  
  55. this.cancellationTokenSource.Cancel();
  56. this.runCompleteEvent.WaitOne();
  57.  
  58. base.OnStop();
  59.  
  60. Trace.TraceInformation("WorkerRole1 has stopped");
  61. }
  62.  
  63. private async Task RunAsync(CancellationToken cancellationToken)
  64. {
  65. // TODO: Replace the following with your own logic.
  66. while (!cancellationToken.IsCancellationRequested)
  67. {
  68. Trace.TraceInformation("Working");
  69. redisjob1.RunReidsCommand();
  70. await Task.Delay(10000);
  71. }
  72. }
  73. }
  74. }

RedisJob:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using StackExchange.Redis;
  7.  
  8. namespace WorkerRole1
  9. {
  10. class RedisJob
  11. {
  12. private static Lazy<ConnectionMultiplexer> lazyConnection = CreateConnection();
  13.  
  14. public static ConnectionMultiplexer Connection
  15. {
  16. get
  17. {
  18. return lazyConnection.Value;
  19. }
  20. }
  21.  
  22. private static Lazy<ConnectionMultiplexer> CreateConnection()
  23. {
  24. return new Lazy<ConnectionMultiplexer>(() =>
  25. {
  26. string cacheConnection = "xxxxxx.redis.cache.chinacloudapi.cn:6380,password=xxxxxx+xxx+xxxx=,ssl=True,sslprotocols=tls12, abortConnect=False";
  27. return ConnectionMultiplexer.Connect(cacheConnection);
  28. });
  29. }
  30.  
  31. public void RunReidsCommand() {
  32.  
  33. IDatabase cache = Connection.GetDatabase();
  34.  
  35. // Perform cache operations using the cache object...
  36.  
  37. // Simple PING command
  38. string cacheCommand = "PING";
  39. Console.WriteLine("\nCache command : " + cacheCommand);
  40. Console.WriteLine("Cache response : " + cache.Execute(cacheCommand).ToString());
  41.  
  42. // Simple get and put of integral data types into the cache
  43. cacheCommand = "GET Message";
  44. Console.WriteLine("\nCache command : " + cacheCommand + " or StringGet()");
  45. Console.WriteLine("Cache response : " + cache.StringGet("Message").ToString());
  46.  
  47. cacheCommand = "SET Message \"Hello! The cache is working from a .NET console app!\"";
  48. Console.WriteLine("\nCache command : " + cacheCommand + " or StringSet()");
  49. Console.WriteLine("Cache response : " + cache.StringSet("Message", "Hello! The cache is working from a .NET console app!").ToString());
  50.  
  51. // Demonstrate "SET Message" executed as expected...
  52. cacheCommand = "GET Message";
  53. Console.WriteLine("\nCache command : " + cacheCommand + " or StringGet()");
  54. Console.WriteLine("Cache response : " + cache.StringGet("Message").ToString());
  55. }
  56. }
  57. }

參考資料

刪除與 Azure Cache for Redis 配合使用的 TLS 1.0 和 1.1:  https://docs.microsoft.com/zh-cn/azure/azure-cache-for-redis/cache-remove-tls-10-11

將應用程式配置為使用 TLS 1.2

大多數應用程式使用 Redis 客戶端庫來處理與快取的通訊。 這裡說明了如何將以各種程式語言和框架編寫的某些流行客戶端庫配置為使用 TLS 1.2。

.NET Framework

在 .NET Framework 4.5.2 或更低版本上,Redis .NET 客戶端預設使用最低的 TLS 版本;在 .NET Framework 4.6 或更高版本上,則使用最新的 TLS 版本。 如果使用的是較舊版本的 .NET Framework,則可以手動啟用 TLS 1.2:

  • StackExchange.Redis: 在連線字串中設定 ssl=true 和 sslprotocols=tls12
  • ServiceStack.Redis: 請按照 ServiceStack.Redis 說明操作,並至少需要 ServiceStack.Redis v5.6。

.NET Core

Redis .NET Core 客戶端預設為作業系統預設 TLS 版本,此版本明顯取決於作業系統本身。

根據作業系統版本和已應用的任何修補程式,有效的預設 TLS 版本可能會有所不同。 有一個關於此內容的資訊源,也可以訪問此處,閱讀適用於 Windows 的相應文章。

但是,如果你使用的是舊作業系統,或者只是想要確保我們建議通過客戶端手動配置首選 TLS 版本。

Java

Redis Java 客戶端基於 Java 版本 6 或更早版本使用 TLS 1.0。 如果在快取中禁用了 TLS 1.0,則 Jedis、Lettuce 和 Redisson 無法連線到 Azure Cache for Redis。 升級 Java 框架以使用新的 TLS 版本。

對於 Java 7,Redis 客戶端預設不使用 TLS 1.2,但可以配置為使用此版本。 Jedis 允許你使用以下程式碼片段指定基礎 TLS 設定:

  1. SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
  2. SSLParameters sslParameters = new SSLParameters();
  3. sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
  4. sslParameters.setProtocols(new String[]{"TLSv1.2"});
  5.  
  6. URI uri = URI.create("rediss://host:port");
  7. JedisShardInfo shardInfo = new JedisShardInfo(uri, sslSocketFactory, sslParameters, null);
  8.  
  9. shardInfo.setPassword("cachePassword");
  10.  
  11. Jedis jedis = new Jedis(shardInfo);

Lettuce 和 Redisson 客戶端尚不支援指定 TLS 版本,因此,如果快取僅接受 TLS 1.2 連線,這些客戶端將無法工作。 我們正在審查這些客戶端的修補程式,因此請檢查那些包是否有包含此支援的更新版本。

在 Java 8 中,預設情況下會使用 TLS 1.2,並且在大多數情況下都不需要更新客戶端配置。 為了安全起見,請測試你的應用程式。

Node.js

Node Redis 和 IORedis 預設使用 TLS 1.2。

PHP

Predis

  • 低於 PHP 7 的版本:Predis 僅支援 TLS 1.0。 這些版本不支援 TLS 1.2;必須升級才能使用 TLS 1.2。

  • PHP 7.0 到 PHP 7.2.1:預設情況下,Predis 僅使用 TLS 1.0 或 TLS 1.1。 可以通過以下變通辦法來使用 TLS 1.2。 在建立客戶端例項時指定 TLS 1.2:

    1. $redis=newPredis\Client([
    2. 'scheme'=>'tls',
    3. 'host'=>'host',
    4. 'port'=>6380,
    5. 'password'=>'password',
    6. 'ssl'=>[
    7. 'crypto_type'=>STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT,
    8. ],
    9. ]);
  • PHP 7.3 及更高版本:Predis 使用最新的 TLS 版本。

PhpRedis

PhpRedis 在任何 PHP 版本上均不支援 TLS。

Python

Redis-py 預設使用 TLS 1.2。

GO

Redigo 預設使用 TLS 1.2。

【完】