博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Redis实现微博后台业务逻辑系列(七)
阅读量:7232 次
发布时间:2019-06-29

本文共 1360 字,大约阅读时间需要 4 分钟。

微博点赞功能的实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import 
redis
 
class 
LikeMessage(
object
):
    
"""实现微博点赞功能"""
    
def 
__init__(
self
, msg_id, client):
        
self
.msg_id 
= 
msg_id
        
self
.client 
= 
client
        
self
.key 
= 
"weibo::message::" 
+ 
str
(msg_id) 
+ 
"::like"
         
    
def 
like(
self
, user_id):
        
"""对该微博点赞"""
        
self
.client.sadd(
self
.key, user_id)
         
    
def 
is_liking(
self
, user_id):
        
"""检查用户是否赞了该微博"""
        
return 
self
.client.sismember(
self
.key, user_id)
         
    
def 
undo(
self
, user_id):
        
"""取消点赞"""
        
self
.client.srem(
self
.key, user_id)
         
    
def 
count(
self
):
        
"""获取该微博点赞人数"""
        
return 
self
.client.scard(
self
.key)
         
    
def 
get_all_liking_user(
self
):
        
"""返回赞了该微博的所有用户"""
        
if 
not 
self
.client.exists(
self
.key):
            
return 
False
        
else
:
            
return 
self
.client.smembers(
self
.key)
             
             
if 
__name__ 
=
= 
"__main__"
:
    
redis_client 
= 
redis.StrictRedis()
    
vote 
= 
LikeMessage(
65535
, redis_client)
    
vote.like(
10010
)
    
vote.like(
10086
)
    
vote.like(
10000
)
    
print
(vote.count())
    
print
(vote.is_liking(
10086
))
    
vote.undo(
10086
)
    
print
(vote.get_all_liking_user())

    在这里我们使用无序集合键来保存对微博的点赞信息,我们在之前的文章已经用无序集合键实现了保存微博用户之间的关系,无序集合键还可以实现例如书籍的标签信息,个人标签等。只要是不在乎数据存储的顺序,并且数据必须是唯一的,都可以用无序集合键来实现功能。对于每条微博,redis都会创建一个"weibo::message::<id>::like"的无序集合键来存储对该微博点赞的用户。

本文转自戴柏阳的博客博客51CTO博客,原文链接http://blog.51cto.com/daibaiyang119/1963055如需转载请自行联系原作者

daibaiyang119

你可能感兴趣的文章
(3)pyspark----dataframe观察
查看>>
MFC 使用位图按钮,并且设置按钮的鼠标悬停效果
查看>>
ceph存储之查找对象
查看>>
IE7下浮动(float)层不能实现环绕的问题
查看>>
LeetCode 【Single Number I II III】
查看>>
BOOL类型和引用,三目运算符
查看>>
rocketMq概念介绍
查看>>
Google推出iOS功能性UI测试框架EarlGrey
查看>>
busybox filesystem ts_config: No such file or directory
查看>>
Unity 3D第三人称视角、用途广泛限定角度(视角不能360度翻转)
查看>>
Spreading the Wealth uva 11300
查看>>
Eclipse 报java.lang.UnsupportedClassVersionError: ("yourclass") bad major version at offset=6
查看>>
快读快输板子
查看>>
vue中父组件给子组件额外添加参数
查看>>
分片上传
查看>>
网络编程初识和socket套接字
查看>>
什么是构造函数?它和普通函数的区别?
查看>>
mysql中key 、primary key 、unique key 与index区别
查看>>
zabbix使用企业微信发送告警信息
查看>>
zabbix4.0离线快速编译安装(编译安装方法)
查看>>