Python Operation Redis

Source: Internet
Author: User
Tags bitwise install redis redis server timedelta

First, Introduction

Redis is a key-value storage system. Similar to memcached, it supports storing more value types, including string (string), list (linked list), set (set), Zset (sorted set-ordered collection), and hash (hash type). These data types support Push/pop, Add/remove, and intersection-set and difference sets, and richer operations, and these operations are atomic. Based on this, Redis supports sorting in a variety of different ways. As with memcached, data is cached in memory to ensure efficiency. The difference is that Redis periodically writes the updated data to disk or writes the modification to the appended record file, and implements the (master-Slave) synchronization on this basis.

Second, Redis installation boot 1, Redis installation
wget Http://download.redis.io/releases/redis-3.0.6.tar.gztar xzf redis-3.0.6.tar.gzcd redis-3.0.6make
2. Redis Boot

Service side

src/redis-server# me when I install srcmake[1]: Leaving directory '/ROOT/REDIS-3.0.6/SRC '

Client

src/redis-cliredis> set foo barokredis> get foo "bar"
Third, Python operation Redis1, install the Redis API
Pip install Redis or Easy_install Redis

Use of the API

APIs used by the API using Redis-py can be categorized as: Connection pooling operation string Operation hash operation list Operation set operation sort Set action pipeline publish subscription

2. Operation mode

The Redis API provides two classes of Redis and Stringredis for Redis commands, Stringredis for most of the official command implementations, and uses the official syntax, Redis is a subclass of Stringredis, Used for backwards compatibility with older versions of the Redis API.

Import Redis r = Redis. Redis (host= ' 192.168.8.246 ', port=6379) r.set (' foo ', ' Bar ') print (R.get (' foo '))

 

3. Connection Pool

The Redis API uses connection pool to manage all links to a Redis server, avoiding the overhead of each build and release, and by default, each Redis instance maintains its own pool of connections. A connection pool can be created directly, and the R case is used as a Redis parameter so that multiple Redis instances can share a single connection pool.

Import Redis pool = Redis. ConnectionPool (host= ' 10.211.55.4 ', port=6379) R = Redis. Redis (Connection_pool=pool) r.set (' foo ', ' Bar ') print (R.get (' foo '))

4. Operation

String operation, the Redis string operation is stored in memory in the form of a name corresponding to a value,

Set (name, value, Ex=none, Px=none, Nx=false, Xx=false) sets the value in Redis, defaults, does not exist, creates, exists, modifies parameters:     ex, Expiration Time (seconds)     px, expiration time (milliseconds)     NX, if set to true, the current set operation only executes XX if the name does not exist, and     if set to true, the pre-post set operation is executed only if name exists

SETNX (name, value) sets the value, and only if name does not exist, perform the set operation (add)

Setex (name, value, time) sets the value parameter:     times, expiration (number of seconds or Timedelta objects)

Psetex (name, Time_ms, value) set value parameter:    Time_ms, Expiration time (numeric milliseconds or Timedelta object)

Mset (*args, **kwargs) batch setting values such as:    Mset (k1= ' v1 ', k2= ' v2 ')    or    mget ({' K1 ': ' v1 ', ' K2 ': ' V2 '})

Get (name) get value

Mget (keys, *args) bulk gain such as:    mget (' K1 ', ' K2 ')    or    r.mget ([' K1 ', ' K2 '])

Getset (name, value) sets the new value and gets the original value

GetRange (name, start, end) gets the subsequence (obtained by Byte, non-character) parameter:    Name,redis name    start, start position (bytes)    end, End position (bytes)

SETRANGE (name, offset, value) modifies the contents of the string, starting from the specified string index and substituting backward (the new value is added backwards when the number of bytes is greater than the old byte) parameter:    offset, index of the string, byte    value, value to set

Setbit (name, offset, value) operates on the bits of the binary representation of the name corresponding value:    Name,redis's name    offset, the index of the bit (the value is transformed into binary and then indexed)    value , the value can only be 1 or 0

Getbit (name, offset) Gets the value of a bit in the binary representation of the name corresponding to the value (0 or 1)

Bitcount (Key, Start=none, End=none) gets the number parameter of 1 in the binary representation of the value of name:    Key,redis name    start, bit start position end    , bit end position

