zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

Redis实战之百度首页新闻热榜的实现代码

Redis百度代码 实现 实战 新闻 首页 热榜
2023-06-13 09:19:49 时间

新闻排行榜以热度为指标降序排序,这里假设热度就是评论数量且统计的热度时间范围以当天为准;根据新闻的时效性,这里假设每15分钟刷新一次新闻榜单。

分析 Zset数据类型:一个有序集合最多 2^{32}-1 个元素,集合元素有序不可重复,每个元素都会关联一个double类型的分数。元素根据分数从小到大的排序,分数可以重复。zscore命令可以对分数实现增量,且如果该Zset中没有该元素,则会创建该条数据。可以将模块名+当天的时间作为Zset的键,用户评论量作为分数,新闻标题作为值,每当用户评论一次新闻,分数则相应地加1。每隔15分钟提取新闻统计中的前30名(包含第30名)榜单,放入到新闻热榜的Zset中。

控制层


package com.shoppingcart.controller;

import com.shoppingcart.service.NewsTopServer;

import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import java.util.List;

import java.util.Map;

 * 新闻排行榜

@RestController

@RequestMapping("/newsTop")

public class NewsTopController {

 @Resource

 public NewsTopServer newsTopServer;

 * http://localhost:8099/newsTop/zscoreNews newTitle=《欢乐喜剧人7》全新赛制养成新人 score=434000

 * 创建新闻统计 实时统计新闻热度

 * @param newTitle 新闻标题 (根据业务也可以写成新闻ID)

 * @param score 热度增量

 * @return 给新闻一个增量以后,返回新闻的当前分数。

 @GetMapping("/zscoreNews")

