Database operations in Python memcache, Redis, SQLAlchemy

Source: Internet
Author: User
Tags bitwise cas hash redis strlen install redis redis server timedelta

First, Memcached

Memcached is a high-performance distributed memory object caching system for dynamic Web applications to reduce database load. It reduces the number of read databases by caching data and objects in memory, thereby increasing the speed of dynamic, database-driven Web sites. Memcached is based on a hashmap that stores key/value pairs. Its daemon (daemon) is written in C, but the client can write in any language and communicate with the daemon through the memcached protocol.

1, installation and basic use

Memcached Installation:

wget http://memcached.org/latest
TAR-ZXVF Latest
CD memcached-1.x.x
./configure && make && make test && sudo make install

PS: Dependency Pack libevent
Yum Install Libevent-devel
Apt-get Install Libevent-dev
Start memcached:

Memcached-d-M 10-u root-l 192.168.20.219-p 12000-c 256-p/tmp/memcached.pi

Parameter description:
-D is to start a daemon
-M is the amount of memory allocated to Memcache, in megabytes
-U is the user running Memcache
-L is a listening server IP address
-P is the port to set memcache listening, preferably over 1024 ports
The-c option is the maximum number of concurrent connections to run, the default is 1024, according to the amount of load on your server to set
-P is to set the PID file to save Memcache
Python Install memcached module:

Python operation memcached using python-memcached module
Download installation: https://pypi.python.org/pypi/python-memcached

Unzip the compressed package and switch to the installation package directory under CMD command
Perform a python setup.py install installation
2. Simple connection

Import Memcache

MC = Memcache. Client (["192.168.20.219:12000"],debug=true)
Mc.set ("foo", "Hello,world")
ret = Mc.get ("foo")
Print (ret)

# Hello,world
Debug = True indicates that an error message is displayed when an error occurs, and then the parameter is removed from the line

3. Cluster

The python-memcached module natively supports cluster operations by maintaining a list of hosts in memory, and the weight of the host in the cluster is proportional to the number of times the host repeats in the list

Host weights
1.1.1.1 1
1.1.1.2 2
1.1.1.3 1

So in the in-memory host list is:
Host_list = ["1.1.1.1", "1.1.1.2", "1.1.1.2", "1.1.1.3",]
If the user wants to create a key-value pair (such as: K1 = "V1") in memory, follow the steps:

Converts K1 into a number based on the algorithm
Calculate the number and host list length by the remainder and get a value of N (0 <= N < list length)
Gets the host for the index in the host list based on the value obtained in step 2nd, for example: Host_list[n]
Connect the host acquired in step 3rd and place k1 = "V1" In the server's memory
The code implementation is as follows:

MC = Memcache. Client ([(' 1.1.1.1:12000 ', 1), (' 1.1.1.2:12000 ', 2), (' 1.1.1.3:12000 ', 1)], debug=true)

Mc.set (' K1 ', ' v1 ')
4, add

Add a key value pair, repeat the add operation exception if a key already exists

#!/usr/bin/env python
#-*-Coding:utf-8-*-
#-author-lian

Import Memcache

MC = Memcache. Client (["192.168.20.219:12000"], debug=true)
Mc.add (' K1 ', ' v1 ')

#MemCached: While expecting ' STORED ', got unexpected response ' not_stored '
#报错, repeated additions to the existing key, failed!!!
5, replace

Replace modifies the value of a key, and if key does not exist, the exception

#!/usr/bin/env python
#-*-Coding:utf-8-*-
#-author-lian

Import Memcache

MC = Memcache. Client (["192.168.20.219:12000"], debug=true)
# if KKKK is present in the memcache, the substitution succeeds, otherwise the exception
Mc.replace (' kkkk ', ' 999 ')

#MemCached: While expecting ' STORED ', got unexpected response ' not_stored '
6, set and Set_multi

Set sets a key value pair, if key does not exist, then create, if key exists, modify
Set_multi sets multiple key-value pairs, if key does not exist, then creates, if key exists, modifies

