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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
| package cn.idea360.multiple.cache;
import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.cache.RemovalListener; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import java.util.concurrent.*;
@Slf4j public class MultipleCacheImpl implements MultipleCache {
private final ConcurrentMap<String, String> readOnlyCacheMap = new ConcurrentHashMap<>();
private final LoadingCache<String, String> readWriteCacheMap;
private CacheConfig cacheConfig;
private DataRepository dataRepository;
public MultipleCacheImpl() { this(1000, 180, 1000L * 30); }
public MultipleCacheImpl(CacheConfig cacheConfig) { this(cacheConfig.getInitialCapacityOfCache(), cacheConfig.getCacheAutoExpirationInSeconds(), cacheConfig.getCacheUpdateIntervalMs()); this.cacheConfig = cacheConfig; }
private MultipleCacheImpl(int initialCapacityOfCache, long cacheAutoExpirationInSeconds, long cacheUpdateIntervalMs) { this.readWriteCacheMap = CacheBuilder.newBuilder().initialCapacity(initialCapacityOfCache) .expireAfterWrite(cacheAutoExpirationInSeconds, TimeUnit.SECONDS) .removalListener((RemovalListener<String, String>) notification -> { String key = notification.getKey(); String value = notification.getValue(); log.debug("cache for key [{}] has been remove, value [{}]", key, value); }) .build(new CacheLoader<>() {
@Override public String load(String key) throws Exception { String value = generatePayload(key); log.debug("load data from db for key [{}], value [{}]", key, value); return value; } });
ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1, new BasicThreadFactory.Builder().namingPattern("multiple-cachefill-schedule-pool-%d").daemon(true).build());
executorService.scheduleAtFixedRate(() -> { for (String key : readOnlyCacheMap.keySet()) { try { String cacheValue = readWriteCacheMap.get(key); String currentCacheValue = readOnlyCacheMap.get(key); if (!cacheValue.equals(currentCacheValue)) { log.debug("readOnlyCache sync cache from readWriteCache for key [{}]", key); readOnlyCacheMap.put(key, cacheValue); } else { log.debug("cacheValue: [{}], currentCacheValue: [{}]", cacheValue, currentCacheValue); } } catch (Throwable th) { log.error("Error while updating the readOnlyCache from readWriteCache for key {}", key, th); } } },2, cacheUpdateIntervalMs, TimeUnit.MILLISECONDS); }
private String generatePayload(String key) { return dataRepository.load(key); }
@Override public String get(String key) { return getValue(key, true); }
private String getValue(final String key, boolean useReadOnlyCache) { String payload = null; try { if (useReadOnlyCache) { final String currentPayload = readOnlyCacheMap.get(key); if (currentPayload != null) { payload = currentPayload; log.debug("load data from readOnlyCache for key [{}], value [{}]", key, payload); } else { payload = readWriteCacheMap.get(key); readOnlyCacheMap.put(key, payload); log.debug("load data from readWriteCache for key [{}], value [{}]", key, payload); } } else { payload = readWriteCacheMap.get(key); } } catch (Throwable t) { log.error("Cannot get value for key : {}", key, t); } return payload; }
@Override public void invalidate(String... keys) { for (String key : keys) { readWriteCacheMap.invalidate(key); } }
@Override public void setDataRepository(DataRepository dataRepository) { this.dataRepository = dataRepository; } }
|