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();
    }
}
相关推荐
karry_k13 小时前
MyBatis批量insert-select踩坑:useGeneratedKeys=true 可能让PostgreSQL返回大量插入结果
java·后端
karry_k13 小时前
PostgreSQL 在 MyBatis 中执行正常 SQL 失效:一次 DELETE USING 踩坑记录
java·后端
SamDeepThinking16 小时前
从源码到代码:MyBatis-Flex 与 MyBatis-Plus 的逐项对比
java·后端·程序员
她的男孩19 小时前
Spring Boot 接 Flowable 工作流:用 3 个注解搭一个请假审批流程
java·后端·架构
荣码21 小时前
LLM结构化输出:让AI返回JSON而不是废话,我踩了4个坑
java·python
plainGeekDev1 天前
Gson → kotlinx.serialization
android·java·kotlin
小bo波1 天前
Java Swing 图形用户界面实验 —— 从算术练习到游戏开发的完整实践
java·课程设计·gui·游戏开发·扫雷·swing
咖啡八杯1 天前
GoF设计模式——备忘录模式
java·后端·spring·设计模式