Python Operation Redis

Source: Internet
Author: User
Tags set set redis server

Basic introduction to the Redis module

[TOC]

Reference
    • Redis Chinese official website
    • Redis Command Reference
    • Beginner's Tutorial
Data cache System:
    • MongoDB: Direct persistence, directly stored in the hard disk's cache system (in doubt)
    • Redis: Semi-persistent, stored in memory and hard disk
    • Memcache: Data can only be stored in memory in the cache system
Redis

redisis a key-value storage system that supports the data types:

    • String
    • List
    • Zet
    • Szet (Ordered collection)
    • Hash (hashed type)

These data types support: Push/pop,add/remove and Fetch intersection, set, and difference sets. The key thing is that these operations are atomic * *

Redis-py's API
    • Connection methods and connection pooling
    • Action: string operation, hash operation, list operation, set operation, sort set operation
    • Use of pipelines (pipeline)
    • Publish a subscription redis-py GitHub link
Connect to Redis

Connection mode: Redis offers 2 classes

    1. StrictRedis: Most of the official orders were fulfilled
    2. Redis: is a StrictRedis subclass that is used for backwards compatibility with older versions of theRedis
Normal connection
import redisredis_config = {    "host": "192.168.189.100",    "port": 6379}# redis连接对象redis_conn = redis.Redis(**redis_config)redis_conn.set("name","ping")print redis_conn.get("name")
Connection pool

Manages all connections to a Redis server, avoiding the overhead of each build and release of the connection. By default, each Redis instance regrets maintaining one of its own connection pools, and can directly establish a connection pool as a parameter to Redis, which enables multiple Redis instances to share a single connection pool.

import redisredis_config = {    "host": "192.168.189.100",    "port": 6379}redis_pool = redis.ConnectPool(**redis_config)r = redis.Redis(connection_pool=redis_pool)r.set(‘name‘,‘qiang‘)print r.get(‘name‘)
Redis string manipulation

The string in Redis is stored in memory by a name corresponding to a value

Set () Parameter: Set (name, value, Ex=none, Px=none, Nx=false, Xx=false)
EX, expiry time (seconds)
PX, Expiration Time (ms)
NX, if set to true, the current set operation executes only if name does not exist, with SETNX (name, value)
XX, if set to true, the current set operation is performed only if name exists

One-time setup Key-value
import redisredis_config = {    "host": "192.168.189.100",    "port": 6379}# 新建一个连接池redis_pool = redis.ConnectionPool(**redis_config)# 新建一个 Redis 连接对象r = redis.Redis(connection_pool=redis_pool)# 在 Redis 中设置值,若不存在则新建,存在则替换r.set("name","ping")print r.get("name")
Batch setup Key-value
import redisredis_config = {    "host": "192.168.189.100",    "port": 6379}# 新建一个连接池redis_pool = redis.ConnectionPool(**redis_config)# 新建一个 Redis 连接对象r = redis.Redis(connection_pool=redis_pool)# 在 Redis 中设置值,若不存在则新建,存在则替换k_v_pair = {    "alpha": "a",    "bete": "b",    "gamma": "c"}# 批量设置值r.mset(**k_v_pair)# 批量取值print r.mget("alpha", "bete", "gamma")
Redis list Operations

redisis List stored in memory according to a name in the corresponding list.

Lpush (name,values)

#在 name 对应的list中添加元素,每个新的元素都添加到列表的最左边r.lpush("list1","alpha")r.lpush("list1",3,4,5)# 查看列表结果print r.lrange("list1",0,-1)# 结果[‘5‘, ‘4‘, ‘3‘, ‘alpha‘]

Rpush (name,values)

# 同lpush,但每个新的元素都添加到列表的最右边

Lpushx (Name,value)

# 在name对应的list中添加元素,只有name已经存在时,值添加到列表的最左边,否则为空

Rpushx (Name,value)

# 在name对应的list中添加元素,只有name已经存在时,值添加到列表的最右边,否则为空

Llen (name)

