current position:Home>Python connects redis, singleton and thread pool, and resolves problems encountered

Python connects redis, singleton and thread pool, and resolves problems encountered

2022-01-31 17:42:16 Coriander Chat Game

「 This is my participation 11 The fourth of the yuegengwen challenge 7 God , Check out the activity details :2021 One last more challenge

I'm going to do a small project recently , The final solution of the project is flask + redis, So you need to connect redis

1、 demand

Want to use redis, In normal development , Generally we use thread pool , The multithreading library will also be used later , The stored object is a string , At this time, you need to serialize the object ,

Directly used redis The built-in json serialize

2、demo

The details of the project will not be mentioned , Because I haven't used it before python Operation on Database , So first write a demo test , attempt to connect redis

We all know that doing database operations , It is better to use connection pool , This reduces the cost of connection , Reduce operation time at high concurrency , At the same time, I want to make a single example in the process of using the program , After looking at various single cases, I choose the simplest way , For one demo Enough is enough .

To sum up : Single case , Thread pool

install redis I won't go into that , Baidu is everywhere .

I don't say much nonsense , Go straight to code

Directly on the console pip install redis That's all right.

Look at the connection pool code :

import redis
​
​
class RedisPool:
    instance = None
​
    def __init__(self):
        self.pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True, db=8)
​
    def __getConnection(self):
        conn = redis.Redis(connection_pool=self.pool)
        return conn
​
    @classmethod
    def getConn(cls):
        if RedisPool.instance is None:
            RedisPool.instance = RedisPool()
        return RedisPool.instance.__getConnection()
​
​
redisConn = RedisPool.getConn()
​
redisConn.set('aaa', 'vvv')
 Copy code 

Object turn json Function of

def toStr(obj):
    return json.dumps(obj,default = lambda x: x.__dict__,ensure_ascii=False)
 Copy code 

Simply define an object

​
class RankData:
    def __init__(self):
        self.data = []
 Call store in redis

from gameRank import RedisPool
from gameRank.JsonUtil import toStr
from gameRank.RankData import RankData
​
rank = RankData()
rank.data.append({' name ':' Coriander ','code':'12345'})
rank.data.append({' name ':' Coriander ','code':'12345'})
rank.data.append({' name ':' Coriander ','code':'12345'})
rank.data.append({' name ':' Coriander ','code':'12345'})
rank.data.append({' name ':' Coriander ','code':'12345'})
rank.data.append({' name ':' Coriander ','code':'12345'})
rank.data.append({' name ':' Coriander ','code':'12345'})
rank.data.append({' name ':' Coriander ','code':'12345'})
rank.data.append({' name ':' Coriander ','code':'12345'})
​
redisConn = RedisPool.getConn()
​
redisConn.hset('20211115','aaa', toStr(rank))
 Copy code 

3、 Problems encountered

3.1 solve Object of type “XXX“ is not JSON serializable terms of settlement

error : Unable to serialize

stay Java There are all kinds of json library , It's used here python Self contained json, But I didn't notice that the custom object can't be serialized , Just add the following line

default = lambda x: x.dict,

3.2 redis Shown in is binary

Show not chinese , It's generating json The statement of add

ensure_ascii=False

image.png

4、 summary

It's not hard to , Just copy mechanically , Comments are welcome on thumb up ,

copyright notice
author[Coriander Chat Game],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201311742154184.html

Random recommended