Second, python operation redis
1. Connection method
redis-py provides two classes Redis and StrictRedis to implement Redis commands. StrictRedis is used to implement most official commands and use official syntax and commands. Redis is a subclass of StrictRedis
#!/usr/bin/env python
# -*- coding:utf-8 -*- import redis r = redis.Redis(host='192.168.0.110', port=6379,db=0) r.set('name', 'zhangsan') #添加 print (r.get('name')) #获取
2. Connection pool
redis-py uses the connection pool to manage all connections to a redis server, avoiding the overhead of establishing and releasing connections each time. By default, each Redis instance maintains its own connection pool. A connection pool can be established directly, and then used as a parameter Redis, so that multiple Redis instances can share a connection pool.
#!/usr/bin/env python
# -*- coding:utf-8 -*- import redis pool = redis.ConnectionPool(host='192.168.0.110', port=6379) r = redis.Redis(connection_pool=pool) r.set('name', 'zhangsan') #添加 print (r.get('name')) #获取
3. Operation
redis detailed operation command
4. Pipes
By default, redis-py will create (connection pool application connection) and disconnect (return the connection pool) a connection operation for each request. If you want to specify multiple commands in one request, you can use pipline to specify multiple commands in one request. commands, and by default a pipline is an atomic operation.
#!/usr/bin/env python
# -*- coding:utf-8 -*- import redis pool = redis.ConnectionPool(host='192.168.0.110', port=6379) r = redis.Redis(connection_pool=pool) pipe = r.pipeline(transaction=True) r.set('name', 'zhangsan') r.set('name', 'lisi') pipe.execute()
5. Publish and subscribe
First define a RedisHelper class, connect to Redis, define the channel as monitor, and define the publish and subscribe methods.
# !/usr/bin/env python
# -*- coding:utf-8 -*- import redis class RedisHelper(object): def __init__ (self): self. __conn = redis. Redis(host= ' 192.168.0.110 ' ,port=6379) #Connect Redis self.channel = ' monitor ' #Define the name def publish(self,msg): #Define the publishing method self .__conn.publish ( self.channel,msg) return True def subscribe(self): #Define subscription method pub = self .__ conn.pubsub () pub.subscribe(self.channel) pub.parse_response() return pub
announcer
#!/usr/bin/env python
# -*- coding:utf-8 -*- #发布 from RedisHelper import RedisHelper obj = RedisHelper() obj.publish('hello')#发布
subscriber
# !/usr/bin/env python
# -*- coding:utf-8 -*- #Subscribe from RedisHelper import RedisHelper obj = RedisHelper() redis_sub = obj.subscribe() #Call the subscription method while True: msg= redis_sub. parse_response() print (msg)