因此,当请求进入并且我将数据保存到缓存时,将调用此方法。请求可以是并发的。 但是,在说了10个请求之后,我希望缓存大小为10,但是第10个请求数据的大小为1。
我在这里缺少一些简单的东西,但无法弄清楚。
@Service
@Slf4j
public class RequestCacheService {
private ReadWriteLock lock;
RequestCacheService() {
lock = new ReentrantReadWriteLock();
}
public void saveToCache(RequestDto requestDto) {
log.info("Saving request");
try {
lock.writeLock().lock();
cache.build();
cache.getRequiredCache()
.put(requestDto.getTimestamp().getEpochSecond(), requestDto.getData());
log.info("Size of cache: " + cache.getRequiredCache().size());
} finally {
lock.writeLock().unlock();
}
}
这是CacheService:
public class CacheService {
private static LoadingCache<Long, String> REQUIRED_CACHE;
public static LoadingCache<Long, String> getRequiredCache() {
return REQUIRED_CACHE;
}
public static void build() {
REQUIRED_CACHE = CacheBuilder.newBuilder()
.expireAfterWrite(30, TimeUnit.SECONDS)
.build(new CacheLoader<Long, String>() {
@Override
public String load(Long s) throws Exception {
return null;
}
});
}
}