forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMemcachedClientCache.cs
More file actions
360 lines (308 loc) · 12.6 KB
/
MemcachedClientCache.cs
File metadata and controls
360 lines (308 loc) · 12.6 KB
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
using System;
using System.Collections.Generic;
using System.Net;
using Enyim.Caching;
using Enyim.Caching.Configuration;
using Enyim.Caching.Memcached;
using ILog = ServiceStack.Logging.ILog;
using LogManager = ServiceStack.Logging.LogManager;
namespace ServiceStack.Caching.Memcached
{
/// <summary>
/// A memcached implementation of the ServiceStack ICacheClient interface.
/// Good practice not to have dependencies on implementations in your business logic.
///
/// Basically delegates all calls to Enyim.Caching.MemcachedClient with added diagnostics and logging.
/// </summary>
public class MemcachedClientCache
: ICacheClient, IMemcachedClient
{
protected ILog Log { get { return LogManager.GetLogger(GetType()); } }
private MemcachedClient _client;
/// <summary>
/// Initializes the Cache using the default configuration section (enyim/memcached) to configure the memcached client
/// </summary>
/// <see cref="Enyim.Caching.Configuration.MemcachedClientSection"/>
public MemcachedClientCache()
{
_client = new MemcachedClient();
}
/// <summary>
/// Initializes the Cache using the provided hosts to configure the memcached client
/// </summary>
/// <param name="hosts"></param>
public MemcachedClientCache(IEnumerable<string> hosts)
{
const int defaultPort = 11211;
const int ipAddressIndex = 0;
const int portIndex = 1;
var ipEndpoints = new List<IPEndPoint>();
foreach (var host in hosts)
{
var hostParts = host.Split(':');
if (hostParts.Length == 0)
throw new ArgumentException("'{0}' is not a valid host IP Address: e.g. '127.0.0.0[:11211]'");
var port = (hostParts.Length == 1) ? defaultPort : int.Parse(hostParts[portIndex]);
var hostAddresses = Dns.GetHostAddresses(hostParts[ipAddressIndex]);
foreach (var ipAddress in hostAddresses)
{
var endpoint = new IPEndPoint(ipAddress, port);
ipEndpoints.Add(endpoint);
}
}
LoadClient(PrepareMemcachedClientConfiguration(ipEndpoints));
}
public MemcachedClientCache(IEnumerable<IPEndPoint> ipEndpoints)
{
LoadClient(PrepareMemcachedClientConfiguration(ipEndpoints));
}
/// <summary>
/// Initializes a new instance of the <see cref="MemcachedClientCache"/> class based on an existing <see cref="IMemcachedClientConfiguration"/>.
/// </summary>
/// <param name="memcachedClientConfiguration">The <see cref="IMemcachedClientConfiguration"/>.</param>
public MemcachedClientCache(IMemcachedClientConfiguration memcachedClientConfiguration)
{
LoadClient(memcachedClientConfiguration);
}
/// <summary>
/// Prepares a MemcachedClientConfiguration based on the provided ipEndpoints.
/// </summary>
/// <param name="ipEndpoints">The ip endpoints.</param>
/// <returns></returns>
private IMemcachedClientConfiguration PrepareMemcachedClientConfiguration(IEnumerable<IPEndPoint> ipEndpoints)
{
var config = new MemcachedClientConfiguration();
foreach (var ipEndpoint in ipEndpoints)
{
config.Servers.Add(ipEndpoint);
}
config.SocketPool.MinPoolSize = 10;
config.SocketPool.MaxPoolSize = 100;
config.SocketPool.ConnectionTimeout = new TimeSpan(0, 0, 10);
config.SocketPool.DeadTimeout = new TimeSpan(0, 2, 0);
return config;
}
private void LoadClient(IMemcachedClientConfiguration config)
{
Enyim.Caching.LogManager.AssignFactory(new EnyimLogFactoryWrapper());
_client = new MemcachedClient(config);
}
public void Dispose()
{
/*
* DO NOTHING!!
*
* Calling _client.Dispose() breaks any call to a service that uses ICachClient
* after a call to ServiceStack.ServiceInterface.ServiceExtension.GetSession.
*
* Enyim.Caching.MemcachedClient defines a destructor that handles all necessary cleanup (disposing is done there, we don't need to worry).
*/
}
public bool Remove(string key)
{
return Execute(() => _client.Remove(key));
}
public object Get(string key)
{
return Get<object>(key);
}
public object Get(string key, out ulong ucas)
{
var result = _client.GetWithCas<MemcachedValueWrapper>(key);
if (result.Result != null)
{
ucas = result.Cas;
return result.Result;
}
ucas = default(ulong);
return null;
}
public T Get<T>(string key)
{
return Execute(() =>
{
var result = _client.Get<MemcachedValueWrapper>(key);
if (result != null)
return (T)result.Value;
return default(T);
});
}
public long Increment(string key, uint amount)
{
return Execute(() => (long)_client.Increment(key, 0, amount));
}
public long Decrement(string key, uint amount)
{
return Execute(() => (long)_client.Decrement(key, 0, amount));
}
public bool Add<T>(string key, T value)
{
return Execute(() => _client.Store(StoreMode.Add, key, new MemcachedValueWrapper(value)));
}
public bool Set<T>(string key, T value)
{
return Execute(() => _client.Store(StoreMode.Set, key, new MemcachedValueWrapper(value)));
}
public bool Replace<T>(string key, T value)
{
return Execute(() => _client.Store(StoreMode.Replace, key, new MemcachedValueWrapper(value)));
}
public bool Add<T>(string key, T value, DateTime expiresAt)
{
return Execute(() => _client.Store(StoreMode.Add, key, new MemcachedValueWrapper(value), expiresAt));
}
public bool Set<T>(string key, T value, DateTime expiresAt)
{
return Execute(() => _client.Store(StoreMode.Set, key, new MemcachedValueWrapper(value), expiresAt));
}
public bool Replace<T>(string key, T value, DateTime expiresAt)
{
return Execute(() => _client.Store(StoreMode.Replace, key, new MemcachedValueWrapper(value), expiresAt));
}
public bool Add<T>(string key, T value, TimeSpan expiresIn)
{
return Execute(() => _client.Store(StoreMode.Add, key, new MemcachedValueWrapper(value), expiresIn));
}
public bool Set<T>(string key, T value, TimeSpan expiresIn)
{
return Execute(() => _client.Store(StoreMode.Set, key, new MemcachedValueWrapper(value), expiresIn));
}
public bool Replace<T>(string key, T value, TimeSpan expiresIn)
{
return Execute(() => _client.Store(StoreMode.Replace, key, new MemcachedValueWrapper(value), expiresIn));
}
public bool Add(string key, object value)
{
return Execute(() => _client.Store(StoreMode.Add, key, new MemcachedValueWrapper(value)));
}
public bool Set(string key, object value)
{
return Execute(() => _client.Store(StoreMode.Set, key, new MemcachedValueWrapper(value)));
}
public bool Replace(string key, object value)
{
return Execute(() => _client.Store(StoreMode.Replace, key, new MemcachedValueWrapper(value)));
}
public bool Add(string key, object value, DateTime expiresAt)
{
return Execute(() => _client.Store(StoreMode.Add, key, new MemcachedValueWrapper(value), expiresAt));
}
public bool Set(string key, object value, DateTime expiresAt)
{
return Execute(() => _client.Store(StoreMode.Set, key, new MemcachedValueWrapper(value), expiresAt));
}
public bool Replace(string key, object value, DateTime expiresAt)
{
return Execute(() => _client.Store(StoreMode.Replace, key, new MemcachedValueWrapper(value), expiresAt));
}
public bool CheckAndSet(string key, object value, ulong cas)
{
return Execute(() => _client.Cas(StoreMode.Replace, key, new MemcachedValueWrapper(value), cas).Result);
}
public bool CheckAndSet(string key, object value, ulong cas, DateTime expiresAt)
{
return Execute(() => _client.Cas(StoreMode.Replace, key, new MemcachedValueWrapper(value), expiresAt, cas).Result);
}
public void FlushAll()
{
Execute(() => _client.FlushAll());
}
public IDictionary<string, T> GetAll<T>(IEnumerable<string> keys)
{
var results = new Dictionary<string, T>();
foreach (var key in keys)
{
var result = Get<T>(key);
results[key] = result;
}
return results;
}
public void SetAll<T>(IDictionary<string, T> values)
{
foreach (var entry in values)
{
Set(entry.Key, entry.Value);
}
}
public IDictionary<string, object> GetAll(IEnumerable<string> keys)
{
var results = new Dictionary<string, object>();
foreach (var key in keys)
{
var result = Get(key);
results[key] = result;
}
return results;
}
public IDictionary<string, object> GetAll(IEnumerable<string> keys, out IDictionary<string, ulong> casValues)
{
var retVal = new Dictionary<string, object>();
casValues = new Dictionary<string, ulong>();
foreach (var casResult in _client.GetWithCas(keys))
{
retVal.Add(casResult.Key, ((MemcachedValueWrapper)casResult.Value.Result).Value);
casValues.Add(casResult.Key, casResult.Value.Cas);
}
return retVal;
}
public void RemoveAll(IEnumerable<string> keys)
{
foreach (var key in keys)
{
try
{
Remove(key);
}
catch (Exception ex)
{
Log.Error(string.Format("Error trying to remove {0} from memcached", key), ex);
}
}
}
/// <summary>
/// Executes the specified expression.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="action">The action.</param>
/// <returns></returns>
private T Execute<T>(Func<T> action)
{
DateTime before = DateTime.Now;
Log.DebugFormat("Executing action '{0}'", action.Method.Name);
try
{
T result = action();
TimeSpan timeTaken = DateTime.Now - before;
if (Log.IsDebugEnabled)
Log.DebugFormat("Action '{0}' executed. Took {1} ms.", action.Method.Name, timeTaken.TotalMilliseconds);
return result;
}
catch (Exception ex)
{
Log.ErrorFormat("There was an error executing Action '{0}'. Message: {1}", action.Method.Name, ex.Message);
throw;
}
}
/// <summary>
/// Executes the specified action (for void methods).
/// </summary>
/// <param name="action">The action.</param>
private void Execute(Action action)
{
DateTime before = DateTime.Now;
Log.DebugFormat("Executing action '{0}'", action.Method.Name);
try
{
action();
TimeSpan timeTaken = DateTime.Now - before;
if (Log.IsDebugEnabled)
Log.DebugFormat("Action '{0}' executed. Took {1} ms.", action.Method.Name, timeTaken.TotalMilliseconds);
}
catch (Exception ex)
{
Log.ErrorFormat("There was an error executing Action '{0}'. Message: {1}", action.Method.Name, ex.Message);
throw;
}
}
}
}