1
+ import redis .clients .jedis .Jedis ;
2
+ import utils .JedisUtils ;
3
+
4
+ import java .util .Set ;
5
+
6
+ public class SocialRelationship {
7
+ private Jedis client = JedisUtils .getClient ();
8
+ private String user ;
9
+
10
+ public SocialRelationship (String user ) {
11
+ this .user = user ;
12
+ }
13
+
14
+ /**
15
+ * 关注目标用户
16
+ *
17
+ * @param target 用户
18
+ */
19
+ public void follow (String target ) {
20
+ String followingKey = JedisUtils .getFollowingKey (user );
21
+ String followersKey = JedisUtils .getFollowersKey (target );
22
+ long now = System .currentTimeMillis ();
23
+ client .zadd (followingKey , now , target );
24
+ client .zadd (followersKey , now , user );
25
+ }
26
+
27
+ /**
28
+ * 取关目标用户
29
+ *
30
+ * @param target 用户
31
+ */
32
+ public void unfollow (String target ) {
33
+ String followingKey = JedisUtils .getFollowingKey (user );
34
+ String followersKey = JedisUtils .getFollowersKey (target );
35
+ client .zrem (followingKey , target );
36
+ client .zrem (followersKey , user );
37
+ }
38
+
39
+ /**
40
+ * 判断是否关注着目标用户
41
+ *
42
+ * @param target 用户
43
+ * @return 是否关注
44
+ */
45
+ public boolean isFollowing (String target ) {
46
+ String followingKey = JedisUtils .getFollowingKey (user );
47
+ return client .zrank (followingKey , target ) != null ;
48
+
49
+ }
50
+
51
+ /**
52
+ * 获取当前用户关注的所有人,并按最近关注时间倒序排列
53
+ *
54
+ * @return 关注人集合
55
+ */
56
+ public Set <String > getAllFollowing () {
57
+ String followingKey = JedisUtils .getFollowingKey (user );
58
+ return client .zrevrange (followingKey , 0 , -1 );
59
+ }
60
+
61
+ /**
62
+ * 获取当前用户的所有粉丝,并按最近关注时间倒序排列
63
+ *
64
+ * @return 粉丝集合
65
+ */
66
+ public Set <String > getAllFollowers () {
67
+ String followersKey = JedisUtils .getFollowersKey (user );
68
+ return client .zrevrange (followersKey , 0 , -1 );
69
+ }
70
+
71
+ /**
72
+ * 获取当前用户关注的人数
73
+ *
74
+ * @return 人数
75
+ */
76
+ public Long countFollowing () {
77
+ String followingKey = JedisUtils .getFollowingKey (user );
78
+ return client .zcard (followingKey );
79
+ }
80
+
81
+ /**
82
+ * 获取当前用户的粉丝数
83
+ *
84
+ * @return 人数
85
+ */
86
+ public Long countFollowers () {
87
+ String followersKey = JedisUtils .getFollowersKey (user );
88
+ return client .zcard (followersKey );
89
+ }
90
+
91
+ /**
92
+ * 获取与某用户的共同关注
93
+ *
94
+ * @param one 用户
95
+ * @return 共同关注的用户集合
96
+ */
97
+ public Set <String > getCommonFollowing (String one ) {
98
+ String commonKey = JedisUtils .getCommonFollowingKey (user , one );
99
+ client .zinterstore (commonKey , JedisUtils .getFollowingKey (user ), JedisUtils .getFollowingKey (one ));
100
+ return client .zrevrange (commonKey , 0 , -1 );
101
+ }
102
+ }
0 commit comments