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的优势在于支持分布式

相关推荐
闻哥1 小时前
23种设计模式深度解析:从原理到实战落地
java·jvm·spring boot·设计模式·面试
前路不黑暗@3 小时前
Java项目:Java脚手架项目的地图服务(十)
java·数据库·spring boot·笔记·学习·spring cloud·maven
前路不黑暗@6 小时前
Java项目:Java脚手架项目通用基类和常量类的封装(九)
java·spring boot·笔记·学习·spring cloud·maven·intellij-idea
前路不黑暗@9 小时前
Java项目:Java脚手架项目的地图的POJO
android·java·开发语言·spring boot·学习·spring cloud·maven
长路 ㅤ   9 小时前
02、Langchain4j tools原理与核心实践(含自定义http插件)
spring boot·langchain4j·ai工具调用·java ai开发
弹简特9 小时前
【JavaEE08-后端部分】SpringMVC03-SpringMVC第二大核心处理请求之Cookie/Session和获取header
java·spring boot·spring·java-ee
TimberWill21 小时前
SpringBoot整合Srping Security实现权限控制
java·spring boot·后端
文艺倾年1 天前
【源码精讲+简历包装】LeetcodeRunner—手搓调试器轮子(20W字-上)
java·jvm·人工智能·tomcat·编辑器·guava
q***76561 天前
工作中常用springboot启动后执行的方法
java·spring boot·后端