package com.ycl.jxkg.utils;
|
|
import com.github.benmanes.caffeine.cache.Cache;
|
import lombok.RequiredArgsConstructor;
|
import lombok.extern.slf4j.Slf4j;
|
import org.springframework.stereotype.Component;
|
|
import java.util.HashMap;
|
import java.util.Map;
|
import java.util.Objects;
|
|
/**
|
* caffeine 保存、获取工具
|
*
|
* @author:xp
|
* @date:2024/7/10 11:50
|
*/
|
@Slf4j
|
@Component
|
@RequiredArgsConstructor
|
public class CaffeineUtil {
|
|
private final Cache<String, Object> caffeineCache;
|
|
/**
|
* 保存
|
*
|
* @param database 数据库/ caffeine map的key
|
* @param key map的key
|
* @param value map的value
|
*/
|
public void put(String database, String key, Object value) {
|
Map<String, Object> map = (Map<String, Object>) caffeineCache.getIfPresent(database);
|
if (Objects.isNull(map)) {
|
log.error("缓存异常");
|
map = new HashMap<>(128);
|
this.createDatabase(database, map);
|
return;
|
}
|
map.put(key, value);
|
}
|
|
/**
|
* 获取
|
*
|
* @param database 数据库/ caffeine map的key
|
* @param key map的key
|
*/
|
public Object get(String database, String key) {
|
Map<String, Object> map = (Map<String, Object>) caffeineCache.getIfPresent(database);
|
if (Objects.isNull(map)) {
|
log.error("缓存异常");
|
return null;
|
}
|
return map.get(key);
|
}
|
|
/**
|
* 创建key
|
*
|
* @param database
|
* @param map
|
*/
|
private void createDatabase(String database, Map<String, Object> map) {
|
caffeineCache.put(database, map);
|
}
|
|
}
|