integrated_traffic/src/main/java/com/zcloud/util/CaffeineUtil.java

89 lines
3.1 KiB
Java
Raw Normal View History

2024-03-06 16:25:53 +08:00
package com.zcloud.util;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.zcloud.mapper.dsno3.eduSystem.EduDictionariesMapper;
import com.zcloud.entity.PageData;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
/**
*
* wangxuan
* www.zcloudchina.com
*/
@Component
public class CaffeineUtil {
private static final Logger logger = Logger.getLogger(CaffeineUtil.class.getName());
@Resource
private EduDictionariesMapper eduDictionariesMapper;
@Bean(name = "caffeineCache")
public Cache<String, Object> caffeineCache() {
Cache<String, Object> build = Caffeine.newBuilder()
//8小时没有读写自动删除
.expireAfterAccess(8, TimeUnit.HOURS)
// 当垃圾收集器需要释放内存时驱逐
.softValues()
//最大容量1个超过会自动清理空间
.maximumSize(1)
.removalListener(((key, value, cause) -> {
//清理通知 key,value ==> 键值对 cause ==> 清理原因
System.out.printf("Key %s was removed (%s)%n", key, cause);
})).build();
// 加载一次
build.get("xzqh", x -> {
List<PageData> all = eduDictionariesMapper.getAll();
Map fileSort = AdministrativeUntil.getFileSort(all);
return fileSort;
});
return build;
}
/**
* @Description: token
* @Author: dearLin
* @Date: 2023/6/12/012 9:27
* @Param: [] []
* @Return: com.github.benmanes.caffeine.cache.Cache<java.lang.String, java.lang.Object>
*/
@Bean(name = "loginToken")
public Cache<String, String> loginToken() {
Cache<String, String> loginToken = Caffeine.newBuilder()
// 30分钟
.expireAfterAccess(30, TimeUnit.MINUTES)
// 当垃圾收集器需要释放内存时驱逐
.softValues()
.removalListener(((key, value, cause) -> {
//清理通知 key,value ==> 键值对 cause ==> 清理原因
System.out.printf("Key %s was removed (%s)%n", key, cause);
})).build();
return loginToken;
}
/**
* @Description:
* @Author: dearLin
* @Date: 2023/6/12/012 9:25
* @Param: [com.github.benmanes.caffeine.cache.Cache<java.lang.String, java.lang.Object>] [build]
* @Return: void
*/
@Async
public void loadOnce(Cache<String, Object> build) {
// 加载一次
build.get("xzqh", x -> {
List<PageData> all = eduDictionariesMapper.getAll();
Map fileSort = AdministrativeUntil.getFileSort(all);
return fileSort;
});
}
}