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

相关推荐
i***395831 分钟前
Springboot中SLF4J详解
java·spring boot·后端
z***948440 分钟前
springboot和springframework版本依赖关系
java·spring boot·后端
艺杯羹1 小时前
从Spring到SpringBoot3的演进:缺陷、优化与最新实践要求
java·spring boot·spring
一 乐1 小时前
宠物管理宠物医院管理|基于Java+vue的宠物医院管理系统(源码+数据库+文档)
java·前端·数据库·vue.js·spring boot·宠物
一 乐1 小时前
学习辅导系统|数学辅导小程序|基于java+小程序的数学辅导小程序设计与实现(源码+数据库+文档)
java·前端·数据库·vue.js·spring boot·学习·小程序
励志成为糕手1 小时前
基于SpringBoot的企业考勤管理系统设计与实现
java·spring boot·后端·web·企业应用
w***4241 小时前
Springboot中使用Elasticsearch(部署+使用+讲解 最完整)
spring boot·elasticsearch·jenkins
e***74951 小时前
SpringBoot项目集成ONLYOFFICE
java·spring boot·后端
Java天梯之路1 小时前
Spring Boot 实战:基于 JWT 优化 Spring Security 无状态登录
spring boot·后端
o***74172 小时前
SpringBoot Maven快速上手
spring boot·后端·maven