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

相关推荐
paterWang3 小时前
基于SpringBoot+Vue的鞋类商品购物商城系统的设计与实现
vue.js·spring boot·后端
paterWang3 小时前
基于SpringBoot的商铺共享点评系统的设计与实现
spring boot·后端
ServBay4 小时前
彻底重绘Spring Boot性能版图,资源占用缩减80%
java·spring boot·后端
康小庄4 小时前
Java阻塞队列——用法及常用场景
java·开发语言·数据库·spring boot·spring·jetty
2301_780669866 小时前
MyBatis(配置,增删改查,注解与XML两种开发方式)、SpringBoot配置文件(yml简化properties)
xml·spring boot·mybatis·javaweb
四谎真好看7 小时前
SSM学习笔记(SpringBoot篇)
spring boot·笔记·学习·学习笔记·ssm
Coder_Boy_7 小时前
Java后端核心技术体系全解析(个人总结)
java·开发语言·spring boot·分布式·spring cloud·中间件
会跑的葫芦怪8 小时前
SaaS点餐平台难点详细解决方案
spring boot·sass