|
|
@@ -0,0 +1,63 @@
|
|
|
+package nju.seec.helper.util.cache;
|
|
|
+
|
|
|
+import com.github.benmanes.caffeine.cache.Cache;
|
|
|
+import com.github.benmanes.caffeine.cache.Caffeine;
|
|
|
+import org.springframework.beans.factory.annotation.Value;
|
|
|
+import org.springframework.stereotype.Component;
|
|
|
+
|
|
|
+import java.util.Collection;
|
|
|
+import java.util.Map;
|
|
|
+import java.util.concurrent.TimeUnit;
|
|
|
+import java.util.stream.Collectors;
|
|
|
+
|
|
|
+/**
|
|
|
+ * @author xst
|
|
|
+ * <p>
|
|
|
+ * updated by cst
|
|
|
+ */
|
|
|
+@Component
|
|
|
+public class CaffeineCacheUtils {
|
|
|
+ private final Cache<String, Object> cache;
|
|
|
+
|
|
|
+ public CaffeineCacheUtils(@Value("${guavaCache.maximumSize}") Long maximumSize,
|
|
|
+ @Value("${guavaCache.expireAfterAccessInSeconds}") Long expireAfterAccessInSeconds,
|
|
|
+ @Value("${guavaCache.expireAfterWriteInSeconds}") Long expireAfterWriteInSeconds) {
|
|
|
+ cache = Caffeine
|
|
|
+ .newBuilder()
|
|
|
+ .maximumSize(maximumSize)
|
|
|
+ .expireAfterAccess(expireAfterAccessInSeconds, TimeUnit.SECONDS)
|
|
|
+ .expireAfterWrite(expireAfterWriteInSeconds, TimeUnit.SECONDS)
|
|
|
+ .build();
|
|
|
+ }
|
|
|
+
|
|
|
+ public void set(String cacheName, String key, Object value) {
|
|
|
+ cache.put(combineKey(cacheName, key), value);
|
|
|
+ }
|
|
|
+
|
|
|
+ public void setAll(String cacheName, Map<String, Object> putAll) {
|
|
|
+ final Map<String, Object> all = putAll.entrySet().stream().collect(Collectors.toMap(entry -> combineKey(cacheName, entry.getKey()), Map.Entry::getValue));
|
|
|
+ cache.putAll(all);
|
|
|
+ }
|
|
|
+
|
|
|
+ public Object get(String cacheName, String key) {
|
|
|
+ cache.get(key, k -> k);
|
|
|
+ return cache.getIfPresent(combineKey(cacheName, key));
|
|
|
+ }
|
|
|
+
|
|
|
+ public Map<String, Object> multiGet(String cacheName, Collection<String> keys) {
|
|
|
+ Collection<String> body = keys.stream().map(s -> combineKey(cacheName, s)).collect(Collectors.toList());
|
|
|
+ return cache.getAllPresent(body);
|
|
|
+ }
|
|
|
+
|
|
|
+ public void invalidate(String cacheName, String key) {
|
|
|
+ cache.invalidate(combineKey(cacheName, key));
|
|
|
+ }
|
|
|
+
|
|
|
+ public void invalidateAll() {
|
|
|
+ cache.invalidateAll();
|
|
|
+ }
|
|
|
+
|
|
|
+ private String combineKey(String cacheName, String key) {
|
|
|
+ return cacheName + ":" + key;
|
|
|
+ }
|
|
|
+}
|