-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRedisServiceExtensions.cs
309 lines (277 loc) · 12.4 KB
/
RedisServiceExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SNetPro.RedisManager;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
namespace NetPro.RedisManager
{
public static class RedisServiceExtensions
{
/// <summary>
/// Redis服务,支持Csredis与StackExchangeRedis
/// RedisCacheOption:RedisComponent=1>csredis;=2> StackExchangeRedis
/// </summary>
/// <param name="services"></param>
/// <param name="configuration"></param>
/// <returns></returns>
/// <remarks>Csredis驱动下非集群模式Cluster必须为fasle,否则指定DataBase无效</remarks>
//[Obsolete("废弃,请单独使用Csredis驱动或 StackExchange.Redis")]
public static IServiceCollection AddRedisManager(this IServiceCollection services, IConfiguration configuration)
{
var option = configuration.GetSection(nameof(RedisCacheOption)).Get<RedisCacheOption>();
if (option == null)
{
throw new ArgumentNullException(nameof(RedisCacheOption), $"未检测到NetPro.RedisManager配置节点{nameof(RedisCacheOption)}");
}
services.AddRedisManager(option);
return services;
}
/// <summary>
///
/// </summary>
/// <param name="services"></param>
/// <param name="redisCacheOption"></param>
/// <returns></returns>
//[Obsolete("废弃,请单独使用Csredis驱动或 StackExchange.Redis")]
public static IServiceCollection AddRedisManager(this IServiceCollection services, RedisCacheOption redisCacheOption)
{
var redisCacheComponent = redisCacheOption?.RedisComponent ?? RedisCacheComponentEnum.NullRedis;
services.AddMemoryCache();
switch (redisCacheComponent)
{
case RedisCacheComponentEnum.CSRedisCore:
services.AddCsRedis(redisCacheOption);
break;
case RedisCacheComponentEnum.StackExchangeRedis:
services.AddStackExchangeRedis(redisCacheOption);
break;
case RedisCacheComponentEnum.NullRedis:
services.AddSingleton<IRedisManager, NullCache>();
break;
default:
services.AddSingleton(redisCacheOption);
services.AddSingleton<IRedisManager, NullCache>();
break;
}
return services;
}
/// <summary>
///
/// </summary>
/// <param name="services"></param>
/// <param name="option"></param>
/// <returns></returns>
//[Obsolete("废弃,请单独使用Csredis驱动或 StackExchange.Redis")]
public static IServiceCollection AddCsRedis(this IServiceCollection services, RedisCacheOption option)
{
services.AddSingleton<ISerializer, NewtonsoftSerializer>();
services.AddSingleton(option);
List<string> csredisConns = new List<string>();
string password = option.Password;
int defaultDb = option.Database;
string ssl = option.SslHost;
string keyPrefix = option.DefaultCustomKey;
int writeBuffer = 10240;
int poolsize = option.PoolSize == 0 ? 10 : option.PoolSize;
int timeout = option.ConnectionTimeout;
foreach (var e in option.Endpoints)
{
string server = e.Host;
int port = e.Port;
if (string.IsNullOrWhiteSpace(server) || port <= 0) { continue; }
csredisConns.Add($"{server}:{port},password={password},defaultDatabase={defaultDb},poolsize={poolsize},ssl={ssl},writeBuffer={writeBuffer},prefix={keyPrefix},preheat={option.Preheat},idleTimeout={timeout},testcluster={option.Cluster}");
}
CSRedis.CSRedisClient csredis;
try
{
csredis = new CSRedis.CSRedisClient(null, csredisConns.ToArray());
}
catch (Exception ex)
{
throw new ArgumentException($"请检查是否为非密码模式,Password必须为空字符串;请检查Database是否为0,只能在非集群模式下才可配置Database大于0;{ex}");
}
RedisHelper.Initialization(csredis);
services.AddSingleton<IRedisManager, CsRedisManager>();
/*注入stackexchange驱动,防止CSRedis驱动下获取IDatabase异常 */
#region 注入stackexchange驱动
var configurationOptions = new ConfigurationOptions
{
KeepAlive = 180,
ConnectTimeout = option.ConnectionTimeout,
Password = option.Password,
Ssl = option.IsSsl,
SslHost = option.SslHost,
AbortOnConnectFail = false,
AsyncTimeout = option.ConnectionTimeout,
DefaultDatabase = option.Database,
};
foreach (var endpoint in option.Endpoints)
{
configurationOptions.EndPoints.Add(endpoint.Host, endpoint.Port);
}
var connect = ConnectionMultiplexer.Connect(configurationOptions);
//注册如下事件
connect.ConnectionFailed += MuxerConnectionFailed;
connect.ConnectionRestored += MuxerConnectionRestored;
connect.ErrorMessage += MuxerErrorMessage;
connect.ConfigurationChanged += MuxerConfigurationChanged;
connect.HashSlotMoved += MuxerHashSlotMoved;
connect.InternalError += MuxerInternalError;
services.AddSingleton(connect);
//services.Add(ServiceDescriptor.Singleton(connect));
#endregion
return services;
}
/// <summary>
///
/// </summary>
/// <param name="services"></param>
/// <param name="config"></param>
/// <returns></returns>
//[Obsolete("废弃,请单独使用Csredis驱动或 StackExchange.Redis")]
public static IServiceCollection AddCsRedis(this IServiceCollection services, IConfiguration config)
{
var option = new RedisCacheOption(config);
services.AddCsRedis(option);
return services;
}
/// <summary>
///
/// </summary>
/// <param name="services"></param>
/// <param name="config"></param>
/// <returns></returns>
//[Obsolete("废弃,请单独使用Csredis驱动或 StackExchange.Redis")]
public static IServiceCollection AddStackExchangeRedis(this IServiceCollection services, IConfiguration config)
{
var redisOption = new RedisCacheOption(config);
services.AddStackExchangeRedis(redisOption);
return services;
}
/// <summary>
///
/// </summary>
/// <param name="services"></param>
/// <param name="redisOption"></param>
/// <returns></returns>
//[Obsolete("废弃,请单独使用Csredis驱动或 StackExchange.Redis")]
public static IServiceCollection AddStackExchangeRedis(this IServiceCollection services, RedisCacheOption redisOption)
{
services.AddSingleton<ISerializer, NewtonsoftSerializer>();
services.AddSingleton(redisOption);
var configurationOptions = new ConfigurationOptions
{
KeepAlive = 180,
ConnectTimeout = redisOption.ConnectionTimeout,
Password = redisOption.Password,
Ssl = redisOption.IsSsl,
SslHost = redisOption.SslHost,
AbortOnConnectFail = false,
AsyncTimeout = redisOption.ConnectionTimeout,
DefaultDatabase = redisOption.Database,
};
foreach (var endpoint in redisOption.Endpoints)
{
configurationOptions.EndPoints.Add(endpoint.Host, endpoint.Port);
}
var connect = ConnectionMultiplexer.Connect(configurationOptions);
//注册如下事件
connect.ConnectionFailed += MuxerConnectionFailed;
connect.ConnectionRestored += MuxerConnectionRestored;
connect.ErrorMessage += MuxerErrorMessage;
connect.ConfigurationChanged += MuxerConfigurationChanged;
connect.HashSlotMoved += MuxerHashSlotMoved;
connect.InternalError += MuxerInternalError;
//services.Add(ServiceDescriptor.Singleton(connect));
services.AddSingleton(connect);
services.AddSingleton<IRedisManager, StackExchangeRedisManager>();
/*注入CSRedis驱动,防止Stackexchange驱动下获取执行RedisHelper异常*/
#region 注入CSRedis驱动
services.AddSingleton(redisOption);
List<string> csredisConns = new List<string>();
string password = redisOption.Password;
int defaultDb = redisOption.Database;
string ssl = redisOption.SslHost;
string keyPrefix = redisOption.DefaultCustomKey;
int writeBuffer = 10240;
int poolsize = redisOption.PoolSize == 0 ? 10 : redisOption.PoolSize;
int timeout = redisOption.ConnectionTimeout;
foreach (var e in redisOption.Endpoints)
{
string server = e.Host;
int port = e.Port;
if (string.IsNullOrWhiteSpace(server) || port <= 0) { continue; }
csredisConns.Add($"{server}:{port},password={password},defaultDatabase={defaultDb},poolsize={poolsize},ssl={ssl},writeBuffer={writeBuffer},prefix={keyPrefix},preheat={redisOption.Preheat},idleTimeout={timeout},testcluster={redisOption.Cluster}");
}
CSRedis.CSRedisClient csredis;
try
{
csredis = new CSRedis.CSRedisClient(null, csredisConns.ToArray());
}
catch (Exception ex)
{
throw new ArgumentException($"Check the configuration for redis;{ex}");
}
RedisHelper.Initialization(csredis);
#endregion
return services;
}
#region 事件
/// <summary>
/// 配置更改时
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerConfigurationChanged(object sender, EndPointEventArgs e)
{
Console.WriteLine("Configuration changed: " + e.EndPoint);
}
/// <summary>
/// 发生错误时
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerErrorMessage(object sender, RedisErrorEventArgs e)
{
Console.WriteLine("ErrorMessage: " + e.Message);
}
/// <summary>
/// 重新建立连接之前的错误
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerConnectionRestored(object sender, ConnectionFailedEventArgs e)
{
Console.WriteLine("ConnectionRestored: " + e.EndPoint);
}
/// <summary>
/// 连接失败 , 如果重新连接成功你将不会收到这个通知
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerConnectionFailed(object sender, ConnectionFailedEventArgs e)
{
Console.WriteLine("Retry:Endpoint failed: " + e.EndPoint + ", " + e.FailureType + (e.Exception == null ? "" : (", " + e.Exception.Message)));
}
/// <summary>
/// 更改集群
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerHashSlotMoved(object sender, HashSlotMovedEventArgs e)
{
Console.WriteLine("HashSlotMoved:NewEndPoint" + e.NewEndPoint + ", OldEndPoint" + e.OldEndPoint);
}
/// <summary>
/// redis类库错误
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerInternalError(object sender, InternalErrorEventArgs e)
{
Console.WriteLine("InternalError:Message" + e.Exception.Message);
}
#endregion 事件
}
}