前言
本人采用sensitive-word
实现敏感词的过滤。
步骤
- 引入pom
<dependency>
<groupId>com.github.houbb</groupId>
<artifactId>sensitive-word</artifactId>
<version>0.2.0</version>
</dependency>
- 配置
/**
* 敏感词配置
*
* @author : cnl
*/
@RequiredArgsConstructor
@Configuration
public class SensitiveWordConfig {
private final DdWordAllowConfig DdWordAllowConfig;
private final MyDdWordDenyConfig DdWordDenyConfig;
@Bean
public SensitiveWordBs sensitiveWordBs() {
return SensitiveWordBs.newInstance()
//可以指定多个过滤WordDenys.chains(WordDeny... wordDeny)
.wordDeny(WordDenys.chains(WordDenys.system(), DdWordAllowConfig))
//可以指定多个放行WordAllows.chains(WordAllow... wordAllow)
.wordAllow(WordAllows.chains(WordAllows.system(), DdWordDenyConfig))
.init();
}
}
/**
* 黑名单
* @author cnl
*/
@RequiredArgsConstructor
@Component
public class DdWordDenyConfig implements IWordDeny {
private final SensitiveProperties sensitiveProperties;
/*你如果想使用查询sql的话,可以另外起一个MyDdWordAllow或者直接在该方法中加入*/
@Override
public List<String> deny() {
List<String> list = new ArrayList<>();
// 黑名单的敏感词文件
String denyPath = sensitiveProperties.getDenyPath();
if (StrUtil.isEmpty(denyPath) || !FileUtil.exist(denyPath)) {
return list;
}
List<String> denys = FileUtil.readUtf8Lines(denyPath);
if (CollectionUtil.isEmpty(denys)) {
return list;
}
list.addAll(denys);
return list;
}
}
/**
* 白名单
* @author cnl
*/
@RequiredArgsConstructor
@Component
public class DdWordAllowConfig implements IWordAllow {
private final SensitiveProperties sensitiveProperties;
/*你如果想使用查询sql的话,可以另外起一个MyDdWordAllow或者直接在该方法中加入*/
@Override
public List<String> allow() {
List<String> list = new ArrayList<>();
// 白名单的敏感词文件
String allowPath = sensitiveProperties.getAllowPath();
if (StrUtil.isEmpty(allowPath) || !FileUtil.exist(allowPath)) {
return list;
}
List<String> allows = FileUtil.readUtf8Lines(allowPath);
if (CollectionUtil.isEmpty(allows)) {
return list;
}
list.addAll(allows);
return list;
}
}
/**
* 敏感词配置
*
* @Author : cnl
*/
@Component
@Data
@ConfigurationProperties(prefix = "drm.cnl.sensitive")
public class SensitiveProperties {
/**
* 白名单文件
*/
private String allowPath;
/**
* 黑名单的文件
*/
private String denyPath;
}
@Service
@RequiredArgsConstructor
public class Test {
private final SensitiveWordBs sensitiveWordBs;
@Override
public void testSensitive(String content) {
//获取content中所有的敏感词
List<String> sensitiveWords = sensitiveWordBs.findAll(content));
//默认会把敏感词转换成 *
String aa = sensitiveWordBs.replace(content);
//也可以自定义替换字符
String aa = sensitiveWordBs.replace(content, "#");
//.... 还有一些其他的不做阐述了
}
}