-
Notifications
You must be signed in to change notification settings - Fork 0
/
SqlCache.cs
47 lines (39 loc) · 1.43 KB
/
SqlCache.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
public class SqlCache : ICache, IDisposable
{
public const int DEFAULT_SLIDING_EXPIRATION_TIME_IN_SECONDS = 20 * 60;
private int SlidingCacheExpiryTimeInSeconds { get; }
private void SpinUpCache(string sqlConnection)
{
SqlServerCacheOptions sqlServerCacheOptions = new SqlServerCacheOptions();
sqlServerCacheOptions.ConnectionString = sqlConnection;
sqlServerCacheOptions.SchemaName = "dbo";
sqlServerCacheOptions.TableName = "TestCache";
sqlServerCacheOptions.DefaultSlidingExpiration = TimeSpan.FromSeconds(SlidingCacheExpiryTimeInSeconds);
_cache = new SqlServerCache(sqlServerCacheOptions);
}
private IDistributedCache _cache;
public SqlCache(string sqlConnection, int slidingExpiryTimeInSeconds)
{
if (_cache == null)
{
SlidingCacheExpiryTimeInSeconds = slidingExpiryTimeInSeconds;
SpinUpCache(sqlConnection);
}
}
public T Get<T>(string key)
{
return _cache.Get(key).FromByteArray<T>();
}
public void Put<T>(string key, T item)
{
this.Put<T>(key, item, SlidingCacheExpiryTimeInSeconds);
}
public void Put<T>(string key, T item, int expirationInSeconds)
{
_cache.Set(key, item.ToByteArray(), new DistributedCacheEntryOptions() { SlidingExpiration = TimeSpan.FromSeconds(expirationInSeconds) });
}
public void Dispose()
{
_cache = null;
}
}