基于Redis的实时排行榜

此文档主要演示了如何使用 Spring Boot 集成Redis的实时排行榜

根据用户点赞数量,获取热点文章

在这里插入图片描述

文章实时排序接口类

/**
 * 文章实时排序接口类
 *
 * @author xiehengxing
 * @date 2020/8/12 15:17
 */
public interface ArticleService {

    /**
     * 文章详情key
     */
    String ARTICLE_DETAIL_KEY = "article:detail:key:";
    /**
     * 文章分值key
     */
    String ARTICLE_SCORE_KEY = "article:score:key";
    /**
     * 文章点赞用户key
     */
    String ARTICLE_LIKE_USER_KEY = "article:like:user:key:";


    /**
     * 创建文章
     *
     * @param articleId
     * @param articleContent
     */
    boolean createArticle(Long articleId, String articleContent);

    /**
     * 分页查询最受欢迎文章
     * @param page
     * @param pageSize
     * @return
     */
    List<ArticleVO> getArticleSort(int page, int pageSize);

    /**
     * 用户点赞文章
     *
     * @param userId
     * @param articleId
     */
    boolean userLikeArticle(Long userId, Long articleId);

    /**
     * 清除文章点赞记录
     *
     * @param articleId
     */
    boolean clearLikeInfo(Long articleId);
}

@Slf4j
@Service
public class ArticleServiceImpl implements ArticleService {

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public boolean clearLikeInfo(Long articleId) {
        // 清除历史点赞用户
        redisTemplate.delete(ARTICLE_LIKE_USER_KEY+ articleId);
        // 重置文章排序
        redisTemplate.opsForZSet().add(ARTICLE_SCORE_KEY, articleId, 0);
        return true;
    }

    /**
     * 创建文章
     *
     * @param articleId
     * @param articleContent
     */
    public boolean createArticle(Long articleId, String articleContent) {
        // 获取历史点赞用户
        Long size = redisTemplate.opsForSet().size(ARTICLE_LIKE_USER_KEY+ articleId);
        // 添加文章到缓存排序列表
        redisTemplate.opsForZSet().add(ARTICLE_SCORE_KEY, articleId, size);
        // 添加文章内容到缓存中
        redisTemplate.opsForValue().set(ARTICLE_DETAIL_KEY+ articleId, articleContent, 1, TimeUnit.HOURS);
        return true;
    }


    /**
     * 用户点赞文章
     *
     * @param userId
     * @param articleId
     */
    public boolean userLikeArticle(Long userId, Long articleId) {
        // 检查文章是否存在
        Long index = redisTemplate.opsForZSet().rank(ARTICLE_SCORE_KEY, articleId);
        if(null == index){
            return false;
        }
        // 检查用户是否已点赞该文章
        boolean isLike = redisTemplate.opsForSet().isMember(ARTICLE_LIKE_USER_KEY + articleId, userId);
        if(isLike){
            log.debug("用户:[{}]已点赞文章:[{}]", userId, articleId);
            return false;
        }
        // 增加文章点赞数量
        // 记录文章点赞用户
        redisTemplate.opsForZSet().incrementScore(ARTICLE_SCORE_KEY, articleId, 1);
        redisTemplate.opsForSet().add(ARTICLE_LIKE_USER_KEY+ articleId, userId);
        return true;
    }

    /**
     * 分页查询最受欢迎文章
     * @param page
     * @param pageSize
     * @return
     */
    public List<ArticleVO> getArticleSort(int page, int pageSize) {
        int start = (page - 1) * pageSize;
        int end = start + pageSize - 1;
        // 根据点赞数倒叙分页查询文章
        Set<DefaultTypedTuple<Long>> tuples = redisTemplate.opsForZSet().reverseRangeByScoreWithScores(ARTICLE_SCORE_KEY, start, end);
        if(CollectionUtils.isEmpty(tuples)){
            return Collections.EMPTY_LIST;
        }

        // 查询文章内容及点赞用户
        List<ArticleVO> list = new ArrayList<>();
        for (DefaultTypedTuple<Long> tuple: tuples) {
            ArticleVO vo = new ArticleVO();
            Long articleId = tuple.getValue();
            vo.setArticleId(tuple.getValue());
            vo.setScore(tuple.getScore());

            // 查询文章内容
            String content = (String) redisTemplate.opsForValue().get(ARTICLE_DETAIL_KEY + articleId);
            vo.setArticleContent(content);
            // 查询点赞用户
            Set<Long> userIds = redisTemplate.opsForSet().members(ARTICLE_LIKE_USER_KEY+ articleId);
            vo.setLikeUserIds(userIds);
            list.add(vo);
        }
        return list;
    }
}

控制层

/**
 * @author xiehengxing
 * @date 2020/8/12 17:27
 */
@Controller
@Slf4j
public class ArticleController {

    @Resource
    private ArticleService articleService;

    @RequestMapping(value ="/getArticle")
    public String getArticle(Model model) {
        List<ArticleVO> articleSort = articleService.getArticleSort(1, 10);
        model.addAttribute("list", articleSort);
        return "page/index";
    }

    @RequestMapping(value ="/add")
    public String index(Model model) {
        for (long i = 0; i < 10; i++) {
            articleService.createArticle(i,  "我是ID:"+ i + "的文章内容~~~");
        }
        List<ArticleVO> articleSort = articleService.getArticleSort(1, 10);
        model.addAttribute("list", articleSort);
        return "redirect:getArticle";
    }

    @RequestMapping(value ="/like")
    public String like(Long articleId, Model model) {
        if (null == articleId) {
            model.addAttribute("errorMassage", "文章ID为空");
            return "page/error";
        }
        // 模拟随机用户ID
        Long userId = System.currentTimeMillis();
        boolean flag = articleService.userLikeArticle(userId, articleId);
        if(!flag){
            return "page/error";
        }
        return "redirect:getArticle";
    }

    @RequestMapping(value ="/clearLike")
    public String clearLike(Long articleId, Model model) {
        if (null == articleId) {
            model.addAttribute("errorMassage", "文章ID为空");
            return "page/error";
        }
        boolean flag = articleService.clearLikeInfo(articleId);
        if(!flag){
            return "page/error";
        }
        return "redirect:getArticle";
    }

}

index.html

<body>
<div id="app" style="margin: 20px 20%">
	<table class="table">
		<thead class="thead-light">
		<th scope="col">序号</th>
		<th scope="col">文章id</th>
		<th scope="col">文章内容</th>
		<th scope="col">排序</th>
		<th scope="col">点赞用户</th>
		<th scope="col">操作</th>
		</thead>
		<tbody>
		<tr th:each="item,stat:${list}" scope="row">
			<td th:text="${stat.count}"></td>
			<td th:text="${item['articleId']}"></td>
			<td th:text="${item['articleContent']}"></td>
			<td th:text="${item['score']}"></td>
			<td th:text="${item['likeUserIds']}"></td>
			<td>
				<a href="#" th:href="@{like(articleId=${item.articleId})}" class="btn btn-large btn-success">点赞</a>
				<a href="#" th:href="@{clearLike(articleId=${item.articleId})}" class="btn btn-large btn-success">清空点赞</a>
			</td>
		</tr>
		</tbody>
	</table>
</div>
</body>
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值