python连接redis002

例子001、

  通过StrictRedis模式连接到redis、并调用get命令读取了一个string类型的值。

#!/usr/bin/python
#!coding:utf-8

import redis

if __name__=="__main__":
    try:
        r=redis.StrictRedis(host='192.168.80.128',port=6379,db=0)
        #StrictRedis 严格模式下连接redis服务器。
        #1、不实现slect 
        #2、redis 的del 命令改用delete命令(原因是python 中del也是关键字)
        print(r.get('slogan').decode('utf-8'))#接收到的对象是byte类型的
    except Exception as err:
        print(err)

 默认情况下每个redis实例都会自行管理一个用于连接到redis-server端的连接池,也就是说如果在程序中用到了多个redis对象就会有多个连接池,这明显是划不来的。

所以redis还提供了一种共用连接池的方式。

例子002、

  多个redis对象共用一个连接池。

#!/usr/bin/python
#!coding:utf-8

import redis

if __name__=="__main__":
    try:
        conn_pool=redis.ConnectionPool(host='192.168.80.128',port=6379,db=0)
        r=redis.Redis(connection_pool=conn_pool)
        #r=redis.StrictRedis(host='192.168.80.128',port=6379,db=0)
        #StrictRedis 严格模式下连接redis服务器。
        #1、不实现slect 
        #2、redis 的del 命令改用delete命令(原因是python 中del也是关键字)
        print(r.get('slogan').decode('utf-8'))#接收到的对象是byte类型的
    except Exception as err:
        print(err)
原文地址:https://www.cnblogs.com/JiangLe/p/5398607.html