最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot?熱搜與不雅文字過濾的實現

 更新時間:2022年07月13日 09:37:47   作者:魅Lemon  
本文主要介紹了SpringBoot?熱搜與不雅文字過濾的實現,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

一、前言

這里主要講springboot整合redis的個人搜索記錄與熱搜、敏感詞過濾與替換兩個功能,下面進行環(huán)境準備,引入相關maven依賴

<dependency>
? ? <groupId>org.springframework.boot</groupId>
? ? <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
? ? <groupId>org.springframework.boot</groupId>
? ? <artifactId>spring-boot-starter-test</artifactId>
? ? <scope>test</scope>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
<dependency>
? ? <groupId>org.springframework.boot</groupId>
? ? <artifactId>spring-boot-starter-data-redis</artifactId>
? ? <version>2.7.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
? ? <groupId>org.apache.commons</groupId>
? ? <artifactId>commons-lang3</artifactId>
? ? <version>3.12.0</version>
</dependency>

application.yml配置為

spring:
  redis:
    #數據庫索引
    database: 0
    host: 192.168.31.28
    port: 6379
    password: 123456
    lettuce:
      pool:
        #最大連接數
        max-active: 8
        #最大阻塞等待時間(負數表示沒限制)
        max-wait: -1
        #最大空閑
        max-idle: 8
        #最小空閑
        min-idle: 0
        #連接超時時間
    timeout: 10000

 最后敏感詞文本文件放在resources/static目錄下,取名為word.txt,敏感詞文本網上很多,這里就隨便貼一個:github敏感詞

二、不雅文字過濾

1、實現原理

簡單原理如下圖所示,使用了DFA算法,創(chuàng)建結點類,里面包含是否是敏感詞結束符,以及一個HashMap,哈希里key值存儲的是敏感詞的一個詞,value指向下一個結點(即指向下一個詞),一個哈希表中可以存放多個值,比如賭博、賭黃這兩個都是敏感詞。

2、實現方法

2.1 敏感詞庫初始化

敏感詞庫的初始化,這里主要工作是讀取敏感詞文件,在內存中構建好敏感詞的Map節(jié)點

