/
DelayedDeleteCacheStrategy.java
36 lines (31 loc) · 1.28 KB
/
DelayedDeleteCacheStrategy.java
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
package com.zshnb.interviewpractice.cache_consistency;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
@Component
public class DelayedDeleteCacheStrategy implements CacheConsistencyStrategy {
private final EntityRepository entityRepository;
private final RedisTemplate<String, Integer> redisTemplate;
public DelayedDeleteCacheStrategy(EntityRepository entityRepository, RedisTemplate<String, Integer> redisTemplate) {
this.entityRepository = entityRepository;
this.redisTemplate = redisTemplate;
}
@Override
public void write() throws InterruptedException {
entityRepository.saveAndFlush(new Entity(Thread.currentThread().getName()));
redisTemplate.delete(key);
Thread.sleep(200);
redisTemplate.delete(key);
}
@Override
public int read() {
ValueOperations<String, Integer> valueOperations = redisTemplate.opsForValue();
Integer countInCache = valueOperations.get(key);
if (countInCache == null) {
int countInDB = (int) entityRepository.count();
valueOperations.set(key, countInDB);
return countInDB;
}
return countInCache;
}
}