📆 业务场景
提交订单评价时需要对评价内容进行判断,如果出现敏感词则提示修改
🔊这不就是写一个敏感词的校验工具类吗,小问题,说干就干
🖥️业务梳理
- 将敏感词存入数据库或者文件中
- 读取文件或数据库中敏感词,循环遍历敏感词,判断评价内容中是否包含敏感词,包含则提示报错
📌小技巧
读取文件时不需要每次都读取,用一个静态代码块坐初始化,读取完毕后放入jvm缓存
//敏感词库 通过jvm缓存
private static final Set<String> sensitiveWords = new HashSet<>();
static {
//静态代码块加载敏感词库
load();
}
📇完整代码
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* 敏感词工具类
* @author woniu
* 2023-11-09
*/
@Slf4j
public class SensitiveWordUtil {
//敏感词库 通过jvm缓存
private static final Set<String> sensitiveWords = new HashSet<>();
static {
//静态代码块加载敏感词库
load();
}
/**
* 从敏感文件中逐行读取,加载到敏感词 set中
*/
public static void load() {
if (CollectionUtils.isEmpty(sensitiveWords)) {
InputStream in = SensitiveWordUtil.class.getResourceAsStream("/file/word.txt");
try (BufferedReader reader = new BufferedReader(new InputStreamReader(in));){
String line;
//逐行读取文件
while ((line = reader.readLine()) != null) {
sensitiveWords.add(line);
}
} catch (FileNotFoundException e) {
log.error("读取敏感词库文件错误,文件不存在");
throw new RuntimeException("读取敏感词库文件错误,文件不存在");
} catch (IOException e) {
log.error("读取敏感词库文件错误,io问题");
throw new RuntimeException("读取敏感词库文件错误,io问题");
}
}
}
/**
* 判断传入文本中是否包含敏感词
* @param word
* @return
*/
public static void containsSensitiveWord(String word) {
Iterator<String> iterator = sensitiveWords.iterator();
while (iterator.hasNext()) {
String sensitiveWord = iterator.next();
if (word.contains(sensitiveWord)) {
log.error("匹配到敏感词"+sensitiveWord);
throw new RuntimeException("评价内容不符合规范,请检查");
}
}
}
public static void main(String[] args) {
// boolean aa = containsSensitiveWord("转让");
// boolean aa1 = containsSensitiveWord("转让");
// boolean aa2 = containsSensitiveWord("转让");
// boolean aa3 = containsSensitiveWord("转让");
// boolean aa4 = containsSensitiveWord("转让");
}
}
嗯,速度很快,可以下班了
🖊️最后总结
🖲要熟练掌握技巧,一定多多练习:纸上得来终觉浅,绝知此事要躬行。