/**
?* @author shawn
?* @version 1.0
?* @ClassName SensitiveWordInit
?* Description:屏蔽一些無關緊要的警告。使開發(fā)者能看到一些他們真正關心的警告。從而提高開發(fā)者的效率
?* 屏蔽敏感詞初始化
?* @date 2022/6/22 18:20
?*/
@Configuration
@SuppressWarnings({ "rawtypes", "unchecked" })
public class SensitiveWordInit {
? ? // 字符編碼
? ? private String ENCODING = "UTF-8";
? ? // 初始化敏感字庫
? ? public Map initKeyWord() throws IOException {
? ? ? ? // 讀取敏感詞庫 ,存入Set中
? ? ? ? Set<String> wordSet = readSensitiveWordFile();
? ? ? ? // 將敏感詞庫加入到HashMap中//確定有窮自動機DFA
? ? ? ? return addSensitiveWordToHashMap(wordSet);
? ? }

? ? // 讀取敏感詞庫 ,存入HashMap中
? ? private Set<String> readSensitiveWordFile() throws IOException {
? ? ? ? Set<String> wordSet = null;
? ? ? ? ClassPathResource classPathResource = new ClassPathResource("static/word.txt");
? ? ? ? InputStream inputStream = classPathResource.getInputStream();
? ? ? ? //敏感詞庫
? ? ? ? try {
? ? ? ? ? ? // 讀取文件輸入流
? ? ? ? ? ? InputStreamReader read = new InputStreamReader(inputStream, ENCODING);
? ? ? ? ? ? // 文件是否是文件 和 是否存在
? ? ? ? ? ? wordSet = new HashSet<String>();
? ? ? ? ? ? // StringBuffer sb = new StringBuffer();
? ? ? ? ? ? // BufferedReader是包裝類,先把字符讀到緩存里,到緩存滿了,再讀入內存,提高了讀的效率。
? ? ? ? ? ? BufferedReader br = new BufferedReader(read);
? ? ? ? ? ? String txt = null;
? ? ? ? ? ? // 讀取文件,將文件內容放入到set中
? ? ? ? ? ? while ((txt = br.readLine()) != null) {
? ? ? ? ? ? ? ? wordSet.add(txt);
? ? ? ? ? ? }
? ? ? ? ? ? br.close();
? ? ? ? ? ? // 關閉文件流
? ? ? ? ? ? read.close();
? ? ? ? } catch (Exception e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }
? ? ? ? return wordSet;
? ? }
? ? // 將HashSet中的敏感詞,存入HashMap中
? ? private Map addSensitiveWordToHashMap(Set<String> wordSet) {
? ? ? ? // 初始化敏感詞容器,減少擴容操作
? ? ? ? Map wordMap = new HashMap(wordSet.size());
? ? ? ? for (String word : wordSet) {
? ? ? ? ? ? Map nowMap = wordMap;
? ? ? ? ? ? for (int i = 0; i < word.length(); i++) {
? ? ? ? ? ? ? ? // 轉換成char型
? ? ? ? ? ? ? ? char keyChar = word.charAt(i);
? ? ? ? ? ? ? ? // 獲取
? ? ? ? ? ? ? ? Object tempMap = nowMap.get(keyChar);
? ? ? ? ? ? ? ? // 如果存在該key,直接賦值
? ? ? ? ? ? ? ? if (tempMap != null) {
? ? ? ? ? ? ? ? ? ? nowMap = (Map) tempMap;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? // 不存在則,則構建一個map,同時將isEnd設置為0,因為他不是最后一個
? ? ? ? ? ? ? ? else {
? ? ? ? ? ? ? ? ? ? // 設置標志位
? ? ? ? ? ? ? ? ? ? Map<String, String> newMap = new HashMap<String, String>();
? ? ? ? ? ? ? ? ? ? newMap.put("isEnd", "0");
? ? ? ? ? ? ? ? ? ? // 添加到集合
? ? ? ? ? ? ? ? ? ? nowMap.put(keyChar, newMap);
? ? ? ? ? ? ? ? ? ? nowMap = newMap;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? // 最后一個
? ? ? ? ? ? ? ? if (i == word.length() - 1) {
? ? ? ? ? ? ? ? ? ? nowMap.put("isEnd", "1");
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? return wordMap;
? ? }
}

2.2 敏感詞過濾器

敏感詞過濾器,主要功能是初始化敏感詞庫,敏感詞的過濾以及替換

/**
?* @author shawn
?* @version 1.0
?* @ClassName SensitiveFilter
?* Description:敏感詞過濾器:利用DFA算法 ?進行敏感詞過濾
?* @date 2022/6/22 18:19
?*/
@Component
public class SensitiveFilter {
? ? /**
? ? ?* 敏感詞過濾器:利用DFA算法 ?進行敏感詞過濾
? ? */
? ? private Map sensitiveWordMap = null;

? ? /**
? ? ?* 最小匹配規(guī)則,如:敏感詞庫["中國","中國人"],語句:"我是中國人",匹配結果:我是[中國]人
? ? */
? ? public static int minMatchType = 1;

? ? /**
? ? ?* 最大匹配規(guī)則,如:敏感詞庫["中國","中國人"],語句:"我是中國人",匹配結果:我是[中國人]
? ? */
? ? public static int maxMatchType = 2;

? ? /**
? ? ?* 敏感詞替換詞
? ? ?*/
? ? public static String placeHolder = "**";

? ? // 單例
? ? private static SensitiveFilter instance = null;

? ? /**
? ? ?* 構造函數,初始化敏感詞庫
? ? */
? ? private SensitiveFilter() throws IOException {
? ? ? ? sensitiveWordMap = new SensitiveWordInit().initKeyWord();
? ? }

? ? /**
? ? ?* 獲取單例
? ? */
? ? public static SensitiveFilter getInstance() throws IOException {
? ? ? ? if (null == instance) {
? ? ? ? ? ? instance = new SensitiveFilter();
? ? ? ? }
? ? ? ? return instance;
? ? }

? ? /**
? ? ?* 獲取文字中的敏感詞
? ? */
? ? public Set<String> getSensitiveWord(String txt, int matchType) {
? ? ? ? Set<String> sensitiveWordList = new HashSet<>();
? ? ? ? for (int i = 0; i < txt.length(); i++) {
? ? ? ? ? ? // 判斷是否包含敏感字符
? ? ? ? ? ? int length = CheckSensitiveWord(txt, i, matchType);
? ? ? ? ? ? // 存在,加入list中
? ? ? ? ? ? if (length > 0) {
? ? ? ? ? ? ? ? sensitiveWordList.add(txt.substring(i, i + length));
? ? ? ? ? ? ? ? // 減1的原因,是因為for會自增
? ? ? ? ? ? ? ? i = i + length - 1;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? return sensitiveWordList;
? ? }


? ? /**
? ? ?* 替換敏感字字符,使用了默認的替換符合,默認最小匹配規(guī)則
? ? ?*/
? ? public String replaceSensitiveWord(String txt) {
? ? ? ? return replaceSensitiveWord(txt, minMatchType ,placeHolder);
? ? }

? ? /**
? ? ?* 替換敏感字字符,使用了默認的替換符合
? ? ?*/
? ? public String replaceSensitiveWord(String txt, int matchType) {
? ? ? ? return replaceSensitiveWord(txt, matchType,placeHolder);
? ? }

? ? /**
? ? ?* 替換敏感字字符
? ? */
? ? public String replaceSensitiveWord(String txt, int matchType,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?String replaceChar) {
? ? ? ? String resultTxt = txt;
? ? ? ? // 獲取所有的敏感詞
? ? ? ? Set<String> set = getSensitiveWord(txt, matchType);
? ? ? ? Iterator<String> iterator = set.iterator();
? ? ? ? String word = null;
? ? ? ? String replaceString = null;
? ? ? ? while (iterator.hasNext()) {
? ? ? ? ? ? word = iterator.next();
? ? ? ? ? ? replaceString = getReplaceChars(replaceChar, word.length());
? ? ? ? ? ? resultTxt = resultTxt.replaceAll(word, replaceString);
? ? ? ? }
? ? ? ? return resultTxt;
? ? }

? ? /**
? ? ?* 獲取替換字符串
? ? ?*/
? ? private String getReplaceChars(String replaceChar, int length) {
? ? ? ? StringBuilder resultReplace = new StringBuilder(replaceChar);
? ? ? ? for (int i = 1; i < length; i++) {
? ? ? ? ? ? resultReplace.append(replaceChar);
? ? ? ? }
? ? ? ? return resultReplace.toString();
? ? }

? ? /**
? ? ?* 檢查文字中是否包含敏感字符,檢查規(guī)則如下:<br>
? ? ?* 如果存在,則返回敏感詞字符的長度,不存在返回0
? ? ?* 核心
? ? ?*/
? ? public int CheckSensitiveWord(String txt, int beginIndex, int matchType) {
? ? ? ? // 敏感詞結束標識位:用于敏感詞只有1的情況結束
? ? ? ? boolean flag = false;
? ? ? ? // 匹配標識數默認為0
? ? ? ? int matchFlag = 0;
? ? ? ? Map nowMap = sensitiveWordMap;
? ? ? ? for (int i = beginIndex; i < txt.length(); i++) {
? ? ? ? ? ? char word = txt.charAt(i);
? ? ? ? ? ? // 獲取指定key
? ? ? ? ? ? nowMap = (Map) nowMap.get(word);
? ? ? ? ? ? // 存在,則判斷是否為最后一個
? ? ? ? ? ? if (nowMap != null) {
? ? ? ? ? ? ? ? // 找到相應key,匹配標識+1
? ? ? ? ? ? ? ? matchFlag++;
? ? ? ? ? ? ? ? // 如果為最后一個匹配規(guī)則,結束循環(huán),返回匹配標識數
? ? ? ? ? ? ? ? if ("1".equals(nowMap.get("isEnd"))) {
? ? ? ? ? ? ? ? ? ? // 結束標志位為true
? ? ? ? ? ? ? ? ? ? flag = true;
? ? ? ? ? ? ? ? ? ? // 最小規(guī)則,直接返回,最大規(guī)則還需繼續(xù)查找
? ? ? ? ? ? ? ? ? ? if (SensitiveFilter.minMatchType == matchType) {
? ? ? ? ? ? ? ? ? ? ? ? break;
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ? ? // 不存在,直接返回
? ? ? ? ? ? else {
? ? ? ? ? ? ? ? break;
? ? ? ? ? ? }
? ? ? ? }

? ? ? ? // 匹配長度如果匹配上了最小匹配長度或者最大匹配長度
? ? ? ? if (SensitiveFilter.maxMatchType == matchType || SensitiveFilter.minMatchType == matchType){
? ? ? ? ? ? //長度必須大于等于1,為詞,或者敏感詞庫還沒有結束(匹配了一半),flag為false
? ? ? ? ? ? if(matchFlag < 2 || !flag){
? ? ? ? ? ? ? ? matchFlag = 0;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? return matchFlag;
? ? }
}

2.3 測試使用

最后進行測試,這里有兩種方式可以獲取,因為容器初始化時會默認執(zhí)行無參構造

@RestController
public class SensitiveController {

? ? private static Logger logger = LoggerFactory.getLogger(SensitiveController.class);

? ? @Autowired
? ? SensitiveFilter sensitiveFilter;


? ? @GetMapping("/sensitive")
? ? public String sensitive(String keyword){
? ? ? ? String s = sensitiveFilter.replaceSensitiveWord(keyword);
? ? ? ? return s;
? ? }

? ? // 兩種方式都可以
? ? public static void main(String[] args) throws IOException {
? ? ? ? String searchKey = "傻逼h";
? ? ? ? String placeholder = "***";
? ? ? ? //非法敏感詞匯判斷
? ? ? ? SensitiveFilter filter = SensitiveFilter.getInstance();
? ? ? ? String s = filter.replaceSensitiveWord(searchKey, 1, placeholder);
? ? ? ? System.out.println(s);
? ? ? ? int n = filter.CheckSensitiveWord(searchKey,0,2);
? ? ? ? //存在非法字符
? ? ? ? if(n > 0){
? ? ? ? ? ? logger.info("這個人輸入了非法字符--> {},不知道他到底要查什么~ userid--> {}",searchKey,1);
? ? ? ? }
? ? }
}

三、Redis搜索欄熱搜

1、前言

使用java和redis實現一個簡單的熱搜功能,具備以下功能:

  • 搜索欄展示當前登陸的個人用戶的搜索歷史記錄,刪除個人歷史記錄
  • 用戶在搜索欄輸入某字符,則將該字符記錄下來 以zset格式存儲的redis中,記錄該字符被搜索的個數以及當前的時間戳 (用了DFA算法)
  • 每當用戶查詢了已在redis存在了的字符時,則直接累加個數, 用來獲取平臺上最熱查詢的十條數據。(可以自己寫接口或者直接在redis中添加一些預備好的關鍵詞)
  • 最后還要做不雅文字過濾功能。

代碼實現熱搜與個人搜索記錄功能,主要controller層下幾個方法就行了 :

  • 向redis 添加熱搜詞匯(添加的時候使用下面不雅文字過濾的方法來過濾下這個詞匯,合法再去存儲
  • 每次點擊給相關詞熱度 +1
  • 根據key搜索相關最熱的前十名
  • 插入個人搜索記錄
  • 查詢個人搜索記錄

2、代碼實現

2.1 創(chuàng)建RedisKeyUtils 工具類

管理redis的鍵,防止太亂了

public class RedisKeyUtils {

? ? /**
? ? ?* 分隔符號
? ? */
? ? private static final String SPLIT = ":";

? ? private static final String SEARCH = "search";

? ? private static final String SEARCH_HISTORY = "search-history";

? ? private static final String HOT_SEARCH = "hot-search";

? ? private static final String SEARCH_TIME = "search-time";

? ? /**
? ? ?* 每個用戶的個人搜索記錄hash
? ? */
? ? public static String getSearchHistoryKey(String userId){
? ? ? ? return SEARCH + SPLIT + SEARCH_HISTORY + SPLIT + userId;
? ? }

? ? /**
? ? ?* 總的熱搜zset
? ? ?*/
? ? public static String getHotSearchKey(){
? ? ? ? return SEARCH + SPLIT + HOT_SEARCH;
? ? }


? ? /**
? ? ?* 每個搜索記錄的時間戳記錄:key-value
? ? ?*/
? ? public static String getSearchTimeKey(String searchKey){
? ? ? ? return SEARCH + SPLIT + SEARCH_TIME + SPLIT + searchKey;
? ? }
? ??
}

2.2 核心搜索文件

兩個文件是一起的

@Service("redisService")
public class RedisService {

? ? private Logger logger = LoggerFactory.getLogger(RedisService.class);

? ? /**
? ? ?* 取熱搜前幾名返回
? ? */
? ? private static final Integer HOT_SEARCH_NUMBER = 9;

? ? /**
? ? ?* 多少時間內的搜索記錄胃熱搜
? ? ?*/
? ? private static final Long HOT_SEARCH_TIME = 30 * 24 * 60 * 60L;
? ??
? ??
? ? @Resource
? ? private StringRedisTemplate redisSearchTemplate;

? ? /**
? ? ?* 新增一條該userid用戶在搜索欄的歷史記錄
? ? */
? ? public Long addSearchHistoryByUserId(String userId, String searchKey) {
? ? ? ? try{
? ? ? ? ? ? String redisKey = RedisKeyUtils.getSearchHistoryKey(userId);
? ? ? ? ? ? // 如果存在這個key
? ? ? ? ? ? boolean b = Boolean.TRUE.equals(redisSearchTemplate.hasKey(redisKey));
? ? ? ? ? ? if (b) {
? ? ? ? ? ? ? ? // 獲取這個關鍵詞hash的值,有就返回,沒有就新增
? ? ? ? ? ? ? ? Object hk = redisSearchTemplate.opsForHash().get(redisKey, searchKey);
? ? ? ? ? ? ? ? if (hk != null) {
? ? ? ? ? ? ? ? ? ? return 1L;
? ? ? ? ? ? ? ? }else{
? ? ? ? ? ? ? ? ? ? redisSearchTemplate.opsForHash().put(redisKey, searchKey, "1");
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }else{
? ? ? ? ? ? ? ? // 沒有這個關鍵詞就新增
? ? ? ? ? ? ? ? redisSearchTemplate.opsForHash().put(redisKey, searchKey, "1");
? ? ? ? ? ? }
? ? ? ? ? ? return 1L;
? ? ? ? }catch (Exception e){
? ? ? ? ? ? logger.error("redis發(fā)生異常,異常原因:",e);
? ? ? ? ? ? return 0L;
? ? ? ? }
? ? }

? ? /**
? ? ?* 刪除個人歷史數據
? ? */
? ? public Long delSearchHistoryByUserId(String userId, String searchKey) {
? ? ? ? try {
? ? ? ? ? ? String redisKey = RedisKeyUtils.getSearchHistoryKey(userId);
? ? ? ? ? ? // 刪除這個用戶的關鍵詞記錄
? ? ? ? ? ? return redisSearchTemplate.opsForHash().delete(redisKey, searchKey);
? ? ? ? }catch (Exception e){
? ? ? ? ? ? logger.error("redis發(fā)生異常,異常原因:",e);
? ? ? ? ? ? return 0L;
? ? ? ? }
? ? }

? ? /**
? ? ?* 獲取個人歷史數據列表
? ? */
? ? public List<String> getSearchHistoryByUserId(String userId) {
? ? ? ? try{
? ? ? ? ? ? List<String> stringList = null;
? ? ? ? ? ? String redisKey = RedisKeyUtils.getSearchHistoryKey(userId);
? ? ? ? ? ? // 判斷存不存在
? ? ? ? ? ? boolean b = Boolean.TRUE.equals(redisSearchTemplate.hasKey(redisKey));
? ? ? ? ? ? if(b){
? ? ? ? ? ? ? ? stringList = new ArrayList<>();
? ? ? ? ? ? ? ? // 逐個掃描,ScanOptions.NONE為獲取全部鍵對,ScanOptions.scanOptions().match("map1").build() 匹配獲取鍵位map1的鍵值對,不能模糊匹配
? ? ? ? ? ? ? ? Cursor<Map.Entry<Object, Object>> cursor = redisSearchTemplate.opsForHash().scan(redisKey, ScanOptions.NONE);
? ? ? ? ? ? ? ? while (cursor.hasNext()) {
? ? ? ? ? ? ? ? ? ? Map.Entry<Object, Object> map = cursor.next();
? ? ? ? ? ? ? ? ? ? String key = map.getKey().toString();
? ? ? ? ? ? ? ? ? ? stringList.add(key);
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? return stringList;
? ? ? ? ? ? }
? ? ? ? ? ? return null;
? ? ? ? }catch (Exception e){
? ? ? ? ? ? logger.error("redis發(fā)生異常,異常原因:",e);
? ? ? ? ? ? return null;
? ? ? ? }
? ? }

? ? /**
? ? ?* 根據searchKey搜索其相關最熱的前十名 (如果searchKey為null空,則返回redis存儲的前十最熱詞條)
? ? */
? ? public List<String> getHotList(String searchKey) {
? ? ? ? try {
? ? ? ? ? ? Long now = System.currentTimeMillis();
? ? ? ? ? ? List<String> result = new ArrayList<>();
? ? ? ? ? ? ZSetOperations<String, String> zSetOperations = redisSearchTemplate.opsForZSet();
? ? ? ? ? ? ValueOperations<String, String> valueOperations = redisSearchTemplate.opsForValue();
? ? ? ? ? ? Set<String> value = zSetOperations.reverseRangeByScore(RedisKeyUtils.getHotSearchKey(), 0, Double.MAX_VALUE);
? ? ? ? ? ? //key不為空的時候 推薦相關的最熱前十名
? ? ? ? ? ? if(StringUtils.isNotEmpty(searchKey)){
? ? ? ? ? ? ? ? for (String val : value) {
? ? ? ? ? ? ? ? ? ? if (StringUtils.containsIgnoreCase(val, searchKey)) {
? ? ? ? ? ? ? ? ? ? ? ? //只返回最熱的前十名
? ? ? ? ? ? ? ? ? ? ? ? if (result.size() > HOT_SEARCH_NUMBER) {
? ? ? ? ? ? ? ? ? ? ? ? ? ? break;
? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? ? ? Long time = Long.valueOf(Objects.requireNonNull(valueOperations.get(val)));
? ? ? ? ? ? ? ? ? ? ? ? //返回最近一個月的數據
? ? ? ? ? ? ? ? ? ? ? ? if ((now - time) < HOT_SEARCH_TIME) {
? ? ? ? ? ? ? ? ? ? ? ? ? ? result.add(val);
? ? ? ? ? ? ? ? ? ? ? ? } else {//時間超過一個月沒搜索就把這個詞熱度歸0
? ? ? ? ? ? ? ? ? ? ? ? ? ? zSetOperations.add(RedisKeyUtils.getHotSearchKey(), val, 0);
? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }else{
? ? ? ? ? ? ? ? for (String val : value) {
? ? ? ? ? ? ? ? ? ? //只返回最熱的前十名
? ? ? ? ? ? ? ? ? ? if (result.size() > HOT_SEARCH_NUMBER) {
? ? ? ? ? ? ? ? ? ? ? ? break;
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? Long time = Long.valueOf(Objects.requireNonNull(valueOperations.get(val)));
? ? ? ? ? ? ? ? ? ? //返回最近一個月的數據
? ? ? ? ? ? ? ? ? ? if ((now - time) < HOT_SEARCH_TIME) {
? ? ? ? ? ? ? ? ? ? ? ? result.add(val);
? ? ? ? ? ? ? ? ? ? } else {
? ? ? ? ? ? ? ? ? ? ? ? //時間超過一個月沒搜索就把這個詞熱度歸0
? ? ? ? ? ? ? ? ? ? ? ? zSetOperations.add(RedisKeyUtils.getHotSearchKey(), val, 0);
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ? ? return result;
? ? ? ? }catch (Exception e){
? ? ? ? ? ? logger.error("redis發(fā)生異常,異常原因:",e);
? ? ? ? ? ? return null;
? ? ? ? }
? ? }
}

接上一個

@Service("redisService")
public class RedisService {

? ? private Logger logger = LoggerFactory.getLogger(RedisService.class);

? ? @Resource
? ? private StringRedisTemplate redisSearchTemplate;


? ? /**
? ? ?* 新增一條熱詞搜索記錄,將用戶輸入的熱詞存儲下來
? ? */
? ? public int incrementScoreByUserId(String searchKey) {
? ? ? ? Long now = System.currentTimeMillis();
? ? ? ? ZSetOperations<String, String> zSetOperations = redisSearchTemplate.opsForZSet();
? ? ? ? ValueOperations<String, String> valueOperations = redisSearchTemplate.opsForValue();
? ? ? ? List<String> title = new ArrayList<>();
? ? ? ? title.add(searchKey);
? ? ? ? for (int i = 0, length = title.size(); i < length; i++) {
? ? ? ? ? ? String tle = title.get(i);
? ? ? ? ? ? try {
? ? ? ? ? ? ? ? if (zSetOperations.score(RedisKeyUtils.getHotSearchKey(), tle) <= 0) {
? ? ? ? ? ? ? ? ? ? zSetOperations.add(RedisKeyUtils.getHotSearchKey(), tle, 0);
? ? ? ? ? ? ? ? ? ? valueOperations.set(RedisKeyUtils.getSearchTimeKey(tle), String.valueOf(now));
? ? ? ? ? ? ? ? }
? ? ? ? ? ? } catch (Exception e) {
? ? ? ? ? ? ? ? zSetOperations.add(RedisKeyUtils.getHotSearchKey(), tle, 0);
? ? ? ? ? ? ? ? valueOperations.set(RedisKeyUtils.getSearchTimeKey(tle), String.valueOf(now));
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? return 1;
? ? }

? ? /**
? ? ?* 每次點擊給相關詞searchKey熱度 +1
? ? */
? ? public Long incrementScore(String searchKey) {
? ? ? ? try{
? ? ? ? ? ? Long now = System.currentTimeMillis();
? ? ? ? ? ? ZSetOperations<String, String> zSetOperations = redisSearchTemplate.opsForZSet();
? ? ? ? ? ? ValueOperations<String, String> valueOperations = redisSearchTemplate.opsForValue();
? ? ? ? ? ? // 沒有的話就插入,有的話的直接更新;add是有就覆蓋,沒有就插入
? ? ? ? ? ? zSetOperations.incrementScore(RedisKeyUtils.getHotSearchKey(), searchKey, 1);
? ? ? ? ? ? valueOperations.getAndSet(RedisKeyUtils.getSearchTimeKey(searchKey), String.valueOf(now));
? ? ? ? ? ? return 1L;
? ? ? ? }catch (Exception e){
? ? ? ? ? ? logger.error("redis發(fā)生異常,異常原因:",e);
? ? ? ? ? ? return 0L;
? ? ? ? }
? ? }
}

2.3 測試使用

以下只是簡單的測試,上面的核心函數可以自己組合,一般組合加上敏感詞過濾

@RestController
public class SearchHistoryController {

? ? @Autowired
? ? RedisService redisService;


? ? @GetMapping("/add")
? ? public String addSearchHistoryByUserId(String userId, String searchKey) {
? ? ? ? redisService.addSearchHistoryByUserId(userId, searchKey);
? ? ? ? redisService.incrementScore(searchKey);
? ? ? ? return null;
? ? }

? ? /**
? ? ?* 刪除個人歷史數據
? ? ?*/
? ? @GetMapping("/del")
? ? public Long delSearchHistoryByUserId(String userId, String searchKey) {
? ? ? ? return redisService.delSearchHistoryByUserId(userId, searchKey);
? ? }

? ? /**
? ? ?* 獲取個人歷史數據列表
? ? ?*/
? ? @GetMapping("/getUser")
? ? public List<String> getSearchHistoryByUserId(String userId) {
? ? ? ? return redisService.getSearchHistoryByUserId(userId);
? ? }

? ? /**
? ? ?* 根據searchKey搜索其相關最熱的前十名 (如果searchKey為null空,則返回redis存儲的前十最熱詞條)
? ? ?*/
? ? @GetMapping("/getHot")
? ? public List<String> getHotList(String searchKey) {
? ? ? ? return redisService.getHotList(searchKey);
? ? }
}

參考文章

Redis6.0學習筆記

到此這篇關于SpringBoot 熱搜與不雅文字過濾的實現的文章就介紹到這了,更多相關SpringBoot 熱搜與不雅文字過濾內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Java中的LinkedHashMap及LRU緩存機制詳解

    Java中的LinkedHashMap及LRU緩存機制詳解

    這篇文章主要介紹了Java中的LinkedHashMap及LRU緩存機制詳解,LinkedHashMap繼承自HashMap,它的多種操作都是建立在HashMap操作的基礎上的,同HashMap不同的是,LinkedHashMap維護了一個Entry的雙向鏈表,保證了插入的Entry中的順序,需要的朋友可以參考下
    2023-09-09
  • SpringBoot開啟Swagger并配置基本信息方式

    SpringBoot開啟Swagger并配置基本信息方式

    這篇文章主要介紹了SpringBoot開啟Swagger并配置基本信息方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-05-05
  • java中@NotBlank限制屬性不能為空

    java中@NotBlank限制屬性不能為空

    在實體類的對應屬性上添 @NotBlank注解,可以實現對空置的限制,本文就來介紹一下java中@NotBlank限制屬性不能為空,感興趣的可以了解一下
    2024-01-01
  • Spring Boot 2.x 實現文件上傳功能

    Spring Boot 2.x 實現文件上傳功能

    這篇文章主要介紹了Spring Boot 2.x 實現文件上傳功能,本文分步驟通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-01-01
  • Eclipse智能提示及快捷鍵

    Eclipse智能提示及快捷鍵

    本文主要介紹了Eclipse智能提示及快捷鍵的相關知識,具有很好的參考價值。下面跟著小編一起來看下吧
    2017-03-03
  • Java編譯錯誤問題:需要class,interface或enum

    Java編譯錯誤問題:需要class,interface或enum

    這篇文章主要介紹了Java編譯錯誤問題:需要class,interface或enum,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-02-02
  • Spring中@DependsOn注解的作用及實現原理解析

    Spring中@DependsOn注解的作用及實現原理解析

    這篇文章主要介紹了Spring中@DependsOn注解的作用及實現原理解析,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-03-03
  • Java操作Excel文件解析與讀寫方法詳解

    Java操作Excel文件解析與讀寫方法詳解

    相信現在很多搞后端的同學大部分做的都是后臺管理系統(tǒng),那么管理系統(tǒng)就肯定免不了Excel的導出導入功能,下面這篇文章主要給大家介紹了關于Java簡單使用EasyExcel操作讀寫與解析的步驟與要點,需要的朋友可以參考下
    2022-11-11
  • Java8之lambda表達式基本語法

    Java8之lambda表達式基本語法

    本文通過示例大家給大家介紹了java8之lambda表達式的基本語法,感興趣的的朋友一起看看吧
    2017-08-08
  • MyBatis-Plus與Druid結合Dynamic-datasource實現多數據源操作數據庫的示例

    MyBatis-Plus與Druid結合Dynamic-datasource實現多數據源操作數據庫的示例

    Dynamic-DataSource 可以和絕大多是連接層插件搭配使用,比如:mybatis,mybatis-plus,hibernate等,本文就來介紹一下MyBatis-Plus與Druid結合Dynamic-datasource實現多數據源操作數據庫的示例,感興趣的可以了解一下
    2023-10-10

最新評論

瓮安县| 城口县| 额敏县| 浦北县| 东丽区| 大英县| 增城市| 侯马市| 南岸区| 株洲市| 家居| 工布江达县| 时尚| 临沂市| 延长县| 舟山市| 都匀市| 黄龙县| 藁城市| 康保县| 抚顺市| 邛崃市| 桑植县| 大竹县| 丰都县| 登封市| 增城市| 金门县| 东宁县| 朔州市| 汉沽区| 田林县| 新建县| 扎兰屯市| 克山县| 五原县| 韩城市| 拜城县| 龙口市| 睢宁县| 大新县|