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

相关推荐
n***44314 分钟前
SpringBoot Maven快速上手
spring boot·后端·maven
a***113520 分钟前
springcloud springboot nacos版本对应
spring boot·spring·spring cloud
聆风吟º25 分钟前
【Spring Boot 报错已解决】Error creating bean with entityManagerFactory 原因分析与解决方案
java·spring boot·后端
o***741726 分钟前
SpringBoot【十一】mybatis-plus实现多数据源配置,开箱即用!
spring boot·后端·mybatis
S***848827 分钟前
【spring boot】 IDEA 启动springboot项目报missing ServletWebServerFactory
spring boot·后端·intellij-idea
W***D45528 分钟前
SpringBoot + vue 管理系统
vue.js·spring boot·后端
r***934832 分钟前
【JavaEE】Spring Boot 项目创建
java·spring boot·java-ee
VX:Fegn089535 分钟前
计算机毕业设计|基于springboot + vue毕业设计选题管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·课程设计
h***673738 分钟前
springboot设置多环境配置文件
java·spring boot·后端
VX:Fegn089539 分钟前
计算机毕设|基springboot+Vue的校园打印系统设计与实现
java·前端·javascript·vue.js·spring boot·后端·课程设计