使用springboot集成redis实现一个简单的热搜功能。
搜索栏展示当前登录的个人用户的搜索历史记录; 删除个人用户的搜索历史记录; 插入个人用户的搜索历史记录; 用户在搜索栏输入某字符,则将该字符记录下来以zset格式存储在redis中,记录该字符被搜索的个数; 当用户再次查询了已在redis存储了的字符时,则直接累加个数; 搜索相关最热的前十条数据;实例
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 |
@Transactional @Service ( "redisService" ) public class RedisService { @Resource private StringRedisTemplate redisSearchTemplate; /** * 新增一条该userId用户在搜索栏的历史记录,searchKey代表输入的关键词 * * @param userId * @param searchKey * @return */ public int addSearchHistoryByUserId(String userId, String searchKey) { String searchHistoryKey = RedisKeyUtil.getSearchHistoryKey(userId); boolean flag = redisSearchTemplate.hasKey(searchHistoryKey); if (flag) { Object hk = redisSearchTemplate.opsForHash().get(searchHistoryKey, searchKey); if (hk != null ) { return 1 ; } else { redisSearchTemplate.opsForHash().put(searchHistoryKey, searchKey, "1" ); } } else { redisSearchTemplate.opsForHash().put(searchHistoryKey, searchKey, "1" ); } return 1 ; } /** * 删除个人历史数据 * * @param userId * @param searchKey * @return */ public long delSearchHistoryByUserId(String userId, String searchKey) { String searchHistoryKey = RedisKeyUtil.getSearchHistoryKey(userId); return redisSearchTemplate.opsForHash().delete(searchHistoryKey, searchKey); } /** * 获取个人历史数据列表 * * @param userId * @return */ public List<String> getSearchHistoryByUserId(String userId) { List<String> history = new ArrayList<>(); String searchHistoryKey = RedisKeyUtil.getSearchHistoryKey(userId); boolean flag = redisSearchTemplate.hasKey(searchHistoryKey); if (flag) { Cursor<Map.Entry<Object, Object>> cursor = redisSearchTemplate.opsForHash().scan(searchHistoryKey, ScanOptions.NONE); while (cursor.hasNext()) { Map.Entry<Object, Object> map = cursor.next(); String key = map.getKey().toString(); history.add(key); } return history; } return null ; } /** * 新增一条热词搜索记录,将用户输入的热词存储下来 * * @param searchKey * @return */ public int addHot(String searchKey) { Long now = System.currentTimeMillis(); ZSetOperations zSetOperations = redisSearchTemplate.opsForZSet(); ValueOperations<String, String> valueOperations = redisSearchTemplate.opsForValue(); List<String> id="codetool">
在向redis添加搜索词汇时需要过滤不雅文字,合法时再去存储到redis中,下面是过滤不雅文字的过滤器。
其中用到的sensitiveWord.txt文件在resources目录下的static目录中,这个文件是不雅文字大全,需要与时俱进,不断进步的。
到此这篇关于springboot+redis实现热搜的文章就介绍到这了,更多相关springboot redis热搜内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持! 原文链接:https://blog.csdn.net/leijie0322/article/details/124801909
查看更多关于springboot+redis实现简单的热搜功能的详细内容... 声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did189692
阅读:31次
|