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

相关推荐
biyezuopinvip2 小时前
基于Spring Boot的企业网盘的设计与实现(任务书)
java·spring boot·后端·vue·ssm·任务书·企业网盘的设计与实现
JavaGuide2 小时前
一款悄然崛起的国产规则引擎,让业务编排效率提升 10 倍!
java·spring boot
figo10tf3 小时前
Spring Boot项目集成Redisson 原始依赖与 Spring Boot Starter 的流程
java·spring boot·后端
zhangyi_viva3 小时前
Spring Boot(七):Swagger 接口文档
java·spring boot·后端
橙露3 小时前
Spring Boot 核心原理:自动配置机制与自定义 Starter 开发
java·数据库·spring boot
程序员敲代码吗3 小时前
Spring Boot与Tomcat整合的内部机制与优化
spring boot·后端·tomcat
NuageL3 小时前
原始Json字符串转化为Java对象列表/把中文键名变成英文键名
java·spring boot·json
jzheng86104 小时前
Spring Boot(快速上手)
java·spring boot·后端
wgslucky4 小时前
SpringBoot解决Request和Response的内容多次读取的问题
java·spring boot·多次读取request数据
不倒翁玩偶5 小时前
IDEA导入新的SpringBoot项目没有启动按钮
java·spring boot·intellij-idea