package com.example.demo.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; @Service public class LikeService { private final RedisTemplate redisTemplate; @Autowired public LikeService(RedisTemplate redisTemplate) { this.redisTemplate = redisTemplate; } public void like(String targetId, String userId) { // 使用集合记录点赞用户,防止重复点赞 redisTemplate.opsForSet().add(targetId + ":likes", userId); // 点赞数自增,使用字符串存储点赞数,方便后续展示 redisTemplate.opsForValue().increment(targetId + ":likeCount", 1); } public void unlike(String targetId, String userId) { redisTemplate.opsForSet().remove(targetId + ":likes", userId); redisTemplate.opsForValue().decrement(targetId + ":likeCount", 1); } public boolean hasLiked(String targetId, String userId) { return redisTemplate.opsForSet().isMember(targetId + ":likes", userId); } public long getLikeCount(String targetId) { Long count = (Long) redisTemplate.opsForValue().get(targetId + ":likeCount"); return count == null? 0 : count; } }