1.引入jar包
<dependency>
<groupId>com.github.houbb</groupId>
<artifactId>sensitive-word</artifactId>
<version>0.18.0</version>
</dependency>
2. 创建配置文件
SpringSensitiveWordConfig 文件
@Configuration
public class SpringSensitiveWordConfig {
@Autowired
private MyDdWordAllow myDdWordAllow;
@Autowired
private MyDdWordDeny myDdWordDeny;
/**
* 初始化引导类
* @return 初始化引导类
* @since 1.0.0
*/
@Bean
public SensitiveWordBs sensitiveWordBs() {
SensitiveWordBs sensitiveWordBs = SensitiveWordBs.newInstance()
.wordAllow(WordAllows.chains(WordAllows.defaults(), myDdWordAllow))
.wordDeny(WordDenys.chains(WordDenys.defaults(),myDdWordDeny))
// 各种其他配置
.init();
return sensitiveWordBs;
}
}
MyDdWordAllow 白名单文件
@Component
public class MyDdWordAllow implements IWordAllow {
@Override
public List<String> allow() {
// 数据库查询
return Arrays.asList("白名单字符串");
}
}
MyDdWordDeny 敏感词名单文件
@Component
public class MyDdWordDeny implements IWordDeny {
private static RedisService redisService;
@Autowired
public void setRedisService(RedisService redisService) {
MyDdWordDeny.redisService = redisService;
}
@Override
public List<String> deny() {
System.out.println(">>>>>>>>>>MyDdWordDeny 初始化成功");
List<String >list= redisService.getCacheObject("MyDdWordDeny");
if(list == null){
list = new ArrayList<>();
}
// 数据库返回的各种信息
return list;
}
}
敏感词 变化重置类 SensitiveWordService
@Component
public class SensitiveWordService {
@Autowired
private SensitiveWordBs sensitiveWordBs;
/**
* 更新词库
*
* 每次数据库的信息发生变化之后,首先调用更新数据库敏感词库的方法。
* 如果需要生效,则调用这个方法。
*
* 说明:重新初始化不影响旧的方法使用。初始化完成后,会以新的为准。
*/
public void refresh() {
// 每次数据库的信息发生变化之后,首先调用更新数据库敏感词库的方法,然后调用这个方法。
sensitiveWordBs.init();
}
}
敏感词 表数据 进行增删改时 处罚 方法
public void refeshSensitiveWord() {
LambdaQueryWrapper<SysWordDeny> wrapper = Wrappers.lambdaQuery();
wrapper.select(SysWordDeny::getKeyword).eq(SysWordDeny::getEnable,1);
ArrayList<String> keywordList= (ArrayList<String>) listObjs(wrapper, Object::toString);
redisService.setCacheObject("MyDdWordDeny",keywordList);
sensitiveWordService.refresh();
}