# name 对应的list元素的个数print r.llen("list1")

Linsert (name,where,refvalue,value) parameter corresponds to: Name:redis name
Where:before (ex) or after (rear)
Refvalue: Values within a list
Value: The data to be inserted

# 在name对应的列表的某一个值前或后插入一个新值r.linsert("list1","BEFORE","alpha","bete")  #在列表内找到第一个元素alpha,在其之前插入 beta

LSet (Name,index,value)

# 对list中的某一个索引位置重新赋值,替换掉以前的元素r.lset("list1",0,"beta")

R.lrem (name,value,num) parameter corresponds to: Name:redis name
Value: The values to remove
num:num=0 deletes all specified values from the list;
Num=2 from front to back, delete 2;
Num=-2 from back forward, remove 2

# 删除name对应的list中的指定值r.lrem("list1","beta",num=1)

R.lpop (name)

# 移除列表的左侧第一个元素,并返回,相当于出桟print r.lpop("list1")

R.lindex (Name,index)

# 根据索引获取列表内元素print r.lindex("list1",1)

Lrange (Name,start,end)

# 分片获取元素,如获取整个listprint r.lrange("list1",0,-1)

LTrim (Name,start,end)

# 移除列表内没有在该索引之内的值r.ltrim("list1",0,2)

Rpoplpush (SRC,DST)

# 从一个列表取出最右边的元素,同时将其添加到另一个列表的最左边# src 要取数据的列表# dst 要添加数据的列表

Brpoplpush (src,dst,timeout=0)

# 同rpoplpush,多了timeout# timeout:取数据的列表没元素后的阻塞时间,0为一直阻塞r.brpoplpush("list1","list2",timeout=0)

Blpop (Keys,timeout)

# 将多个列表排序,按照从左到右去移除各个列表内的元素r.lpush("list1",3,4,5)r.lpush("list2",3,4,5)while True:    print r.blpop(["list1","list2"],timeout=0)    print r.lrange("list1",0,-1),r.lrange("name",0,-1)#结果如下:(‘list1‘, ‘5‘)[‘4‘, ‘3‘] [‘5‘, ‘4‘, ‘3‘](‘list1‘, ‘4‘)[‘3‘] [‘5‘, ‘4‘, ‘3‘](‘list1‘, ‘3‘)[] [‘5‘, ‘4‘, ‘3‘](‘list2‘, ‘5‘)[] [‘4‘, ‘3‘](‘list2‘, ‘4‘)[] [‘3‘](‘list2‘, ‘3‘)[] []

Brpop (Keys,timeout)

# 同 blpop,将多个列表排序,按照从右往左移除各个列表内的元素
Redis Set operation

Set set is a list that is not duplicated

Sadd (name,values)

# 给name对应的集合中添加元素r.sadd("set1","aa")r.sadd("set2","aa",1,2,"bb")

Smembers (name)

# 获取name对应的集合的所有成员

SCard (name)

# 获取name对应的集合中的元素个数r.scard("set1")
Ordered collection

On the basis of the collection, for each element ordered, the ordering of the elements needs to be compared according to another value, so for an ordered set, each element has two values, namely: values and fractions, and fractions are specifically sorted by open.

*Zadd (name,Args,**kwargs)

# 在name对应的有序集合中添加元素r.zadd("set1","a",1,"b",2,"c",3)# 或者r.zadd("set1",b1=10,b2=5)

Zcard (name)

# 获取有序集合内元素的数量

Zcount (Name,min,max)

# 获取有序集合中分数在[min,max]之间的个数print r.zcount("set1",1,5)
Redis Hash Operations

hashIt is a Redis2.0 collection of key-value pairs that, like the data structures in most programming languages, are added later, map meaning that Redis it holds a mapping between strings and strings. Because of this feature, it is hash particularly useful for storing an object. Talking about an object stored in hash will consume less memory and can easily access the entire object.

Hset command

