当前位置: 代码网 > it编程>编程语言>Java > SpringBoot 框架下高效敏感词过滤功能的实现方案

SpringBoot 框架下高效敏感词过滤功能的实现方案

2026年01月21日 Java 我要评论
在实际项目开发中,内容安全审核是一个非常重要的功能。本文将详细介绍如何在springboot项目中实现一个功能完善的敏感词过滤系统。我们将从项目搭建、核心代码实现到实际应用场景逐步展开讲解。一、项目准

在实际项目开发中,内容安全审核是一个非常重要的功能。本文将详细介绍如何在springboot项目中实现一个功能完善的敏感词过滤系统。我们将从项目搭建、核心代码实现到实际应用场景逐步展开讲解。

一、项目准备

首先,创建一个springboot项目,在pom.xml中添加必要的依赖:

  • spring web:用于构建 restful api。
  • lombok:简化 javabean 的编写,这里主要用于日志记录注解。
  • apache commons lang3:提供了一些常用的工具类,如字符串处理等。
  • spring data redis:如果要将敏感词存储在 redis 中,用于操作 redis 数据库。
    <dependencies>
        <!-- springboot web -->
        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-web</artifactid>
        </dependency>
        <!-- redis依赖 -->
        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-data-redis</artifactid>
        </dependency>
        <!-- lombok -->
        <dependency>
            <groupid>org.projectlombok</groupid>
            <artifactid>lombok</artifactid>
            <optional>true</optional>
        </dependency>
        <!-- commons lang3 -->
        <dependency>
            <groupid>org.apache.commons</groupid>
            <artifactid>commons-lang3</artifactid>
        </dependency>
    </dependencies>

二、核心代码实现

1、敏感词过滤器实现类

@component
@slf4j
public class sensitivewordfilter {

    // 敏感词字典树,用于存储敏感词
    private map<character, map> sensitivewordmap;

    // 最小匹配规则,表示找到第一个匹配到的敏感词就返回
    public static final int match_type_min = 1;

    // 最大匹配规则,表示找到最长的匹配敏感词再返回
    public static final int match_type_max = 2;

    // 注入redis模板,用于从redis中加载敏感词
    @resource
    private stringredistemplate stringredistemplate;

    /**
     * 初始化敏感词过滤器,包括从redis加载敏感词
     */
    @postconstruct
    public void init() {
        sensitivewordmap = new hashmap<>();
        // 从redis加载敏感词并初始化字典树
        loadsensitivewordsfromredis();
    }

    /**
     * 从redis加载敏感词并初始化到字典树中
     */
    private void loadsensitivewordsfromredis() {
        try {
            // 从redis的sensitive_words集合中获取所有敏感词
            set<string> words = stringredistemplate.opsforset().members("sensitive_words");
            if (words != null) {
                // 遍历敏感词集合,将每个敏感词添加到字典树中
                words.foreach(this::addwordtomap);
            }
        } catch (exception e) {
            // 记录加载敏感词失败日志
            log.error("failed to load sensitive words from redis", e);
        }
    }

