前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >点赞模块设计 - Redis缓存 + 定时写入数据库实现高性能点赞功能

点赞模块设计 - Redis缓存 + 定时写入数据库实现高性能点赞功能

作者头像
solocoder
发布2022-04-06 13:00:00
1.9K0
发布2022-04-06 13:00:00
举报
文章被收录于专栏:大前端客栈

源码地址:https://github.com/cachecats/coderiver

点赞是作为整个系统的一个小模块,代码在 user-service 用户服务下。

本文基于 SpringCloud, 用户发起点赞、取消点赞后先存入 Redis 中,再每隔两小时从 Redis 读取点赞数据写入数据库中做持久化存储。

点赞功能在很多系统中都有,但别看功能小,想要做好需要考虑的东西还挺多的。

点赞、取消点赞是高频次的操作,若每次都读写数据库,大量的操作会影响数据库性能,所以需要做缓存。

至于多久从 Redis 取一次数据存到数据库中,根据项目的实际情况定吧,我是暂时设了两个小时。

项目需求需要查看都谁点赞了,所以要存储每个点赞的点赞人、被点赞人,不能简单的做计数。

文章分四部分介绍:

  • Redis 缓存设计及实现
  • 数据库设计
  • 数据库操作
  • 开启定时任务持久化存储到数据库

一、Redis 缓存设计及实现

1.1 Redis 安装及运行

Redis 安装请自行查阅相关教程。

说下Docker 安装运行 Redis

代码语言:javascript
复制
docker run -d -p 6379:6379 redis:4.0.8

如果已经安装了 Redis,打开命令行,输入启动 Redis 的命令

代码语言:javascript
复制
redis-server

1.2 Redis 与 SpringBoot 项目的整合

  1. pom.xml 中引入依赖
代码语言:javascript
复制
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
  1. 在启动类上添加注释 @EnableCaching
代码语言:javascript
复制
@SpringBootApplication
@EnableDiscoveryClient
@EnableSwagger2
@EnableFeignClients(basePackages = "com.solo.coderiver.project.client")
@EnableCaching
public class UserApplication {

<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
    SpringApplication.run(UserApplication.class, args);
}

}
  1. 编写 Redis 配置类 RedisConfig
代码语言:javascript
复制
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

import java.net.UnknownHostException;
@Configuration
public class RedisConfig {
<span class="hljs-meta">@Bean</span>
<span class="hljs-meta">@ConditionalOnMissingBean</span>(name = <span class="hljs-string">"redisTemplate"</span>)
<span class="hljs-function"><span class="hljs-keyword">public</span> RedisTemplate&lt;String, Object&gt; <span class="hljs-title">redisTemplate</span><span class="hljs-params">(
        RedisConnectionFactory redisConnectionFactory)</span>
        <span class="hljs-keyword">throws</span> UnknownHostException </span>{

    Jackson2JsonRedisSerializer&lt;Object&gt; jackson2JsonRedisSerializer = <span class="hljs-keyword">new</span> Jackson2JsonRedisSerializer&lt;Object&gt;(Object.class);
    ObjectMapper om = <span class="hljs-keyword">new</span> ObjectMapper();
    om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    jackson2JsonRedisSerializer.setObjectMapper(om);

    RedisTemplate&lt;String, Object&gt; template = <span class="hljs-keyword">new</span> RedisTemplate&lt;String, Object&gt;();
    template.setConnectionFactory(redisConnectionFactory);
    template.setKeySerializer(jackson2JsonRedisSerializer);
    template.setValueSerializer(jackson2JsonRedisSerializer);
    template.setHashKeySerializer(jackson2JsonRedisSerializer);
    template.setHashValueSerializer(jackson2JsonRedisSerializer);
    template.afterPropertiesSet();
    <span class="hljs-keyword">return</span> template;
}


<span class="hljs-meta">@Bean</span>
<span class="hljs-meta">@ConditionalOnMissingBean</span>(StringRedisTemplate.class)
<span class="hljs-function"><span class="hljs-keyword">public</span> StringRedisTemplate <span class="hljs-title">stringRedisTemplate</span><span class="hljs-params">(
        RedisConnectionFactory redisConnectionFactory)</span>
        <span class="hljs-keyword">throws</span> UnknownHostException </span>{
    StringRedisTemplate template = <span class="hljs-keyword">new</span> StringRedisTemplate();
    template.setConnectionFactory(redisConnectionFactory);
    <span class="hljs-keyword">return</span> template;
}

}

