Guava 缓存
public interface CacheService {
//存
void setCache(String key, Object value);
//取
Object getCache(String key);
/**
* 删除该key关联的缓存
*/
void invalidate(Object key);
}
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;
/**
* @title
* @description
* @author LJHao
* @updateTime 2021/6/9 11:38
* @throws
*/
@Service
public class CacheServiceImpl implements CacheService {
private Cache<String, Object> commonCache = null;
//代理此bean时会首先执行该初始化方法
@PostConstruct
public void init() {
commonCache = CacheBuilder.newBuilder()
//设置并发数为5,即同一时间最多只能有5个线程往cache执行写入操作
.concurrencyLevel(5)
//设置缓存容器的初始化容量为10(可以存10个键值对)
.initialCapacity(10)
//最大缓存容量是500,超过500后会安装LRU策略-最近最少使用,
.maximumSize(500)
//设置写入缓存后2分钟后过期
.expireAfterWrite(120, TimeUnit.SECONDS).build();
}
@Override
public void setCache(String key, Object value) {
commonCache.put(key, value);
}
@Override
public Object getCache(String key) {
return commonCache.getIfPresent(key);
}
@Override
public void invalidate(Object key) {
commonCache.invalidate(key);
}
}
@Autowired
private CacheServiceImpl cacheService;
Object cacheDate = cacheService.getCache(merchantMenuKeys);
cacheService.setCache(merchantMenuKeys, JSON.toJSONString(availableMerchantList));
能力是有限的,努力是无限的。