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

相关推荐
阿维的博客日记7 分钟前
‘version‘ must be a constant version but is ‘${revision}‘
java·spring boot·后端
zlpzlpzyd16 分钟前
spring boot 4.1发布
java·数据库·spring boot
我登哥MVP21 分钟前
SpringCloud 核心组件解析:服务网关
java·spring boot·后端·spring·spring cloud·java-ee·maven
北城以北88881 小时前
RocketMQ简介
java·spring boot·后端·rocketmq
梦@_@境12 小时前
面向 Spring Boot 的可观测业务流程编排引擎
java·spring boot·后端
仙俊红13 小时前
SpringBoot启动原理
java·spring boot·后端
記億揺晃着的那天15 小时前
告别误操作!Spring Boot 多环境配置隔离与启动守卫实战
java·spring boot·后端·环境隔离
skywalker_1115 小时前
SpringBoot速通(实战教学)
java·spring boot·redis·rpc·ssm·mybatis-plus
码不停蹄的玄黓16 小时前
Spring Boot 实现过滤器(Filter)三种常用方式
java·spring boot·后端
Flittly18 小时前
【AgentScope Java新手村系列】(4)结构化输出
java·spring boot·spring·ai