至此 Redis 在 SpringBoot 项目中的配置已经完成,可以愉快的使用了。

1.3 Redis 的数据结构类型

Redis 可以存储键与5种不同数据结构类型之间的映射,这5种数据结构类型分别为String(字符串)、List(列表)、Set(集合)、Hash(散列)和 Zset(有序集合)。

下面来对这5种数据结构类型作简单的介绍:

结构类型

结构存储的值

结构的读写能力

String

可以是字符串、整数或者浮点数

对整个字符串或者字符串的其中一部分执行操作;对象和浮点数执行自增(increment)或者自减(decrement)

List

一个链表,链表上的每个节点都包含了一个字符串

从链表的两端推入或者弹出元素;根据偏移量对链表进行修剪(trim);读取单个或者多个元素;根据值来查找或者移除元素

Set

包含字符串的无序收集器(unorderedcollection),并且被包含的每个字符串都是独一无二的、各不相同

添加、获取、移除单个元素;检查一个元素是否存在于某个集合中;计算交集、并集、差集;从集合里卖弄随机获取元素

Hash

包含键值对的无序散列表

添加、获取、移除单个键值对;获取所有键值对

Zset

字符串成员(member)与浮点数分值(score)之间的有序映射,元素的排列顺序由分值的大小决定

添加、获取、删除单个元素;根据分值范围(range)或者成员来获取元素

1.4 点赞数据在 Redis 中的存储格式

用 Redis 存储两种数据,一种是记录点赞人、被点赞人、点赞状态的数据,另一种是每个用户被点赞了多少次,做个简单的计数。

由于需要记录点赞人和被点赞人,还有点赞状态(点赞、取消点赞),还要固定时间间隔取出 Redis 中所有点赞数据,分析了下 Redis 数据格式中 Hash 最合适。

因为 Hash 里的数据都是存在一个键里,可以通过这个键很方便的把所有的点赞数据都取出。这个键里面的数据还可以存成键值对的形式,方便存入点赞人、被点赞人和点赞状态。

设点赞人的 id 为 likedPostId,被点赞人的 id 为 likedUserId ,点赞时状态为 1,取消点赞状态为 0。将点赞人 id 和被点赞人 id 作为键,两个 id 中间用 :: 隔开,点赞状态作为值。

所以如果用户点赞,存储的键为:likedUserId::likedPostId,对应的值为 1 。

取消点赞,存储的键为:likedUserId::likedPostId,对应的值为 0 。

取数据时把键用 :: 切开就得到了两个id,也很方便。

在可视化工具 RDM 中看到的是这样子

1.5 操作 Redis

Redis 各种数据格式的操作方法可以看看 这篇文章 ,写的非常好。

将具体操作方法封装到了 RedisService 接口里

RedisService.java

代码语言:javascript
复制
import com.solo.coderiver.user.dataobject.UserLike;
import com.solo.coderiver.user.dto.LikedCountDTO;