Bitop (operation, dest, *keys) gets multiple values and makes a bitwise operation of the value, saving the final result to the new name corresponding to the value parameter:    operation,and (and), or (or), not (non), XOR (XOR)    Dest, the new redis name    *keys, is looking for a redis name such as:    Bitop ("and", ' new_name ', ' N1 ', ' N2 ', ' N3 ')    get Redis in N1,n2, N3 corresponds to the value, then says all the values do bitwise operations with, and then saves the result new_name the corresponding value

strlen (name) returns the byte length of the corresponding value of name (not the length of the character)

INCR (self, name, amount=1) increment the value corresponding to name, create Name=amount if name does not exist, otherwise, increment. Parameter:    name,redis name    amount, self-increment (must be an integer) Note: Same as Incrby

Incrbyfloat (self, name, amount=1.0) increment the value corresponding to name, create Name=amount if name does not exist, otherwise, increment. Parameter:    name,redis name    amount, self-increment (floating point)

DECR (self, name, amount=1) subtract the value of name, and when name does not exist, create a name=amount, otherwise, subtract. Parameter:    name,redis name    amount, self-meiosis (integer)

Append (key, value) # append content after Redis name Value # parameter:    key, Redis name    value, string to append

Hash operation, the hash stored in the Redis form is a key corresponding to one or more hashes

Hset (name, key, value) name corresponds to a hash in which a key value pair is set (not present, then created; otherwise, modified) parameter:    name,redis name    key,name key    in the corresponding hash Value,name value in the corresponding hash:    hsetnx (name, key, value), created when the current key does not exist in the hash of name (equivalent to add)

Hmset (name, mapping) sets the key value pair parameter in the hash of name:    Name,redis name    mapping, dictionary, such as: {' K1 ': ' v1 ', ' K2 ': ' v2 '} such as:    R.hmset (' xx ', {' K1 ': ' v1 ', ' K2 ': ' V2 '})

Hget (Name,key) Gets the value based on key in the hash of name

Hmget (name, keys, *args) Gets the value parameter of multiple keys in the hash of name:    name,reids corresponding name    keys, to get the key collection, such as: [' K1 ', ' K2 ', ' K3 ']    *args, to get the key, such as: K1,k2,k3 such as:    r.mget (' xx ', [' K1 ', ' K2 '])    or    print r.hmget (' xx ', ' K1 ', ' K2 ')

Hgetall (name) gets the name of all the key values corresponding to the hash

Hlen (name) gets the number of key-value pairs corresponding to the name of the hash

Hkeys (name) Gets the value of all keys in the hash corresponding to name

Hvals (name) Gets the value of all the values in the hash corresponding to name

Hexists (name, key) checks if the hash name corresponds to the current key being passed in

Hdel (Name,*keys) deletes the key value of the specified key in the hash name corresponding to

Hincrby (name, key, amount=1) self-increment name corresponds to the value of the specified key in the hash, and does not exist to create the Key=amount parameter:    name,redis name    key, hash corresponding key    amount, self-increment (whole number)

The Hincrbyfloat (name, key, amount=1.0) increment name corresponds to the value of the specified key in the hash, and does not exist to create the Key=amount parameter:    the name key in Name,redis    , Hash corresponding to the key    amount, the increment (floating point) from the name corresponding to the hash of the specified key value, does not exist to create the Key=amount

Hscan (name, cursor=0, Match=none, Count=none) incremental iterative acquisition, for the data is very useful, hscan can achieve the Shard of data acquisition, not a single time to complete the data, so that the memory is placed in the burst parameters:    name,redis name Cursor    , cursor (fetch data based on cursor batches) match    , matches the specified key, the default none means all key    count, the minimum number of fetches per shard, Default None means that the default number of shards using Redis is:    first: cursor1, data1 = R.hscan (' xx ', cursor=0, Match=none, Count=none)    second time: Cursor2, Data1 = R.hscan (' xx ', Cursor=cursor1, Match=none, Count=none) ...    Until the value of the cursor in the return value is 0 o'clock, indicating that the data has been fetched through the Shard

Hscan_iter (name, Match=none, Count=none) uses yield encapsulation hscan to create generators to get data parameters in batches to Redis: Match    , matches the specified key, default None means all keys    count, the minimum number of shards per shard, default none indicates the number of default shards using Redis, such as: For    item in R.hscan_iter (' xx '):        print Item

  

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.