当前位置:   article > 正文

springboot java+redis 实现简单实用的搜索栏热搜功能,不雅文字过滤功能。_springboot redis 一个value里面有几万条数据,如何过滤查询

springboot redis 一个value里面有几万条数据,如何过滤查询

使用java和redis实现一个简单的热搜功能,具备以下功能:

1:搜索栏展示当前登陆的个人用户的搜索历史记录,删除个人历史记录

2:用户在搜索栏输入某字符,则将该字符记录下来 以zset格式存储的redis中,记录该字符被搜索的个数以及当前的时间戳 (用了DFA算法,感兴趣的自己百度学习吧)

3:每当用户查询了已在redis存在了的字符时,则直接累加个数, 用来获取平台上最热查询的十条数据。 (可以自己写接口或者直接在redis中添加一些预备好的关键词)

4:最后还要做不雅文字过滤功能。这个很重要不说了你懂的。

代码实现热搜与个人搜索记录功能,主要controller层下几个方法就行了 :

1:向redis 添加热搜词汇(添加的时候使用下面不雅文字过滤的方法来过滤下这个词汇,合法再去存储

2:每次点击给相关词热度 +1

3: 根据key搜索相关最热的前十名

4:插入个人搜索记录

5:查询个人搜索记录


首先配置好redis数据源等等基础 (不熟悉的看我另一篇博客,redis多数据元配置)

最后贴上核心的 服务层的代码 :

  1. package com.****.****.****.user;
  2. import com.jianlet.service.user.RedisService;
  3. import org.apache.commons.lang.StringUtils;
  4. import org.springframework.data.redis.core.*;
  5. import org.springframework.stereotype.Service;
  6. import javax.annotation.Resource;
  7. import java.util.*;
  8. import java.util.concurrent.TimeUnit;
  9. /**
  10. * @author: mrwanghc
  11. * @date: 2020/5/13
  12. * @description:
  13. */
  14. @Transactional
  15. @Service("redisService")
  16. public class RedisServiceImpl implements RedisService {
  17. //导入数据源
  18. @Resource(name = "redisSearchTemplate")
  19. private StringRedisTemplate redisSearchTemplate;
  20. //新增一条该userid用户在搜索栏的历史记录
  21. //searchkey 代表输入的关键词
  22. @Override
  23. public int addSearchHistoryByUserId(String userid, String searchkey) {
  24. String shistory = RedisKeyUtils.getSearchHistoryKey(userid);
  25. boolean b = redisSearchTemplate.hasKey(shistory);
  26. if (b) {
  27. Object hk = redisSearchTemplate.opsForHash().get(shistory, searchkey);
  28. if (hk != null) {
  29. return 1;
  30. }else{
  31. redisSearchTemplate.opsForHash().put(shistory, searchkey, "1");
  32. }
  33. }else{
  34. redisSearchTemplate.opsForHash().put(shistory, searchkey, "1");
  35. }
  36. return 1;
  37. }
  38. //删除个人历史数据
  39. @Override
  40. public Long delSearchHistoryByUserId(String userid, String searchkey) {
  41. String shistory = RedisKeyUtils.getSearchHistoryKey(userid);
  42. return redisSearchTemplate.opsForHash().delete(shistory, searchkey);
  43. }
  44. //获取个人历史数据列表
  45. @Override
  46. public List<String> getSearchHistoryByUserId(String userid) {
  47. List<String> stringList = null;
  48. String shistory = RedisKeyUtils.getSearchHistoryKey(userid);
  49. boolean b = redisSearchTemplate.hasKey(shistory);
  50. if(b){
  51. Cursor<Map.Entry<Object, Object>> cursor = redisSearchTemplate.opsForHash().scan(shistory, ScanOptions.NONE);
  52. while (cursor.hasNext()) {
  53. Map.Entry<Object, Object> map = cursor.next();
  54. String key = map.getKey().toString();
  55. stringList.add(key);
  56. }
  57. return stringList;
  58. }
  59. return null;
  60. }
  61. //新增一条热词搜索记录,将用户输入的热词存储下来
  62. @Override
  63. public int incrementScoreByUserId(String searchkey) {
  64. Long now = System.currentTimeMillis();
  65. ZSetOperations zSetOperations = redisSearchTemplate.opsForZSet();
  66. ValueOperations<String, String> valueOperations = redisSearchTemplate.opsForValue();
  67. List<String> title = new ArrayList<>();
  68. title.add(searchkey);
  69. for (int i = 0, lengh = title.size(); i < lengh; i++) {
  70. String tle = title.get(i);
  71. try {
  72. if (zSetOperations.score("title", tle) <= 0) {
  73. zSetOperations.add("title", tle, 0);
  74. valueOperations.set(tle, String.valueOf(now));
  75. }
  76. } catch (Exception e) {
  77. zSetOperations.add("title", tle, 0);
  78. valueOperations.set(tle, String.valueOf(now));
  79. }
  80. }
  81. return 1;
  82. }
  83. //根据searchkey搜索其相关最热的前十名 (如果searchkey为null空,则返回redis存储的前十最热词条)
  84. @Override
  85. public List<String> getHotList(String searchkey) {
  86. String key = searchkey;
  87. Long now = System.currentTimeMillis();
  88. List<String> result = new ArrayList<>();
  89. ZSetOperations zSetOperations = redisSearchTemplate.opsForZSet();
  90. ValueOperations<String, String> valueOperations = redisSearchTemplate.opsForValue();
  91. Set<String> value = zSetOperations.reverseRangeByScore("title", 0, Double.MAX_VALUE);
  92. //key不为空的时候 推荐相关的最热前十名
  93. if(StringUtils.isNotEmpty(searchkey)){
  94. for (String val : value) {
  95. if (StringUtils.containsIgnoreCase(val, key)) {
  96. if (result.size() > 9) {//只返回最热的前十名
  97. break;
  98. }
  99. Long time = Long.valueOf(valueOperations.get(val));
  100. if ((now - time) < 2592000000L) {//返回最近一个月的数据
  101. result.add(val);
  102. } else {//时间超过一个月没搜索就把这个词热度归0
  103. zSetOperations.add("title", val, 0);
  104. }
  105. }
  106. }
  107. }else{
  108. for (String val : value) {
  109. if (result.size() > 9) {//只返回最热的前十名
  110. break;
  111. }
  112. Long time = Long.valueOf(valueOperations.get(val));
  113. if ((now - time) < 2592000000L) {//返回最近一个月的数据
  114. result.add(val);
  115. } else {//时间超过一个月没搜索就把这个词热度归0
  116. zSetOperations.add("title", val, 0);
  117. }
  118. }
  119. }
  120. return result;
  121. }
  122. //每次点击给相关词searchkey热度 +1
  123. @Override
  124. public int incrementScore(String searchkey) {
  125. String key = searchkey;
  126. Long now = System.currentTimeMillis();
  127. ZSetOperations zSetOperations = redisSearchTemplate.opsForZSet();
  128. ValueOperations<String, String> valueOperations = redisSearchTemplate.opsForValue();
  129. zSetOperations.incrementScore("title", key, 1);
  130. valueOperations.getAndSet(key, String.valueOf(now));
  131. return 1;
  132. }
  133. }

核心的部分写完了,剩下的需要你自己将如上方法融入到你自己的代码中就行了。


 代码实现过滤不雅文字功能,在springboot 里面写一个配置类加上@Configuration注解,在项目启动的时候加载一下,代码如下: 

  1. package com.***.***.interceptor;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.core.io.ClassPathResource;
  4. import java.io.*;
  5. import java.util.HashMap;
  6. import java.util.HashSet;
  7. import java.util.Map;
  8. import java.util.Set;
  9. //屏蔽敏感词初始化
  10. @Configuration
  11. @SuppressWarnings({ "rawtypes", "unchecked" })
  12. public class SensitiveWordInit {
  13. // 字符编码
  14. private String ENCODING = "UTF-8";
  15. // 初始化敏感字库
  16. public Map initKeyWord() throws IOException {
  17. // 读取敏感词库 ,存入Set中
  18. Set<String> wordSet = readSensitiveWordFile();
  19. // 将敏感词库加入到HashMap中//确定有穷自动机DFA
  20. return addSensitiveWordToHashMap(wordSet);
  21. }
  22. // 读取敏感词库 ,存入HashMap中
  23. private Set<String> readSensitiveWordFile() throws IOException {
  24. Set<String> wordSet = null;
  25. ClassPathResource classPathResource = new ClassPathResource("static/censorword.txt");
  26. InputStream inputStream = classPathResource.getInputStream();
  27. //敏感词库
  28. try {
  29. // 读取文件输入流
  30. InputStreamReader read = new InputStreamReader(inputStream, ENCODING);
  31. // 文件是否是文件 和 是否存在
  32. wordSet = new HashSet<String>();
  33. // StringBuffer sb = new StringBuffer();
  34. // BufferedReader是包装类,先把字符读到缓存里,到缓存满了,再读入内存,提高了读的效率。
  35. BufferedReader br = new BufferedReader(read);
  36. String txt = null;
  37. // 读取文件,将文件内容放入到set中
  38. while ((txt = br.readLine()) != null) {
  39. wordSet.add(txt);
  40. }
  41. br.close();
  42. // 关闭文件流
  43. read.close();
  44. } catch (Exception e) {
  45. e.printStackTrace();
  46. }
  47. return wordSet;
  48. }
  49. // 将HashSet中的敏感词,存入HashMap中
  50. private Map addSensitiveWordToHashMap(Set<String> wordSet) {
  51. // 初始化敏感词容器,减少扩容操作
  52. Map wordMap = new HashMap(wordSet.size());
  53. for (String word : wordSet) {
  54. Map nowMap = wordMap;
  55. for (int i = 0; i < word.length(); i++) {
  56. // 转换成char型
  57. char keyChar = word.charAt(i);
  58. // 获取
  59. Object tempMap = nowMap.get(keyChar);
  60. // 如果存在该key,直接赋值
  61. if (tempMap != null) {
  62. nowMap = (Map) tempMap;
  63. }
  64. // 不存在则,则构建一个map,同时将isEnd设置为0,因为他不是最后一个
  65. else {
  66. // 设置标志位
  67. Map<String, String> newMap = new HashMap<String, String>();
  68. newMap.put("isEnd", "0");
  69. // 添加到集合
  70. nowMap.put(keyChar, newMap);
  71. nowMap = newMap;
  72. }
  73. // 最后一个
  74. if (i == word.length() - 1) {
  75. nowMap.put("isEnd", "1");
  76. }
  77. }
  78. }
  79. return wordMap;
  80. }
  81. }

然后这是工具类代码 : 

  1. package com.***.***.interceptor;
  2. import java.io.IOException;
  3. import java.util.HashSet;
  4. import java.util.Iterator;
  5. import java.util.Map;
  6. import java.util.Set;
  7. //敏感词过滤器:利用DFA算法  进行敏感词过滤
  8. public class SensitiveFilter {
  9. //敏感词过滤器:利用DFA算法 进行敏感词过滤
  10. private Map sensitiveWordMap = null;
  11. // 最小匹配规则
  12. public static int minMatchType = 1;
  13. // 最大匹配规则
  14. public static int maxMatchType = 2;
  15. // 单例
  16. private static SensitiveFilter instance = null;
  17. // 构造函数,初始化敏感词库
  18. private SensitiveFilter() throws IOException {
  19. sensitiveWordMap = new SensitiveWordInit().initKeyWord();
  20. }
  21. // 获取单例
  22. public static SensitiveFilter getInstance() throws IOException {
  23. if (null == instance) {
  24. instance = new SensitiveFilter();
  25. }
  26. return instance;
  27. }
  28. // 获取文字中的敏感词
  29. public Set<String> getSensitiveWord(String txt, int matchType) {
  30. Set<String> sensitiveWordList = new HashSet<String>();
  31. for (int i = 0; i < txt.length(); i++) {
  32. // 判断是否包含敏感字符
  33. int length = CheckSensitiveWord(txt, i, matchType);
  34. // 存在,加入list中
  35. if (length > 0) {
  36. sensitiveWordList.add(txt.substring(i, i + length));
  37. // 减1的原因,是因为for会自增
  38. i = i + length - 1;
  39. }
  40. }
  41. return sensitiveWordList;
  42. }
  43. // 替换敏感字字符
  44. public String replaceSensitiveWord(String txt, int matchType,
  45. String replaceChar) {
  46. String resultTxt = txt;
  47. // 获取所有的敏感词
  48. Set<String> set = getSensitiveWord(txt, matchType);
  49. Iterator<String> iterator = set.iterator();
  50. String word = null;
  51. String replaceString = null;
  52. while (iterator.hasNext()) {
  53. word = iterator.next();
  54. replaceString = getReplaceChars(replaceChar, word.length());
  55. resultTxt = resultTxt.replaceAll(word, replaceString);
  56. }
  57. return resultTxt;
  58. }
  59. /**
  60. * 获取替换字符串
  61. *
  62. * @param replaceChar
  63. * @param length
  64. * @return
  65. */
  66. private String getReplaceChars(String replaceChar, int length) {
  67. String resultReplace = replaceChar;
  68. for (int i = 1; i < length; i++) {
  69. resultReplace += replaceChar;
  70. }
  71. return resultReplace;
  72. }
  73. /**
  74. * 检查文字中是否包含敏感字符,检查规则如下:<br>
  75. * 如果存在,则返回敏感词字符的长度,不存在返回0
  76. * @param txt
  77. * @param beginIndex
  78. * @param matchType
  79. * @return
  80. */
  81. public int CheckSensitiveWord(String txt, int beginIndex, int matchType) {
  82. // 敏感词结束标识位:用于敏感词只有1位的情况
  83. boolean flag = false;
  84. // 匹配标识数默认为0
  85. int matchFlag = 0;
  86. Map nowMap = sensitiveWordMap;
  87. for (int i = beginIndex; i < txt.length(); i++) {
  88. char word = txt.charAt(i);
  89. // 获取指定key
  90. nowMap = (Map) nowMap.get(word);
  91. // 存在,则判断是否为最后一个
  92. if (nowMap != null) {
  93. // 找到相应key,匹配标识+1
  94. matchFlag++;
  95. // 如果为最后一个匹配规则,结束循环,返回匹配标识数
  96. if ("1".equals(nowMap.get("isEnd"))) {
  97. // 结束标志位为true
  98. flag = true;
  99. // 最小规则,直接返回,最大规则还需继续查找
  100. if (SensitiveFilter.minMatchType == matchType) {
  101. break;
  102. }
  103. }
  104. }
  105. // 不存在,直接返回
  106. else {
  107. break;
  108. }
  109. }
  110. if (SensitiveFilter.maxMatchType == matchType){
  111. if(matchFlag < 2 || !flag){ //长度必须大于等于1,为词
  112. matchFlag = 0;
  113. }
  114. }
  115. if (SensitiveFilter.minMatchType == matchType){
  116. if(matchFlag < 2 && !flag){ //长度必须大于等于1,为词
  117. matchFlag = 0;
  118. }
  119. }
  120. return matchFlag;
  121. }
  122. }

在你代码的controller层直接调用方法判断即可: 

  1. //非法敏感词汇判断
  2. SensitiveFilter filter = SensitiveFilter.getInstance();
  3. int n = filter.CheckSensitiveWord(searchkey,0,1);
  4. if(n > 0){ //存在非法字符
  5. logger.info("这个人输入了非法字符--> {},不知道他到底要查什么~ userid--> {}",searchkey,userid);
  6. return null;
  7. }

也可将敏感文字替换*等字符 :

  1. SensitiveFilter filter = SensitiveFilter.getInstance();
  2. String text = "敏感文字";
  3. String x = filter.replaceSensitiveWord(text, 1, "*");

最后刚才的 SensitiveWordInit.java 里面用到了 censorword.text 文件,放到你项目里面的 resources 目录下的 static 目录中,这个文件就是不雅文字大全,也需要您与时俱进的更新,项目启动的时候会加载该文件。

可以自己百度下载这个东西很多的。我就不贴链接了,贴了能会被禁用和无法访问该链接,有需要的可以在该文章下面留言,我私聊发给你行了  over ! 

如果您觉得写的不错的话,望给个赏钱吧~~~~~~

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/355602?site
推荐阅读
相关标签
  

闽ICP备14008679号