import java.util.List;
public interface RedisService {
<span class="hljs-comment">/**
 * 点赞。状态为1
 * <span class="hljs-doctag">@param</span> likedUserId
 * <span class="hljs-doctag">@param</span> likedPostId
 */</span>
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">saveLiked2Redis</span><span class="hljs-params">(String likedUserId, String likedPostId)</span></span>;

<span class="hljs-comment">/**
 * 取消点赞。将状态改变为0
 * <span class="hljs-doctag">@param</span> likedUserId
 * <span class="hljs-doctag">@param</span> likedPostId
 */</span>
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">unlikeFromRedis</span><span class="hljs-params">(String likedUserId, String likedPostId)</span></span>;

<span class="hljs-comment">/**
 * 从Redis中删除一条点赞数据
 * <span class="hljs-doctag">@param</span> likedUserId
 * <span class="hljs-doctag">@param</span> likedPostId
 */</span>
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">deleteLikedFromRedis</span><span class="hljs-params">(String likedUserId, String likedPostId)</span></span>;

<span class="hljs-comment">/**
 * 该用户的点赞数加1
 * <span class="hljs-doctag">@param</span> likedUserId
 */</span>
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">incrementLikedCount</span><span class="hljs-params">(String likedUserId)</span></span>;

<span class="hljs-comment">/**
 * 该用户的点赞数减1
 * <span class="hljs-doctag">@param</span> likedUserId
 */</span>
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">decrementLikedCount</span><span class="hljs-params">(String likedUserId)</span></span>;

<span class="hljs-comment">/**
 * 获取Redis中存储的所有点赞数据
 * <span class="hljs-doctag">@return</span>
 */</span>
<span class="hljs-function">List&lt;UserLike&gt; <span class="hljs-title">getLikedDataFromRedis</span><span class="hljs-params">()</span></span>;

<span class="hljs-comment">/**
 * 获取Redis中存储的所有点赞数量
 * <span class="hljs-doctag">@return</span>
 */</span>
<span class="hljs-function">List&lt;LikedCountDTO&gt; <span class="hljs-title">getLikedCountFromRedis</span><span class="hljs-params">()</span></span>;

}

实现类 RedisServiceImpl.java

代码语言:javascript
复制
import com.solo.coderiver.user.dataobject.UserLike;
import com.solo.coderiver.user.dto.LikedCountDTO;
import com.solo.coderiver.user.enums.LikedStatusEnum;
import com.solo.coderiver.user.service.LikedService;
import com.solo.coderiver.user.service.RedisService;
import com.solo.coderiver.user.utils.RedisKeyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Service
@Slf4j
public class RedisServiceImpl implements RedisService {
<span class="hljs-meta">@Autowired</span>
RedisTemplate redisTemplate;

<span class="hljs-meta">@Autowired</span>
LikedService likedService;

<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">saveLiked2Redis</span><span class="hljs-params">(String likedUserId, String likedPostId)</span> </span>{
    String key = RedisKeyUtils.getLikedKey(likedUserId, likedPostId);
    redisTemplate.opsForHash().put(RedisKeyUtils.MAP_KEY_USER_LIKED, key, LikedStatusEnum.LIKE.getCode());
}

<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">unlikeFromRedis</span><span class="hljs-params">(String likedUserId, String likedPostId)</span> </span>{
    String key = RedisKeyUtils.getLikedKey(likedUserId, likedPostId);
    redisTemplate.opsForHash().put(RedisKeyUtils.MAP_KEY_USER_LIKED, key, LikedStatusEnum.UNLIKE.getCode());
}

<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">deleteLikedFromRedis</span><span class="hljs-params">(String likedUserId, String likedPostId)</span> </span>{
    String key = RedisKeyUtils.getLikedKey(likedUserId, likedPostId);
    redisTemplate.opsForHash().delete(RedisKeyUtils.MAP_KEY_USER_LIKED, key);
}

<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">incrementLikedCount</span><span class="hljs-params">(String likedUserId)</span> </span>{
    redisTemplate.opsForHash().increment(RedisKeyUtils.MAP_KEY_USER_LIKED_COUNT, likedUserId, <span class="hljs-number">1</span>);
}

<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">decrementLikedCount</span><span class="hljs-params">(String likedUserId)</span> </span>{
    redisTemplate.opsForHash().increment(RedisKeyUtils.MAP_KEY_USER_LIKED_COUNT, likedUserId, -<span class="hljs-number">1</span>);
}