#!/usr/bin/env python
#-*-Coding:utf-8-*-
#-author-lian

Import Memcache

MC = Memcache. Client (["192.168.20.219:12000"], debug=true)

Mc.set (' Key0 ', ' Lianzhilei ')

Mc.set_multi ({' Key1 ': ' Val1 ', ' key2 ': ' Val2 '})
7, delete and Delete_multi

Delete Deletes a specified key value pair in memcached
Delete_multi deletes the specified number of key value pairs in memcached

#!/usr/bin/env python
#-*-Coding:utf-8-*-
#-author-lian

Import Memcache

MC = Memcache. Client ([' 192.168.20.219:12000 '], debug=true)

Mc.delete (' Key0 ')
Mc.delete_multi ([' Key1 ', ' Key2 '])
8, Get and Get_multi

Get gets a key value pair
Get_multi get one more key value pair

#!/usr/bin/env python
#-*-Coding:utf-8-*-
#-author-lian

Import Memcache

MC = Memcache. Client ([' 192.168.20.219:12000 '], debug=true)

val = mc.get (' Key0 ')
Item_dict = Mc.get_multi (["Key1", "Key2", "Key3"])
9, Append and prepend

Append modifies the value of the specified key and appends the value after
Prepend modifies the value of the specified key and inserts the contents before the value

Import Memcache

MC = Memcache. Client (["192.168.20.219:12000"], debug=true)
# k1 = "V1"

Mc.append (' K1 ', ' after ')
# k1 = "V1after"

Mc.prepend (' K1 ', ' before ')
10, DECR and INCR

INCR, add a value of memcached to N (n defaults to 1)

DECR, reduce a value in memcached by N (n defaults to 1)

#!/usr/bin/env python
#-*-Coding:utf-8-*-
#-author-lian

Import Memcache

MC = Memcache. Client (["192.168.20.219:12000"], debug=true)
Mc.set (' K1 ', ' 777 ')

MC.INCR (' K1 ')
# K1 = 778

MC.INCR (' K1 ', 10)
# K1 = 788

MC.DECR (' K1 ')
# k1 = 787

MC.DECR (' K1 ', 10)
# k1 = 777
11, gets and CAs

such as the number of shopping malls, the assumption that the change is saved in memcache, Product_count = 900

A user refreshes the page read from memcache to Product_count = 900

b User Refresh page read from memcache to Product_count = 900

If a, B users are buying goods

A user changes the number of items remaining product_count=899

b user changes the number of products remaining product_count=899

So that the data in the cache is not correct, two users after the purchase of goods, merchandise remaining or 899

If you use Python's set and get to manipulate the above procedure, then the program will look like this!

If you want to avoid this, just use gets and CAs, such as:

#!/usr/bin/env python
#-*-Coding:utf-8-*-
#-author-lian

Import Memcache

MC = Memcache. Client ([' 192.168.20.219:12000 '], debug=true, cache_cas=true)

v = mc.gets (' Product_count ')
# ...
# If someone has modified product_count before gets and CAs, the following settings will fail to perform an exception to prevent abnormal data from being generated
Mc.cas (' Product_count ', "899")
Ps: In essence, every time the implementation of gets, will get a memcache from the number, through the CAs to modify the value of gets, will carry the previous gain and memcache of the self-appreciation in comparison, if equal, you can submit, if you do not want to wait, That means that between gets and CAs execution, another person performs the gets (gets the specified value of the buffer) so that abnormal data is possible, and no modification is allowed

Second, Redis

Redis is a key-value storage system. Like memcached, it supports a relatively greater number of stored value types, including string (string), list (linked list), set (set), Zset (sorted set-ordered set), and hash (hash type). These data types support Push/pop, Add/remove and intersection-set and differential sets and richer operations, and these operations are atomic. On this basis, Redis supports a variety of different ways of ordering. As with memcached, data is cached in memory to ensure efficiency. The difference is that Redis periodically writes the updated data to the disk or writes the modification operation to the appended record file, and on this basis realizes the Master-slave (master-Slave) synchronization

1, installation and basic use

Redis Installation:

wget http://download.redis.io/releases/redis-3.0.6.tar.gz
Tar xzf redis-3.0.6.tar.gz
CD redis-3.0.6
Make
Start the service side:

Src/redis-server
To start the client:

Src/redis-cli
Redis> set Foo Bar
Ok
Redis> get foo
"Bar
2, Python installation Redis module

sudo pip install Redis
Or
sudo easy_install Redis
Or
SOURCE Installation

See: Https://github.com/WoLpH/redis-py
The use of Redis-py APIs can be categorized as:

Connection mode
Connection pool
Operation Pipeline
String operation
Hash operation
List operation
Set operation
Sort Set operation
Pipeline
Publish Subscriptions
3. Simple connection

Redis-py provides two classes of Redis and Strictredis to implement Redis commands, Strictredis to implement most of the official commands, and use official syntax and commands, Redis is a subclass of Strictredis, Redis-py for backward compatibility with older versions

#!/usr/bin/env python
#-*-Coding:utf-8-*-
#-author-lian

Import Redis

R = Redis. Redis (host= ' 192.168.20.219 ', port=6379)
R.set (' foo ', ' Hello,world ')
Print (R.get (' foo '))

# b ' Hello,world '
4. Connection Pool

Redis-py uses connection pool to manage all connections to a Redis server, avoiding the overhead of each build and release of the connection. By default, each Redis instance maintains a connection pool of its own. You can set up a connection pool directly and then Redis as a parameter, which enables multiple Redis instances to share a connection pool

#!/usr/bin/env python
#-*-Coding:utf-8-*-
#-author-lian

Import Redis

Pool = Redis. ConnectionPool (host= ' 192.168.20.219 ', port=6379)

R = Redis. Redis (Connection_pool=pool)
R.set (' foo ', ' Hello,world ')
Print (R.get (' foo '))

# b ' Hello,world '
5. String operation

The string in Redis is stored in memory by a value corresponding to a name. As shown in figure:

①set (name, value, Ex=none, Px=none, Nx=false, Xx=false)

Set a value in Redis, default, no exist, create, exist modify
Parameters:
Ex, Expiration Time (SEC)
PX, Expiration Time (ms)
NX, if set to true, the current set operation executes only if name does not exist
XX, if set to true, the current set operation executes only if name exists

127.0.0.1:6379> set name Lzl Ex 2
Ok
127.0.0.1:6379> Get Name
"Lzl"
127.0.0.1:6379> Get Name
(nil)
②SETNX (name, value)

Set the value and perform the Setup action (add) if name does not exist

127.0.0.1:6379> setnx name Lianzhilei
(integer) 0
127.0.0.1:6379> Get Name
"Lzl"
127.0.0.1:6379> setnx name2 Lianzhilei
(integer) 1
127.0.0.1:6379> Get Name2
"Lianzhilei"
③setex (name, value, time)

# Set values
Parameters
# time, expiration (digit seconds or Timedelta object)

127.0.0.1:6379> Setex Age 2 18
Ok
127.0.0.1:6379> Get Age
"18"
127.0.0.1:6379> Get Age
(nil)
④psetex (name, Time_ms, value)

# Set values
Parameters
# Time_ms, Expiration time (numeric millisecond or Timedelta object)
⑤mset (*args, **kwargs)

Batch Set Value
Such as:
Mset (k1= ' v1 ', k2= ' v2 ')
Or
Mget ({' K1 ': ' v1 ', ' K2 ': ' V2 '})

127.0.0.1:6379[2]> mset name Lzl age 18
Ok
127.0.0.1:6379[2]> keys *
1) "Age"
2) "Name"
⑥get (name)

#获取值

R.set ("name", "Lzl")
Print (R.get (' name '))
# b ' Lzl '
⑦mget (keys, *args)

Bulk acquisition
Such as:
Mget (' name ', ' age ')
Or
R.mget ([' Name ', ' age '])

127.0.0.1:6379[2]> Mget name Age
1) "Lzl"
2) "18"
⑧getset (name, value)

Set the new value and get the original value

