Assume there are below users:
USER_ID | USER_NAME |
---|---|
1 | JASON |
2 | TONY |
3 | TOM |
4 | TIM |
5 | RUBY |
6 | PYTHON |
The following relationship show below:
USER_ID | FOLLOW_USER_ID |
---|---|
1 | 2 |
1 | 5 |
2 | 4 |
2 | 6 |
3 | 1 |
4 | 6 |
Redis command sample
While the login user<1> click follow user<2> button:
sadd followed:userid:1:list 2
sadd follower:userid:2:list 1
While the login user<1> click follow user<5> button:
sadd followed:userid:1:list 5
sadd follower:userid:5:list 1
………
After followed the user, the “Follow” link should replaced with “Unfollow”:
sismember followed:userid:1:list 2
> 1
#return 1 means that user<2> included in the list
#so the link will show as "Unfollow"
sismember followed:userid:1:list 4
> 0
#return 0 means that user<4> excluded in the list
#so the link will show as "Follow"
Unfollow the user
#assume user<1> unfollow user<2>
srem followed:userid:1:list 2
srem follower:userid:2:list 1
Find out your followers:
get follower:userid:6:list
> 2
> 4
Push the blog to the followers
#foreach the folowers (include self)
#current case is [6 2 4]
lpush accept:followerid:6 1 #blog id
lpush accept:followerid:2 1
lpush accept:followerid:4 1
#if user<4> login, use below command to show the blog list
sort accept:followerid:4 DESC
get accept:followerid:4
#Think about if there are millions followers?
#It it not the best way to loop millions
Pull the blogs from following users
#user<1> write the blogs:
zadd pulllist:userid:1 1 1
zadd pulllist:userid:1 2 2
...
zadd pulllist:userid:1 20 20
set lastpull:userid:1 20
#assume that only 20 blogs need pull
zcard pulllist:userid:1
> 20
#if zcard return more than 20
#remove the oldest one
zremrangebyrank pullist:userid:1 0 1
#The followed user<2> login to pull the blog list
get followed:userid:1:list
#for each the list to pull the blog list
zrangebyscore pullist:userid:1 (get lastpull:userid:1) 2^32-1
How to find the same followers
#user<4> and user<6> have the same followers user<2>
sinter follower:userid:4:list follower:userid:6:list
> 2
Store the blog as hash structure
hmset blog:blogid:1 userid "1" username "jason" content "test" time "2015-11-26"
hmget blog:blogid:1 userid content time nofield
> 1
> jason
> test
> 2015-11-26
> nil