    /**
     * 将敏感词添加到字典树中
     * @param word 要添加的敏感词
     */
    public void addwordtomap(string word) {
        map<character, map> currentmap = sensitivewordmap;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charat(i);
            map<character, map> submap = currentmap.get(c);

            if (submap == null) {
                // 如果当前字符不存在于字典树中,则创建新的节点
                submap = new hashmap<>();
                currentmap.put(c, submap);
            }

            currentmap = submap;

            // 如果是敏感词的最后一个字符,则标记为敏感词结束
            if (i == word.length() - 1) {
                currentmap.put('$', null);
            }
        }
    }

    /**
     * 检查文本中是否包含敏感词(最小匹配规则)
     * @param text 要检查的文本
     * @return 如果包含敏感词则返回true,否则返回false
     */
    public boolean containssensitiveword(string text) {
        if (stringutils.isblank(text)) {
            return false;
        }

        // 遍历文本中的每个字符,检查是否存在敏感词
        for (int i = 0; i < text.length(); i++) {
            int length = checksensitiveword(text, i, match_type_min);
            if (length > 0) {
                return true;
            }
        }
        return false;
    }

    /**
     * 在文本中找到所有敏感词(最大匹配规则)
     * @param text 要查找的文本
     * @return 包含所有找到的敏感词的集合
     */
    public set<string> findsensitivewords(string text) {
        set<string> sensitivewords = new hashset<>();
        if (stringutils.isblank(text)) {
            return sensitivewords;
        }

        // 遍历文本中的每个字符,查找敏感词并添加到集合中
        for (int i = 0; i < text.length(); i++) {
            int length = checksensitiveword(text, i, match_type_max);
            if (length > 0) {
                sensitivewords.add(text.substring(i, i + length));
                // 更新索引以跳过已找到的敏感词
                i = i + length - 1;
            }
        }
        return sensitivewords;
    }

    /**
     * 过滤文本中的敏感词,用'*'替换
     * @param text 要过滤的文本
     * @return 过滤后的文本
     */
    public string filter(string text) {
        if (stringutils.isblank(text)) {
            return text;
        }

        stringbuilder result = new stringbuilder(text);
        set<string> words = findsensitivewords(text);

        // 遍历找到的敏感词,用'*'替换
        for (string word : words) {
            int index = result.indexof(word);
            while (index != -1) {
                for (int i = index; i < index + word.length(); i++) {
                    result.setcharat(i, '*');
                }
                index = result.indexof(word, index + 1);
            }
        }

        return result.tostring();
    }

    /**
     * 检查文本中从指定索引开始的子串是否包含敏感词
     * @param text 要检查的文本
     * @param beginindex 开始检查的索引
     * @param matchtype 匹配规则(最小匹配或最大匹配)
     * @return 找到的敏感词长度,如果没有找到则返回0
     */
    private int checksensitiveword(string text, int beginindex, int matchtype) {
        map<character, map> currentmap = sensitivewordmap;
        int wordlength = 0;
        int maxlength = 0;

        // 从指定索引开始遍历文本字符
        for (int i = beginindex; i < text.length(); i++) {
            char c = text.charat(i);
            currentmap = currentmap.get(c);

            if (currentmap == null) {
                break;
            }

            wordlength++;

            // 如果当前节点标记为敏感词结束
            if (currentmap.containskey('$')) {
                if (matchtype == match_type_min) {
                    // 最小匹配规则,返回当前敏感词长度
                    return wordlength;
                } else {
                    // 最大匹配规则,记录当前敏感词长度,继续检查是否还有更长的敏感词
                    maxlength = wordlength;
                }
            }
        }

        // 最大匹配规则下返回最长敏感词长度
        return maxlength;
    }
}

2. 配置类

import org.springframework.context.annotation.configuration;
import org.springframework.data.redis.connection.redisconnectionfactory;
import org.springframework.data.redis.core.stringredistemplate;
import org.springframework.context.annotation.bean;

@configuration
public class redisconfig {

    /**
     * 创建并配置stringredistemplate的bean实例
     *
     * @param connectionfactory redis连接工厂实例,用于创建与redis服务器的连接
     * @return 配置好的stringredistemplate实例,可用于在spring应用中方便地操作redis中的字符串数据类型
     */
    @bean
    public stringredistemplate stringredistemplate(redisconnectionfactory connectionfactory) {
        stringredistemplate template = new stringredistemplate();
        template.setconnectionfactory(connectionfactory);
        return template;
    }
}

3. controller实现

import lombok.extern.slf4j.slf4j;
import org.springframework.http.httpstatus;
import org.springframework.http.responseentity;
import org.springframework.web.bind.annotation.postmapping;
import org.springframework.web.bind.annotation.requestbody;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.restcontroller;
import org.springframework.beans.factory.annotation.resource;
import java.util.set;

@restcontroller
@requestmapping("/api/sensitive")
@slf4j
public class sensitivewordcontroller {

    @resource
    private sensitivewordfilter sensitivewordfilter;

    @resource
    private stringredistemplate stringredistemplate;

    /**
     * 处理添加敏感词的请求
     *
     * @param word 要添加的敏感词内容,通过请求体传入
     * @return 返回添加结果的响应实体,添加成功则返回状态码200及"添加成功"消息,添加失败则返回状态码500及"添加失败"消息
     */
    @postmapping("/word")
    public responseentity<string> addsensitiveword(@requestbody string word) {
        try {
            // 将敏感词添加到redis的集合中
            stringredistemplate.opsforset().add("sensitive_words", word);
            // 将敏感词添加到敏感词过滤器的字典树中
            sensitivewordfilter.addwordtomap(word);
            return responseentity.ok("添加成功");
        } catch (exception e) {
            log.error("添加敏感词失败", e);
            return responseentity.status(httpstatus.internal_server_error).body("添加失败");
        }
    }

