Redis指南——05 实践

第5章 实践

5.1 Python与Redis

Redis官方推荐的Python客户端是redis-py① 。

注释:①见https://github.com/andymccurdy/redis-py

5.1.1 安装

推荐使用pip install redis安装最新版本的redis-py,也可以使用easy_install:easy_ install redis。

5.1.2 使用方法

首先需要引入redis-py:

import redis

下面的代码将创建一个默认连接到地址127.0.0.1,端口6379的Redis连接:

r=redis.StrictRedis()

也可以显式地指定需要连接的地址:

r=redis.StrictRedis(host='127.0.0.1', port=6379, db=0)

使用起来很容易,这里以SET和GET命令作为示例:

r.set('foo', 'bar') # True

r.get('foo') # 'bar'

5.1.3 简便用法

1.HMSET/HGETALL

HMSET支持将字典作为参数存储,同时HGETALL的返回值也是一个字典,搭配使用十分方便:

r.hmset('dict', {'name': 'Bob'})

people=r.hgetall('dict')

print(people) # {'name': 'Bob'}

2.事务和管道

redis-py的事务使用方式如下:

pipe=r.pipeline()

pipe.set('foo', 'bar')

pipe.get('foo')

result=pipe.execute()

print (result) # [True, 'bar']

管道的使用方式和事务相同,只不过需要在创建时加上参数transaction=False:

pipe=r.pipeline(transaction=False)

事务和管道还支持链式调用:

result=r.pipeline().set('foo', 'bar').get('foo').execute() # [True, 'bar']

代码如下:

import redis
#r=redis.StrictRedis()

#连接远程,我这里是node5
r=redis.StrictRedis(host='node5', port=6379, db=0)
#1SETGET
"""
s=r.set('foo','bar')
print(s)
g=r.get('foo')
print(g)
"""


#2HMSET/HGETALL
"""
r.hmset('dict', {'name': 'Bob'})
people=r.hgetall('dict')
print(people) # {'name': 'Bob'}
"""


#3、事务和管道
"""
#3.1
、事务使用方式
pipe=r.pipeline()
pipe.set('foo', 'bar')
pipe.get('foo')
result=pipe.execute()
print(result) # [True, 'bar']
"""


#3.2、管道的使用方式和事务相同,只不过需要在创建时加上参数transaction=False
pipe=r.pipeline(transaction=False)
#事务和管道还支持链式调用:
result=r.pipeline().set('foo', 'bar').get('foo').execute()
print(result)
# [True, 'bar']

结合我之前的一篇博客:https://blog.csdn.net/Allenzyg/article/details/107663985

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AllenGd

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值