redis实现存储帖子的点赞状态和数量的示例代码

 更新时间:2023年09月06日 10:54:58   作者:退役熬夜冠军选手  
使用Redis来实现点赞功能是一种高效的选择,因为Redis是一个内存数据库,适用于处理高并发的数据操作,这篇文章主要介绍了redis实现存储帖子的点赞状态和数量的示例代码,需要的朋友可以参考下

redis实现存储帖子的点赞状态和数量

1 对redis进行配置并封装一个redis工具类

@Configuration //编写redis的配置类
public class RedisConfig {
    @Bean //参数声明了连接工厂
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        // 设置key的序列化方式
        template.setKeySerializer(RedisSerializer.string());
        // 设置value的序列化方式
        template.setValueSerializer(RedisSerializer.json());
        // 设置hash的key的序列化方式
        template.setHashKeySerializer(RedisSerializer.string());
        // 设置hash的value的序列化方式
        template.setHashValueSerializer(RedisSerializer.json());
           //让设置生效
        template.afterPropertiesSet();
        return template;
    }
}
public class RedisKeyUtil {
    private static final String SPLIT = ":";
    private static final String PREFIX_ENTITY_LIKE = "like:entity";
    // 某个实体的赞
    // like:entity:entityType:entityId -> set(userId)
    public static String getEntityLikeKey(int entityType, int entityId) {
        return PREFIX_ENTITY_LIKE + SPLIT + entityType + SPLIT + entityId;
    }
    }

2 reids操作起来比较简单,所以一般不需要写dao层,直接在service里面对数据进行操作

@Service
public class LikeService {
    @Autowired
    private RedisTemplate redisTemplate;
    // 点赞  谁点的赞 点赞的实体 实体的id 实体的用户
    public void like(int userId, int entityType, int entityId, ) {
        redisTemplate.execute(new SessionCallback() {
            @Override
            public Object execute(RedisOperations operations) throws DataAccessException {
                String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
                boolean isMember = operations.opsForSet().isMember(entityLikeKey, userId);
                   //是否已经点过赞
                if (isMember) { //移除userid
                    operations.opsForSet().remove(entityLikeKey, userId);
                    operations.opsForValue().decrement(userLikeKey);
                } else { //添加userid
                    operations.opsForSet().add(entityLikeKey, userId);
                    operations.opsForValue().increment(userLikeKey);
                }
            }
        });
    }
    // 查询某实体点赞的数量
    public long findEntityLikeCount(int entityType, int entityId) {
        String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
        return redisTemplate.opsForSet().size(entityLikeKey);
    }
    // 查询某人对某实体的点赞状态
    public int findEntityLikeStatus(int userId, int entityType, int entityId) {
        String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
        //1表示点赞 0表示没有
        return redisTemplate.opsForSet().isMember(entityLikeKey, userId) ? 1 : 0;
    }

3controller层接受post请求带来的参数,将查询到的数据放进map里,传给前端回调函数,处理前端页面

@Controller
public class LikeController {
    @Autowired
    private LikeService likeService;
    @Autowired
    private HostHolder hostHolder;
    @RequestMapping(path = "/like", method = RequestMethod.POST)
    @ResponseBody
    public String like(int entityType, int entityId, int entityUserId) {
        User user = hostHolder.getUser();
        // 点赞
        likeService.like(user.getId(), entityType, entityId, entityUserId);
        // 数量
        long likeCount = likeService.findEntityLikeCount(entityType, entityId);
        // 状态
        int likeStatus = likeService.findEntityLikeStatus(user.getId(), entityType, entityId);
        // 返回的结果
        Map<String, Object> map = new HashMap<>();
        map.put("likeCount", likeCount);
        map.put("likeStatus", likeStatus);
        return CommunityUtil.getJSONString(0, null, map);
    }
}
//回调函数
function like(btn, entityType, entityId, entityUserId) {
    $.post(
        CONTEXT_PATH + "/like",
        {"entityType":entityType,"entityId":entityId,"entityUserId":entityUserId},
        function(data) {
            data = $.parseJSON(data);
            if(data.code == 0) {
                $(btn).children("i").text(data.likeCount);
                $(btn).children("b").text(data.likeStatus==1?'已赞':"赞");
            } else {
                alert(data.msg);
            }
        }
    );
}

使用Redis来实现点赞功能的基本思路

使用Redis来实现点赞功能是一种高效的选择,因为Redis是一个内存数据库,适用于处理高并发的数据操作。以下是一个基本的点赞功能在Redis中的设计示例:

假设我们有一个文章或帖子,用户可以对其进行点赞,取消点赞,以及查看点赞总数。

存储点赞信息:

使用Redis的Hash数据结构来存储每篇文章的点赞信息。每篇文章对应一个Hash,Hash的字段表示用户ID,字段值表示点赞状态(例如1代表已点赞,0代表未点赞)(值也可以存放用户点赞时间)。

HSET article_likes:<article_id> <user_id> 1

记录点赞总数:

使用 Redis 的 Set 数据结构来存储每篇文章的点赞用户集合,用于查询文章的点赞数量。每篇文章对应一个 Set,其中的元素为用户ID。

SADD article_likes_count:<article_id> <user_id>

取消点赞:

取消点赞时,从Hash中删除用户的点赞记录,同时从对应的 Set 中删除用户ID。

HDEL article_likes:<article_id> <user_id>
SREM article_likes_count:<article_id> <user_id>

查询点赞状态:

查询某篇文章的点赞状态,只需要查询对应的Hash数据结构中的字段值。

HGET article_likes:<article_id> <user_id>

查询点赞总数:

查询某篇文章的点赞总数,使用Redis的PFCount命令来统计HyperLogLog的数量。

SCARD article_likes_count:<article_id>

这只是一个简单的Redis设计示例。在实际应用中,您可能还需要考虑数据过期策略、持久化选项、缓存更新机制等等。另外,确保对Redis进行适当的配置和优化,以满足您应用的性能和可靠性需求。

到此这篇关于redis实现存储帖子的点赞状态和数量的文章就介绍到这了,更多相关redis点赞状态和数量内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 解析高可用Redis服务架构分析与搭建方案

