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

相关推荐
源码_空间9 小时前
基于Springboot在线考试系统(源码+文档)
java·spring boot·后端
AI开源软件10 小时前
用MQTT跑通一台模拟设备:看懂IoT产品、物模型和告警
java·vue.js·spring boot·物联网·mqtt·iot·企业管理
不甘平凡的小鸟12 小时前
vs code 打开spring boot项目
java·spring boot·后端
CoderYanger15 小时前
Java EE 进阶:16. Spring原理(第二弹)
java·服务器·spring boot·后端·spring·面试·java-ee
YuePeng+17 小时前
一个注解,生成一个完整管理后台:erupt 上手实录
java·spring boot·低代码·开源
nice_lcj52019 小时前
在 Spring Boot 里学会使用 RabbitMQ:从入门到实战
java·spring boot·spring·rabbitmq·java-rabbitmq
千寻技术帮19 小时前
基于微信小程序的装修管理系统(源码+脚本+文档)50032
数据库·spring boot·微信小程序·毕业设计·装修管理
nice_lcj52020 小时前
Jakarta Validation:从注解到自定义约束的完整实践
java·开发语言·spring boot
Resean022320 小时前
SpringBoot 源码分析(二)自动装配原理
java·spring boot·后端·spring
沐知全栈开发21 小时前
基于SpringBoot的费用报销审批管理系统-毕业设计
spring boot·后端·课程设计