ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

使用Redis实现关注好友的功能

2021-06-16 14:33:28  阅读:175  来源: 互联网

标签:功能 otherUserId String userId Redis jedis static null 好友


现在很多社交都有关注或者添加粉丝的功能, 类似于这样的功能我们如果采用数据库做的话只是单纯得到用户的一些粉丝或者关注列表的话是很简单也很容易实现, 但是如果我想要查出两个甚至多个用户共同关注了哪些人或者想要查询两个或者多个用户的共同粉丝的话就会很麻烦, 效率也不会很高. 但是如果你用redis去做的话就会相当的简单而且效率很高. 原因是redis自己本身带有专门针对于这种集合的交集,并集, 差集的一些操作。

设计思路如下:

总体思路我们采用redis里面的zset完成整个功能, 原因是zset有排序(我们要按照关注时间的倒序排列), 去重(我们不能多次关注同一用户)功能. 一个用户我们存贮两个集合, 一个是保存用户关注的人 另一个是保存关注用户的人.
用到的命令是:

1、 zadd 添加成员:命令格式:zadd key score member [[score][member] …]

2、zrem 移除某个成员:命令格式:zrem key member [member …]

3、 zcard 统计集合内的成员数:命令格式:zcard key

4、 zrange 查询集合内的成员:命令格式:ZRANGE key start stop [WITHSCORES]

描述:返回指定区间的成员。其中成员位置按 score 值递增(从小到大)来排序。 WITHSCORES选项是用来让成员和它的score值一并返回.

5、 zrevrange跟zrange作用相反
6、zrank获取成员的排名:命令格式:zrank key member

描述:返回有序集key中成员member的排名。成员按 score 值递增(从小到大)顺序排列。排名以0开始,也就是说score 值最小的为0。返回值:返回成员排名,member不存在返回nil.

7、 zinterstore 取两个集合的交集:命令格式:ZINTERSTORE destination numkeys key [key …][WEIGHTS weight [weight …]] [AGGREGATE SUM|MIN|MAX]

描述:计算给定的一个或多个有序集的交集。其中给定 key 的数量必须以 numkeys 参数指定,并将该交集(结果集)储存到 destination 。默认情况下,结果集中某个成员的 score 值是所有给定集下该成员 score 值之 和 。

返回值:保存到 destination 的结果集成员数。

下面我用Java写了一个简单的例子 maven构建

第一步: 添加Redis客户端

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
</dependency>

第二步: 封装一个简单的redis工具类

import redis.clients.jedis.Jedis;
    import redis.clients.jedis.JedisPool;
    import redis.clients.jedis.JedisPoolConfig;
    public final class RedisUtil {
        //Redis服务器IP
        private static String ADDR = "localhost";
        //Redis的端口号
        private static int PORT = 6379;
        //访问密码
        private static String AUTH = "admin";
        //控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。
        private static int MAX_IDLE = 200;
        private static int TIMEOUT = 10000;
        //在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
        private static boolean TEST_ON_BORROW = true;
        private static JedisPool jedisPool = null;

        static {
            try {
                JedisPoolConfig config = new JedisPoolConfig();
                config.setMaxIdle(MAX_IDLE);
                config.setTestOnBorrow(TEST_ON_BORROW);
                jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT, AUTH);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public synchronized static Jedis getJedis() {
            try {
                if (jedisPool != null) {
                    Jedis resource = jedisPool.getResource();
                    return resource;
                } else {
                    return null;
                }
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

        @SuppressWarnings("deprecation")
        public static void returnResource(final Jedis jedis) {
            if (jedis != null) {
                jedisPool.returnResource(jedis);
            }
        }
    }

  

第三步: 封装简单的Follow类

 

 import java.util.HashSet;
    import java.util.Set;

    import redis.clients.jedis.Jedis;

    import com.indulgesmart.base.util.RedisUtil;
    public class FollowUtil {

        private static final String FOLLOWING = "FOLLOWING_";
        private static final String FANS = "FANS_";
        private static final String COMMON_KEY = "COMMON_FOLLOWING";

        // 关注或者取消关注
        public static int addOrRelease(String userId, String followingId) {
            if (userId == null || followingId == null) {
                return -1;
            }
            int isFollow = 0; // 0 = 取消关注 1 = 关注
            Jedis jedis = RedisUtil.getJedis();
            String followingKey = FOLLOWING + userId;
            String fansKey = FANS + followingId;
            if (jedis.zrank(followingKey, followingId) == null) { // 说明userId没有关注过followingId
                jedis.zadd(followingKey, System.currentTimeMillis(), followingId);
                jedis.zadd(fansKey, System.currentTimeMillis(), userId);
                isFollow = 1;
            } else { // 取消关注
                jedis.zrem(followingKey, followingId);
                jedis.zrem(fansKey, fansKey);
            }
            return isFollow;
        }


         // 验证两个用户之间的关系 
         // 0=没关系  1=自己 2=userId关注了otherUserId 3= otherUserId是userId的粉丝 4=互相关注
        public int checkRelations (String userId, String otherUserId) {

            if (userId == null || otherUserId == null) {
                return 0;
            }

            if (userId.equals(otherUserId)) {
                return 1;
            }
            Jedis jedis = RedisUtil.getJedis();
            String followingKey = FOLLOWING + userId;
            int relation = 0;
            if (jedis.zrank(followingKey, otherUserId) != null) { // userId是否关注otherUserId
                relation = 2;
            }
            String fansKey = FANS + userId;
            if (jedis.zrank(fansKey, userId) != null) {// userId粉丝列表中是否有otherUserId
                relation = 3;
            }
            if ((jedis.zrank(followingKey, otherUserId) != null) 
                    && jedis.zrank(fansKey, userId) != null) {
                relation = 4;
            }
            return relation;
        }

        // 获取用户所有关注的人的id
        public static Set<String> findFollwings(String userId) {
            return findSet(FOLLOWING + userId);
        }

        // 获取用户所有的粉丝
        public static Set<String> findFans(String userId) {
            return findSet(FANS + userId);
        }

        // 获取两个共同关注的人
        public static Set<String> findCommonFollowing(String userId, String otherUserId) {
            if (userId == null || otherUserId == null) {
                return new HashSet<>();
            }
            Jedis jedis = RedisUtil.getJedis();
            String commonKey = COMMON_KEY + userId + "_" + otherUserId;
            // 取交集
            jedis.zinterstore(commonKey + userId + "_" + otherUserId, FOLLOWING + userId, FOLLOWING + otherUserId); 
            Set<String> result = jedis.zrange(commonKey, 0, -1);
            jedis.del(commonKey);
            return result;
        }

        // 根据key获取set
        private static Set<String> findSet(String key) {
            if (key == null) {
                return new HashSet<>();
            }
            Jedis jedis = RedisUtil.getJedis();
            Set<String> result = jedis.zrevrange(key, 0, -1); // 按照score从大到小排序
            return result;
        }
    }

  

 

标签:功能,otherUserId,String,userId,Redis,jedis,static,null,好友
来源: https://www.cnblogs.com/lixiaochong/p/14889241.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有