使用Redis的SET数据结构来存储每个实体的点赞用户ID列表,方便进行点赞数量的计数和用户点赞状态的检查。以下是一个小demo,只提供简单思路。
java
@Service
public class LikeService {
@Autowired
private 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();
}
}