Python client for Redis 官翻文档2.10.1(二)

Stella981
• 阅读 448

更多的细节

连接池:

在幕后,redis-py 使用连接池管理连接到redis-server的连接.默认, 一旦你创建了一个Redis的实例 ,这个实例相应有自己的连接池。你可以重写此行为,在创建一个Redis实例的时候指定一个创建的连接池,告诉这个实例是使用哪个连接。(我的理解:如果存在多个redis-server,指定连接哪个)

>>> pool = redis.ConnectionPool(host='localhost', port=6379, db=0)
>>> r = redis.Redis(connection_pool=pool)

连接:

ConnectionPoll管理一组连接,redis-py提供两种方式连接到redis-server.

一种是(也是默认的)TCP 套接字类型

另一种是使用 UnixDomainSocket连接。通过传递unix_socket_path参数,这是一个字符串,代表unix domain socket
文件。 另外确保在redis.conf定义unixsocket,默认是注释掉的。(这个俺不懂,接触的少)

>>> r = redis.Redis(unix_socket_path='/tmp/redis.sock')

您可以创建自己的连接子类。如果你想控制套接字的行为在一个异步框架将会非常有用。

实例化一个客户端类使用你自己的连接,您需要创建一个连接池,通过你的connection_class类,还有相应的参数

>>> pool = redis.ConnectionPool(connection_class=YourConnectionClass,   
                             your_arg='...', ...)

解析器

Parser classes provide a way to control how responses from the Redis server are parsed. redis-py ships with two parser classes, the PythonParser and the HiredisParser. By default, redis-py will attempt to use the HiredisParser if you have the hiredis module installed and will fallback to the PythonParser otherwise.

解析器类提供了怎么样解析从Redis-server服务器返回的数据。

redis-py提供了两种解析器类,PythonParser 和 HiredisParser。默认使用HiredisParser,如果没有安装这个第三方模块就会使用PythonParser。(内部会尝试倒入HiredisParser,失败了就使用默认的)

Hiredis is a C library maintained by the core Redis team. Pieter Noordhuis was kind enough to create Python bindings. Using Hiredis can provide up to a 10x speed improvement in parsing responses from the Redis server. The performance increase is most noticeable when retrieving many pieces of data, such as from LRANGE or SMEMBERS operations.

Hiredis就是用C写,而且是redis核心组成员写的,速度是另一个的10倍,(这么严重)当检索大量数据时性能提升最为明显  如这几个LRANGE or SMEMBERS

Hiredis is available on PyPI, and can be installed via pip or easy_install just like redis-py.

$ pip install hiredis

or

$ easy_install hiredis

响应回调

The client class uses a set of callbacks to cast Redis responses to the appropriate Python type. There are a number of these callbacks defined on the Redis client class in a dictionary called RESPONSE_CALLBACKS.

客户端类用一组回调函数处理Redis返回的数据,同时转换成合适的python的类型。在Redis客户端类中定义了很多这种回调函数。(实际是放在StrictRedis类中,放在RESPONSE_CALLBACKS中,这是个字典)

Custom callbacks can be added on a per-instance basis using the set_response_callback method. This method accepts two arguments: a command name and the callback. Callbacks added in this manner are only valid on the instance the callback is added to. If you want to define or override a callback globally, you should make a subclass of the Redis client and add your callback to its REDIS_CALLBACKS class dictionary.

可以使用每个实例的set_response_callback方法添加自定义回调函数。回调函数接受两个参数:redis的命令和回调函数名。

def set_response_callback(self, command, callback):
        "Set a custom Response Callback"
        self.response_callbacks[command] = callback

如果你想定义一个新的回调或复写存在的回调函数,需要写一个Redis client继承原来的Redis client,添加你的回调放到REDIS_CALLBACKS中。

Response callbacks take at least one parameter: the response from the Redis server. Keyword arguments may also be accepted in order to further control how to interpret the response. These keyword arguments are specified during the command's call to execute_command. The ZRANGE implementation demonstrates the use of response callback keyword arguments with its "withscores" argument.

Thread Safety

线程安全

Redis client instances can safely be shared between threads. Internally, connection instances are only retrieved from the connection pool during command execution, and returned to the pool directly after. Command execution never modifies state on the client instance.

redis客户端实例在现成之间安全共享。在内部,执行命令时从连接池中取出一个连接,使用完后再放回连接池。在客户端实例,命令执行不会修改状态.

However, there is one caveat: the Redis SELECT command. The SELECT command allows you to switch the database currently in use by the connection. That database remains selected until another is selected or until the connection is closed. This creates an issue in that connections could be returned to the pool that are connected to a different database.

但是有一个警告:Redis的select命令。select命令允许你从0号数据库切换到1号数据库使用当前的连接。0号数据库会被当前连接仍然选择直到其他连接选择它,或者当前的连接关闭。这就产生了一个问题,This creates an issue in that connections could be returned to the pool that are connected to a different database.

As a result, redis-py does not implement the SELECT command on client instances. If you use multiple Redis databases within the same application, you should create a separate client instance (and possibly a separate connection pool) for each database.

所以,redis-py没有实现select的命令。要是想在一个web应用程序中使用多个redis的数据库,应该创建一个单独的redis客户端为每个数据库(可能是一个单独的连接池)

red0 = redis.StrictRedis(
            host='localhost', port=6379,
            db=0, password=None, #用的是0号数据库
             charset='utf-8'
        )

red1 = redis.StrictRedis(
            host='localhost', port=6379,
            db=1, password=None,#用的是1号数据库
            charset='utf-8'
        )

It is not safe to pass PubSub or Pipeline objects between threads.

在线程之间传递PubSub 和 Pipeline是不安全的。

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Easter79 Easter79
2年前
Twitter的分布式自增ID算法snowflake (Java版)
概述分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的。有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。而twitter的snowflake解决了这种需求,最初Twitter把存储系统从MySQL迁移
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这