服务敏感词解决方案sensitive-word

敏感词校验可以做成一个单独的公共服务。

 

1.相关依赖

<dependency>
            <groupId>com.github.houbb</groupId>
            <artifactId>sensitive-word</artifactId>
            <version>0.17.0</version>
</dependency>

2.配置类

@Configuration
public class SpringSensitiveWordConfig {

    /**
     * 初始化引导类
     * @return 初始化引导类
     * @since 1.0.0
     */
    @Resource
    private SensitiveWordAllow sensitiveWordAllow;
    @Resource
    private SensitiveWordDeny sensitiveWordDeny;
    @Bean
    public SensitiveWordBs sensitiveWordBs() {
        SensitiveWordBs sensitiveWordBs = SensitiveWordBs.newInstance()
                .ignoreCase(true)
                .ignoreWidth(true)
                .ignoreNumStyle(true)
                .ignoreChineseStyle(true)
                .ignoreEnglishStyle(true)
                .ignoreRepeat(true)
                .enableWordCheck(true)
                .enableNumCheck(true)
                .charIgnore(SensitiveWordCharIgnores.specialChars())
                .wordDeny(WordDenys.chains(WordDenys.defaults(),sensitiveWordDeny))
                .wordAllow(WordAllows.chains(WordAllows.defaults(),sensitiveWordAllow))
                // 各种其他配置
                .init();
        return sensitiveWordBs;
    }

}

3.策略配置类

这里策略通过读取数据配置可以实时控制敏感词库
// 允许策略
@Component
public class SensitiveWordAllow implements IWordAllow { @Resource private WordMapper wordMapper; @Override public List<String> allow() { Word cond = new Word(); cond.setDelFlag(ShareConstant.BYTE_1); cond.setType(ShareConstant.BYTE_2); List<Word> listWord = wordMapper.select(cond); List<String> list = listWord.stream().map(i -> i.getWord()).collect(Collectors.toList()); return list; } }

// 拒绝策略
@Component
public class SensitiveWordDeny implements IWordDeny {

@Resource
private WordMapper wordMapper;

@Override
public List<String> deny() {
Word cond = new Word();
cond.setDelFlag(ShareConstant.BYTE_1);
cond.setType(ShareConstant.BYTE_1);
List<Word> listWord = wordMapper.select(cond);
List<String> list = listWord.stream().map(i -> i.getWord()).collect(Collectors.toList());
return list;
}

}
 

4.具体使用

sensitiveWordBs.contains(words); // 校验是否包含敏感词

sensitiveWordBs.init(); // 可以搭配数据实时刷新敏感词库

5.相关数据库表

create table word
(
id int unsigned auto_increment comment '应用自增主键'
primary key,
word varchar(128) not null comment '单词',
type tinyint null comment '类型1拒绝 2允许',
tags varchar(200) null comment '标签',
del_flag tinyint null comment '删除标记 1正常 2删除',
remark varchar(200) default '' not null comment '配置描述',
create_user bigint null comment '创建人',
update_user bigint null comment '更新人',
create_time datetime null comment '创建时间',
update_time datetime null comment '更新时间',
constraint uk_word
unique (word) comment '唯一索引'
)
comment '敏感词表' charset=utf8;

 

posted @ 2024-06-28 17:47  D·Felix  阅读(56)  评论(0)    收藏  举报