这儿建一个抽象类封装缓存, 以后如果换了其他的缓存只需要修改这儿就可以了.
package com.rapid.common.core.cache;
import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.LRUCache;
import cn.hutool.core.date.DateUnit;
import java.util.function.Supplier;
/**
* @Description: 缓存支持
* @Author zbh
* @Date 2023/6/20
*/
public abstract class LRUCacheAble {
protected final Integer capacity;
protected final Long milliseconds;
protected final LRUCache<String, Object> lruCache;
//todo 抽象类的构造函数只能在子类的构造函数中调用,可以根据构造函数传入的值来打到延迟初始化值的效果,有点等效于模版方法类.
public LRUCacheAble(int capacity,long milliseconds) {
this.capacity = capacity;
this.milliseconds = milliseconds;
this.lruCache = CacheUtil.newLRUCache(capacity);
}
public LRUCacheAble() {
this(10000, DateUnit.HOUR.getMillis());
}
protected <T> T getWithCache(String key, Supplier<T> supplierT){
if(lruCache.containsKey(key)){
return (T)lruCache.get(key);
}
else{
T rlt = supplierT.get();
lruCache.put(key,rlt, milliseconds);
return rlt;
}
}
}
然后在要使用到缓存的地方 继承这个抽象类,并在构造函数里面设置初始值, 上述有一个默认构造函数加入了默认值
package com.rapid.trade.goods.infrastructure.repositories.impl;
import com.rapid.common.core.cache.LRUCacheAble;
import com.rapid.trade.goods.domain.entities.categoryspec.Category;
import com.rapid.trade.goods.infrastructure.repositories.database.daos.CategoryDao;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Map;
@Repository
@RequiredArgsConstructor
public class CategoryRepository extends LRUCacheAble {
private final CategoryDao categoryDao;
//todo 如果要修改缓存参数,就手动创建构造函数.
// public CategoryRepository(CategoryDao categoryDao) {
// super(10000, DateUnit.HOUR.getMillis()*6);
// this.categoryDao = categoryDao;
// }
public Category row(int categoryId){
return categoryDao.getTbCategory().row(categoryId)
.process(x->x.set("isLeaf", _isLeaf(categoryId)))
.toClass(Category.class);
}
public Category rowCached(int categoryId){
return getWithCache("row_category_" + categoryId, ()->row(categoryId));
}
public List<Category> list(int parentId){
return categoryDao.getTbCategory().listRow(
Map.of("parentId",parentId),
mp->mp.process(x->x.set("isLeaf",_isLeaf(x.i("categoryId")))).toClass(Category.class)
);
}
public List<Category> listCached(int parentId){
System.out.println(super.milliseconds);
return getWithCache("list_category_" + parentId, ()->list(parentId));
}
private Boolean _isLeaf(Integer categoryId){
return categoryDao.getTbCategory().listRow(Map.of("parentId",categoryId)).isEmpty();
}
}
网友评论