The Hset command is used to specify the value of the key for the love of that hash, if it does not exist, creates and sets the corresponding value, returns an integer of 1, and if the key already exists, the corresponding value is overwritten and the integer 0 is returned. The specific format is:

hset hash_name field value#示例:127.0.0.1:6379> hset myhash name fred(integer) 1127.0.0.1:6379> hset myhash name fred2(integer) 0

* * Hmset Command * *

The Hmset command is similar to the Hset command, and can be used to set the hash key and value. The difference is that Hmset can set multiple key-value pairs at the same time, and the Hmset command returns a simple string ' OK ' after the operation succeeds. The format is as follows:

hmset hash_name field1 value1 field2 value2...#示例127.0.0.1:6379> hmset myhash name fred age 24OK127.0.0.1:6379> hget myhash name"fred"127.0.0.1:6379> hget myhash age"24"

HSETNX command

The HSETNX command is also used to set the key value information if the specified key does not exist. If the key does not exist, Redis creates the key first, then sets the corresponding value, and returns the integer 1 after the operation succeeds. If the key already exists, the command does nothing and returns a value of 0. The format is as follows:

hsetnx hash_name field value#示例127.0.0.1:6379> hsetnx myhsh address hangzhou(integer) 1127.0.0.1:6379> hsetnx myhsh address guangzhou(integer) 0127.0.0.1:6379> hget myhsh address"hangzhou"

Hget command

The Hget command takes a hash to specify the value of the key. If the key exists, return the corresponding value directly, otherwise nil is returned. The specific format is as follows:

hget hash_name field#示例127.0.0.1:6379> hset myhash name fred(integer) 0127.0.0.1:6379> hget myhash name"fred"127.0.0.1:6379> hget myhash nonkey(nil)

Hmget command

The Hmget command is similar to the Hget command, which returns a list of values for a hash of multiple keys, and a nil value for a nonexistent key. The specific format is as follows:

hmget hash_name field1 field2...#示例127.0.0.1:6379> hmset myhash name fred age 24OK127.0.0.1:6379> hmget myhash name age weight1) "fred"2) "24"3) (nil)

hexists command

The hexists command is used to determine if a hash specified key exists and returns 0 if there is a return integer of 1. The specific format is as follows:

hexists hash_name field#示例127.0.0.1:6379> hset myhash name fred(integer) 0127.0.0.1:6379> hexists myhash name(integer) 1127.0.0.1:6379> hexists myhash home(integer) 0

Hlen command

The Hlen command is used to return the number of keys in a hash. The specific format is as follows:

hlen hash_name#示例:127.0.0.1:6379> hmset myhash name fred age 24OK127.0.0.1:6379> hlen myhash(integer) 2127.0.0.1:6379> hlen nonhash(integer) 0

Hdel command

The Hdel command is used to delete the key specified by a hash, and if the key does not exist, no action is made. The return value of the Hdel command is the number of keys that were successfully deleted (not including nonexistent keys). The specific format is:

hdel hash_name field:#示例127.0.0.1:6379> hmset myhash name fred age 24OK127.0.0.1:6379> hdel myhash name age(integer) 2127.0.0.1:6379> hmget myhash name age1) (nil)2) (nil)

Hgetall command

The Hgetall command returns a list that contains all the keys and values for a hash. In the return value, the first key, the next element is the corresponding value, so the Hgetall command returns the list length is twice times the hash size. The specific format is as follows:

hgetall hash_name#示例127.0.0.1:6379> hmset myhash name fred age 24OK127.0.0.1:6379> hgetall myhash1) "name"2) "fred"3) "age"4) "24"
Other operations

Executing in the Redis client

# 根据name删除redis中的任意数据类型delete(*name)# 检测redis的name是否存在exists(name)# 根据 *?等通配符匹配获取redis的namekeys(pattern=‘*‘)# 为某个name设置超时时间expire(name,time)# 重命名rename(src,dst)# 将redis的某个值移动到指定的db下move(name,db)# 随机获取一个redis的name(不删除)randomkey()# 获取name对应值的类型type(name)

Python Operation Redis

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.