<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> List&lt;UserLike&gt; <span class="hljs-title">getLikedDataFromRedis</span><span class="hljs-params">()</span> </span>{
    Cursor&lt;Map.Entry&lt;Object, Object&gt;&gt; cursor = redisTemplate.opsForHash().scan(RedisKeyUtils.MAP_KEY_USER_LIKED, ScanOptions.NONE);
    List&lt;UserLike&gt; list = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();
    <span class="hljs-keyword">while</span> (cursor.hasNext()){
        Map.Entry&lt;Object, Object&gt; entry = cursor.next();
        String key = (String) entry.getKey();
        <span class="hljs-comment">//分离出 likedUserId,likedPostId</span>
        String[] split = key.split(<span class="hljs-string">"::"</span>);
        String likedUserId = split[<span class="hljs-number">0</span>];
        String likedPostId = split[<span class="hljs-number">1</span>];
        Integer value = (Integer) entry.getValue();

        <span class="hljs-comment">//组装成 UserLike 对象</span>
        UserLike userLike = <span class="hljs-keyword">new</span> UserLike(likedUserId, likedPostId, value);
        list.add(userLike);

        <span class="hljs-comment">//存到 list 后从 Redis 中删除</span>
        redisTemplate.opsForHash().delete(RedisKeyUtils.MAP_KEY_USER_LIKED, key);
    }

    <span class="hljs-keyword">return</span> list;
}

<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> List&lt;LikedCountDTO&gt; <span class="hljs-title">getLikedCountFromRedis</span><span class="hljs-params">()</span> </span>{
    Cursor&lt;Map.Entry&lt;Object, Object&gt;&gt; cursor = redisTemplate.opsForHash().scan(RedisKeyUtils.MAP_KEY_USER_LIKED_COUNT, ScanOptions.NONE);
    List&lt;LikedCountDTO&gt; list = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();
    <span class="hljs-keyword">while</span> (cursor.hasNext()){
        Map.Entry&lt;Object, Object&gt; map = cursor.next();
        <span class="hljs-comment">//将点赞数量存储在 LikedCountDT</span>
        String key = (String)map.getKey();
        LikedCountDTO dto = <span class="hljs-keyword">new</span> LikedCountDTO(key, (Integer) map.getValue());
        list.add(dto);
        <span class="hljs-comment">//从Redis中删除这条记录</span>
        redisTemplate.opsForHash().delete(RedisKeyUtils.MAP_KEY_USER_LIKED_COUNT, key);
    }
    <span class="hljs-keyword">return</span> list;
}

}

用到的工具类和枚举类

RedisKeyUtils, 用于根据一定规则生成 key

代码语言:javascript
复制
public class RedisKeyUtils {

<span class="hljs-comment">//保存用户点赞数据的key</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> String MAP_KEY_USER_LIKED = <span class="hljs-string">"MAP_USER_LIKED"</span>;
<span class="hljs-comment">//保存用户被点赞数量的key</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> String MAP_KEY_USER_LIKED_COUNT = <span class="hljs-string">"MAP_USER_LIKED_COUNT"</span>;

<span class="hljs-comment">/**
 * 拼接被点赞的用户id和点赞的人的id作为key。格式 222222::333333
 * <span class="hljs-doctag">@param</span> likedUserId 被点赞的人id
 * <span class="hljs-doctag">@param</span> likedPostId 点赞的人的id
 * <span class="hljs-doctag">@return</span>
 */</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> String <span class="hljs-title">getLikedKey</span><span class="hljs-params">(String likedUserId, String likedPostId)</span></span>{
    StringBuilder builder = <span class="hljs-keyword">new</span> StringBuilder();
    builder.append(likedUserId);
    builder.append(<span class="hljs-string">"::"</span>);
    builder.append(likedPostId);
    <span class="hljs-keyword">return</span> builder.toString();
}

}

LikedStatusEnum 用户点赞状态的枚举类

代码语言:javascript
复制
package com.solo.coderiver.user.enums;

import lombok.Getter;
/**

用户点赞的状态

 */
@Getter
public enum LikedStatusEnum {
    LIKE(1, "点赞"),
    UNLIKE(0, "取消点赞/未点赞"),
    ;
<span class="hljs-keyword">private</span> Integer code;

<span class="hljs-keyword">private</span> String msg;

LikedStatusEnum(Integer code, String msg) {
    <span class="hljs-keyword">this</span>.code = code;
    <span class="hljs-keyword">this</span>.msg = msg;
}

}

二、数据库设计

数据库表中至少要包含三个字段:被点赞用户id,点赞用户id,点赞状态。再加上主键id,创建时间,修改时间就行了。

建表语句