127.0.0.1:6379[2]> Getset name Eric
"Lzl"
127.0.0.1:6379[2]> Get Name
"Eric."
⑨getrange (key, start, end)

# Gets the subsequence (obtained from bytes, not characters)
Parameters
# Name,redis's name
# Start, start position (bytes)
# end, ending position (bytes)
# For example: "Lian Zhilei", 0-3 means "Lian"

127.0.0.1:6379[2]> GetRange name 0 5
"Lianzh"
⑩setrange (name, offset, value)

# modifies the contents of the string and replaces it backwards from the specified string index (added backwards when the new value is too long)
Parameters
# Offset, index of string, byte (three bytes of a kanji)
# value, values to set
⑪setbit (name, offset, value)

# manipulate the bits of the binary representation of the corresponding value of the name





Parameters


# Name,redis's name


# Offset, index of bit (convert value to binary and index)


# value, the value can only be 1 or 0





# Note: If there is a correspondence in the Redis: N1 = "Foo",


Then the binary representation of String Foo is: 01100110 01101111 01101111


So, if you execute Setbit (' N1 ', 7, 1), you will set the 7th bit to 1,


Then the final binary becomes 01100111 01101111 01101111, namely: "Goo"





# extension, Transformation binary representation:





# source = ' Lian Zhilei '


Source = "Foo"





For I in Source:


num = Ord (i)


