Recently used in the project redis To store data , In summary redis The installation and python call .
Yes redis For details, please refer to :
https://baike.baidu.com/item/Redis/6549233
https://www.cnblogs.com/powertoolsteam/p/redis.html
Redis(Remote Dictionary Server ), Remote dictionary service , Is a high-performance key-value database .
Contains a variety of data structures 、 Support network 、 Memory based 、 Optional persistent key value pair to store database , It has the following characteristics :
Let's introduce Redis Service installation , as well as python Of api Use .
I'm using linux System , Simple installation
yum install redis
Start the service
systemctl start redis
And then through ps -ef | grep 6379 With the default port number, you can see redis service
View service status
systemctl status redis
Out of Service
systemctl stop redis
If you want to modify the file configuration, you can redis.conf Internal modification
Use python call redis Of API, Need to install python library
pip install redis
Use import reids Check to see if the installation was successful
redis yes key-value Storage form of , It's also easy to use , Mainly set and get Two interfaces , We use the local default service to test :
# redis The result is byte by default , We can set decode_responses=True Change to string . redis_conn = redis.Redis(host='127.0.0.1', port= 6379 , db= 0) redis_conn.set('key','Hello redis') print(redis_conn.get('key'))
You can see the return key Corresponding data .
If value The corresponding is numpy Array , It cannot be simply used directly set Interface , Here we need to make a transformation , stay set Data time , We will numpy transposition bytes, And then in get Data time , We will again bytes Data is restored to numpy that will do .
Main interface code :
class RedisModel: def __init__(self,): self.conn_redis = redis.Redis(host='127.0.0.1', port=6379, db=0) def array_to_bytes(self, array): """ numpy Array to bytes, Pass in redis :return: encoded bytes """ h, w = array.shape shape = struct.pack('>II', h, w) encoded = shape + array.tobytes() return encoded def bytes_to_array(self, bytes): """ redis From values Convert to numpy :return: array """ h, w = struct.unpack('>II', bytes[:8]) # Note that there dtype Consistent with input , Prevent data length alignment problems a = np.frombuffer(bytes[8:], dtype=np.float32).reshape(h, w) return a def get(self, key): """ obtain redis Inside key Corresponding packet :param key: room_id :return: value(M*N matrix ),key non-existent , return None """ # value = None # if self.conn_redis.exists(key): value = self.conn_redis.get(key) value = self.bytes_to_array(value) return value def set(self, key, item): """ New information writing redis :param key: **** :param item:***** """ b_value = self.array_to_bytes(item) self.conn_redis.set(key, b_value)