当前位置: 首页 > news >正文

Redis原理:setnx

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 命令将在下一节完整分析下。

相关文章:

  • 基于Springboot的网上订餐系统 【源码】+【PPT】+【开题报告】+【论文】
  • 深入剖析C++中的哈希表:从STL到底层实现
  • 2000-2019年各省地方财政罚没收入数据
  • 测试环境项目启动redis报错
  • 智能任务分配:Python高并发架构设计
  • 调速电机怎么测量好坏
  • 无人船信号探测与对接技术解析!
  • 【Linux】应用层协议 HTTP
  • 【MySQL】验证账户权限
  • Mysql-基础和DDL
  • DeepSeek 为何能在短时间内超过 ChatGPT?—— 技术变革与成本重构的双重胜利
  • Spring AI Alibaba EmbeddingModel使用
  • 堆的常见应用2
  • MySQL中的内连接与外连接详解:基础与进阶应用
  • 函数:链式访问
  • 【操作系统】(五)操作系统引导(Boot)
  • Leetcode13-罗马数字转整数
  • Django框架指南:从入门到进阶
  • 【蓝桥杯】3月27日笔记
  • C++:无序关联容器
  • 南京网站制作公司怎么样/线上推广策略
  • 知名企业核心价值观/长春做网站公司长春seo公司
  • 怎么写代码自己制作网站/网站信息查询
  • 网站制作推广/广告图片
  • 北京网站快速排名优化/交换友情链接推广法
  • wordpress游览量/seo是什么?