1
|
|
|
package io.mcarle.sciurus.cache.redis; |
|
|
|
|
2
|
|
|
|
3
|
|
|
import io.lettuce.core.RedisClient; |
4
|
|
|
import io.lettuce.core.SetArgs; |
5
|
|
|
import io.lettuce.core.api.StatefulRedisConnection; |
6
|
|
|
import io.lettuce.core.api.sync.RedisCommands; |
7
|
|
|
import io.mcarle.sciurus.ExecutionIdentifier; |
8
|
|
|
import io.mcarle.sciurus.cache.CustomCache; |
9
|
|
|
|
10
|
|
|
import java.io.Serializable; |
11
|
|
|
import java.time.Duration; |
12
|
|
|
|
13
|
|
|
public class RedisCache implements CustomCache { |
|
|
|
|
14
|
|
|
|
15
|
|
|
private RedisClient redisClient; |
|
|
|
|
16
|
|
|
private StatefulRedisConnection<String, RedisData> connection; |
17
|
|
|
private RedisCommands<String, RedisData> syncCommands; |
18
|
|
|
|
19
|
1 |
|
public RedisCache(RedisClient redisClient) { |
|
|
|
|
20
|
1 |
|
this.redisClient = redisClient; |
|
|
|
|
21
|
1 |
|
this.connection = redisClient.connect(new RedisJsonCodec()); |
22
|
1 |
|
this.syncCommands = connection.sync(); |
23
|
1 |
|
} |
24
|
|
|
|
25
|
|
|
@Override |
26
|
|
|
public Object get(ExecutionIdentifier executionIdentifier) { |
|
|
|
|
27
|
1 |
|
RedisData redisData = syncCommands.get(getKey(executionIdentifier)); |
|
|
|
|
28
|
1 |
|
if (redisData == null) { |
|
|
|
|
29
|
1 |
|
return CustomCache.EMPTY; |
|
|
|
|
30
|
|
|
} else { |
|
|
|
|
31
|
1 |
|
return redisData.getCachedValue(); |
|
|
|
|
32
|
|
|
} |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
@Override |
36
|
|
|
public void put(ExecutionIdentifier executionIdentifier, Serializable result, Duration duration) { |
|
|
|
|
37
|
1 |
|
syncCommands.set(getKey(executionIdentifier), new RedisData(result), SetArgs.Builder.px(duration.toMillis())); |
|
|
|
|
38
|
1 |
|
} |
39
|
|
|
|
40
|
|
|
@Override |
41
|
|
|
public void postDeregister() { |
|
|
|
|
42
|
1 |
|
connection.close(); |
|
|
|
|
43
|
1 |
|
redisClient.shutdown(); |
44
|
1 |
|
} |
45
|
|
|
|
46
|
|
|
private String getKey(ExecutionIdentifier executionIdentifier) { |
|
|
|
|
47
|
1 |
|
return executionIdentifier.toString() + executionIdentifier.hashCode(); |
|
|
|
|
48
|
|
|
} |
49
|
|
|
} |
50
|
|
|
|