日常写代码过程中,经常需要连接redis进行操作。下面我就介绍下python操作redis模块redis中的几个常见类,包括redis连接池。

一、StrictRedis 类

请看代码:。

  #!/usr/bin/env python
# -*- coding:utf-8 -*-
import redis # 引入python的redis库 r = redis.StrictRedis(host="192.168.163.229", port=6379) # 创建StrictRedis对象
r.lpush("city", "shanghai") # 开始操作redis(利用lpush方法向city中加入"shanghai") r2 = redis.StrictRedis(unix_socket_path="/tmp/redis.socket") # 创建StrictRedis对象
r2.lpush("city", "hangzhou") # 开始操作redis(利用lpush方法向city中加入"hangzhou")
 

代码解析:

line 3 :引入redis库。如果未安装redis库,请先安装该库。安装方法这里就不赘述了。

line 5: 创建StricRedis对象,传入的参数是host 和port,分别为redis主机的ip和port。 当然也可以创建Redis对象。redis库中Redis类和StricRedis类都可以操作redis,只不过两者有区别,区别这里不作介绍

line 6: 利用StricRedis中的方法操作redis,非常方便

line 8~9:通过socket连接redis

二、Redis类

请看代码:

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
import redis # 引入python的redis库 r = redis.Redis(unix_socket_path="/tmp/redis.socket") # 创建StrictRedis对象
r.lpush("city", "beijing") # 开始操作redis(利用lpush方法向city中加入"hangzhou")

代码解析:Redis类和StricRedis类使用方式基本是一样的,但是不推荐使用Redis类,至于原因,请自行查阅。

三、ConnectionPool 类

  

 redis_pool = redis.ConnectionPool(connection_class=redis.StrictRedis,
unix_socket_path="/dev/shm/cache.socket", max_connections=5)
conn = redis_pool.make_connection()
conn.lpush("city", "shenzhen")

代码解析:

line1: 创建redis连接池,指定连接使用的类时StricRedis, 并且通过socket方式连接,最大连接数是5.

line3:  创建连接

line3: 操作redis

以上三个类,也可以自定义一些其他参数,具体请参照源码或者官方文档。

题外话:关于redis socket连接。

默认情况下,当安装好了redis,并且以默认的配置文件启动,则redis的连接方式只有host:port,那么如何配置redis的socket连接方式呢?

修改redis.conf文件

  TCP listen() backlog.
#
# In high requests-per-second environments you need an high backlog in order
# to avoid slow clients connections issues. Note that the Linux kernel
# will silently truncate it to the value of /proc/sys/net/core/somaxconn so
# make sure to raise both the value of somaxconn and tcp_max_syn_backlog
# in order to get the desired effect.
tcp-backlog # Unix socket.
#
# Specify the path for the Unix socket that will be used to listen for
# incoming connections. There is no default, so Redis will not listen
# on a unix socket when not specified.
#
unixsocket /tmp/redis.sock
unixsocketperm # Close the connection after a client is idle for N seconds ( to disable)
timeout # TCP keepalive.
#
# If non-zero, use SO_KEEPALIVE to send TCP ACKs to clients in absence
# of communication. This is useful for two reasons:
#
# ) Detect dead peers.
# ) Take the connection alive from the point of view of network
# equipment in the middle.
#
# On Linux, the specified value (in seconds) is the period used to send ACKs.
# Note that to close the connection the double of the time is needed.
# On other kernels the period depends on the kernel configuration.

其中修改的项是

unixsocket /tmp/redis.sock
unixsocketperm

其中unixsocket 后面的目录为sock文件的绝对路径。

修改完配置,重启redis,就可以使用socket方式进行连接了。linux命令行可以使用redsi-cli -s /tmp/redis.sock 进行socket方式的redis连接。

一般生产环境,redis是使用代理进行连接的。因此如何配置twemproxy代理的socket呢?别急,听我慢慢道来

在需要连接redis的机器安装tw代理。如何安装twemproxy?传送门

安装完成之后进行配置。

cd /usr/local/twemproxy  # 进入twemproxy目录

mkdir conf                     # 创建conf目录,默认没有该目录

cd conf

vim ethan.yml
ethan:
listen: /tmp/ethan.socket
hash: fnv1a_64
hash_tag: "{}"
distribution: ketama
auto_eject_hosts: false
timeout:
redis: true
servers:
- 192.168.163.229::

其中ethan 为自定义的名称,只要全局唯一即可。

listen 为tw侦听的socket文件。

hash: hash函数,支持md5,crc16,crc32,finv1a_32等十多种;

timeout: The timeout value in msec that we wait for to establish a connection to the server or receive a response from a server. By default, we wait indefinitely. 即超时时间。

servers 可以定义多个redis服务器,最后面的数字表示负载均衡的权重。

配置完成之后,启动twemproxy:

/usr/local/twemproxy/sbin/nutcracker -c /usr/local/twemproxy/conf/ethan.yml &

