-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathRedisOutputCache.cs
71 lines (58 loc) · 2.29 KB
/
RedisOutputCache.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
using System;
using System.Collections.Generic;
using System.Linq;
using Jil;
using StackExchange.Redis;
using WebApi.OutputCache.Core.Cache;
namespace WebAPI.OutputCache.Redis
{
public class RedisOutputCache : IApiOutputCache
{
private readonly IJsonSerializer _jsonSerializer;
private readonly IRedisConnectionSettings _connectionSettings;
private readonly Lazy<IConnectionMultiplexer> _multiplexer;
readonly Options _options;
public RedisOutputCache(IJsonSerializer jsonSerializer, IRedisConnectionSettings connectionSettings)
{
_jsonSerializer = jsonSerializer;
_connectionSettings = connectionSettings;
_multiplexer = new Lazy<IConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(_connectionSettings.ConnectionString));
_options = null;//TODO:
}
private IDatabase Db => _multiplexer.Value.GetDatabase(_connectionSettings.Db);
public void RemoveStartsWith(string key)
{
//AutoInvalidateCacheOutputAttribute and InvalidateCacheOutputAttribute uses this method.
//TODO: delete by pattern
//EVAL "return redis.call('del', unpack(redis.call('keys', ARGV[1])))" 0 prefix:*
//CAUTION : while deleting keys please use scan
Db.KeyDelete(key);
}
public T Get<T>(string key) where T : class
{
string redisValue = Db.StringGet(key);
if (!string.IsNullOrEmpty(redisValue))
return _jsonSerializer.DeserializeObject<T>(redisValue, _options);
return null;
}
public object Get(string key)
{
return Db.StringGet(key);
}
public void Remove(string key)
{
Db.KeyDelete(key);
}
public bool Contains(string key)
{
return Db.KeyExists(key);
}
public void Add(string key, object o, DateTimeOffset expiration, string dependsOnKey = null)
{
TimeSpan timeSpan = expiration.DateTime.Subtract(DateTime.Now);
Db.StringSet(key, _jsonSerializer.SerializeObject(o, _options), timeSpan);
}
//TODO: use SCAN to get keys
public IEnumerable<string> AllKeys => Enumerable.Empty<string>();
}
}