在redis中存儲(chǔ)ndarray的示例代碼
如何在redis中存儲(chǔ)ndarray
在Redis中存儲(chǔ)NumPy數(shù)組(ndarray)通常需要將數(shù)組轉(zhuǎn)換為二進(jìn)制格式,然后將其存儲(chǔ)為字符串。以下是使用Python和Redis-py庫的一個(gè)簡(jiǎn)單示例:
首先,確保你已經(jīng)安裝了Redis-py庫:
pip install redis
然后,你可以使用以下代碼將NumPy數(shù)組存儲(chǔ)到Redis中:
import redis import numpy as np import pickle # 連接到本地Redis服務(wù)器,端口默認(rèn)是6379 redis_client = redis.StrictRedis(host='localhost', port=6379, db=0) # 創(chuàng)建一個(gè)示例的NumPy數(shù)組 arr = np.array([[1, 2, 3], [4, 5, 6]]) # 將NumPy數(shù)組轉(zhuǎn)換為二進(jìn)制字符串 arr_binary = pickle.dumps(arr) # 存儲(chǔ)二進(jìn)制字符串到Redis redis_client.set('numpy_array_key', arr_binary) # 從Redis中檢索數(shù)據(jù)并轉(zhuǎn)換回NumPy數(shù)組 stored_data = redis_client.get('numpy_array_key') if stored_data: retrieved_arr = pickle.loads(stored_data) print("Retrieved NumPy Array:") print(retrieved_arr) else: print("Key not found in Redis.")
在這個(gè)例子中,pickle模塊被用來將NumPy數(shù)組轉(zhuǎn)換為二進(jìn)制字符串,然后使用Redis-py庫的set方法將其存儲(chǔ)在Redis中。在檢索時(shí),使用get方法獲取二進(jìn)制字符串,并使用pickle.loads將其轉(zhuǎn)換回NumPy數(shù)組。
補(bǔ)充:
如何把Numpy數(shù)組存進(jìn)Redis
import (base64, struct, numpy, redis) HOST = 'localhost' PORT = 6379 connection_pool = redis.ConnectionPool(host=HOST, port=PORT, decode_responses=True) # 連接池 def redis_save(key: str, numpy_ndarray: numpy.ndarray) -> None: """將Numpy數(shù)組存入Redis數(shù)據(jù)庫。 Parameters ---------- key : str 鍵字符串。 numpy_ndarray : numpy.ndarray 待存儲(chǔ)數(shù)組。 """ shape = numpy_ndarray.shape dim = len(shape) value = struct.pack(''.join(['>I']+['I'*dim]), *((dim,)+shape)) value = base64.a85encode(value+numpy_ndarray.tobytes()) # 得轉(zhuǎn)換成字符串,不然取出時(shí)候會(huì)報(bào)一個(gè)錯(cuò) conn = redis.Redis(connection_pool=connection_pool) conn.set(key, value) conn.close() def redis_read(key: str, dtype) -> numpy.ndarray: """從Redis中讀取一個(gè)Numpy數(shù)組。 Parameters ---------- key : str 鍵字符串。 dtype : Any 指定數(shù)組元素?cái)?shù)據(jù)類型。 Returns ------- numpy.ndarray 從Redis鍵值對(duì)取出的數(shù)組。 """ SIZE = 4 conn = redis.Redis(connection_pool=connection_pool) bytes = base64.a85decode(conn.get(key)) conn.close() dim = struct.unpack('>I', bytes[:1*SIZE])[0] shape = struct.unpack('>%s' % ('I'*dim), bytes[1*SIZE:(dim+1)*SIZE]) ret = numpy.frombuffer( bytes, offset=(dim+1)*SIZE, dtype=dtype ).reshape(shape) return ret
經(jīng)檢驗(yàn)的,存入后可以正常取出,放心食用。
到此這篇關(guān)于如何在redis中存儲(chǔ)ndarray的文章就介紹到這了,更多相關(guān)redis存儲(chǔ)ndarray內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
odoo中使用redis實(shí)現(xiàn)緩存的步驟
這篇文章主要介紹了odoo中使用redis實(shí)現(xiàn)緩存的步驟,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-04-04redis?Template.opsForValue()中方法實(shí)例詳解
這篇文章主要介紹了redis?Template.opsForValue()中方法講解,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-05-05Redis分布式鎖Redlock的實(shí)現(xiàn)
本文主要介紹了Redis分布式鎖Redlock的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-08-08利用redis lua腳本實(shí)現(xiàn)時(shí)間窗分布式限流
Lua是一種輕量小巧的腳本語言,Redis是高性能的key-value內(nèi)存數(shù)據(jù)庫,在部分場(chǎng)景下,是對(duì)關(guān)系數(shù)據(jù)庫的良好補(bǔ)充,本文給大家介紹了如何利用redis lua腳本實(shí)現(xiàn)時(shí)間窗分布式限流,需要的朋友可以參考下2024-03-03Redis過期數(shù)據(jù)是否會(huì)被立馬刪除
這篇文章主要為大家介紹了Redis過期數(shù)據(jù)會(huì)被立馬刪除么的問題解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07手把手教你使用redis實(shí)現(xiàn)排行榜功能
使用Redis中有序集合的特性來實(shí)現(xiàn)排行榜是又好又快的選擇,一般排行榜都是有實(shí)效性的,比如“用戶積分榜”,下面這篇文章主要給大家介紹了關(guān)于使用redis實(shí)現(xiàn)排行榜功能的相關(guān)資料,需要的朋友可以參考下2023-04-04