手把手教你用Redis实现点赞功能并且与数据库同步

2022-11-13 08:11:39 同步 手把手 教你用

一、Redis 缓存设计及实现

linux下安装Redis或者Docker下安装Redis并且启动(redis-server)

springBoot整合Redis

1.在 pom.xml 中引入依赖

<dependency>    
    <groupId>org.springframework.boot</groupId>    
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2.在启动类上添加注释 @EnableCaching

3.编写 Redis 配置类 RedisConfig

@Configuration
public class RedisConfig {    
    @Bean    
    @ConditionalOnMissingBean(name = "redisTemplate")    
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)throws UnknownHostException {
        Jackson2JSONRedisSerializer<Object> jackson2jsonRedisSerializer= new Jackson2JsonRedisSerializer<Object>(Object.class);        
        ObjectMapper om = new ObjectMapper();        
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(redisConnectionFactory);
        template.seTKEySerializer(jackson2JsonRedisSerializer);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashKeySerializer(jackson2JsonRedisSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;    
      }    
    @Bean    
    @ConditionalOnMissingBean(StringRedisTemplate.class)    
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory)throws UnknownHostException {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);        
    return template;  
    }
}

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

用 Redis 存储两种数据:

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

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

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

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

类似于这样:

在这里插入图片描述

在service层操作Redis

public interface RedisService {    
    
void saveLiked2Redis(String likedUserId, String giveLikeId);    
    
void unlikeFromRedis(String likedUserId, String giveLikeId);    
    
void deleteLikedFromRedis(String likedUserId, String giveLikeId);    
    
void incrementLikedCount(String likedUserId);    
    
void decrementLikedCount(String likedUserId);    
    
List<UserLike> getLikedDataFromRedis();    
    
List<LikedCountDTO> getLikedCountFromRedis();}

实现类 RedisServiceImpl :

@Service
@Slf4j
public class RedisServiceImpl implements RedisService {    
    @Autowired    
    RedisTemplate redisTemplate;    
    @Autowired    
    LikedService likedService;    
  @Override    
  public void saveLiked2Redis(String likedUserId, String giveLikeId) {          
      String key = RedisKeyUtils.getLikedKey(likedUserId, giveLikeId);            
      redisTemplate.opsForHash().put(RedisKeyUtils.MAP_USER_LIKED, 
      key, LikedStatusEnum.LIKE.getCode());    
      }    
  @Override    
  public void unlikeFromRedis(String likedUserId, String giveLikeId) {          
      String key = RedisKeyUtils.getLikedKey(likedUserId, giveLikeId);            
      redisTemplate.opsForHash().put(RedisKeyUtils.MAP_USER_LIKED, 
      key, LikedStatusEnum.UNLIKE.getCode());    
      }    
  @Override    
  public void deleteLikedFromRedis(String likedUserId, String giveLikeId) {    
      String key = RedisKeyUtils.getLikedKey(likedUserId, giveLikeId);            
      redisTemplate.opsForHash().delete(RedisKeyUtils.MAP_USER_LIKED, key);   
      }    
  @Override    
  public void incrementLikedCount(String likedUserId) {
      redisTemplate.opsForHash().increment(RedisKeyUtils.MAP_USER_LIKED_COUNT,likedUserId,1);    
 }    
 @Override
 public void decrementLikedCount(String likedUserId) {        
     redisTemplate.opsForHash().increment(RedisKeyUtils.MAP_USER_LIKED_COUNT,likedUserId,-1);    
 }    
 @Override
 public List<UserLike> getLikedDataFromRedis() {                
     Cursor<Map.Entry<Object, Object>> cursor =redisTemplate.opsForHash().scan(RedisKeyUtils.MAP_USER_LIKED, ScanOptions.NONE);        
     List<UserLike> list = new ArrayList<>();
     while (cursor.hasNext()){
         Map.Entry<Object, Object> entry = cursor.next();
         String key = (String) entry.getKey();
         //分离出 likedUserId,giveLikeId
         String[] split = key.split("::");
         String likedUserId = split[0];
         String giveLikeId = split[1];
         Integer value = (Integer) entry.getValue();
         //组装成 UserLike 对象
         UserLike userLike = new UserLike(likedUserId, giveLikeId, value);
         list.add(userLike);
         //存到 list 后从 Redis 中删除
         redisTemplate.opsForHash().delete(RedisKeyUtils.MAP_USER_LIKED, key);        
         }        return list;    
    }   
 @Override    
 public List<LikedCountDTO> getLikedCountFromRedis() {
     Cursor<Map.Entry<Object, Object>> cursor =    redisTemplate.opsForHash().scan(RedisKeyUtils.MAP_USER_LIKED_COUNT,  ScanOptions.NONE);
     List<LikedCountDTO> list = new ArrayList<>();
     while (cursor.hasNext()){
        Map.Entry<Object, Object> map = cursor.next();
        //将点赞数量存储在 LikedCountDT
          String key = (String)map.getKey(); 
        LikedCountDTO dto = new LikedCountDTO(key, (Integer)    map.getValue());
        list.add(dto);
        //从Redis中删除这条记录 
          redisTemplate.opsForHash().delete(RedisKeyUtils.MAP_USER_LIKED_COUNT, key);        
        }        
    return list;    
    }
}

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

public class RedisKeyUtils {

    //保存用户点赞数据的key
    public static final String MAP_USER_LIKED = "MAP_USER_LIKED";
    //保存用户被点赞数量的key
    public static final String MAP_USER_LIKED_COUNT = "MAP_USER_LIKED_COUNT";

    
    public static String getLikedKey(String likedUserId, String giveLikeId){
        StringBuilder builder = new StringBuilder();
        builder.append(likedUserId);
        builder.append("::");
        builder.append(giveLikeId);
        return builder.toString();
    }
}

