redis Use of modules
1. Install the module
2. The import module
4. Connection pool
5. operation
The Conduit
Business
subscribe \ Release
redis Use of modules 1. Install the modulepip3 install redis
2. The import module import redis
3. How to connect
Strict connection mode :r=redis.StrictRedis(host=“”,port=)
more Python Standardized connection mode :r=redis.Redis(host=“”,port=)
StrictRedis Used to implement most official commands , And use the official syntax and commands
Redis And StrictRedis Is the difference between the :Redis yes StrictRedis Subclasses of , For forward compatibility with older versions redis-py, And this connection is more "python turn " Of
4. Connection poolIn order to save resources , Reduce multiple connection losses , The role of connection pool is equivalent to taking over the connections between multiple clients and servers , When a new client needs to connect , Just get a connection from the connection pool , In fact, only one connection is shared with multiple clients .
import redispool= redis.ConnectionPool(host='localhost',port=6379,decode_responses=True)r=redis.Redis(connection_pool=pool)r2=redis.Redis(connection_pool=pool)r.set('apple','a')print(r.get('apple'))r2.set('banana','b')print(r.get('banana'))print(r.client_list())print(r2.client_list())# You can see that the two are connected id It's consistent , Description is a client connection
5. operation Value setting and acquisition , You can refer to redis The order of ,redis The function name of the corresponding function in the module is basically the same as redis In the same
Note that by default , The value set or obtained is bytes type , If you want to change it to str type , You need to add... When connecting decode_responses=True】
Set the value :
redis in set() ==>r.set()redis in setnx() ==>r.set()redis in setex() ==>r.setex()redis in setbit() ==>r.setbit()redis in mset() == > r.mset()redis in hset() ==>r.hset()redis in sadd() == >r.sadd()# other ... basic redis Command name and redis The function names in the module are consistent
obtain :
redis in get() ==》r.get()redis in mget() ==》r.mget()redis in getset() ==》r.getset()redis in getrange() ==》r.getrange()# other ... basic redis Command name and redis The function names in the module are consistent
import redisr=redis.Redis(host='localhost',port=6379,decode_responses=True)# r=redis.StrictRedis(host='localhost',port=6379)r.set('key','value')value=r.get('key')# print(type(value))print(value)r.hset('info','name','lilei')r.hset('info','age','18')print(r.hgetall('info'))r.sadd('course','math','english','chinese')print(r.smembers('course'))
The Conduit In general , After executing a command, you must wait for the result before entering the next command , Pipes are used to execute multiple commands in one request .
Parameter Introduction :
transaction: Indicates whether all commands should be executed atomically .
import redis,timer=redis.Redis(host="localhost",port=6379,decode_responses=True)pipe=r.pipeline(transaction=True)pipe.set('p1','v2')pipe.set('p2','v3')pipe.set('p3','v4')time.sleep(5)pipe.execute()
Business python Pipes can be used in place of transactions :
Add : monitor watch:pipe.watch()
import redis,timeimport redis.exceptionsr=redis.Redis(host='localhost',port=6379,decode_responses=True)pipe=r.pipeline()print(r.get('a'))try: # pipe.watch('a') pipe.multi() pipe.set('here', 'there') pipe.set('here1', 'there1') pipe.set('here2', 'there2') time.sleep(5) pipe.execute()except redis.exceptions.WatchError as e: print("Error")
subscribe \ Release Issued by :
import redisr=redis.Redis(host="localhost",port=6379,decode_responses=True)# Release and use publish(self, channel, message):Publish ``message`` on ``channel``.Flag=Truewhile Flag: msg=input(" Anchor, please speak >>:") if len(msg)==0: continue elif msg=='quit': break else: r.publish('cctv0',msg)
Subscriber :
When the subscription is successful , The first message returned from the first reception is a subscription confirmation message :
import redisr=redis.Redis(host="localhost",port=6379,decode_responses=True)# Release and use publish(self, channel, message):Publish ``message`` on ``channel``.Flag=Truechan=r.pubsub()# Return a release / Subscription object msg_reciver=chan.subscribe('cctv0')# subscribe msg=chan.parse_response()# The subscription confirmation information will be returned for the first time print(msg)print(" Subscription succeeded , Start receiving ------")while Flag: msg=chan.parse_response()# receive messages print(">>:",msg[2])# The message format here [' Message type ', ' channel ', ' news '], So use [2] To get
This is about python Use redis Module to follow redis This is the end of the article on implementing interaction , More about python redis For interactive content, please search the previous articles of SDN or continue to browse the relevant articles below. I hope you will support SDN more in the future !