1.导入依赖
com.github.ben-manes.caffeine caffeine2.9.2
2.配置caffeine缓存
@Component
public class AuthBefeorCache {
@Autowired
private UserMapper userMapper;
//缓存最大数量
private final Integer MAX_SIZE = 300000;
//缓存有效期值30
private final Long DURATION = 30L;
//定义及配置Caffeine本地缓存
private LoadingCache cache = Caffeine.newBuilder()
//配置淘汰最大条数策略
.maximumSize(MAX_SIZE)
//配置有效期单位(TimeUnit.DAYS天)
.expireAfterWrite(DURATION, TimeUnit.DAYS)
//加载缓存,当在本地缓存中找不到的时候,通过load方法将数据加载到缓存中,并返回给需 要的地方
.build(new CacheLoader() {
@Override
public User load(@NonNull String userId) throws Exception {
HashMap
3.使用Caffeine
@Slf4j
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserCache userCache;
@Autowired
private UserMapper userMapper;
//从本地缓存获取数据
public User getUserById(String userId){
User user = userCache.getData(userId);
if (user == null) {
//1. 如果没有,再尝试查询本地缓存
synchronized (this.getClass()) {
user = userCache.getData(userId);
if (user == null) {
User user=authAfterCache.getData(vin);
return user;
}else {
log.info("再尝试查询本地缓存");
return user;
}
}
} else {
//2. 如果本地缓存有数据则直接返回
return user;
}
}
//从数据库获取数据再插入本地缓存
public User putUser(String userId){
User user=userMapper.selectUserById(userId);
userCache.getData(user);
return user;
}
}