代码语言:javascript
复制
create table `user_like`(
    `id` int not null auto_increment,
    `liked_user_id` varchar(32) not null comment '被点赞的用户id',
    `liked_post_id` varchar(32) not null comment '点赞的用户id',
    `status` tinyint(1) default '1' comment '点赞状态,0取消,1点赞',
    `create_time` timestamp not null default current_timestamp comment '创建时间',
  `update_time` timestamp not null default current_timestamp on update current_timestamp comment '修改时间',
    primary key(`id`),
    INDEX `liked_user_id`(`liked_user_id`),
    INDEX `liked_post_id`(`liked_post_id`)
) comment '用户点赞表';

对应的对象 UserLike

代码语言:javascript
复制
import com.solo.coderiver.user.enums.LikedStatusEnum;
import lombok.Data;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**

用户点赞表

 */
@Entity
@Data
public class UserLike {
<span class="hljs-comment">//主键id</span>
<span class="hljs-meta">@Id</span>
<span class="hljs-meta">@GeneratedValue</span>(strategy = GenerationType.IDENTITY)
<span class="hljs-keyword">private</span> Integer id;

<span class="hljs-comment">//被点赞的用户的id</span>
<span class="hljs-keyword">private</span> String likedUserId;

<span class="hljs-comment">//点赞的用户的id</span>
<span class="hljs-keyword">private</span> String likedPostId;

<span class="hljs-comment">//点赞的状态.默认未点赞</span>
<span class="hljs-keyword">private</span> Integer status = LikedStatusEnum.UNLIKE.getCode();

<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">UserLike</span><span class="hljs-params">()</span> </span>{
}

<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">UserLike</span><span class="hljs-params">(String likedUserId, String likedPostId, Integer status)</span> </span>{
    <span class="hljs-keyword">this</span>.likedUserId = likedUserId;
    <span class="hljs-keyword">this</span>.likedPostId = likedPostId;
    <span class="hljs-keyword">this</span>.status = status;
}

}

三、数据库操作

操作数据库同样封装在接口中

LikedService

代码语言:javascript
复制
import com.solo.coderiver.user.dataobject.UserLike;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.List;
public interface LikedService {
<span class="hljs-comment">/**
 * 保存点赞记录
 * <span class="hljs-doctag">@param</span> userLike
 * <span class="hljs-doctag">@return</span>
 */</span>
<span class="hljs-function">UserLike <span class="hljs-title">save</span><span class="hljs-params">(UserLike userLike)</span></span>;

<span class="hljs-comment">/**
 * 批量保存或修改
 * <span class="hljs-doctag">@param</span> list
 */</span>
<span class="hljs-function">List&lt;UserLike&gt; <span class="hljs-title">saveAll</span><span class="hljs-params">(List&lt;UserLike&gt; list)</span></span>;


<span class="hljs-comment">/**
 * 根据被点赞人的id查询点赞列表(即查询都谁给这个人点赞过)
 * <span class="hljs-doctag">@param</span> likedUserId 被点赞人的id
 * <span class="hljs-doctag">@param</span> pageable
 * <span class="hljs-doctag">@return</span>
 */</span>
<span class="hljs-function">Page&lt;UserLike&gt; <span class="hljs-title">getLikedListByLikedUserId</span><span class="hljs-params">(String likedUserId, Pageable pageable)</span></span>;

<span class="hljs-comment">/**
 * 根据点赞人的id查询点赞列表(即查询这个人都给谁点赞过)
 * <span class="hljs-doctag">@param</span> likedPostId
 * <span class="hljs-doctag">@param</span> pageable
 * <span class="hljs-doctag">@return</span>
 */</span>
<span class="hljs-function">Page&lt;UserLike&gt; <span class="hljs-title">getLikedListByLikedPostId</span><span class="hljs-params">(String likedPostId, Pageable pageable)</span></span>;

<span class="hljs-comment">/**
 * 通过被点赞人和点赞人id查询是否存在点赞记录
 * <span class="hljs-doctag">@param</span> likedUserId
 * <span class="hljs-doctag">@param</span> likedPostId
 * <span class="hljs-doctag">@return</span>
 */</span>
<span class="hljs-function">UserLike <span class="hljs-title">getByLikedUserIdAndLikedPostId</span><span class="hljs-params">(String likedUserId, String likedPostId)</span></span>;

<span class="hljs-comment">/**
 * 将Redis里的点赞数据存入数据库中
 */</span>
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">transLikedFromRedis2DB</span><span class="hljs-params">()</span></span>;

<span class="hljs-comment">/**
 * 将Redis中的点赞数量数据存入数据库
 */</span>
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">transLikedCountFromRedis2DB</span><span class="hljs-params">()</span></span>;

}

