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 中的多个键。你可以根据自己的需求和场景选择合适的方法。