Spring Boot读取resources目录下文件(打成jar可用),并放入Guava缓存

@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); } }
上一篇:Springboot 文件上传


下一篇:解决方法