Redis 是一個高性能的鍵值數據庫,支持多種數據結構,如字符串、列表、集合、有序集合和哈希表等
redis-py
庫來實現管道。import redis
r = redis.StrictRedis(host='localhost', port=6379, db=0)
pipe = r.pipeline()
pipe.set('key1', 'value1')
pipe.set('key2', 'value2')
pipe.set('key3', 'value3')
values = pipe.get(['key1', 'key2', 'key3'])
print(values)
import redis
r = redis.StrictRedis(host='localhost', port=6379, db=0)
values = r.mget(['key1', 'key2', 'key3'])
print(values)
-- add_values.lua
local key1 = KEYS[1]
local key2 = KEYS[2]
local key3 = KEYS[3]
local value1 = tonumber(ARGV[1])
local value2 = tonumber(ARGV[2])
local value3 = tonumber(ARGV[3])
redis.call('SET', key1, value1)
redis.call('SET', key2, value2)
redis.call('SET', key3, value3)
return {key1, key2, key3}
在 Python 中,你可以使用 redis-py
庫來執行 Lua 腳本:
import redis
r = redis.StrictRedis(host='localhost', port=6379, db=0)
script = '''
local key1 = KEYS[1]
local key2 = KEYS[2]
local key3 = KEYS[3]
local value1 = tonumber(ARGV[1])
local value2 = tonumber(ARGV[2])
local value3 = tonumber(ARGV[3])
redis.call('SET', key1, value1)
redis.call('SET', key2, value2)
redis.call('SET', key3, value3)
return {key1, key2, key3}
'''
keys = ['key1', 'key2', 'key3']
args = [10, 20, 30]
result = r.eval(script, len(keys), *keys, *args)
print(result)
這些方法可以幫助你更有效地操作 Redis 中的多個鍵。你可以根據自己的需求和場景選擇合適的方法。