LikedStatusEnum 用户点赞状态的枚举类


@Getter
public enum LikedStatusEnum {
    LIKE(1, "点赞"),
    UNLIKE(0, "取消点赞/未点赞"),
    ;

    private Integer code;

    private String msg;

    LikedStatusEnum(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }
}

三、数据库设计

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

create table `user_like`(
    `id` int not null auto_increment,
    `liked_user_id` varchar(32) not null comment '被点赞的用户id',
    `give_liked_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 `give_liked_id`(`give_liked_id`)
) comment '用户点赞表';

对应的对象 UserLike


@Entity
@Data
public class UserLike {

    //主键id
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    //被点赞的用户的id
    private String likedUserId;

    //点赞的用户的id
    private String giveLikedId;

    //点赞的状态.默认未点赞
    private Integer status = LikedStatusEnum.UNLIKE.getCode();

    public UserLike() {
    }

    public UserLike(String likedUserId, String giveLikedId, Integer status) {
        this.likedUserId = likedUserId;
        this.giveLikedId = giveLikedId;
        this.status = status;
    }
}

在service层操作数据库

public interface LikedService {

    
    UserLike save(UserLike userLike);

    
    List<UserLike> saveAll(List<UserLike> list);


    
    Page<UserLike> getLikedListByLikedUserId(String likedUserId, Pageable pageable);

    
    Page<UserLike> getLikedListByGiveLikedId(String giveLikedId, Pageable pageable);

    
    UserLike getByLikedUserIdAndGiveLikedId(String likedUserId, String giveLikedId);

    
    void transLikedFromRedis2DB();

    
    void transLikedCountFromRedis2DB();

}

LikedServiceImpl 实现类

@Service
@Slf4j
public class LikedServiceImpl implements LikedService {

    @Autowired
    UserLikeRepository likeRepository;

    @Autowired
    RedisService redisService;

    @Autowired
    UserService userService;

    @Override
    @Transactional
    public UserLike save(UserLike userLike) {
        return likeRepository.save(userLike);
    }

    @Override
    @Transactional
    public List<UserLike> saveAll(List<UserLike> list) {
        return likeRepository.saveAll(list);
    }

    @Override
    public Page<UserLike> getLikedListByLikedUserId(String likedUserId, Pageable pageable) {
        return likeRepository.findByLikedUserIdAndStatus(likedUserId, LikedStatusEnum.LIKE.getCode(), pageable);
    }

    @Override
    public Page<UserLike> getLikedListByGiveLikedId(String giveLikedId, Pageable pageable) {
        return likeRepository.findByGiveLikedIdAndStatus(giveLikedId, LikedStatusEnum.LIKE.getCode(), pageable);
    }

    @Override
    public UserLike getByLikedUserIdAndGiveLikedId(String likedUserId, String giveLikedId) {
        return likeRepository.findByLikedUserIdAndLikedPostId(likedUserId, giveLikedId);
    }

    @Override
    @Transactional
    public void transLikedFromRedis2DB() {
        List<UserLike> list = redisService.getLikedDataFromRedis();
        for (UserLike like : list) {
            UserLike ul = getByLikedUserIdAndGiveLikedId(like.getLikedUserId(), like.getGiveLikedId());
            if (ul == null){
                //没有记录,直接存入
                save(like);
            }else{
                //有记录,需要更新
                ul.setStatus(like.getStatus());
                save(ul);
            }
        }
    }

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

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

这里使用的是定时任务 Quartz框架

1、 添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-quartz</artifactId>
</dependency>

2、 编写配置文件

@Configuration
public class QuartzConfig {

    private static final String LIKE_TASK_IDENTITY = "LikeTaskQuartz";

    @Bean
    public JobDetail quartzDetail(){
        return JobBuilder.newJob(LikeTask.class).withIdentity(LIKE_TASK_IDENTITY).storeDurably().build();
    }

    @Bean
    public Trigger quartzTrigger(){
        SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule()
                        .withIntervalInSeconds(10)  //设置时间周期单位秒
                .withIntervalInHours(2)  //两个小时执行一次
                .repeatForever();
        return TriggerBuilder.newTrigger().forJob(quartzDetail())
                .withIdentity(LIKE_TASK_IDENTITY)
                .withSchedule(scheduleBuilder)
                .build();
    }
}

3、 编写执行任务的类继承自 QuartzJobBean


@Slf4j
public class LikeTask extends QuartzJobBean {

    @Autowired
    LikedService likedService;

    private SimpleDateFORMat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        log.info("LikeTask-------- {}", sdf.format(new Date()));

        //将 Redis 里的点赞信息同步到数据库里
        likedService.transLikedFromRedis2DB();
        likedService.transLikedCountFromRedis2DB();
    }
}

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

五、注意事项

1.点赞 / 取消点赞 跟 点赞数 +1/ -1 应该保证是原子操作 ,不然出现并发问题就会有两条重复的点赞记录 , 所以要给整个原子操作加

2.同时需要在 Spring Boot 的系统关闭钩子函数中补充同步 redis 中点赞数据到 Mysql 中的过程 . 不然有可能出现距离上一次同步 1 小时 59 分的时候服务器更新 , 把整整两小时的点赞数据都给清空了 。

到此这篇关于手把手教你用Redis 实现点赞功能并且与数据库同步的文章就介绍到这了,更多相关Redis 点赞内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关文章