-
-
Notifications
You must be signed in to change notification settings - Fork 454
/
Copy pathProgram.cs
364 lines (298 loc) · 12.8 KB
/
Program.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
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
361
362
363
364
using System;
using System.Threading;
using CacheManager.Core;
using Microsoft.Extensions.Logging;
#if NET451
using Microsoft.Practices.Unity;
#else
using Unity;
#endif
namespace CacheManager.Examples
{
public class Program
{
private static void Main()
{
EventsExample();
UnityInjectionExample();
UnityInjectionExample_Advanced();
SimpleCustomBuildConfigurationUsingConfigBuilder();
SimpleCustomBuildConfigurationUsingFactory();
UpdateTest();
UpdateCounterTest();
LoggingSample();
}
#if !NETCOREAPP
private static void MostSimpleCacheManager()
{
var config = new ConfigurationBuilder()
.WithSystemRuntimeCacheHandle()
.Build();
var cache = new BaseCacheManager<string>(config);
// or
var cache2 = CacheFactory.FromConfiguration<string>(config);
}
private static void MostSimpleCacheManagerB()
{
var cache = new BaseCacheManager<string>(
new CacheManagerConfiguration()
.Builder
.WithSystemRuntimeCacheHandle()
.Build());
}
private static void MostSimpleCacheManagerC()
{
var cache = CacheFactory.Build<string>(
p => p.WithSystemRuntimeCacheHandle());
}
private static void MostSimpleCacheManagerWithLogging()
{
var config = new ConfigurationBuilder()
.WithMicrosoftLogging(l => l.AddConsole(LogLevel.Information))
.WithSystemRuntimeCacheHandle()
.Build();
var cache = new BaseCacheManager<string>(config);
// or
var cache2 = CacheFactory.FromConfiguration<string>(config);
}
private static void EditExistingConfiguration()
{
var config = new ConfigurationBuilder()
.WithSystemRuntimeCacheHandle()
.EnableStatistics()
.Build();
config = new ConfigurationBuilder(config)
.WithMicrosoftLogging(f => f.AddConsole())
.Build();
}
#endif
private static void LoggingSample()
{
var cache = CacheFactory.Build<string>(
c =>
c.WithMicrosoftLogging(log =>
{
log.AddConsole(LogLevel.Trace);
})
.WithDictionaryHandle()
.WithExpiration(ExpirationMode.Sliding, TimeSpan.FromSeconds(10)));
cache.AddOrUpdate("myKey", "someregion", "value", _ => "new value");
cache.AddOrUpdate("myKey", "someregion", "value", _ => "new value");
cache.Expire("myKey", "someregion", TimeSpan.FromMinutes(10));
var val = cache.Get("myKey", "someregion");
}
#if !NETCOREAPP
private static void AppConfigLoadInstalledCacheCfg()
{
var cache = CacheFactory.FromConfiguration<object>("myCache");
cache.Add("key", "value");
}
#endif
private static void EventsExample()
{
var cache = CacheFactory.Build<string>(s => s.WithDictionaryHandle());
cache.OnAdd += (sender, args) => Console.WriteLine("Added " + args.Key);
cache.OnGet += (sender, args) => Console.WriteLine("Got " + args.Key);
cache.OnRemove += (sender, args) => Console.WriteLine("Removed " + args.Key);
cache.Add("key", "value");
var val = cache.Get("key");
cache.Remove("key");
}
#if !NETCOREAPP
private static void RedisSample()
{
var cache = CacheFactory.Build<int>(settings =>
{
settings
.WithSystemRuntimeCacheHandle()
.And
.WithRedisConfiguration("redis", config =>
{
config.WithAllowAdmin()
.WithDatabase(0)
.WithEndpoint("localhost", 6379);
})
.WithMaxRetries(1000)
.WithRetryTimeout(100)
.WithRedisBackplane("redis")
.WithRedisCacheHandle("redis", true);
});
cache.Add("test", 123456);
cache.Update("test", p => p + 1);
var result = cache.Get("test");
}
#endif
private static void SimpleCustomBuildConfigurationUsingConfigBuilder()
{
// this is using the CacheManager.Core.Configuration.ConfigurationBuilder to build a
// custom config you can do the same with the CacheFactory
var cfg = ConfigurationBuilder.BuildConfiguration(settings =>
{
settings.WithUpdateMode(CacheUpdateMode.Up)
.WithDictionaryHandle()
.EnablePerformanceCounters()
.WithExpiration(ExpirationMode.Sliding, TimeSpan.FromSeconds(10));
});
var cache = CacheFactory.FromConfiguration<string>(cfg);
cache.Add("key", "value");
// reusing the configuration and using the same cache for different types:
var numbers = CacheFactory.FromConfiguration<int>(cfg);
numbers.Add("intKey", 2323);
numbers.Update("intKey", v => v + 1);
}
private static void SimpleCustomBuildConfigurationUsingFactory()
{
var cache = CacheFactory.Build(settings =>
{
settings
.WithUpdateMode(CacheUpdateMode.Up)
.WithDictionaryHandle()
.EnablePerformanceCounters()
.WithExpiration(ExpirationMode.Sliding, TimeSpan.FromSeconds(10));
});
cache.Add("key", "value");
}
private static void UnityInjectionExample()
{
var container = new UnityContainer();
container.RegisterType<ICacheManager<object>>(
new ContainerControlledLifetimeManager(),
new InjectionFactory((c) => CacheFactory.Build(s => s.WithDictionaryHandle())));
container.RegisterType<UnityInjectionExampleTarget>();
// resolving the test target object should also resolve the cache instance
var target = container.Resolve<UnityInjectionExampleTarget>();
target.PutSomethingIntoTheCache();
// our cache manager instance should still be there so should the object we added in the
// previous step.
var checkTarget = container.Resolve<UnityInjectionExampleTarget>();
checkTarget.GetSomething();
}
private static void UnityInjectionExample_Advanced()
{
var container = new UnityContainer();
container.RegisterType(
typeof(ICacheManager<>),
new ContainerControlledLifetimeManager(),
new InjectionFactory(
(c, t, n) => CacheFactory.FromConfiguration(
t.GetGenericArguments()[0],
ConfigurationBuilder.BuildConfiguration(cfg => cfg.WithDictionaryHandle()))));
var stringCache = container.Resolve<ICacheManager<string>>();
// testing if we create a singleton instance per type, every Resolve of the same type should return the same instance!
var stringCacheB = container.Resolve<ICacheManager<string>>();
stringCache.Put("key", "something");
var intCache = container.Resolve<ICacheManager<int>>();
var intCacheB = container.Resolve<ICacheManager<int>>();
intCache.Put("key", 22);
var boolCache = container.Resolve<ICacheManager<bool>>();
var boolCacheB = container.Resolve<ICacheManager<bool>>();
boolCache.Put("key", false);
Console.WriteLine("Value type is: " + stringCache.GetType().GetGenericArguments()[0].Name + " test value: " + stringCacheB["key"]);
Console.WriteLine("Value type is: " + intCache.GetType().GetGenericArguments()[0].Name + " test value: " + intCacheB["key"]);
Console.WriteLine("Value type is: " + boolCache.GetType().GetGenericArguments()[0].Name + " test value: " + boolCacheB["key"]);
}
private static void UpdateTest()
{
var cache = CacheFactory.Build<string>(s => s.WithDictionaryHandle());
Console.WriteLine("Testing update...");
if (!cache.TryUpdate("test", v => "item has not yet been added", out string newValue))
{
Console.WriteLine("Value not added?: {0}", newValue == null);
}
cache.Add("test", "start");
Console.WriteLine("Initial value: {0}", cache["test"]);
cache.AddOrUpdate("test", "adding again?", v => "updating and not adding");
Console.WriteLine("After AddOrUpdate: {0}", cache["test"]);
cache.Remove("test");
try
{
var removeValue = cache.Update("test", v => "updated?");
}
catch
{
Console.WriteLine("Error as expected because item didn't exist.");
}
// use try update to not deal with exceptions
if (!cache.TryUpdate("test", v => v, out string removedValue))
{
Console.WriteLine("Value after remove is null?: {0}", removedValue == null);
}
}
private static void UpdateCounterTest()
{
var cache = CacheFactory.Build<long>(s => s.WithDictionaryHandle());
Console.WriteLine("Testing update counter...");
cache.AddOrUpdate("counter", 0, v => v + 1);
Console.WriteLine("Initial value: {0}", cache.Get("counter"));
for (var i = 0; i < 12345; i++)
{
cache.Update("counter", v => v + 1);
}
Console.WriteLine("Final value: {0}", cache.Get("counter"));
}
private static void MultiCacheEvictionWithoutRedisCacheHandle()
{
var config = new ConfigurationBuilder("Redis with Redis Backplane")
.WithDictionaryHandle(true)
.WithExpiration(ExpirationMode.Absolute, TimeSpan.FromSeconds(5))
.And
.WithRedisBackplane("redisConfig")
.WithRedisConfiguration("redisConfig", "localhost,allowadmin=true", enableKeyspaceNotifications: true)
//.WithMicrosoftLogging(new LoggerFactory().AddConsole(LogLevel.Debug))
.Build();
var cacheA = new BaseCacheManager<string>(config);
var cacheB = new BaseCacheManager<string>(config);
var key = "someKey";
cacheA.OnRemove += (s, args) =>
{
Console.WriteLine("A triggered remove: " + args.ToString() + " - key still exists? " + cacheA.Exists(key));
};
cacheB.OnRemove += (s, args) =>
{
Console.WriteLine("B triggered remove: " + args.ToString() + " - key still exists? " + cacheB.Exists(key));
};
cacheA.OnRemoveByHandle += (s, args) =>
{
cacheA.Remove(args.Key);
Console.WriteLine("A triggered removeByHandle: " + args.ToString() + " - key still exists? " + cacheA.Exists(key));
};
cacheB.OnRemoveByHandle += (s, args) =>
{
Console.WriteLine("B triggered removeByHandle: " + args.ToString() + " - key still exists? " + cacheA.Exists(key) + " in A? " + cacheA.Exists(key));
};
cacheA.OnAdd += (s, args) =>
{
Console.WriteLine("A triggered add: " + args.ToString());
};
cacheB.OnAdd += (s, args) =>
{
Console.WriteLine("B triggered add: " + args.ToString());
};
Console.WriteLine("Add to A: " + cacheA.Add(key, "some value"));
Console.WriteLine("Add to B: " + cacheB.Add(key, "some value"));
Thread.Sleep(2000);
cacheA.Remove(key);
}
}
public class UnityInjectionExampleTarget
{
private ICacheManager<object> _cache;
public UnityInjectionExampleTarget(ICacheManager<object> cache)
{
_cache = cache ?? throw new ArgumentNullException(nameof(cache));
}
public void GetSomething()
{
var value = _cache.Get("myKey");
var x = value;
if (value == null)
{
throw new InvalidOperationException();
}
}
public void PutSomethingIntoTheCache()
{
_cache.Put("myKey", "something");
}
}
}