This article describes how to use pythonredis
This article describes how to use python redis
1. install
Pip install redis
2. Basic usage
Usage:
Import redis
R = redis. Redis (host = 'localhost', port = 6379, db = 0)
R ['test'] = 'test' # or you can set the key in r. set ('test', 'test ').
R. get ('test') # obtain the value of test
R. delete ('test') # delete this key
R. flushdb () # clear the database
R. keys () # List all keys
R. exists ('test') # check whether this key exists
R. dbsize () # Number of items in the database
>>> import redis>>> pool = redis.ConnectionPool(host='localhost', port=6379, db=0)>>> r = redis.StrictRedis(connection_pool = pool)>>> r.set('foo', 'bar')True>>> r.get('foo')'bar'
3. API reference
The official Redis documentation details each command (#). Redis-py provides two client classes that implement these commands. The StrictRedis class tries to comply with the official command syntax, but there are several exceptions:
· SELECT: not implemented. For more information, see the "thread security" section.
· DEL: 'Del 'is the reserved keyword of Python syntax. Therefore, redis-py uses "delete" instead.
· Config get | SET: use config_get and config_set respectively.
· MULTI/EXEC: implemented as part of the Pipeline class. If use_transaction = True is specified when the pipeline method is called, the pipeline operation is encapsulated with MULTI and EXEC when the pipeline method is executed. See the Pipeline section below.
· SUBSCRIBE/LISTEN: Similar to pipeline, PubSub is also implemented as a separate class because the connection at the lower layer is maintained. Call the pubsub method of the Redis client to return a PubSub instance through which you can subscribe to channels or listen on messages. Both the StrictRedis and PubSub classes can PUBLISH (PUBLISH) messages.
In addition to the above changes, the StrictRedis subclass Redis provides compatibility with the old version of redis-py:
· LREM: the order of 'num' and 'value' is exchanged, so that 'num' can provide the default value 0.
· ZADD
· SETEX: the order of time and value is reversed.
Note: it is best not to use Redis. this class is only compatible.
4. Detailed description
4.1 connection pool
In the background, redis-py uses a connection pool (ConnectionPool) to manage connections to the Redis server. By default, each Redis instance creates its own connection pool. You can also pass the created connection pool to the connection_pool parameter of the Redis class. In this way, you can implement client sharding or precisely control connection management:
>>> pool = redis.ConnectionPool(host='localhost', port=6379, db=0)>>> r = redis.StrictRedis(connection_pool=pool)
4.2 Connection
ConnectionPool manages a group of Connection instances. Redis-py provides two types of Connection. By default, Connection is a common TCP Connection. UnixDomainSocketConnection allows a client running on the same device as the server to connect through a unix socket. To use the UnixDomainSocketConnection connection, you only need to pass the string of a unix socket file through the unix_socket_path parameter. In addition, make sure that the unixsocket parameter is configured in the redis. conf file (commented out by default ):
>>> r = redis.StrictRedis(unix_socket_path='/tmp/redis.sock')
You can also create a Connection subclass by yourself. This feature can be used to control socket behavior when an asynchronous framework is used. To use your Connection to initialize the client class, you need to create a Connection pool and pass your class through the connection_class parameter. Other passed keyword parameters will be passed to the custom class during initialization:
>>> pool = redis.ConnectionPool(connection_class=YourConnectionClass, your_arg='...', ...)
4.3 analyzer
The analysis class provides a way to control how to analyze the response of the Redis server. Redis-py provides two Analysis classes: PythonParser and HiredisParser. By default, if the hiredis module is installed, redis-py tries to use HiredisParser; otherwise, PythonParser is used.
Hiredis is a C-database maintained by the Redis core team. Pieter Noordhuis creates Python implementation. When analyzing the response of the Redis server, Hiredis can increase the speed by 10 times. Performance improvement is obvious when retrieving a large amount of data, such as LRANGE and SMEMBERS operations.
Like redis-py, Hiredis is available in Pypi and can be installed through pip or easy_install:
$ pip install hiredis
Or:
$ easy_install hiredis
4.4 response callback function
The client class uses a series of callback functions to convert Redis responses to a suitable Python type. Some callback functions are defined in the RESPONSE_CALLBACKS Dictionary of the Redis client class.
You can use the set_response_callback method to add custom callback functions to a single instance. This method accepts two parameters: a command name and a callback function. The callback function added in this way is only valid for the added object. To define or reload a callback function globally, create a subclass of the Redis client and add the callback function to the RESPONSE_CALLBACKS (originally REDIS_CALLBACKS) of the class.
The response callback function has at least one parameter: the response of the Redis server. To further control how to interpret the response, you can also use the keyword parameter. These keyword parameters are specified when calling the execute_command command. Through the "withscores" parameter, ZRANGE demonstrates how the callback function uses the keyword parameter.
4.5 thread security
Redis client instances can be securely shared among threads. For internal implementation, the connection instance is obtained only when the command is executed. after the connection pool is completed, the connection pool is directly returned. The Command never modifies the status of the client instance.
However, note the following: SELECT command. The SELECT command allows you to switch the database used by the current connection. The new database remains Selected until another database is selected or the connection is closed. This may cause other databases to be specified when the connection pool is returned.
Therefore, redis-py does not implement the SELECT command in the client instance. If you want to use multiple Redis databases in the same application, you should create an independent client instance for the first database (an independent connection pool may also be required ).
It is insecure to pass PubSub and Pipeline objects between threads.
4.6 Pipeline
Pipeline is a subclass of the StrictRedis class. it supports sending multiple buffered commands in a request. By reducing data packets between the client and the server, you can greatly improve the performance of the command group.
Pipeline is easy to use:
>>> r = redis.Redis(...)>>> r.set('bing', 'baz')>>> # Use the pipeline() method to create a pipeline instance>>> pipe = r.pipeline()>>> # The following SET commands are buffered>>> pipe.set('foo', 'bar')>>> pipe.get('bing')>>> # the EXECUTE call sends all bufferred commands to the server, returning>>> # a list of responses, one for each command.>>> pipe.execute()[True, 'baz']
For ease of use, all the commands buffered to pipeline return the pipeline object itself. Therefore, the call can be linked up:
>>> pipe.set('foo', 'bar').sadd('faz', 'baz').incr('auto_number').execute()[True, True, 6]
In addition, pipeline can also ensure that the buffered command group is used as an atomic operation. This mode is used by default. To use command buffering, but disable the atomic operation attribute of pipeline, you can disable transaction:
>>> pipe = r.pipeline(transaction=False)
A common problem is that you need to obtain the data used in the transaction from Redis before performing atomic transaction operations. For example, suppose the INCR command does not exist, but we need to create an atomic version of INCR using Python.
An immature implementation is to GET a value (GET), add one in Python, and SET a new value (SET. However, this is not an atomic operation, because multiple clients may do this at the same time, and each of them obtains the same value through GET.
The WATCH Command provides the ability to monitor one or more keys before starting a transaction. If any of these keys changes before the transaction is executed, the entire transaction will be canceled and a WatchError exception will be thrown. To implement our customer INCR command, perform the following operations:
>>> With r. pipeline () as pipe :... while 1 :... try :... # WATCH the key of the serial number... pipe. watch ('hour-SEQUENCE-key ')... # After WATCH is executed, pipeline is set to immediate execution mode until we notify it... # Restart the buffer command .... # This allows us to get the serial number value... current_value = pipe. get ('Ur-SEQUENCE-key ')... next_value = unicode (int (current_value) + 1 )... # Now we can use the MULTI command to set the pipeline to the buffer mode... pipe. multi ()... pipe. set ('Ur-SEQUENCE-key', next_value )... # finally, run the pipeline (set command )... pipe.exe cute ()... # If WatchError is not thrown during execution, what we just did is "atomic "... # completed... break... failed T WatchError :... # It must have been modified between the start of WATCH and the execution of pipeline by other clients... # 'hour-SEQUENCE-key'. the best choice is to try again... continue
Note: Throughout the WATCH process, Pipeline must be bound to a connection and the reset () method must be called to ensure that the connection returns to the connection pool. If Pipeline is used as Context Manager (as shown in the preceding example), reset () is automatically called. Of course, you can also manually call reset ():
>>> pipe = r.pipeline()>>> while 1:... try:... pipe.watch('OUR-SEQUENCE-KEY')... current_value = pipe.get('OUR-SEQUENCE-KEY')... next_value = unicode(int(current_value) + 1)... pipe.multi()... pipe.set('OUR-SEQUENCE-KEY', next_value)... pipe.execute()... break... except WatchError:... continue... finally:... pipe.reset()
Important ):
· After WATCH is executed, pipeline is set to immediate execution mode.
· Use the MULTI command to set the pipeline to the buffer mode.
· Either use with or explicitly call reset ()
There is a simple method named "transaction" to handle this processing and retry in WatchError mode. Its parameter is an executable object and a key that requires any number of watches. The Executable Object accepts a pipeline object as the parameter. The preceding client INCR command can be rewritten as follows (more readable ):
>>> def client_side_incr(pipe):... current_value = pipe.get('OUR-SEQUENCE-KEY')... next_value = unicode(int(current_value) + 1)... pipe.multi()... pipe.set('OUR-SEQUENCE-KEY', next_value)>>> >>> r.transaction(client_side_incr, 'OUR-SEQUENCE-KEY')
The above is a detailed description of how to use python redis. For more information, see other related articles in the first PHP community!