Redis:如何设置一个键等于另一个键的值? [英] Redis : How to set one key equal to the value of another key?

查看:447
本文介绍了Redis:如何设置一个键等于另一个键的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

REDIS中是否有任何快速命令可以让我执行以下操作?

Is there any quick command in REDIS which allows me to do the following

我想将键Y的值设置为等于键X的值。

I want to set the Value of key Y equal to the value of Key X .

我如何从Redis Client进行此操作。

How do I go about doing this from the Redis Client .

我使用标准的Redis-cli客户端。

I use the standard Redis-cli client .

基本上我正在寻找以下等效项-

Basically I am looking for some equivalent of the following -

 Y.Val() = X.Val()


推荐答案

您可以使用Lua脚本执行此操作:

You can do this with a Lua script:

redis.call('SET', KEYS[2], redis.call('GET', KEYS[1])); return 1;




  1. KEYS1是源密钥

  2. KEYS2是目标键

下面的示例使用脚本加载创建脚本并使用 EVALSHA 传递以下参数:

The example below uses SCRIPT LOAD to create the script and invokes it using EVALSHA passing the following arguments:


  1. 脚本加载返回的SHA1

  2. a 2将传递的密钥数量

  3. 源密钥

  4. 目标密钥。

  1. The SHA1 returned from the script load
  2. a 2 for the number of keys that will be passed
  3. The source key
  4. The target key.

输出:

redis 127.0.0.1:6379> set src.key XXX
OK
redis 127.0.0.1:6379> get src.key
"XXX"
redis 127.0.0.1:6379> SCRIPT LOAD "redis.call('SET', KEYS[2], redis.call('GET', KEYS[1])); return 1;"
"1119c244463dce1ac3a19cdd4fda744e15e02cab"
redis 127.0.0.1:6379> EVALSHA 1119c244463dce1ac3a19cdd4fda744e15e02cab 2 src.key target.key
(integer) 1
redis 127.0.0.1:6379> get target.key
"XXX"

相比之下,确实有很多东西简单地先执行GET然后执行SET,但是一旦加载了脚本(并存储了SHA1),便可以重复使用它。

It does appear to be a lot of stuff compared to simply doing a GET and then s SET, but once you've loaded the script (and memorized the SHA1) then you can reuse it repeatedly.

这篇关于Redis:如何设置一个键等于另一个键的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