如果没有报错,证明socket已经配置完成。

此时就可以通过文件/tmp/ethan.socket连接redis了。

python redis模块的常见的几个类 Redis 、StricRedis和ConnectionPool的更多相关文章

  1. python之模块datetime 常见操作

    # -*- coding: utf-8 -*- #python 27 #xiaodeng #python之模块datetime #http://blog.sina.com.cn/s/blog_6c37 ...

  2. Python之模块IO

    目录 Python之模块IO io概叙 io类层次结构 io模块的类图 io模块的3种I/O 原始I/O,即RawIOBase及其子类 文本I/O,即TextIOBase及其子类 字节I/O(缓存I/ ...

  3. python基础知识9——模块2——常见内置模块

    内置模块 内置模块是Python自带的功能,在使用内置模块相应的功能时,需要[先导入]再[使用] 1.sys 用于提供对Python解释器相关的操作: sys.argv 命令行参数List,第一个元素 ...

  4. python datetime模块strptime/strptime format常见格式命令_施罗德_新浪博客

    python datetime模块strptime/strptime format常见格式命令_施罗德_新浪博客     python datetime模块strptime/strptime form ...

  5. python中os模块和sys模块的常见用法

    OS模块的常见用法 os.remove()   删除文件 os.rename()   重命名文件 os.walk()    生成目录树下的所有文件名 os.chdir()    改变目录 os.mkd ...

  6. python redis模块详解

    前言  现在越来越觉得知识的沉淀尤为重要,最近打算慢慢的把一些知识点做个记录,如果长期不用生疏了也可以快速回顾.下面我会依次介绍在python中常用组件redis,rabbitmq,mongodb,E ...

  7. Python 连接 redis 模块

    redis 模块使用可以分类为: 连接方式 连接池 操作 String操作 Hash操作 List操作 Set操作 Sort Set操作 管道 发布订阅 (1)操作模式 redis提供两个类Redis ...

  8. python之模块pprint之常见用法

    # -*- coding: cp936 -*- #python 27 #xiaodeng #python之模块pprint之常见用法 import pprint data = [(1,{'a':'A' ...

  9. python之模块poplib之常见用法

    # -*- coding: cp936 -*- #python 27 #xiaodeng #python之模块poplib之常见用法 ''' 所以,收取邮件分两步: 第一步:用poplib把邮件的原始 ...

随机推荐

  1. (NO.00004)iOS实现打砖块游戏(十一):"一闪一闪亮晶晶,我们都是小星星"

    大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处. 如果觉得写的不好请告诉我,如果觉得不错请多多支持点赞.谢谢! hopy ;) 现在一个基本的游戏逻辑已经搭建好了,但是感觉还是缺点什么呢? 蠢 ...

  2. CentOS6 上OpenWRT交叉编译

    目的不是为了编译固件,而是为了一个是编译可执行文件,放倒op的路由器上跑,另一个目的是安装一些开源软件折腾下(例如ss-lib),需要打包成 .ipk 格式 路由设备信息 erya@ERYA:~$ c ...

  3. 基于IMX515EVK+WINCE6.0---支持PB6.0通过USB下载镜像文件

    基于IMX515EVK+WINCE6.0---支持PB6.0通过USB下载镜像文件 在INAND还没有写入镜像文件之前,通过ATK工具烧录xldr.nb0和eboot.nbo到INAND中,见相关链接 ...

  4. javascript之BOM浏览器对象模型引入

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  5. Python+Visual Studio

    一直在找一个比较好的Python IDE,无奈找来找去都不太好用,由于经常用Visual Studio,所以很希望找到一个能够在VS中的Python扩展.今天发现了一个很给力的VS扩展,可以在VS中方 ...

  6. numpy教程:矩阵matrix及其运算

    http://blog.csdn.net/pipisorry/article/details/48791403 numpy矩阵简介 NumPy函数库中存在两种不同的数据类型(矩阵matrix和数组ar ...

  7. Leetcode_20_Valid Parentheses

    本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/41450987 通过本文你能学到如下知识: (1)对数据结构 ...

  8. 9.5、Libgdx加速度计

    (官网:www.libgdx.cn) 加速度计可以让设备通过三个坐标轴检测加速度.通过加速度可以检测设备的方向. 加速度的单位是米每秒的平方.如果一个坐标轴指向地心,加速度大概是-10米每秒的平方.如 ...

  9. RecyclerView实现瀑布流效果(二)

    在上篇中我们知道RecyclerView中默认给我们提供了三种布局管理器,分别是LinearLayoutManager.GridLayoutManager.StaggeredGridLayoutMan ...

  10. 关于Android自定义view 你所需要知道的基本函数

    开始时之前想吐槽一句..iphone的闹钟,12小时制.我成功的把闹钟订到了下午5:00 导致错过一班飞机.心疼改签费. 候机ing,没有事做,来写一下学习自定义view必须掌握的基本函数.这里只挑一 ...