springboot+redis实现热词搜索推荐(Java)

redis多数据源

import cc.datebook.common.JsonResult;
import cc.datebook.entity.BookInfo;
import cc.datebook.enums.ResultCode;
import cc.datebook.service.BookInfoService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;

@RestController
@RequestMapping("/hotKey")
public class HotKeyController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource(name = "redisKeyDatabase")
    private RedisTemplate redisKeyDatabase;

    @Resource(name = "redisKeyTimeDatabase")
    private RedisTemplate redisKeyTimeDatabase;

    @Autowired
    private BookInfoService bookInfoService;

    /**
     * 手动导入若干数据以供测试
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public JsonResult redisAdd() {
        List<BookInfo> bookInfos = bookInfoService.getBookInfos();
        for (BookInfo bookInfo : bookInfos) {
            if (StringUtils.isNotBlank(bookInfo.getAuthor())) {
                String author = bookInfo.getAuthor().replaceAll("\\﹝.*?\\﹞|\\〔.*?\\〕|\\(.*?\\)|\\{.*?}|\\[.*?]|\\[.*?]|\\【.*?】|(.*?)|等|著|编者|主编|[^0-9a-zA-Z\u4e00-\u9fa5.,,•·《 》]", "").trim();
                author = author.replaceAll("\\s+", " ").trim();
                try {
                    if (author.endsWith(",") || author.endsWith(",")) {
                        author = author.substring(0, author.length() - 1);
                    }
                } catch (Exception e) {
                    logger.error("1111111" + bookInfo.toString());
                }
                try {
                    String tem = author.substring(author.lastIndexOf(",") + 1, author.length());
                    String tem1 = author.substring(author.lastIndexOf(",") + 1, author.length());
                    if (StringUtils.isBlank(tem)) {
                        author = author.substring(0, author.lastIndexOf(","));
                    }
                    if (StringUtils.isBlank(tem1)) {
                        author = author.substring(0, author.lastIndexOf(","));
                    }
                } catch (Exception e) {
                    logger.error("2222222" + bookInfo.toString());
                }
                bookInfo.setAuthor(author);
                bookInfoService.updateByPrimaryKeySelective(bookInfo);
            }
        }
        Long now = System.currentTimeMillis();
        ZSetOperations zSetOperations = redisKeyDatabase.opsForZSet();
        ValueOperations<String, Long> valueOperations = redisKeyTimeDatabase.opsForValue();
        List<String> title = bookInfoService.getBookTitle();
        List<String> author = bookInfoService.getBookAuthor();
        for (int i = 0, lengh = title.size(); i < lengh; i++) {
            String tle = title.get(i);
            try {
                if (zSetOperations.score("title", tle) <= 0) {
                    zSetOperations.add("title", tle, 0);
                    valueOperations.set(tle, now);
                }
            } catch (Exception e) {
                zSetOperations.add("title", tle, 0);
                valueOperations.set(tle, now);
            }
        }
        for (int i = 0, lengh = author.size(); i < lengh; i++) {
            String aut = author.get(i);
            if (StringUtils.isNotBlank(aut)) {
                String auth[] = aut.split(",|,");
                for (String str : auth) {
                    if (StringUtils.isNotBlank(str)) {
                        try {
                            if (zSetOperations.score("title", str.trim()) <= 0) {
                                zSetOperations.add("title", str.trim(), 0);
                                valueOperations.set(str.trim(), now);
                            }
                        } catch (Exception e) {
                            zSetOperations.add("title", str.trim(), 0);
                            valueOperations.set(str.trim(), now);
                        }
                    }
                }
            }
        }
        return new JsonResult(ResultCode.SUCCESS, "成功");
    }

    /**
     * 根据key搜索相关最热的前十名
     */
    @RequestMapping(value = "/get", method = RequestMethod.POST)
    public JsonResult redisGet(@RequestBody Map<String, Object> params) {
        String key = params.get("key").toString();
        Long now = System.currentTimeMillis();
        List<String> result = new ArrayList<>();
        ZSetOperations zSetOperations = redisKeyDatabase.opsForZSet();
        ValueOperations<String, Long> valueOperations = redisKeyTimeDatabase.opsForValue();
        Set<String> value = zSetOperations.reverseRangeByScore("title", 0, Double.MAX_VALUE);
        //key不为空的时候 推荐相关的最热前十名
        for (String val : value) {
            if (StringUtils.containsIgnoreCase(val, key)) {
                if (result.size() > 9) {//只返回最热的前十名
                    break;
                }
                Long time = valueOperations.get(val);
                if ((now - time) < 2592000000L) {//返回最近一个月的数据
                    result.add(val);
                } else {//时间超过一个月没搜索就把这个词热度归0
                    zSetOperations.add("title", val, 0);
                }
            }
        }
        return new JsonResult(ResultCode.SUCCESS, "成功", result);
    }

    /**
     * 每次点击给相关词热度+1
     */
    @RequestMapping(value = "/incrementScore", method = RequestMethod.POST)
    public JsonResult incrementScore(@RequestBody Map<String, Object> params) {
        String key = params.get("key").toString();
        Long now = System.currentTimeMillis();
        ZSetOperations zSetOperations = redisKeyDatabase.opsForZSet();
        ValueOperations<String, Long> valueOperations = redisKeyTimeDatabase.opsForValue();
        zSetOperations.incrementScore("title", key, 1);
        valueOperations.getAndSet(key, now);
        return new JsonResult(ResultCode.SUCCESS, "成功");
    }
}

  • 6
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值