redistemplate实现点赞相关功能

        使用Redis的SET数据结构来存储每个实体的点赞用户ID列表,方便进行点赞数量的计数和用户点赞状态的检查。以下是一个小demo,只提供简单思路。

@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();
    }
}

好的,那我来回答你的问题。在SpringBoot中,实现点赞功能通常会使用Redis进行缓存,可以将点赞数存储到Redis中,每当一个用户进行点赞操作时,就会将点赞数从Redis中读取,进行加1操作,再将结果存储回Redis中。具体实现步骤如下: 1. 首先,在pom.xml文件中添加Redis的依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 在application.properties文件中配置Redis连接信息: ``` spring.redis.host=127.0.0.1 spring.redis.port=6379 ``` 3. 创建一个Redis工具类,用于封装一些Redis操作: ``` @Component public class RedisUtil { @Autowired private StringRedisTemplate redisTemplate; public void increment(String key) { redisTemplate.opsForValue().increment(key); } public String get(String key) { return redisTemplate.opsForValue().get(key); } public void set(String key, String value) { redisTemplate.opsForValue().set(key, value); } } ``` 4. 在点赞接口中,调用RedisUtil中封装的方法,完成点赞功能实现: ``` @RestController public class LikeController { @Autowired private RedisUtil redisUtil; @PostMapping("/like") public void like(@RequestParam("id") Integer id) { String key = "like:" + id; redisUtil.increment(key); } @GetMapping("/like") public String getLike(@RequestParam("id") Integer id) { String key = "like:" + id; return redisUtil.get(key); } } ``` 以上就是SpringBoot整合Redis实现点赞功能的具体步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值