Python读书笔记-进阶篇-2.Redis

目录

1.Redis连接

1.1新建连接

1.2连接池

2.Redis操作


 


Redis是一个高效的key-value数据存储系统,支持多种数据结构。Redis是基于内存的操作,支持的数据类型有字符串、哈希表、列表、集合以及有序集合,主要用于缓存、高速队列以及消息的订阅与发布等。

Redis本身涉及到的内容很丰富,本文只概述学习Redis在Python中的应用。Redis的详细内容再另文概述。

Redis在Python中的应用包括Redis的连接以及各种数据结构的操作。

1.Redis连接

redis-py提供了Redis与StrictRedis两个类用于实现Redis的命令。StrictRedis用于实现官方大部分的命令,Redis是StrictRedis的子类,用于向后兼容。首先预览一下Redis类的构造函数。Redis连接方式有两种,直接创建连接或者通过连接池的方式。

 def __init__(self, 
            host='localhost',                     #Redis服务器地址 
            port=6379,                            #Redis连接端口
            db=0,                                 #db
            password=None,                        #Redis连接秘钥(服务器需要打开认证)
            socket_timeout=None,                  #客户端空闲断开连接
            socket_connect_timeout=None,          
            socket_keepalive=None, 
            socket_keepalive_options=None,
            connection_pool=None,                 #使用连接池方式连接Redis
            unix_socket_path=None,                #unix socket 实现Redis本地连接
            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='required', 
            ssl_ca_certs=None,
            max_connections=None):                #最大连接数

1.1新建连接

redis-py每次请求时都会创建redis连接。即使使用的是直接创建连接方式,redis-py也会首先创建一个redis连接池,然后再向连接池申请一个连接。这种方式下,redis连接池没有复用。

# !/usr/bin/env python3
# Filename:redis_helper.py

conf = {'HOST':'192.168.9.130',
    'PORT':6379
}

import redis

class RedisHelper(object):
    
    def getValue(self,
                 host = '127.0.0.1',
                 port = 6379,
                 db = 0,
                 *args):
        try:
            connection = redis.Redis(host = host,
                        port = port,
                        db = db,
                        decode_responses = True)
            if len(args) == 0:
                keys = connection.keys()
                for key in keys:
                    print(key)
            else:
                for key in args:
                    print("{0:<10}:{1}".format(key,str(connection.get(key))))
        except Exception as e:
            print("redis connect error!",e)
            
if __name__ == "__main__":
    helper = RedisHelper()
    helper.getValue(conf['HOST'], conf['PORT'], 0,'user.age')

1.2连接池

redis-py通过ConnectionPool管理所有的redis连接,避免了每次创建redis连接的系统开销。

# !/usr/bin/env python3
# Filename:redis_helper.py

conf = {'HOST':'192.168.9.130',
    'PORT':6379
}

import redis

class RedisHelper(object):
    
    #redis连接池
    pool = ''
    def __init__(self,
                 host = '127.0.0.1',
                 port = 6379,
                 db = 0,):
        try:
            self.pool = redis.ConnectionPool(host = host,
                                             port = port,
                                             db = db,
                                             decode_responses = True)
        except Exception as e:
            print("redis connect error!",e)
    
    
    def getValue(self,*args):
        try:
            connection = redis.Redis(connection_pool = self.pool)
            if len(args) == 0:
                keys = connection.keys()
                for key in keys:
                    print(key)
            else:
                for key in args:
                    print("{0:<10}:{1}".format(key,str(connection.get(key))))
        except Exception as e:
            print("redis connect error!",e)
            
if __name__ == "__main__":
    helper = RedisHelper(conf['HOST'], conf['PORT'], 0)
    helper.getValue('user.age')

2.Redis操作

redis-py支持Redis的所有操作,api接口命名方式也基本相同。详细命令可以参阅Redis官网《The full list of commands》或者参阅《Redis命令参考

2.1Key

Key(键)相关操作移步《Key

#!/usr/bin/env python3
#Filename:redis_helper.py

conf = {'HOST':'192.168.9.130',
    'PORT':6379
}

import redis,time

class RedisHelper(object):
    
    #redis连接池
    pool = ''
    def __init__(self,
                 host = '127.0.0.1',
                 port = 6379,
                 db = 0,):
        try:
            self.pool = redis.ConnectionPool(host = host,
                                             port = port,
                                             db = db,
                                             decode_responses = True)
        except Exception as e:
            print("redis connect error!",e)
    
    
    def op_keys(self):
        try:
            connection = redis.StrictRedis(connection_pool = self.pool)
            key = "user.name"
            #redis所有的键值
            rt = connection.keys("user.*");
            self.__print__(rt,"所有键值") 
            #检测key是否存在
            rt = connection.exists(key) 
            self.__print__(rt,"键值是否存在") 
            #删除给定的一个或者多个key
            rt = connection.delete("key")            
            self.__print__(rt,"删除给定键值")
            #给key赋值
            rt = connection.set(key, "lreis", ex=1000)
            self.__print__(rt,"给key赋值")
            #查询key的过期时间
            time.sleep(10)
            rt = connection.ttl(key)
            self.__print__(rt,"查询key值生存时间")
            #修改key过期时间
            rt = connection.expire(key, 100)
            self.__print__(rt,"修正key生存时间")
            rt = connection.ttl(key)
            self.__print__(rt,"查询key值生存时间")
            #键值对应的数据类型
            rt = connection.type(key)
            self.__print__(rt,"键值对应的数据类型")
            #键值重命名
            rt = connection.rename(key, "user.nickname")
            self.__print__(rt,"键值重命名")
            rt = connection.exists(key) 
            self.__print__(rt,"键值是否存在") 
        except Exception as e:
            print("redis connect error!",e)
           
    def __print__(self,rt,*args):
        if len(args)>0:
            print("[命令测试]%s==>"%args[0])
        if isinstance(rt, int):
            print("Redis操作结果:%d"%rt)
        elif isinstance(rt, str):
            print("Redis操作结果:%s"%rt)
        elif isinstance(rt, list):
            print("Redis操作结果:%s"%(",".join(rt)))
        else:
            print("Redis操作结果类型:%s"%type(rt))
            pass       
if __name__ == "__main__":
    helper = RedisHelper(conf['HOST'], conf['PORT'], 0)
    helper.op_keys()

2.2String

字符串类型

 def op_string(self):
        try:
            connection = redis.StrictRedis(connection_pool = self.pool)
            #给key赋值 set key val (ex 有效期秒)(px 有效期毫秒)(nx 不存在添加)(xx 存在才添加)
            key = "user.name"
            #删除key
            rt = connection.delete(key)
            self.__print__(rt,"删除给定键")
            rt = connection.set(key,"lreis2010",ex = 1000)
            self.__print__(rt,"键值赋值")
            #给key值附加新的属性append key value
            rt = connection.append(key, " is a nickname!")
            self.__print__(rt,"字符追加")
            #赋值数值型数据
            age = "user.age"
            rt = connection.set(age, 19)
            #数值型数据自增
            rt = connection.incr(age, 1)
            self.__print__(rt,"数值型数据自增")
            #数值型数据自减
            rt = connection.decr(age, 1)
            self.__print__(rt,"数值型数据自减")
            #获取字符串片段
            rt = connection.getrange(key, 0, 4)
            self.__print__(rt,"获取字符串片段")
            #位图操作
            rt = connection.setbit("bit1",0, 1)
            rt = connection.setbit("bit1",3, 1)
        except Exception as e:
            print("redis connect error!",e)

猜你喜欢

转载自blog.csdn.net/lreis2010/article/details/87720503