Scenario:
Create a Sign on service to allow creation of users in our app. The web App calls this service to get all users. Cache the data into memcached and serve the next request from cache till it expires.
Solution:
You need the Memcached server and then you need to get the .NET client API (like easyCaching).
- Install:
- Download from http://memcached.org/
- command prompt -> C:\..\memcached -d install
- It is avialble on "127.0.0.1" and port "11211".
- Install Nuget package - EasyCaching.Memcached
- Add ICache.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
| namespace Web.Services
{
public interface ICache<TValue>
{
bool TrySet(string key, TValue value);
bool TryGet(string key, out TValue value);
void Remove(string key);
void RemoveAll();
}
}
|
- Add ICacheService.cs
1
2
3
4
5
6
7
| namespace Web.Services
{
public interface ICacheService
{
ICache<TValue> GetCache<TValue>(string name);
}
}
|
- Add MemCacheService.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
| using EasyCaching.Core;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Primitives;
using System;
using System.Collections.Generic;
using System.Threading;
namespace Web.Services
{
//InMemory cache
public class MemCacheService : ICacheService
{
private static IEasyCachingProvider _easyCache;
private static readonly Dictionary<string, object> _repo;
private readonly ReaderWriterLockSlim Lock = new ReaderWriterLockSlim();
public MemCacheService(IEasyCachingProvider easyCache)
{
_easyCache = easyCache;
}
static MemCacheService()
{
//create cache repo
_repo = new Dictionary<string, object>();
}
public ICache<TValue> GetCache<TValue>(string name)
{
object cache = null;
Lock.EnterUpgradeableReadLock();
try
{
Lock.EnterWriteLock();
if (!_repo.TryGetValue(name, out cache))
{
cache = new MemCache<TValue>(_easyCache);
_repo[name] = cache;
}
}
finally
{
Lock.ExitWriteLock();
Lock.ExitUpgradeableReadLock();
}
return (ICache<TValue>)cache;
}
}
public class MemCache<TValue> : ICache<TValue>
{
private static IEasyCachingProvider _cache;
private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
static MemCache()
{
}
public MemCache(IEasyCachingProvider cache)
{
_cache = cache;
}
public void Remove(string key)
{
_lock.EnterWriteLock();
try
{
_cache.Remove(key);
}
finally
{
_lock.ExitWriteLock();
}
}
public bool TryGet(string key, out TValue value)
{
_lock.EnterUpgradeableReadLock();
try
{
value = _cache.Get<TValue>(key).Value;
if (value != null)
{
return true;
}
}
catch (Exception)
{
value = default(TValue);
}
finally
{
_lock.ExitUpgradeableReadLock();
}
return false;
}
public bool TrySet(string key, TValue value)
{
_lock.EnterWriteLock();
var result = _cache.Get<TValue>(key).Value;
if (result == null)
{
try
{
_cache.Set<TValue>(key, value, TimeSpan.FromSeconds(10));
return true;
}
catch (Exception e)
{
return false;
}
finally
{
_lock.ExitWriteLock();
}
}
return true;
}
public void RemoveAll()
{
_lock.EnterWriteLock();
try
{
_cache.Flush();
}
catch (Exception)
{
}
finally
{
_lock.ExitWriteLock();
}
}
}
}
|
|
|
- In Startup.cs
1
2
3
4
5
6
| public void ConfigureServices(IServiceCollection services)
services.AddSingleton<ICacheService, MemCacheService>();
services.AddSingleton<ICache<object>, MemCache<object>>();
services.AddEasyCaching(option => option.UseMemcached(config => config.DBConfig.AddServer("127.0.0.1", 11211)));
}
|
- Add HomeController.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
| public class HomeController : Controller
{
private ILogger _logger;
private readonly ICache<List<string>> _userCache;
public HomeController(ILoggerFactory loggerFactory, SignOn.SignOnClient signOnClient, ICacheService cacheService, IMemoryCache memoryCache)
{
_logger = loggerFactory.CreateLogger<InMemoryCacheService>();
_userCache = cacheService.GetCache<List<string>>("cache_users");
_cache = memoryCache;
}
private async Task<Tuple<bool, List<string>>> GetUsers()
{
var userlist = new List<string>();
string name = string.Empty;
var cachekey = CacheKeys.Users;
_usersLock.EnterReadLock();
try
{
if (_userCache.TryGet(cachekey, out userlist))
{
return new Tuple<bool, List<string>>(true, userlist);
}
if (_userCache.TryGet(CacheKeys.CallbackMessage, out var message))
{
_logger.LogDebug(message.First());
}
}
finally
{
_usersLock.ExitReadLock();
}
try
{
_usersLock.EnterWriteLock();
using (var call = _signOnClient.GetAllUsers(new UserRequest()))
{
userlist = new List<string>();
while (await call.ResponseStream.MoveNext())
{
var user = call.ResponseStream.Current;
userlist.Add(user.Name);
}
}
if (_userCache.TrySet(cachekey,userlist))
{
return new Tuple<bool, List<string>>(true, userlist);
}
return new Tuple<bool, List<string>>(false, null);
}
catch (Exception)
{
return new Tuple<bool, List<string>>(false, null);
}
finally
{
_usersLock.ExitWriteLock();
}
}
try
{
if (!all)
{
_userCache.Remove(CacheKeys.Users);
}
else
{
_userCache.RemoveAll();
}
}
catch (Exception e)
{
throw e;
}
return View();
}
}
|
Notes
- For Atomic operations Memcache d provides functions "getidentifiable()" which is called before you update cache and gets the current state and before updating it calls "putIfUntoched()", so if the 2 concurrent requests comes and the 2 nd one has already updated the value before the first the putIfUntoched() would not update the cache.
- Difference between L1 and L2 cache
- L1 is first and then L2 in the hierarchy.
- L1 in-built in chip [SRAM], L2 is soldered to motherboard close to the chip [DRAM].L1 need refreshing, L2 does not.
- Memory capacity: L1 < L2.
- Access speed: L1 > L2.
- L2 accessed only if requested data not in L1.
No comments:
Post a Comment