热帖排行
- 实现,在发帖、点赞、加精时将发生变化的帖子存入Redis中。再通过定时任务,每隔一定的时间,计算帖子的分数进行更新
- 新建PostScoreRefreshJob类进行处理
1.RedisKeyUtil
//帖子分数
public static String getPostScoreKey(){
return PREFIX_POST + SPLIT + "score";
}
2.处理Controller
DiscussPostController
//发布帖子
@RequestMapping(path = "/add", method = RequestMethod.POST)
@ResponseBody
public String addDiscussPost(String title, String content) {
User user = hostHolder.getUser();
if (user == null) {
return CommunityUtil.getJSONString(403, "你还没有登录哦!");
}
DiscussPost post = new DiscussPost();
post.setUserId(user.getId());
post.setTitle(title);
post.setContent(content);
post.setCreateTime(new Date());
discussPostService.addDiscussPost(post);
//在发布帖子时,异步地将帖子存到es中
//使用生产者生产事件
Event event = new Event()
.setTopic(TOPIC_PUBLISH)
.setEntityType(ENTITY_TYPE_POST)
.setEntityId(post.getId())
.setUserId(user.getId());
eventProducer.fireEvent(event);
//发布帖子时,也会有初始的分数,将其存在Redis
String redisKey = RedisKeyUtil.getPostScoreKey();
//选择set的原因:set中没有重复的数据,因此可保证我们不会存入多个重复的帖子,减少后面的计算量
redisTemplate.opsForSet().add(redisKey, post.getId());
//报错的情况,将来统一处理.
return CommunityUtil.getJSONString(0, "发布成功!");
}
//加精
@RequestMapping(path = "/wonderful", method = RequestMethod.POST)
@ResponseBody
public String setWonderful(int id) {
discussPostService.updateStatus(id, 1);
// 触发发帖事件
Event event = new Event()
.setTopic(TOPIC_PUBLISH)
.setUserId(hostHolder.getUser().getId())
.setEntityType(ENTITY_TYPE_POST)
.setEntityId(id);
eventProducer.fireEvent(event);
//帖子加精,会改变其分数,将其存在Redis
String redisKey = RedisKeyUtil.getPostScoreKey();
//选择set的原因:set中没有重复的数据,因此可保证我们不会存入多个重复的帖子,减少后面的计算量
redisTemplate.opsForSet().add(redisKey, id);
return CommunityUtil.getJSONString(0);
}
CommentController
//添加评论
@RequestMapping(path = "/add/{discussPostId}", method = RequestMethod.POST)
public String addComment(@PathVariable("discussPostId") int discussPostId, Comment comment){
//客户端表单中向服务器需要提交以下内容
/*
private int id;
private int userId;
private int entityType; //评论的类型,比如帖子的评论,评论用户评论的评论
private int entityId; //评论的帖子的id
private int targetId; //记录评论指向的人
private String content; //评论的内容
private int status; //表明状态,是否被拉黑
private Date createTime; //创建的时间*/
//其中 entityType entityId targetId content 需要表单中进行提交
/* comment.setId(user.getId());
String username = user.getUsername();
System.out.println(username);
model.addAttribute("username",username);*/
comment.setUserId(hostHolder.getUser().getId());
comment.setStatus(0);
comment.setCreateTime(new Date());
commentService.addComment(comment);
//当用户评论后,系统给发帖人或者发表评论的人发送信息
//1. 新建事件
//2. 设置各种参数
Event event = new Event()
.setTopic(TOPIC_COMMENT)
.setUserId(hostHolder.getUser().getId())
.setEntityType(comment.getEntityType())
.setEntityId(comment.getEntityId())
.setData("postId", discussPostId);
if (comment.getEntityType() == ENTITY_TYPE_POST) {
DiscussPost target = discussPostService.findDiscussPostById(comment.getEntityId());
event.setEntityUserId(target.getUserId());
} else if (comment.getEntityType() == ENTITY_TYPE_COMMENT) {
Comment target = commentService.findCommentById(comment.getEntityId());
event.setEntityUserId(target.getUserId());
}
eventProducer.fireEvent(event);
//添加帖子评论时,将评论添加至es
if (comment.getEntityType() == ENTITY_TYPE_POST) {
// 触发发帖事件
event = new Event()
.setTopic(TOPIC_PUBLISH)
.setUserId(comment.getUserId())
.setEntityType(ENTITY_TYPE_POST)
.setEntityId(discussPostId);
eventProducer.fireEvent(event);
//只有对帖子进行评论才会增加热度,将帖子存在Redis
String redisKey = RedisKeyUtil.getPostScoreKey();
//选择set的原因:set中没有重复的数据,可保证我们不会存入多个重复的帖子,减少后面的计算量
redisTemplate.opsForSet().add(redisKey, discussPostId);
}
//添加成功后,重定向至帖子详情页
return "redirect:/discuss/detail/" + discussPostId;
}
}
LikeController
if (entityType == ENTITY_TYPE_POST){
//对帖子点赞,将帖子存在Redis
String redisKey = RedisKeyUtil.getPostScoreKey();
//选择set的原因:set中没有重复的数据,可保证我们不会存入多个重复的帖子,减少后面的计算量
redisTemplate.opsForSet().add(redisKey, postId);
}
3.定时任务
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.RedisTemplate;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class PostScoreRefreshJob implements Job, CommunityConstant {
private static final Logger logger = LoggerFactory.getLogger(PostScoreRefreshJob.class);
// 从Redis中取出需要查询的帖子
@Autowired
private RedisTemplate redisTemplate;
// 帖子
@Autowired
private DiscussPostService discussPostService;
// 点赞
@Autowired
private LikeService likeService;
// 同步回Elasticsearch
@Autowired
private ElasticsearchService elasticsearchService;
//初始化论坛创建时间
private static final Date epoch;
static {
try {
epoch = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2020-10-1 00:00:00");
} catch (ParseException e) {
throw new RuntimeException("初始化论坛创建时间失败"+e);
}
}
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
//实现定时任务
//1. 从Redis中取出需要重新计算分数的帖子
String redisKey = RedisKeyUtil.getPostScoreKey();
//boundSetOps获取了一个指定操作对象(key)的operator
BoundSetOperations operations = redisTemplate.boundSetOps(redisKey);
if (operations.size()==0){
logger.info("任务取消,没有需要刷新帖子");
return;
}
// 处理之前记录日志
logger.info("[任务开始] 正在刷新帖子分数."+"共有"+operations.size()+"帖子需要刷新");
while (operations.size() > 0){
//刷新分数, operations.pop()默认为Object
this.refresh((Integer) operations.pop());
}
logger.info("[任务结束] 已完成刷新帖子分数.");
}
private void refresh(int postId) {
// 查询帖子
DiscussPost post = discussPostService.findDiscussPostById(postId);
// 帖子不存在
if (post == null) {
logger.error("该帖子不存在: id = " + postId);
return;
}
// 是否加精 加75分
boolean wonderful = post.getStatus() == 1;
// 评论数量
int commentCount = post.getCommentCount();
// 点赞数量
long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, postId);
// 计算权重
double w = (wonderful ? 75 : 0) + commentCount * 10 + likeCount * 2;
// 分数 = 帖子权重 + 距离天数
// Math.max(w, 1):防止w<0
double score = Math.log10(Math.max(w, 1))
+ (post.getCreateTime().getTime() - epoch.getTime()) / (1000 * 3600 * 24);
// 更新帖子分数
discussPostService.updateScore(postId, score);
// 同步搜索数据
post.setScore(score);
elasticsearchService.saveDiscussPost(post);
}
}
4.配置定时 QuartzConfig
// 刷新帖子分数任务
@Bean
public JobDetailFactoryBean postScoreRefreshJobDetail() {
JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();
factoryBean.setJobClass(PostScoreRefreshJob.class);
factoryBean.setName("postScoreRefreshJob");
factoryBean.setGroup("communityJobGroup");
factoryBean.setDurability(true);
factoryBean.setRequestsRecovery(true);
return factoryBean;
}
@Bean
public SimpleTriggerFactoryBean postScoreRefreshTrigger(JobDetail postScoreRefreshJobDetail) {
SimpleTriggerFactoryBean factoryBean = new SimpleTriggerFactoryBean();
factoryBean.setJobDetail(postScoreRefreshJobDetail);
factoryBean.setName("postScoreRefreshTrigger");
factoryBean.setGroup("communityTriggerGroup");
factoryBean.setRepeatInterval(1000 * 60 * 60); //60min刷新一次分数
factoryBean.setJobDataMap(new JobDataMap());
return factoryBean;
}
5.修改展示页面
点击最热,按照分数进行排序
index.html
<div class="position-relative">
<!-- 筛选条件 -->
<ul class="nav nav-tabs mb-3">
<li class="nav-item">
<a th:class="|nav-link ${orderMode==0?'active':''}|" th:href="@{/index(orderMode=0)}">最新</a>
</li>
<li class="nav-item">
<a th:class="|nav-link ${orderMode==1?'active':''}|" th:href="@{/index(orderMode=1)}">最热</a>
</li>
</ul>
<button type="button" class="btn btn-primary btn-sm position-absolute rt-0"
data-toggle="modal" data-target="#publishModal" th:if="${loginUser!=null}">我要发布
</button>
</div>
修改DiscussPostMapper的selectDiscussPosts方法,同时修改调用该方法的地方
@Mapper
public interface DiscussPostMapper {
// 增加orderMode,当orderMode=0按照类型、创建时间排序
// 当orderMode=1按照类型、分数、创建时间排序
List<DiscussPost> selectDiscussPosts(int userId, int offset, int limit, int orderMode);
}
discuss-post.xml
<select id="selectDiscussPosts" resultType="DiscussPost">
select <include refid="selectFields"></include>
from discuss_post
where status != 2
<if test="userId!=0">
and user_id = #{userId}
</if>
<if test="orderMode==0">
order by type desc, create_time desc
</if>
<if test="orderMode==1">
order by type desc, score desc, create_time desc
</if>
limit #{offset}, #{limit}
</select>
HomeController
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
public class HomeController implements CommunityConstant {
@Autowired
private DiscussPostService discussPostService;
@Autowired
private UserService userService;
@Autowired
private LikeService likeService;
@RequestMapping(path = "/index", method = RequestMethod.GET)
public String getIndexPage(Model model, Page page,
@RequestParam(name = "orderMode", defaultValue = "0") int orderMode) {
// 方法调用前, SpringMVC会自动实例化Model和Page, 并将Page注入Model.
// 所以, 在thymeleaf中可以直接访问Page对象中的数据.
page.setRows(discussPostService.findDiscussPostRows(0));
page.setPath("/index?orderMode=" + orderMode);
List<DiscussPost> list = discussPostService
.findDiscussPosts(0, page.getOffset(), page.getLimit(), orderMode);
List<Map<String, Object>> discussPosts = new ArrayList<>();
if (list != null) {
for (DiscussPost post : list) {
Map<String, Object> map = new HashMap<>();
map.put("post", post);
User user = userService.findUserById(post.getUserId());
map.put("user", user);
long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getId());
map.put("likeCount", likeCount);
discussPosts.add(map);
}
}
model.addAttribute("discussPosts", discussPosts);
model.addAttribute("orderMode", orderMode);
return "/index";
}
@RequestMapping(path = "/error", method = RequestMethod.GET)
public String getErrorPage() {
return "/error/500";
}
@RequestMapping(path = "/denied", method = RequestMethod.GET)
public String getDeniedPage() {
return "/error/404";
}
}
index.html
<!-- 筛选条件 -->
<ul class="nav nav-tabs mb-3">
<li class="nav-item">
<a th:class="|nav-link ${orderMode==0?'active':''}|" th:href="@{/index(orderMode=0)}">最新</a>
</li>
<li class="nav-item">
<a th:class="|nav-link ${orderMode==1?'active':''}|" th:href="@{/index(orderMode=1)}">最热</a>
</li>
</ul>
362



被折叠的 条评论
为什么被折叠?