Print (Bin (num). replace (' B ', '))





In particular, what if source is the Chinese character "Lian Zhilei"?


A: For Utf-8, each Chinese character occupies 3 bytes, then "Wu Jianzi" has 9 bytes


For Chinese characters, the For loop is iterated by Byte, then, at the time of iteration, converts each byte to decimal, and then converts the decimal number to binary


11100110 10101101 10100110 11100110 10110010 10011011 11101001 10111101 10010000

127.0.0.1:6379[2]> set N1 foo
Ok
127.0.0.1:6379[2]> Setbit N1 7 1
(integer) 0
127.0.0.1:6379[2]> get N1
"Goo"
Setbit of the great abuses of the application scenario, think about what circumstances will use this function? Super large application platform, such as Sina Weibo, I would like to see the current landing of the user, how to achieve? Of course, you will think of the user logged on the database on the user information to make a mark, then count to count the number of users to do the tag, so, the current user to see the solved; OK, good, first each user login to set the tag, if the current user a few billion, then have to save a few billion mark bit, The overhead of a Super occupancy library; now there is an unbeatable and efficient way to count the current online users and display online user IDs, which is using bits, what does that mean? Look at the code below and you'll see.

Count Online Users

127.0.0.1:6379[2]> setbit lineuser 1000 1 #1000表示用户id
(integer) 0
127.0.0.1:6379[2]> Setbit Lineuser 55 1
(integer) 0
127.0.0.1:6379[2]> setbit Lineuser 6000 1
(integer) 0
127.0.0.1:6379[2]> Bitcount Lineuser #统计当前二进制位1的个数, that is, the number of users currently online
(integer) 3
Bitcount Statistics 1 of the number of secondary system, setbit and Bitcount with the use of easy to solve the current number of online users, which is not the most powerful, we can also use this statistic currently online who

See if the user ID is online

127.0.0.1:6379[2]> getbit Lineuser 1000 #查看id1000 1 indicates that online 0 is not on line
(integer) 1
127.0.0.1:6379[2]> getbit Lineuser 100
(integer) 0
Of course, we can also print out all the online user id,1 bytes = 8 bits through a for loop or yield generator, then 10m=8000 million, that is, a billion of online users will be able to handle more than 10m of memory, optimization in the intravenous drip between

⑫getbit (name, offset)

# Gets the value of a bit in the binary representation of the value of the name (0 or 1)
⑬bitcount (Key, Start=none, End=none)

# Gets the number of 1 in the binary representation of the value corresponding to name
Parameters
# Key,redis's name
# start, bit start position
# end, bit ending position
⑭bitop (operation, dest, *keys)

# gets multiple values and bitwise operations, saves the final result to the new name corresponding to the value

Parameters
# Operation,and (and), or (or), not (non), XOR (exclusive OR)
# dest, name of the new Redis
# *keys, the name of the Redis to find

As
Bitop ("and", ' new_name ', ' N1 ', ' N2 ', ' N3 ')
# Gets the value of the n1,n2,n3 in the Redis, then all the values are bitwise operations (the set) and the result is saved new_name the corresponding value
⑮strlen (name)

# returns the byte length of the name corresponding value (3 bytes of a kanji)

127.0.0.1:6379[2]> Get Name
"Lianzhilei"
127.0.0.1:6379[2]> strlen Name
(integer) 10
⑯INCR (self, name, amount=1)

# Add the value of the name, create the Name=amount when name does not exist, or it will increase itself.

Parameters
# Name,redis's name
# Amount, self-increment (must be integer)

# Note: Same Incrby

127.0.0.1:6379[2]> incr login_users #自增
(integer) 1
127.0.0.1:6379[2]> incr login_users
(integer) 2
127.0.0.1:6379[2]> incr login_users
(integer) 3
⑰incrbyfloat (self, name, amount=1.0)

# Add the value of the name, create the Name=amount when name does not exist, or it will increase itself.

Parameters
# Name,redis's name
# Amount, self-increasing (floating-point type)
⑱DECR (self, name, amount=1)

# The value that corresponds to the name, and when name does not exist, creates the Name=amount, otherwise, the decrement.

Parameters
# Name,redis's name
# Amount, self-meiosis (integer)

127.0.0.1:6379[2]> DECR login_users #自减
(integer) 2
127.0.0.1:6379[2]> DECR login_users
(integer) 1
127.0.0.1:6379[2]> DECR login_users
(integer) 0
⑲append (key, value)

# append content after Redis name's value

Parameters
Key, name of Redis
Value, the string to append

127.0.0.1:6379[2]> Append name Jjjj
(integer) 14
127.0.0.1:6379[2]> Get Name
"LIANZHILEIJJJJ"
6. Hash operation

The hash in memory in Redis is stored in the following figure:

①hset (name, key, value)

# NAME to set a key-value pair (not present, create; otherwise, modify)

Parameters
# Name,redis's name
# The key in the hash corresponding to the Key,name
# value,name corresponds to the value of the hash

Note
# HSETNX (name, key, value) created (equivalent to add) when the current key does not exist in the hash of name corresponding to


127.0.0.1:6379[3]> hset class14 name Lzl
(integer) 1
127.0.0.1:6379[3]> Hset Class14 age 18
(integer) 1
127.0.0.1:6379[3]> hset class14 ID 10001
(integer) 1
127.0.0.1:6379[3]> Hgetall CLASS14
1) "Name"
2) "Lzl"
3) "Age"
4) "18"
5) "id"
6) "10001"
127.0.0.1:6379[3]> hget class14 Name
"Lzl"
127.0.0.1:6379[3]> Hkeys CLASS14
1) "Name"
2) "Age"
3) "id"
127.0.0.1:6379[3]> hvals CLASS14
1) "Lzl"
2) "18"
3) "10001"
②hmset (name, mapping)

# Set the key value pairs in the hash corresponding to name

Parameters
# Name,redis's name
# mapping, dictionaries, such as: {' K1 ': ' v1 ', ' K2 ': ' V2 '}

As
# r.hmset (' xx ', {' K1 ': ' v1 ', ' K2 ': ' V2 '})

127.0.0.1:6379[3]> hmset Info K1 1 K2 2
Ok
127.0.0.1:6379[3]> Hmget Info K1 K2
1) "1"
2) "2"
③hget (Name,key)

# gets value based on key in the hash corresponding to name
④hmget (name, keys, *args)

# Gets the value of multiple keys in the hash corresponding to name

Parameters
# name,reids corresponds to name
# keys, to get the key set, such as: [' K1 ', ' K2 ', ' K3 ']
# *args, to get the key, such as: K1,K2,K3

