Establish a connection to Redis
Import Redispool = Redis. ConnectionPool (host= ' localhost ', port=6379) # By default, each Redis instance is created with a ConnectionPool instance, and every access to Redis gets a connection from this connection pool. When the operation is completed, the connection is put back into the connection pool (the connection is not released), and a unified ConnectionPool can be constructed, which can be passed in when the Redis instance is created. The subsequent operation will get a connection from the given ConnectionPool and no more connectionpool will be created. # KeepAlive and timeout are not set by default, and the established connection is a short connection in blocking mode. # Connections in the connection pool are destroyed uniformly in connectionpool.disconnect, regardless of the underlying TCP. #r = Redis. Redis (Connection_pool=pool)
Operation
Mode one: Depending on the data type, call the appropriate method to complete the read and write
R.set (' name ', ' hello ') temp = r.get (' name ') print (temp) >> b ' Hello ' # b stands for binary. Decode () just a moment.
Way two: Pipline
Buffers multiple commands, then executes at once, reducing server-to-client TCP database packets for increased efficiency
Pipe = R.pipeline () pipe.set (' Name ', ' World ') pipe.get (' name ') Pipe.execute () # command to execute the cache once
Example: User Login
- The business process is as follows:
- Enter user name, password
- Password encryption
- Determine if the user name is logged in Redis, and if there is a success
- If no user name is in Redis, query in MySQL
- Log user name to Redis after successful query from MySQL
python--Connecting a Redis database