 public Map String, Object zscoreNews(

 @RequestParam(value = "newTitle", required = true) String newTitle,

 @RequestParam(value = "score", defaultValue = "1") double score

 Map String, Object map = newsTopServer.incrementScore(newTitle, score);

 return map;

 * http://localhost:8099/newsTop/findNewByNewTitle newTitle=《欢乐喜剧人7》全新赛制养成新人

 * 查询某条新闻的热度

 * @param newTitle

 * @return

 @GetMapping("/findNewByNewTitle")

 public Map String, Object findNewByNewTitle(

 @RequestParam(value = "newTitle", required = true) String newTitle

 Map String, Object map = newsTopServer.findNewByNewTitle(newTitle);

 return map;

 * http://localhost:8099/newsTop/createNewsTop startPage=0 endPage=29

 * 对统计的新闻数据降序排序,并将[29,0]之间的数据放入新闻排行榜。(这个方法可以设置成定时任务。)

 * @param startPage 开始下标

 * @param endPage 结束下标

 * @return

 @GetMapping("/createNewsTop")

 public Map String, Object createNewsTop(

 @RequestParam(value = "startPage", defaultValue = "0") int startPage,

 @RequestParam(value = "endPage", defaultValue = "29") int endPage

 Map String, Object map = newsTopServer.createNewsTop(startPage, endPage);

 return map;

 * http://localhost:8099/newsTop/newsTop startPage=20 endPage=29

 * 对统计的新闻数据降序排序,并将[29,0]之间的数据放入新闻排行榜。(这个方法可以设置成定时任务。)

 * @param startPage 开始下标

 * @param endPage 结束下标

 * @return

 @GetMapping("/newsTop")

 public Map String, Object newsTop(

 @RequestParam(value = "startPage", defaultValue = "0") int startPage,

 @RequestParam(value = "endPage", defaultValue = "9") int endPage

 Map String, Object map = newsTopServer.newsTop(startPage, endPage);

 return map;

 * http://localhost:8099/newsTop/addTestData

 * 批量增加测试数据(新闻统计)

 @PostMapping("/addTestData")

 public void addTestData(@RequestBody List Map String, Object list) {

 for (int i = 0; i list.size(); i++) {

 System.out.println(list.get(i).get("value").toString());

 System.out.println(Double.parseDouble(list.get(i).get("score").toString()));

 zscoreNews(list.get(i).get("value").toString(), Double.parseDouble(list.get(i).get("score").toString()));

 /**新增测试数据:

 "score": 2356428.0,

 "value": "《蒙面唱将猜猜猜》第五季收官"

 "score": 2335456.0,

 "value": "《欢乐喜剧人7》全新赛制养成新人"

 "score": 987655.0,

 "value": "《星光大道》2020年度总决赛"

 "score": 954566.0,

 "value": "网易北京:重构梦幻西游项目"

 "score": 943665.0,

 "value": "神武惊现靓号:44488888"

 "score": 876653.0,

 "value": "小米手机:红米"

 "score": 875444.0,

 "value": "英特尔扩大外包"

 "score": 755656.0,

 "value": "多益广州举办神武4手游比赛"

 "score": 687466.0,

 "value": "亮剑重播超记录"

 "score": 567645.0,

 "value": "春节快到了"

 "score": 554342.0,

 "value": "购票狂潮"

 "score": 466654.0,

 "value": "达摩院旗下拥有20多位世界级的科学家"

 "score": 456666.0,

 "value": "NBA MVP候选人"

 "score": 435654.0,

 "value": "CBA最佳新秀"

 "score": 392875.0,

 "value": "数字货币新时代"

 "score": 300454.0,

 "value": "网易新手游即将发布"

 "score": 277654.0,

 "value": "CBA12强排名:四强格局已定"

 "score": 265656.0,

 "value": "用黑科技悄悄改变大众生活"

 "score": 234665.0,

 "value": "玉溪:致力打造全省数字经济第一城"

 "score": 234665.0,

 "value": "广西培育消费新业态新模式"

 "score": 234656.0,

 "value": "互联网产品是顺从用户?还是教育用户?"

 "score": 234564.0,

 "value": "蒋军:企业做强,做大跟产品的关系是什么?"

 "score": 234564.0,

 "value": "热搜第一!微信又有重大更新,这次有点炸"

 "score": 234555.0,

 "value": "成功的人,往往都读这“6”种书"

 "score": 134566.0,

 "value": "外地职工留苏州过年 落户加15分"

 "score": 133455.0,

 "value": "蒋军:成功创业的7种思维!创业者必读!"

 "score": 98554.0,

 "value": "阿里平头哥:首个RISC - V版安卓10系统顺畅运行"

 "score": 87654.0,

 "value": "不断增强人民群众就医获得感"

 "score": 54347.0,

 "value": "《星光大道》年度总冠军出炉"

 "score": 43335.0,

 "value": "流量应是榜样,榜样应成力量"

 "score": 23555.0,

 "value": "《山海情》:主旋律可以这样好看"

 "score": 23456.0,

 "value": "2021艺考新动向"

}

 

业务层


package com.shoppingcart.service;

import java.util.Map;

public interface NewsTopServer {

 Map String, Object incrementScore(String newTitle,double zscore);

 Map String, Object findNewByNewTitle(String newTitle);

 Map String, Object createNewsTop(int startPage, int endPage);

 Map String, Object newsTop(int startPage, int endPage);

}

import com.shoppingcart.service.NewsTopServer; import com.shoppingcart.utils.RedisService; import org.springframework.data.redis.core.ZSetOperations; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.*; @Service public class NewsTopServerImpl implements NewsTopServer { @Resource private RedisService redisService; @Override public Map String, Object incrementScore(String newTitle, double score) { Map String, Object map = new HashMap (); //String key= "newsSta:"+DateUtils.dateToString(new Date(),"yyyyMMdd"); String key = "newsSta:" + "20210123"; Double d = redisService.incrementScore(key, newTitle, score); Map String, Object m = new HashMap String, Object () { put("key", key); put("newTitle", newTitle); put("score", d); map.put("data", m); map.put("code", 0); return map; @Override public Map String, Object findNewByNewTitle(String newTitle) { //String key= "newsSta:"+DateUtils.dateToString(new Date(),"yyyyMMdd"); String key = "newsSta:" + "20210123"; Double d = redisService.score(key, newTitle); Map String, Object map = new HashMap (); Map String, Object m = new HashMap String, Object () { put("key", key); put("newTitle", newTitle); put("score", d); map.put("data", m); map.put("code", 0); return map; * @param startPage * @param endPage * @return @Override public Map String, Object createNewsTop(int startPage, int endPage) { Map String, Object map = new HashMap (); //新闻统计键 //String newsStaKey= "newsSta:"+DateUtils.dateToString(new Date(),"yyyyMMdd"); String newsStaKey = "newsSta:" + "20210123"; //新闻前30排名键 //String newsTopKey= "newsSta:"+DateUtils.dateToString(new Date(),"yyyyMMdd"); String newsTopKey = "newsTop:" + "20210123"; //查询前30的信息(Interface Comparable T :该接口对实现它的每个类的对象强加一个整体排序。) Set ZSetOperations.TypedTuple Object set = redisService.reverseRangeWithScores(newsStaKey, startPage, endPage); if (set == null || set.size() == 0) { map.put("data", null); map.put("code", 1); return map; //删除旧的新闻排行榜 redisService.del(newsTopKey); //添加新闻排行榜数据 Long zsetSize = redisService.zsetAdd(newsTopKey, set); Map String, Object m = new HashMap String, Object () { put("data", set); put("size", zsetSize); map.put("data", m); map.put("code", 0); return map; * 查看新闻热榜(TOP30) * @param startPage * @param endPage * @return @Override public Map String, Object newsTop(int startPage, int endPage) { //新闻统计键 //String newsStaKey= "newsSta:"+DateUtils.dateToString(new Date(),"yyyyMMdd"); String newsStaKey = "newsSta:" + "20210123"; //新闻前30排名键 //String newsTopKey= "newsSta:"+DateUtils.dateToString(new Date(),"yyyyMMdd"); String newsTopKey = "newsTop:" + "20210123"; Set ZSetOperations.TypedTuple Object set = redisService.reverseRangeWithScores(newsTopKey, startPage, endPage); Map String, Object m = new HashMap String, Object m.put("data", set); m.put("size", set.size()); //新闻排行榜为空,也许现在正在添加数据,先查询新闻统计键。 if (set == null || set.size() == 0) { //查询前30的信息(Interface Comparable T :该接口对实现它的每个类的对象强加一个整体排序。) Set ZSetOperations.TypedTuple Object set2 = redisService.reverseRangeWithScores(newsStaKey, startPage, endPage); m.put("data", set); m.put("size", set.size()); Map String, Object map = new HashMap (); map.put("data", m); map.put("code", 0); return map; }

 

工具类


package com.shoppingcart.utils;

import java.text.SimpleDateFormat;

import java.util.Date;

public class DateUtils {

 // 日期转字符串,返回指定的格式

 public static String dateToString(Date date, String dateFormat) {

 SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);

 return sdf.format(date);

}

import com.alibaba.fastjson.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.connection.RedisZSetCommands; import org.springframework.data.redis.connection.SortParameters; import org.springframework.data.redis.core.DefaultTypedTuple; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ZSetOperations; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import org.w3c.dom.ranges.Range; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; @Service public class RedisService { @Autowired private RedisTemplate String, Object redisTemplate; // =============================common============================ * 指定缓存失效时间 * @param key 键 * @param time 时间(秒) * @return public boolean expire(String key, long time) { try { if (time 0) { redisTemplate.expire(key, time, TimeUnit.SECONDS); return true; } catch (Exception e) { e.printStackTrace(); return false; * 根据key 获取过期时间 * @param key 键 不能为null * @return 时间(秒) 返回0代表为永久有效 public long getExpire(String key) { return redisTemplate.getExpire(key, TimeUnit.SECONDS); * 判断key是否存在 * @param key 键 * @return true 存在 false不存在 public boolean hasKey(String key) { try { return redisTemplate.hasKey(key); } catch (Exception e) { e.printStackTrace(); return false; * 删除缓存 * @param key 可以传一个值 或多个 @SuppressWarnings("unchecked") public void del(String... key) { if (key != null key.length 0) { if (key.length == 1) { redisTemplate.delete(key[0]); } else { List String list = new ArrayList (Arrays.asList(key)); redisTemplate.delete(list); * 删除缓存 * @param keys 可以传一个值 或多个 @SuppressWarnings("unchecked") public void del(Collection keys) { if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(keys)) { redisTemplate.delete(keys); // ============================String============================= * 普通缓存获取 * @param key 键 * @return 值 public Object get(String key) { return key == null null : redisTemplate.opsForValue().get(key); * 普通缓存放入 * @param key 键 * @param value 值 * @return true成功 false失败 public boolean set(String key, Object value) { try { redisTemplate.opsForValue().set(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; * 普通缓存放入并设置时间 * @param key 键 * @param value 值 * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期 * @return true成功 false 失败 public boolean set(String key, Object value, long time) { try { if (time 0) { redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); } else { set(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; * 递增 * @param key 键 * @param delta 要增加几(大于0) * @return public long incr(String key, long delta) { if (delta 0) { throw new RuntimeException("递增因子必须大于0"); return redisTemplate.opsForValue().increment(key, delta); * 递减 * @param key 键 * @param delta 要减少几(小于0) * @return public long decr(String key, long delta) { if (delta 0) { throw new RuntimeException("递减因子必须大于0"); return redisTemplate.opsForValue().increment(key, -delta); // ================================Hash================================= * HashGet * @param key 键 不能为null * @param item 项 不能为null * @return 值 public Object hget(String key, String item) { return redisTemplate.opsForHash().get(key, item); * 获取hashKey对应的所有键值 * @param key 键 * @return 对应的多个键值 public Map Object, Object hmget(String key) { Map Object, Object entries = redisTemplate.opsForHash().entries(key); return entries; * HashSet * @param key 键 * @param map 对应多个键值 * @return true 成功 false 失败 public boolean hmset(String key, Map String, Object map) { try { redisTemplate.opsForHash().putAll(key, map); return true; } catch (Exception e) { e.printStackTrace(); return false; * HashSet 并设置时间 * @param key 键 * @param map 对应多个键值 * @param time 时间(秒) * @return true成功 false失败 public boolean hmset(String key, Map String, Object map, long time) { try { redisTemplate.opsForHash().putAll(key, map); if (time 0) { expire(key, time); return true; } catch (Exception e) { e.printStackTrace(); return false; * 向一张hash表中放入数据,如果不存在则不添加。 * @param key 键 * @param item 项 * @param value 值 * @return true 成功 false失败 public boolean hsetnx(String key, String item, Object value) { try { Boolean success = redisTemplate.opsForHash().putIfAbsent(key, item, value); return success; } catch (Exception e) { e.printStackTrace(); return false; * 向一张hash表中放入数据,如果存在就覆盖原来的值。 * @param key 键 * @param item 项 * @param value 值 * @return true 成功 false失败 public boolean hset(String key, String item, Object value) { try { redisTemplate.opsForHash().put(key, item, value); return true; } catch (Exception e) { e.printStackTrace(); return false; * 向一张hash表中放入数据,如果存在就覆盖原来的值。 * @param key 键 * @param item 项 * @param value 值 * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间 * @return true 成功 false失败 public boolean hset(String key, String item, Object value, long time) { try { redisTemplate.opsForHash().put(key, item, value); if (time 0) { expire(key, time); return true; } catch (Exception e) { e.printStackTrace(); return false; * 删除hash表中的值 * @param key 键 不能为null * @param item 项 可以使多个 不能为null * 返回被删除的数量 public Long hdel(String key, Object... item) { return redisTemplate.opsForHash().delete(key, item); * 删除hash表中的值 * @param key 键 不能为null * @param items 项 可以使多个 不能为null public void hdel(String key, Collection items) { redisTemplate.opsForHash().delete(key, items.toArray()); * 判断hash表中是否有该项的值 * @param key 键 不能为null * @param item 项 不能为null * @return true 存在 false不存在 public boolean hHasKey(String key, String item) { return redisTemplate.opsForHash().hasKey(key, item); * hash数据类型:给元素一个增量 如果不存在,就会创建一个 并把新增后的值返回 * @param key 键 * @param item 项 * @param delta 要增加几(大于0) * @return public double hincr(String key, String item, double delta) { return redisTemplate.opsForHash().increment(key, item, delta); // ============================set============================= * 根据key获取Set中的所有值 * @param key 键 * @return public Set Object sGet(String key) { try { return redisTemplate.opsForSet().members(key); } catch (Exception e) { e.printStackTrace(); return null; * 根据value从一个set中查询,是否存在 * @param key 键 * @param value 值 * @return true 存在 false不存在 public boolean sHasKey(String key, Object value) { try { return redisTemplate.opsForSet().isMember(key, value); } catch (Exception e) { e.printStackTrace(); return false; * 将数据放入set缓存 * @param key 键 * @param values 值 可以是多个 * @return 成功个数 public long sSet(String key, Object... values) { try { return redisTemplate.opsForSet().add(key, values); } catch (Exception e) { e.printStackTrace(); return 0; * 将数据放入set缓存 * @param key 键 * @param values 值 可以是多个 * @return 成功个数 public long sSet(String key, Collection values) { try { return redisTemplate.opsForSet().add(key, values.toArray()); } catch (Exception e) { e.printStackTrace(); return 0; * 将set数据放入缓存 * @param key 键 * @param time 时间(秒) * @param values 值 可以是多个 * @return 成功个数 public long sSetAndTime(String key, long time, Object... values) { try { Long count = redisTemplate.opsForSet().add(key, values); if (time 0) expire(key, time); return count; } catch (Exception e) { e.printStackTrace(); return 0; * 获取set缓存的长度 * @param key 键 * @return public long sGetSetSize(String key) { try { return redisTemplate.opsForSet().size(key); } catch (Exception e) { e.printStackTrace(); return 0; * 移除值为value的 * @param key 键 * @param values 值 可以是多个 * @return 移除的个数 public long setRemove(String key, Object... values) { try { Long count = redisTemplate.opsForSet().remove(key, values); return count; } catch (Exception e) { e.printStackTrace(); return 0; // ===============================list================================= * 获取list缓存的内容 * @param key 键 * @param start 开始 * @param end 结束 0 到 -1代表所有值 * @return public List Object lGet(String key, long start, long end) { try { return redisTemplate.opsForList().range(key, start, end); } catch (Exception e) { e.printStackTrace(); return null; * 获取list缓存的长度 * @param key 键 * @return public long lGetListSize(String key) { try { return redisTemplate.opsForList().size(key); } catch (Exception e) { e.printStackTrace(); return 0; * 通过索引 获取list中的值 * @param key 键 * @param index 索引 index =0时, 0 表头,1 第二个元素,依次类推;index 0时,-1,表尾,-2倒数第二个元素,依次类推 * @return public Object lGetIndex(String key, long index) { try { return redisTemplate.opsForList().index(key, index); } catch (Exception e) { e.printStackTrace(); return null; * 将list放入缓存 * @param key 键 * @param value 值 * @return public boolean lSet(String key, Object value) { try { redisTemplate.opsForList().rightPush(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; * 将list放入缓存 * @param key 键 * @param value 值 * @param time 时间(秒) * @return public boolean lSet(String key, Object value, long time) { try { redisTemplate.opsForList().rightPush(key, value); if (time 0) expire(key, time); return true; } catch (Exception e) { e.printStackTrace(); return false; * 将list放入缓存 * @param key 键 * @param value 值 * @return public boolean lSet(String key, List Object value) { try { redisTemplate.opsForList().rightPushAll(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; * 将list放入缓存 * @param key 键 * @param value 值 * @param time 时间(秒) * @return public boolean lSet(String key, List Object value, long time) { try { redisTemplate.opsForList().rightPushAll(key, value); if (time 0) expire(key, time); return true; } catch (Exception e) { e.printStackTrace(); return false; * 根据索引修改list中的某条数据 * @param key 键 * @param index 索引 * @param value 值 * @return public boolean lUpdateIndex(String key, long index, Object value) { try { redisTemplate.opsForList().set(key, index, value); return true; } catch (Exception e) { e.printStackTrace(); return false; * 移除N个值为value * @param key 键 * @param count 移除多少个 * @param value 值 * @return 移除的个数 public long lRemove(String key, long count, Object value) { try { Long remove = redisTemplate.opsForList().remove(key, count, value); return remove; } catch (Exception e) { e.printStackTrace(); return 0; // ===============================Zset================================= * 给key键的value增加value分数,没有则会创建。 * @param key 键 * @param value 值 * @param score 分数 public Double incrementScore(String key, String value, double score) { //Boolean add = redisTemplate.boundZSetOps(key).add(value, score); Double add = redisTemplate.boundZSetOps(key).incrementScore(value, score); return add; * 获得指定Zset元素的分数 * @param key * @param value * @return public Double score(String key, String value) { Double score = redisTemplate.boundZSetOps(key).score(value); return score; * 升序查询key集合内[endTop,startTop]如果是负数表示倒数 * endTop=-1,startTop=0表示获取所有数据。 * @param key * @param startPage * @param endPage public Set ZSetOperations.TypedTuple Object rangeWithScores(String key, int startPage, int endPage) { Set ZSetOperations.TypedTuple Object set = redisTemplate.boundZSetOps(key).rangeWithScores(startPage, endPage); return set; * 降序查询key集合内[endTop,startTop],如果是负数表示倒数 * endTop=-1,startTop=0表示获取所有数据。 * @param key * @param startPage * @param endPage public Set ZSetOperations.TypedTuple Object reverseRangeWithScores(String key, int startPage, int endPage) { Set ZSetOperations.TypedTuple Object set = redisTemplate.boundZSetOps(key).reverseRangeWithScores(startPage, endPage); return set; * 批量新增数据 * @param key * @param set * @return public Long zsetAdd(String key, Set set) { Long add = redisTemplate.boundZSetOps(key).add(set); return add; * 删除指定键的指定下标范围数据 * @param key * @param startPage * @param endPage public Long zsetRemoveRange(String key, int startPage, int endPage) { Long l = redisTemplate.boundZSetOps(key).removeRange(startPage, endPage); return l; * 删除指定键的指定值 * @param key * @param value public Long zsetRemove(String key, String value) { Long remove = redisTemplate.boundZSetOps(key).remove(value); return remove;

到此这篇关于Redis实战之百度首页新闻热榜的文章就介绍到这了,更多相关Redis百度首页新闻热榜内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!


我想要获取技术服务或软件
服务范围:MySQL、ORACLE、SQLSERVER、MongoDB、PostgreSQL 、程序问题
服务方式:远程服务、电话支持、现场服务,沟通指定方式服务
技术标签:数据恢复、安装配置、数据迁移、集群容灾、异常处理、其它问题

本站部分文章参考或来源于网络,如有侵权请联系站长。
数据库远程运维 Redis实战之百度首页新闻热榜的实现代码