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

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

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

设计思路以下:

​ 整体思路咱们采用redis里面的zset完成整个功能, 缘由是zset有排序(咱们要按照关注时间的倒序排列), 去重(咱们不能屡次关注同一用户)功能. 一个用户咱们存贮两个集合, 一个是保存用户关注的人 另外一个是保存关注用户的人.
用到的命令是:
​ 一、 zadd 添加成员:命令格式: zadd key score member [score …]
​ 二、zrem 移除某个成员:命令格式: zrem key member [member ...]
​ 三、 zcard 统计集合内的成员数:命令格式: zcard key
​ 四、 zrange 查询集合内的成员:命令格式: ZRANGE key start stop [WITHSCORES]
​ 描述:返回指定区间的成员。其中成员位置按 score 值递增(从小到大)来排序。 WITHSCORES选项是用来让成员和它的score值一并返回.
​ 五、 zrevrange跟zrange做用相反
​ 六、zrank获取成员的排名:命令格式: zrank key member
​ 描述:返回有序集key中成员member的排名。成员按 score 值递增(从小到大)顺序排列。排名以0开始,也就是说score 值最小的为0。返回值:返回成员排名,member不存在返回nil.
​ 七、 zinterstore 取两个集合的交集:命令格式:ZINTERSTORE destination numkeys key key ...] [AGGREGATE SUM|MIN|MAX]
​ 描述:计算给定的一个或多个有序集的交集。其中给定 key 的数量必须以 numkeys 参数指定,并将该交集(结果集)储存到 destination 。默认状况下,结果集中某个成员的 score 值是全部给定集下该成员 score 值之 和 。
返回值:保存到 destination 的结果集成员数。redis

下面我用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;
        }
    }

这是一点点小小的总结, 但愿能帮到要用到的人。服务器

相关文章
相关标签/搜索