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

相关推荐
vx+_bysj68696 分钟前
【免费领源码】基于springboot欣欣汽车租赁系统 计算机毕业设计项目推荐上万套实战教程JAVA,node.js,C++、python、大屏数据可视化
java·spring boot·mysql·汽车
常利兵23 分钟前
Spring Boot3 实战:WebSocket+STOMP+集群+Token认证,实现可靠服务器单向消息推送
服务器·spring boot·websocket
2401_8480097230 分钟前
RabbitMQ整合springboot
spring boot·rabbitmq·java-rabbitmq
huahailing102436 分钟前
Spring Boot 异步事务最佳实践:TransactionTemplate 实战指南
数据库·spring boot·后端
Detachym38 分钟前
InsightFlow:基于 Spring Boot+Redis+Docker 的实时监控告警系统全流程开发与部署
spring boot·redis·docker
二月夜42 分钟前
记SpringBoot升级Tomcat引发的两类典型问题及解决方案
spring boot·后端·tomcat
李白的粉1 小时前
基于springboot的来访管理系统
java·spring boot·毕业设计·课程设计·源代码·来访管理系统
天才梦浪1 小时前
wsl的网络导致springboot启动提示端口占用
网络·spring boot·后端
Chan161 小时前
LeetCode 热题 100 | 链表
java·数据结构·spring boot·算法·leetcode·链表·java-ee
常利兵1 小时前
Spring Boot 4.0 牵手RabbitMQ:注解魔法开启消息之旅
spring boot·rabbitmq·java-rabbitmq