    解析高可用Redis服务架构分析与搭建方案

    我们按照由简至繁的步骤,搭建一个最小型的高可用的Redis服务。 本文通过四种方案给大家介绍包含每种方案的优缺点及详细解说,具体内容详情跟随小编一起看看吧
    2021-06-06
  • Redis数据结构原理浅析

    Redis数据结构原理浅析

    这篇文章主要为大家介绍了Redis数据结构原理浅析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-02-02
  • Redis哨兵模式介绍

    Redis哨兵模式介绍

    这篇文章介绍了Redis哨兵模式,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-02-02
  • Redis如何正确关闭和开启持久化

    Redis如何正确关闭和开启持久化

    本文主要介绍了Redis如何正确关闭和开启持久化,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-01-01
  • redis中的事务操作案例分析

    redis中的事务操作案例分析

    这篇文章主要介绍了redis中的事务操作案例,结合具体实例形式详细分析了redis事务操作的概念、原理、使用技巧与相关注意事项,需要的朋友可以参考下
    2019-07-07
  • Redis突现拒绝连接问题处理方案

    Redis突现拒绝连接问题处理方案

    这篇文章主要介绍了Redis突现拒绝连接问题处理方案,分析原因是由于redis与业务共一个服务器,内存只有8G,业务服务启动过多,内存不足导致redis拒绝连接,需要的朋友可以参考下
    2024-02-02
  • redis 集群批量操作实现

    redis 集群批量操作实现

    这篇文章主要介绍了redis 集群批量操作,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-04-04
  • Windows系统设置Redis服务使其开机自启动

    Windows系统设置Redis服务使其开机自启动

    Redis是一种键值对数据库,也称为内存数据库,因为它可以将数据存储在内存中,而不是在磁盘上,下面这篇文章主要给大家介绍了关于Windows系统设置Redis服务使其开机自启动的相关资料,需要的朋友可以参考下
    2024-01-01
  • 使用RediSearch实现在Redis中全文检索

    使用RediSearch实现在Redis中全文检索

    RediSearch 是 Redis 的一个插件,它为 Redis 数据库添加了全文搜索和查询功能,使开发人员能够在 Redis 中高效地执行全文检索操作,下面我们就来看看是具体如何使用的吧
    2023-08-08
  • 浅谈redis采用不同内存分配器tcmalloc和jemalloc

    浅谈redis采用不同内存分配器tcmalloc和jemalloc

    下面小编就为大家带来一篇浅谈redis采用不同内存分配器tcmalloc和jemalloc。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2016-12-12

最新评论