这篇文章主要介绍了Python与Redis的连接教程,Redis是一个高性能的基于内存的数据库,需要的朋友可以参考下
今天在写zabbix storm job监控脚本的时候用到了python的redis模块,之前也有用过,但是没有过多的了解,今天看了下相关的api和源码,看到有ConnectionPool的实现,这里简单说下。 在ConnectionPool之前,如果需要连接redis,我都是用StrictRedis这个类,在源码中可以看到这个类的具体解释: redis.StrictRedis Implementation of the Redis protocol.This abstract class provides a Python interface to all Redis commands and an implementation of the Redis protocol.Connection and Pipeline derive from this, implementing how the commands are sent and received to the Redis server
使用的方法:
1
2
|
r
=
redis.StrictRedis(host
=
xxxx, port
=
xxxx, db
=
xxxx)
r.xxxx()
|
有了ConnectionPool这个类之后,可以使用如下方法
1
2
|
pool
=
redis.ConnectionPool(host
=
xxx, port
=
xxx, db
=
xxxx)
r
=
redis.Redis(connection_pool
=
pool)
|
这里Redis是StrictRedis的子类 简单分析如下: 在StrictRedis类的__init__方法中,可以初始化connection_pool这个参数,其对应的是一个ConnectionPool的对象:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
class
StrictRedis(
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
,
ssl_cert_reqs
=
None
, ssl_ca_certs
=
None
):
if
not
connection_pool:
..........
|