As
# r.mget (' xx ', [' K1 ', ' K2 '])
# or
# Print R.hmget (' xx ', ' K1 ', ' K2 ')

127.0.0.1:6379[3]> hmset Info K1 1 K2 2
Ok
127.0.0.1:6379[3]> Hmget Info K1 K2
1) "1"
2) "2"
⑤hgetall (name)

Get all key values for name hash
⑥hlen (name)

# Gets the number of key-value pairs in the hash corresponding to name

127.0.0.1:6379[3]> Hlen Info
(integer) 2
⑦hkeys (name)

# Gets the value of all keys in the hash of name
⑧hvals (name)

# Gets the value of all value in the hash of name
⑨hexists (name, key)

# Check to see if the hash of name corresponds to the current incoming key

127.0.0.1:6379[3]> hexists Info K1
(integer) 1
127.0.0.1:6379[3]> hexists Info K3
(integer) 0
⑩hdel (Name,*keys)

# Deletes the key value of the specified key in the hash corresponding to name
⑪hincrby (name, key, Amount=1)

# Add the value of the specified key in the hash corresponding to the name, and do not exist to create the Key=amount
Parameters
# name in the Name,redis
# key, hash corresponding key
# Amount, self-increasing (whole number)

127.0.0.1:6379[3]> Hincrby Info K3 1
(integer) 1
127.0.0.1:6379[3]> Hincrby Info K3 1
(integer) 2
127.0.0.1:6379[3]> Hincrby Info K3 1
(integer) 3
⑫hincrbyfloat (name, key, amount=1.0)

# Add the value of the specified key in the hash corresponding to the name, and do not exist to create the Key=amount

Parameters
# name in the Name,redis
# key, hash corresponding key
# Amount, self-increasing (floating-point number)

# Add the value of the specified key in the hash corresponding to the name, and do not exist to create the Key=amount
⑬hscan (name, cursor=0, Match=none, Count=none)

# Incremental iterative acquisition, for large data data is very useful, hscan can achieve fragmentation of the acquisition of data, not a one-time to complete the data, so put the memory is burst

Parameters
# Name,redis's name
# Cursor, cursors (batch fetch data based on cursors)
# match, matching specified key, default None to represent all key
# count, minimum number of slices per fragment, default None to indicate the default number of slices with Redis

As
# First time: 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 return value cursor value is 0 o'clock, indicating that the data has been fetched through the fragment

127.0.0.1:6379[3]> Hscan Info 0 Match k*
1) "0"
2) 1) "K1"
2) "1"
3) "K2"
4) "2"
5) "K3"
6) "3"
⑭hscan_iter (name, Match=none, Count=none)

# Create generators using yield encapsulation hscan to get data in batches to Redis

Parameters
# match, matching specified key, default None to represent all key
# count, minimum number of slices per fragment, default None to indicate the default number of slices with Redis

As
# for item in R.hscan_iter (' xx '):
# Print Item
7. List operation

The list in Redis is stored in memory by a list corresponding to a name. As shown in figure:

①lpush (name,values)

# add elements to the list in name, and each new element is added to the leftmost

As
# R.lpush (' oo ', 11,22,33)
# Save Order as: 33,22,11

Extension
# Rpush (name, values) represents Right-to-left operation

127.0.0.1:6379[3]> lpush names Lzl Alex Wupeiqi
(integer) 3
127.0.0.1:6379[3]> lrange Names 0-1
1) "Wupeiqi"
2) "Alex"
3) "Lzl"
②lpushx (Name,value)

# Add an element to the list in name, and the value is added to the left of the listing only if name already exists

More
# RPUSHX (name, value) represents Right-to-left operation
③llen (name)

Number of list elements corresponding to name

127.0.0.1:6379[3]> llen Names
(integer) 3
④linsert (name, where, Refvalue, value))

# Inserts a new value before or after a value in the list corresponding to name

Parameters
# Name,redis's name
# Where,before or after
# Refvalue, the benchmark value, that is: Insert data before and after it
# value, the data to insert

