Spring Boot读取resources目录下文件(打成jar可用),并放入Guava缓存

1、文件所在位置:

2、需要Guava依赖:

xml 复制代码
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>23.0</version>
        </dependency>

3、启动时就读取放入缓存的代码:

java 复制代码
@Service
@AllArgsConstructor
@Slf4j
public class SensitiveCheckService {

    private static final Cache<String, String> SENSITIVE_WORDS_CACHE = CacheBuilder.newBuilder()
            // 设置缓存容量数
            .maximumSize(1)
            .build();

    static {
        try {
            ClassLoader classLoader = DemoApplication.class.getClassLoader();
            Enumeration<URL> resources = classLoader.getResources("static/sensitive/敏感词库.txt");
            List<String> allSensitiveList = new ArrayList<>();
            while (resources.hasMoreElements()) {
                URL resource = resources.nextElement();
                BufferedReader reader = new BufferedReader(new InputStreamReader(resource.openStream(), "utf-8"));
                String line;
                while ((line = reader.readLine()) != null) {
                    // 一行行读取
                    allSensitiveList.add(line);
                }
                SENSITIVE_WORDS_CACHE.put(RedisKeyConstant.ALL_SENSITIVE_WORDS, JSON.toJSONString(allSensitiveList));
            }
        } catch (Exception e) {
            log.error("加载敏感词失败", e);
        }
    }

    public List<String> getSensitiveWordsCache() {
        return JSON.parseArray(SENSITIVE_WORDS_CACHE.getIfPresent(RedisKeyConstant.ALL_SENSITIVE_WORDS), String.class);
    }

}

Guava的缓存类似于redis。比起Redis,Guava的缓存优势在于更轻更快,而Redis的优势在于支持分布式

相关推荐
paopaokaka_luck1 小时前
基于springboot3+vue3的智能文库平台(AI智能搜索、AI智能汇总、实时在线状态展示、多格式文档预览与富文本编辑、Echarts图形化分析)
前端·网络·spring boot·网络协议·echarts
热心市民lcj6 小时前
Spring Boot 整合 Caffeine 本地缓存实战
spring boot·后端·缓存
天丁o7 小时前
Spring Boot + MyBatis Plus 考勤日报统计报表:打卡记录聚合、异常分类和明细下钻 Demo
spring boot·mybatis plus·企业数字化·考勤系统·报表统计
智_永无止境7 小时前
Spring Boot 集成 OnlyOffice
java·spring boot·后端
Devin~Y8 小时前
从本地生活电商到 AI RAG:互联网大厂 Java 面试场景完整实战
java·spring boot·redis·elasticsearch·spring cloud·kafka·rag
米码收割机8 小时前
SA508-3钢回火焊道焊接温度场数值模拟(模拟图+论文)
spring boot·express·宠物
米码收割机10 小时前
【项目】spring boot+vue3 宠物领养系统(源码+文档)【独一无二】
java·spring boot·宠物
momo19 小时前
Java+WebAI黑马知识点
java·spring boot·mybatis
Circ.1 天前
IDEA 引入 nx JAR:原目录可用,复制后失效的原因与解决
pycharm·intellij-idea·jar
就改了1 天前
Mybatis快速入门大全(详细版)
java·spring boot·mybatis