    /**
     * 处理检查文本是否包含敏感词的请求
     *
     * @param text 要检查的文本内容,通过请求体传入
     * @return 返回检查结果的响应实体,包含文本是否包含敏感词的布尔值,状态码为200
     */
    @postmapping("/check")
    public responseentity<boolean> checktext(@requestbody string text) {
        return responseentity.ok(sensitivewordfilter.containssensitiveword(text));
    }

    /**
     * 处理过滤文本中敏感词的请求
     *
     * @param text 要过滤的文本内容,通过请求体传入
     * @return 返回过滤后的文本内容的响应实体,状态码为200
     */
    @postmapping("/filter")
    public responseentity<string> filtertext(@requestbody string text) {
        return responseentity.ok(sensitivewordfilter.filter(text));
    }

    /**
     * 处理获取文本中所有敏感词的请求
     *
     * @param text 要获取敏感词的文本内容,通过请求体传入
     * @return 返回包含文本中所有敏感词的集合的响应实体,状态码为200
     */
    @postmapping("/find")
    public responseentity<set<string>> findsensitivewords(@requestbody string text) {
        return responseentity.ok(sensitivewordfilter.findsensitivewords(text));
    }
}

三、配置文件

application.yml中添加redis配置:

spring:  
    redis:    
        host: localhost    
        port: 6379    
        database: 0    
        timeout: 10000

四、使用示例

1. 添加敏感词

curl -x post http://localhost:8080/api/sensitive/word -d "敏感词1"

2. 检查文本

curl -x post http://localhost:8080/api/sensitive/check -d "这是一段包含敏感词1的文本"

3. 过滤文本

curl -x post http://localhost:8080/api/sensitive/filter -d "这是一段包含敏感词1的文本"

五、性能优化建议

1、redis优化

使用redis集群提高可用性

通过redis cluster模式,将数据分散存储在多个节点上,实现水平扩展和负载均衡。这不仅可以提高并发处理能力,还能在主节点故障时,通过自动的故障转移机制保证系统的可用性。

实现redis缓存预热

在系统上线前或低峰期,提前将热点数据加载到redis缓存中,以减少用户请求时的数据库查询压力,提高响应速度。可以通过分析历史访问记录,确定热点数据,并使用脚本程序触发数据预热过程。

添加redis连接池配置

使用连接池来管理redis的连接,可以减少频繁创建和关闭连接的开销,提高连接复用率。配置连接池时,需要根据实际业务需求和服务器资源情况,合理设置最大连接数、最大空闲连接数等参数。

并发处理

redis本身支持高并发处理,但可以通过进一步优化配置和使用相关技术来提高并发性能。例如,使用redis的pipeline功能将多个命令打包并一次性执行,减少网络通信的开销;使用分布式锁和乐观锁等技术来协调多个客户端之间的并发访问。

使用本地缓存减少redis访问

在应用服务器本地设置一层缓存(如guava cache或caffeine等),用于存储一些访问频率高且变化不频繁的数据。当数据在本地缓存中命中时,可以直接返回结果,减少对redis的访问压力。

2、功能扩展

支持敏感词分级

根据敏感词的严重程度或影响范围,将其分为不同的级别。在过滤敏感词时,可以根据级别采取不同的处理措施(如替换、删除或警告等)。

实现自定义替换规则

提供一种机制,允许用户根据自己的需求定义敏感词的替换规则。例如,可以将某些敏感词替换为指定的占位符或符号,以避免直接显示敏感内容。

添加白名单机制优化

对于一些特定的用户或内容,可以将其添加到白名单中,以允许其包含敏感词而不被过滤。这可以用于一些特殊的场景,如内部测试或特定用户的权限管理。

实现敏感词的定时更新机制

通过设置定时任务或使用redis的发布订阅系统,定期从外部数据源(如数据库、文件或远程服务器等)获取最新的敏感词列表,并更新到redis缓存中。这可以确保敏感词过滤的准确性和及时性。

添加并发控制

在处理敏感词过滤等操作时,需要考虑并发控制的问题。可以使用redis的分布式锁或其他并发控制技术来确保多个客户端之间不会同时修改敏感词列表或缓存数据,从而避免数据不一致的问题。

六、总结

本文介绍了如何在springboot中实现敏感词过滤功能,主要特点包括:

  • 使用dfa算法实现高效的敏感词匹配
  • 结合redis实现敏感词的持久化存储
  • 提供完整的rest api接口
  • 支持敏感词的动态添加和更新
  • 考虑了实际应用场景和性能优化

到此这篇关于springboot 框架下高效敏感词过滤功能的实现方案的文章就介绍到这了,更多相关springboot高效敏感词过滤功能内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com