127.0.0.1:6379[3]> linsert names before Alex Befor
(integer) 4
127.0.0.1:6379[3]> lrange Names 0-1
1) "Wupeiqi"
2) "befor"
3) "Alex"
4) "Lzl"
⑤lset (name, index, value)

# re-assign an index position in the list corresponding to name

Parameters
# Name,redis's name
# index position of Index,list
# value, values to set

127.0.0.1:6379[3]> LSet Names 3 Lianzhilei
Ok
127.0.0.1:6379[3]> lrange Names 0-1
1) "Wupeiqi"
2) "befor"
3) "Alex"
4) "Lianzhilei"
⑥lrem (name, value, num)

# deletes the specified value in the name corresponding to the list

Parameters
# Name,redis's name
# value, values to delete
# num, num=0, delete all the specified values in the list;
# num=2, before and after, delete 2;
# num=-2, from the back forward, delete 2

127.0.0.1:6379[3]> lrem names 1 befor
(integer) 1
127.0.0.1:6379[3]> lrange Names 0-1
1) "Wupeiqi"
2) "Alex"
3) "Lianzhilei"
⑦lpop (name)

# Gets the first element on the left side of the list with name and removes it in the list, the return value is the first element

More
# Rpop (name) indicates right-to-left operation

127.0.0.1:6379[3]> lpop Names
"Wupeiqi"
⑧lindex (name, index)

Gets the list element from the index in the list corresponding to name
⑨lrange (name, start, end)

# to get the data in the list fragment corresponding to name
Parameters
# Name,redis's name
# Start, start position of index
# end, index ending position
⑩ltrim (name, start, end)

# Remove values that are not in the Start-end index in the list corresponding to name
Parameters
# Name,redis's name
# Start, start position of index
# end, index ending position

127.0.0.1:6379[3]> lrange Names 0-1
1) "Eric"
2) "Wupeiqi"
3) "Alex"
4) "Lianzhilei"
127.0.0.1:6379[3]> LTrim names 1 2
Ok
127.0.0.1:6379[3]> lrange Names 0-1
1) "Wupeiqi"
2) "Alex"
⑪rpoplpush (SRC, DST)

# Remove the rightmost element from a list and add it to the leftmost of the other list
Parameters
# SRC, name of the list of data to be fetched
# DST, name of the list to which you want to add data

127.0.0.1:6379[3]> Rpush Names2 Lzl
(integer) 1
127.0.0.1:6379[3]> rpoplpush Names Names2
"Alex."
127.0.0.1:6379[3]> lrange Names 0-1
1) "Wupeiqi"
127.0.0.1:6379[3]> Lrange Names2 0-1
1) "Alex"
2) "Lzl"
⑫blpop (keys, timeout)

# Arrange multiple lists, follow the elements from left to right pop corresponding to the list

Parameters
# A collection of Keys,redis's name
# timeout, timeout, when the element of all the elements of a list is fetched, the time in the wait list is blocked (in seconds), and 0 means blocking forever

More
# R.brpop (keys, timeout), getting data from right to left
⑬brpoplpush (SRC, DST, timeout=0)

# Remove an element from the right side of a list and add it to the left of another list

Parameters
# src, remove and remove the list of elements corresponding to name
# DST, to insert the list of elements corresponding to the name
# timeout, when there is no data in the corresponding list of SRC, the timeout (in seconds) that blocks waiting for their data, 0 means blocking forever
⑭ Custom Incremental iterations

# because an incremental iteration of the list element is not provided in the Redis class library, if you want to loop through all the elements of the list of name, you need to:
    # 1, get all the lists for name
     # 2, loop list
# However, if the list is very large, it is possible to explode the contents of the program in the first step, all of which are necessary to customize the functionality of an incremental iteration:
 
def list_iter (name):
    ""
    Custom Redis list incremental Iteration
   :p Aram Name:redis name, That is, the list of iteration name
   : Return:yield Returns the list element
    ""
    List_ Count = R.llen (name)
    for index in Xrange (list_count):
      & nbsp Yield R.lindex (name, index)
 
# Use
for item in List_iter (' PP '):
    Print Item

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.