redistemplate实现点赞相关功能

使用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();
    }
}
相关推荐
码匠许师傅12 分钟前
【C++ 面试真题】聊聊 C++ 的虚函数和多态
java·c++·面试
chuan.bai39 分钟前
Java RAG 实战(第 8 篇):Spring Boot RAG 查询 API
java·spring boot·贪心算法
FlyWIHTSKY39 分钟前
idea中集成claude功能
java·ide·人工智能·intellij-idea·cloudera
breeze jiang42 分钟前
Next.js App Router 父子组件 RSC 拆分实战:从 Redis Hash 到客户端交互的最小化边界
javascript·redis·哈希算法
Java成神之路-44 分钟前
Spring AI 统一结构化返回:ChatModel / ChatClient 两种实现方式
java·springaialibaba
Mr. zhihao1 小时前
深度解析:为什么Java序列化需要搭配ByteArrayOutputStream?IO装饰器模式的精妙设计
java·开发语言·装饰器模式
存在morning1 小时前
【Python 开发实践 一】Python vs Go vs Java 三门语言对比
java·python·golang
vx-程序开发1 小时前
springboot旅游推介平台---附源码24175
java·spring boot·python·spring cloud·eclipse·django·idea
艾莉丝努力练剑1 小时前
【QT:解决问题】Qt5Core.dll:无法定位程序输入点
java·开发语言·qt·学习·面试
小蒜学长2 小时前
“喵汪联盟”宠物领养系统的设计与实现(代码+数据库+LW)
java·spring boot·后端·宠物