I encountered a problem at work, because business requirements require redis acceleration, so how can the list stored in redis be completely stored and then completely taken out? (Recommended learning: Redis Video Tutorial)
If you use the list storage method of redis, traverse the elements in the list = [1,2,3,4] list one by one Take it out, and then use the lpush method to store the elements one by one. In the end, if you use the complete lrange('name',0,-1) to take it out, you will find that the taken out list becomes a str, for example (list = '[1,2,3,4]'), this is very troublesome to deal with.
After constant attempts, I found a relatively easy-to-use library pickle.
The advantage of pickle is that the serialization process converts text information into Convert to binary data stream. In this way, the information is easily stored in the hard disk. When a file needs to be read, the data is read from the hard disk and then deserialized to obtain the original data.
I have obtained some strings, lists, dictionaries and other data during the running of the Python program. I want to save them for a long time for future use, instead of simply putting them into the memory and losing them when the power is turned off. data.
The Pickle module in the python module collection comes in handy, it can convert objects into a format that can be transmitted or stored. This ensures the integrity of stored and retrieved data.
from redis import StrictRedis # 选取一个默认的redis的db仓库 db = StrictRedis(host='localhost', port=6379, db=0,decode_responses=True) #导入pickle包 import pickle list = [1,2,3,4] # pickle 封装list new_list = pickle.dumps(list) # redis中存储数据,设置过期时间 db.setx('list',3600,new_list) result = db.get('list') get_list = pickle.loads(result) print(get_list) # get_list = [1,2,3,4]
After processing with pickle, you will find that the extracted list is much easier to use. You no longer have to worry about data conversion, and you can also process data of json and other data types.
For more Redis-related technical articles, please visit the Redis Getting Started Tutorial column to learn!
The above is the detailed content of How redis stores list. For more information, please follow other related articles on the PHP Chinese website!