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

相关推荐
i220818 Faiz Ul1 小时前
动漫商城|基于springboot + vue动漫商城系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·动漫商城系统
ybwycx3 小时前
SpringBoot下获取resources目录下文件的常用方法
java·spring boot·后端
zdl6864 小时前
springboot+全局异常处理
java·spring boot·spring
Full Stack Developme5 小时前
SpringBoot多线程池配置
spring boot·后端·firefox
计算机毕业论文辅导5 小时前
毕业设计避坑指南:工资信息管理系统的设计与实现(Java+SpringBoot实战)
java·spring boot·课程设计
sxhcwgcy6 小时前
SpringBoot 使用 spring.profiles.active 来区分不同环境配置
spring boot·后端·spring
清风絮柳7 小时前
65.少儿英语微信小程序
vue.js·spring boot·微信小程序·小程序·毕业设计
Java成神之路-7 小时前
MyBatis 开发模式演进:原生、Spring 与 Spring Boot 整合实战(MyBatis系列2)
spring boot·spring·mybatis
Yiyi_Coding8 小时前
SpringBoot4.X: 彻底消灭 NullPointerException
spring boot
她说..8 小时前
Java 基本数据类型高频面试题
java·开发语言·jvm·spring boot