redistemplate实现点赞相关功能
使用Redis的SET数据结构来存储每个实体的点赞用户ID列表,方便进行点赞数量的计数和用户点赞状态的检查。以下是一个小demo,只提供简单思路。
@Service
public class LikeService {@Autowiredprivate RedisTemplate redisTemplate;//点赞public Long like(String userId,String entityId){String key = "like:" + entityId;return redisTemplate.opsForSet().add(key,userId) == 1L ? 1L : 0L;}//取消点赞public Long unLike(String userId,String entityId){String key = "like:" + entityId;return redisTemplate.opsForSet().remove(key,userId) == 1L ? 1L : 0L;}//查询点赞数量public Long isLiked(String userId,String entityId){String key = "like:" + entityId;return redisTemplate.opsForSet().remove(key,userId) == 1L ? 1L : 0L;}//查询用户点赞状态public Long countLikes(String entityId){String key = "like:" + entityId;return redisTemplate.opsForSet().size(key).longValue();}
}