redis提供了多种语言的客户端, python连接使用redis 官方推荐使用叫redis的第三方库
python redis 对于redis的使用以及一些管理都很方便:
安装:
pip install redis
这里安装使用的是目前最新版本 3.2.1
redis连接
单连接
# coding:utf-8
import redis
r = redis.Redis(host='100.69.169.13', port=4410, db=13)
r.set('m1', 'test')
print r.get('m1')
python3只允许 bytes, strings or numbers (ints, longs and floats)
而python2会尝试将用户的输入转换为string, 这有时候会引起DataError异常
获取锁
try:
with r.lock('my-lock-key', blocking_timeout=5) as lock:
# code you want executed only after the lock has been acquired
except LockError:
# the lock wasn't acquired
连接池
pool = redis.ConnectionPool(host=‘localhost’, port=6379, db=0)
r = redis.Redis(connection_pool=pool)
线程安全, 可以在线程之间安全地共享Redis客户端实例
这里详解一下redis及redispool
REDIS定义:
class Redis(object):
def __init__(self, host='localhost', port=6379,
db=0, password=None, socket_timeout=None,
socket_connect_timeout=None,
socket_keepalive=None, socket_keepalive_options=None,
connection_pool=None, unix_socket_path=None,
encoding='utf-8', encoding_errors='strict',
charset=None, errors=None,
decode_responses=False, retry_on_timeout=False,
ssl=False, ssl_keyfile=None, ssl_certfile=None,