LikedServiceImpl 实现类

代码语言:javascript
复制
import com.solo.coderiver.user.dataobject.UserInfo;
import com.solo.coderiver.user.dataobject.UserLike;
import com.solo.coderiver.user.dto.LikedCountDTO;
import com.solo.coderiver.user.enums.LikedStatusEnum;
import com.solo.coderiver.user.repository.UserLikeRepository;
import com.solo.coderiver.user.service.LikedService;
import com.solo.coderiver.user.service.RedisService;
import com.solo.coderiver.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
@Slf4j
public class LikedServiceImpl implements LikedService {
<span class="hljs-meta">@Autowired</span>
UserLikeRepository likeRepository;

<span class="hljs-meta">@Autowired</span>
RedisService redisService;

<span class="hljs-meta">@Autowired</span>
UserService userService;

<span class="hljs-meta">@Override</span>
<span class="hljs-meta">@Transactional</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> UserLike <span class="hljs-title">save</span><span class="hljs-params">(UserLike userLike)</span> </span>{
    <span class="hljs-keyword">return</span> likeRepository.save(userLike);
}

<span class="hljs-meta">@Override</span>
<span class="hljs-meta">@Transactional</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> List&lt;UserLike&gt; <span class="hljs-title">saveAll</span><span class="hljs-params">(List&lt;UserLike&gt; list)</span> </span>{
    <span class="hljs-keyword">return</span> likeRepository.saveAll(list);
}

<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> Page&lt;UserLike&gt; <span class="hljs-title">getLikedListByLikedUserId</span><span class="hljs-params">(String likedUserId, Pageable pageable)</span> </span>{
    <span class="hljs-keyword">return</span> likeRepository.findByLikedUserIdAndStatus(likedUserId, LikedStatusEnum.LIKE.getCode(), pageable);
}

<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> Page&lt;UserLike&gt; <span class="hljs-title">getLikedListByLikedPostId</span><span class="hljs-params">(String likedPostId, Pageable pageable)</span> </span>{
    <span class="hljs-keyword">return</span> likeRepository.findByLikedPostIdAndStatus(likedPostId, LikedStatusEnum.LIKE.getCode(), pageable);
}

<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> UserLike <span class="hljs-title">getByLikedUserIdAndLikedPostId</span><span class="hljs-params">(String likedUserId, String likedPostId)</span> </span>{
    <span class="hljs-keyword">return</span> likeRepository.findByLikedUserIdAndLikedPostId(likedUserId, likedPostId);
}

<span class="hljs-meta">@Override</span>
<span class="hljs-meta">@Transactional</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">transLikedFromRedis2DB</span><span class="hljs-params">()</span> </span>{
    List&lt;UserLike&gt; list = redisService.getLikedDataFromRedis();
    <span class="hljs-keyword">for</span> (UserLike like : list) {
        UserLike ul = getByLikedUserIdAndLikedPostId(like.getLikedUserId(), like.getLikedPostId());
        <span class="hljs-keyword">if</span> (ul == <span class="hljs-keyword">null</span>){
            <span class="hljs-comment">//没有记录,直接存入</span>
            save(like);
        }<span class="hljs-keyword">else</span>{
            <span class="hljs-comment">//有记录,需要更新</span>
            ul.setStatus(like.getStatus());
            save(ul);
        }
    }
}

