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

相关推荐
2401_8955213439 分钟前
SpringBoot Maven快速上手
spring boot·后端·maven
yoyo_zzm39 分钟前
JAVA (Springboot) i18n国际化语言配置
java·spring boot·python
李白的粉1 小时前
基于springboot+vue的旅游民宿管理系统
java·spring boot·vue·毕业设计·课程设计·源代码·旅游民宿管理系统
ictI CABL1 小时前
Spring Boot与MyBatis
spring boot·后端·mybatis
花千树-0101 小时前
兼容 ThreadLocal 的用户上下文透传方案:WebFlux 项目改造实践
java·spring boot·servlet·jetty
s1mple“”4 小时前
大厂Java面试实录:从Spring Boot到AI技术的电商场景深度解析
spring boot·redis·微服务·kafka·向量数据库·java面试·ai技术
yhole6 小时前
springboot三层架构详细讲解
spring boot·后端·架构
golang学习记7 小时前
IDEA 2026.1全新调试新特性:Spring Boot调试不再靠猜!
java·spring boot·intellij-idea
橘子编程7 小时前
OpenClaw(小龙虾)完整知识汇总
java·前端·spring boot·spring·spring cloud·html5
大阿明7 小时前
SpringBoot - Cookie & Session 用户登录及登录状态保持功能实现
java·spring boot·后端