现有如下要求,模拟博客系统中展示本周热议文章;现实体类、数据层、控制层都已书写完毕,需将业务补全。 文章Post实体如下: @Data @Accessors(chain = true) @TableName("m_post") public class Post implements Serializable { private static final long serialVersionUID = 1L; @TableId(value = "id", type = IdType.AUTO) private Long id; private Date created; private Date modified; /** * 标题 */ @NotBlank(message = "标题不能为空") private String title; /** * 内容 */ @NotBlank(message = "内容不能为空") private String content; @NotNull(message = "分类不能为空") private Long categoryId; /** * 评论数量 */ private Integer commentCount; //其他省略 } PostMapper 数据层接口如下,注意,使用的是mybatis-plus: @Component public interface PostMapper extends BaseMapper<Post> { } 现需将业务操作补全: @Service public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements PostService { @Autowired private RedisTemplate redisTemplate; /** * 本周热议初始化 */ @Override public void initWeekRank() { // 数据库查询获取最近7天发表的文章 // 初始化文章的总评论量,按照评论数量倒序将文章信息缓存到redis中, // 其中key值为文章id,value为文章对象,并设置7天后自动过期,注意有效时间的//计算 } }
时间: 2024-01-29 13:03:43 浏览: 32
实现本周热议文章的业务操作可以按照以下步骤进行:
1. 获取最近7天发表的文章
可以使用PostMapper中的selectList方法,结合LambdaQueryWrapper条件构造器查询最近7天发表的文章,具体实现如下:
```
LocalDate now = LocalDate.now();
LocalDate lastWeek = now.minusDays(7);
List<Post> posts = baseMapper.selectList(new LambdaQueryWrapper<Post>()
.gt(Post::getCreated, lastWeek)
.orderByDesc(Post::getCommentCount));
```
2. 初始化文章的总评论量
对于获取到的文章列表,需要进行评论数量的统计,可以使用MyBatis-Plus中的@Sql注解实现:
```
@Sql("update m_post set comment_count = (select count(*) from m_comment where post_id = #{id}) where id = #{id}")
void updateCommentCount(@Param("id") Long id);
```
在获取到文章列表后,需要遍历列表,并对每篇文章的评论数量进行统计,并更新到数据库中,具体实现如下:
```
for (Post post : posts) {
post.setCommentCount(commentService.getCommentCountByPostId(post.getId()));
baseMapper.updateById(post);
}
```
3. 将文章信息缓存到Redis中
对于获取到的文章列表,需要将其按照评论数量倒序排序,并将文章信息缓存到Redis中,具体实现如下:
```
String hotPostKey = "week:hot:post";
redisTemplate.delete(hotPostKey); //先删除之前的缓存
BoundListOperations<String, Post> boundListOps = redisTemplate.boundListOps(hotPostKey);
for (Post post : posts) {
boundListOps.rightPush(post);
}
boundListOps.expire(7, TimeUnit.DAYS); //设置缓存有效期为7天
```
以上就是实现本周热议文章的业务操作的具体步骤。