<span class="hljs-meta">@Override</span>
<span class="hljs-meta">@Transactional</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">transLikedCountFromRedis2DB</span><span class="hljs-params">()</span> </span>{
    List&lt;LikedCountDTO&gt; list = redisService.getLikedCountFromRedis();
    <span class="hljs-keyword">for</span> (LikedCountDTO dto : list) {
        UserInfo user = userService.findById(dto.getId());
        <span class="hljs-comment">//点赞数量属于无关紧要的操作,出错无需抛异常</span>
        <span class="hljs-keyword">if</span> (user != <span class="hljs-keyword">null</span>){
            Integer likeNum = user.getLikeNum() + dto.getCount();
            user.setLikeNum(likeNum);
            <span class="hljs-comment">//更新点赞数量</span>
            userService.updateInfo(user);
        }
    }
}

}

数据库的操作就这些,主要还是增删改查。

四、开启定时任务持久化存储到数据库

定时任务 Quartz 很强大,就用它了。

Quartz 使用步骤:

  1. 添加依赖
代码语言:javascript
复制
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
  1. 编写配置文件
代码语言:javascript
复制
package com.solo.coderiver.user.config;

import com.solo.coderiver.user.task.LikeTask;
import org.quartz.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class QuartzConfig {
<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> String LIKE_TASK_IDENTITY = <span class="hljs-string">"LikeTaskQuartz"</span>;

<span class="hljs-meta">@Bean</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> JobDetail <span class="hljs-title">quartzDetail</span><span class="hljs-params">()</span></span>{
    <span class="hljs-keyword">return</span> JobBuilder.newJob(LikeTask.class).withIdentity(LIKE_TASK_IDENTITY).storeDurably().build();
}

<span class="hljs-meta">@Bean</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> Trigger <span class="hljs-title">quartzTrigger</span><span class="hljs-params">()</span></span>{
    SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule()

//                .withIntervalInSeconds(10)  //设置时间周期单位秒
                .withIntervalInHours(2)  //两个小时执行一次
                .repeatForever();
        return TriggerBuilder.newTrigger().forJob(quartzDetail())
                .withIdentity(LIKE_TASK_IDENTITY)
                .withSchedule(scheduleBuilder)
                .build();
    }
}
  1. 编写执行任务的类继承自 QuartzJobBean
代码语言:javascript
复制
package com.solo.coderiver.user.task;

import com.solo.coderiver.user.service.LikedService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import java.text.SimpleDateFormat;
import java.util.Date;
/**

点赞的定时任务

 */
@Slf4j
public class LikeTask extends QuartzJobBean {
<span class="hljs-meta">@Autowired</span>
LikedService likedService;

<span class="hljs-keyword">private</span> SimpleDateFormat sdf = <span class="hljs-keyword">new</span> SimpleDateFormat(<span class="hljs-string">"yyyy-MM-dd HH:mm:ss"</span>);

<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">executeInternal</span><span class="hljs-params">(JobExecutionContext jobExecutionContext)</span> <span class="hljs-keyword">throws</span> JobExecutionException </span>{

    log.info(<span class="hljs-string">"LikeTask-------- {}"</span>, sdf.format(<span class="hljs-keyword">new</span> Date()));

    <span class="hljs-comment">//将 Redis 里的点赞信息同步到数据库里</span>
    likedService.transLikedFromRedis2DB();
    likedService.transLikedCountFromRedis2DB();
}

}

在定时任务中直接调用 LikedService 封装的方法完成数据同步。

以上就是点赞功能的设计与实现,不足之处还请各位大佬多多指教。

如有更好的实现方案欢迎在评论区交流…

项目地址:https://github.com/cachecats/coderiver

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018/11/02 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、Redis 缓存设计及实现
    • 1.1 Redis 安装及运行
      • 1.2 Redis 与 SpringBoot 项目的整合
        • 1.3 Redis 的数据结构类型
          • 1.4 点赞数据在 Redis 中的存储格式
            • 1.5 操作 Redis
            • 二、数据库设计
            • 三、数据库操作
            • 四、开启定时任务持久化存储到数据库
            相关产品与服务
            云数据库 Redis
            腾讯云数据库 Redis(TencentDB for Redis)是腾讯云打造的兼容 Redis 协议的缓存和存储服务。丰富的数据结构能帮助您完成不同类型的业务场景开发。支持主从热备,提供自动容灾切换、数据备份、故障迁移、实例监控、在线扩容、数据回档等全套的数据库服务。
            领券
            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档