Redis is an open source, high-performance key-value storage system, commonly used in cache, message queue, counter and other scenarios. As a concise and efficient scripting language, Python is also widely used in Web background processing, data analysis and mining, machine learning, artificial intelligence and other fields. This article will discuss the application of Redis in Python, including the installation of Redis, the use of Python Redis client module and specific application cases.
1. Redis installation
$ tar xzf redis-5.0.3.tar.gz
$ cd redis-5.0.3
$ make
$ src/redis-server
$ src/redis-cli
127.0.0.1:6379> SET mykey "Hello Redis"
OK
127.0. 0.1:6379> GET mykey
"Hello Redis"
2. Use of Python Redis client module
In order to facilitate the use of Redis in Python, you can use the redis-py module as Redis client library. You can use the pip command to install:
$ pip install redis
import redis
rds = redis.Redis(host='localhost', port=6379, db=0)
where host and port are respectively is the address and port number of the Redis server, db represents the number of the Redis database, and the default is 0.
rds.set('name', 'Alice')
name = rds.get('name')
print(name) # Output: b'Alice'
Among them, the set method is used to set the key-value pair, and the get method is used to obtain the key-value pair. It should be noted that the data type returned by the get method is bytes and needs to be converted to a string using the decode method.
pipe = rds.pipeline()
pipe.set('key1', 'value1')
pipe.set('key2', 'value2')
pipe.set('key3', 'value3')
pipe.execute()
import time
pubsub = rds.pubsub()
pubsub.subscribe('channel')
rds.publish('channel', 'Hello')
time.sleep(1) # Wait for 1 second
msg = pubsub.get_message()
print(msg) # Output: {'type': 'message', 'channel': b'channel' , 'data': b'Hello'}
Among them, the subscribe method means subscribing to a channel, and the publish method means publishing a message. Use the get_message method to get the message.
3. Specific application cases
import time
import redis
class Cache:
def __init__(self): self.rds = redis.Redis(host='localhost', port=6379, db=0) def get(self, key): val = self.rds.get(key) if val: return val.decode() return None def set(self, key, val, ttl=60): self.rds.set(key, val, ex=ttl)
cache = Cache()
val = cache.get('key')
if not val:
# 从数据库中查询数据 val = 'value' cache.set('key', val, ttl=60)
print(val)
The Cache class encapsulates the implementation of Redis cache, and you can use the get and set methods to obtain or set cache data. Query the cache before getting the data. If it does not exist in the cache, read the data from the database and cache it.
import time
import redis
class Lock:
def __init__(self): self.rds = redis.Redis(host='localhost', port=6379, db=0) self.locked = False def acquire(self, lockname, ttl=60): identifier = str(time.time()) self.locked = self.rds.setnx(lockname, identifier) if self.locked: self.rds.expire(lockname, ttl) return self.locked def release(self, lockname): if self.locked: self.rds.delete(lockname)
lock = Lock()
if lock.acquire('mylock'):
# 处理业务逻辑... lock.release('mylock')
The Lock class encapsulates the implementation of distributed locks, and the acquire and release methods can be used to acquire or release locks. When acquiring a lock, return False if the lock is already occupied; if the lock is not occupied, acquire the lock and set the expiration time.
In summary, Redis is widely used in Python and can be used in cache, distributed locks, message queues, counters and other scenarios. The Python Redis client library also provides a simple and easy-to-use API for convenient data operations.
The above is the detailed content of Application of Redis in Python. For more information, please follow other related articles on the PHP Chinese website!