当前位置: 首页> 科技> 名企 > 线上商城app_大前端最新网站_国家培训网官网_上海百度推广电话客服

线上商城app_大前端最新网站_国家培训网官网_上海百度推广电话客服

时间:2025/7/10 1:43:46来源:https://blog.csdn.net/u011992620/article/details/146568028 浏览次数:0次
线上商城app_大前端最新网站_国家培训网官网_上海百度推广电话客服

setnx 命令的使用方式如下:

SETNX key value

Set key to hold string value if key does not exist. In that case, it is equal to SET. When key already holds a value, no operation is performed. SETNX is short for "SET if Not eXists".

中文:如果key不存在,则创建key,并设置相应的值

源码

void setnxCommand(client *c) {c->argv[2] = tryObjectEncoding(c->argv[2]);// 调用通用的方法,并传递OBJ_SET_NX标号setGenericCommand(c,OBJ_SET_NX,c->argv[1],c->argv[2],NULL,0,shared.cone,shared.czero);
}

setGenericCommand 是一个通用方法,比较多的命令也都是通过该方法来处理的

void setGenericCommand(client *c, int flags, robj *key, robj *val, robj *expire, int unit, robj *ok_reply, robj *abort_reply) {long long milliseconds = 0; /* initialized to avoid any harmness warning */int found = 0;int setkey_flags = 0;if (expire && getExpireMillisecondsOrReply(c, expire, flags, unit, &milliseconds) != C_OK) {return;}if (flags & OBJ_SET_GET) {if (getGenericCommand(c) == C_ERR) return;}// 按key进行查询found = (lookupKeyWrite(c->db,key) != NULL);// 如果是SetNx命令,并且找到,则直接返回if ((flags & OBJ_SET_NX && found) ||(flags & OBJ_SET_XX && !found)){if (!(flags & OBJ_SET_GET)) {addReply(c, abort_reply ? abort_reply : shared.null[c->resp]);}return;}setkey_flags |= (flags & OBJ_KEEPTTL) ? SETKEY_KEEPTTL : 0;setkey_flags |= found ? SETKEY_ALREADY_EXIST : SETKEY_DOESNT_EXIST;setKey(c,c->db,key,val,setkey_flags);server.dirty++;notifyKeyspaceEvent(NOTIFY_STRING,"set",key,c->db->id);.. 省略部分代码if (!(flags & OBJ_SET_GET)) {addReply(c, ok_reply ? ok_reply : shared.ok);}.. 省略部分代码
}

这里只看关于setnx相关的代码,其实也很简单,从数据库获取key对应的值,如果存在,则直接返回。

如果不存在,则通过setkey方法进行创建key。

在官方文档的setnx命令的开始,就有如下的说明

As of Redis version 2.6.12, this command is regarded as deprecated.

It can be replaced by SET with the NX argument when migrating or writing new code.

从2.6.12 开始,setnx 已经被标识为deprecated, 需要通过set 命令中,通过指定nx参数来替代。

SET key value [NX | XX] [GET] [EX seconds | PX milliseconds |EXAT unix-time-seconds | PXAT unix-time-milliseconds | KEEPTTL]

set 命令将在下一节完整分析下。

关键字:线上商城app_大前端最新网站_国家培训网官网_上海百度推广电话客服

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: