Blog follow/unfollow implementation

Assume there are below users:

USER_IDUSER_NAME
1JASON
2TONY
3TOM
4TIM
5RUBY
6PYTHON

The following relationship show below:

USER_IDFOLLOW_USER_ID
12
15
24
26
31
46

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值