漫话Redis源码之二十八

2024-02-06 09:48
文章标签 源码 redis 二十八 漫话

本文主要是介绍漫话Redis源码之二十八,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

这里主要是一些控制信息,看似复杂,其实还是比较明朗的:

/* Cluster Manager Command Info */
typedef struct clusterManagerCommand {char *name;int argc;char **argv;int flags;int replicas;char *from;char *to;char **weight;int weight_argc;char *master_id;int slots;int timeout;int pipeline;float threshold;char *backup_dir;char *from_user;char *from_pass;int from_askpass;
} clusterManagerCommand;static void createClusterManagerCommand(char *cmdname, int argc, char **argv);static redisContext *context;
static struct config {char *hostip;int hostport;char *hostsocket;int tls;cliSSLconfig sslconfig;long repeat;long interval;int dbnum; /* db num currently selected */int input_dbnum; /* db num user input */int interactive;int shutdown;int monitor_mode;int pubsub_mode;int latency_mode;int latency_dist_mode;int latency_history;int lru_test_mode;long long lru_test_sample_size;int cluster_mode;int cluster_reissue_command;int cluster_send_asking;int slave_mode;int pipe_mode;int pipe_timeout;int getrdb_mode;int stat_mode;int scan_mode;int intrinsic_latency_mode;int intrinsic_latency_duration;sds pattern;char *rdb_filename;int bigkeys;int memkeys;unsigned memkeys_samples;int hotkeys;int stdinarg; /* get last arg from stdin. (-x option) */char *auth;int askpass;char *user;int quoted_input;   /* Force input args to be treated as quoted strings */int output; /* output mode, see OUTPUT_* defines */int push_output; /* Should we display spontaneous PUSH replies */sds mb_delim;sds cmd_delim;char prompt[128];char *eval;int eval_ldb;int eval_ldb_sync;  /* Ask for synchronous mode of the Lua debugger. */int eval_ldb_end;   /* Lua debugging session ended. */int enable_ldb_on_eval; /* Handle manual SCRIPT DEBUG + EVAL commands. */int last_cmd_type;int verbose;int set_errcode;clusterManagerCommand cluster_manager_command;int no_auth_warning;int resp3;int in_multi;int pre_multi_dbnum;
} config;/* User preferences. */
static struct pref {int hints;
} pref;static volatile sig_atomic_t force_cancel_loop = 0;
static void usage(void);
static void slaveMode(void);
char *redisGitSHA1(void);
char *redisGitDirty(void);
static int cliConnect(int force);static char *getInfoField(char *info, char *field);
static long getLongInfoField(char *info, char *field);/*------------------------------------------------------------------------------* Utility functions*--------------------------------------------------------------------------- */static void cliPushHandler(void *, void *);uint16_t crc16(const char *buf, int len);static long long ustime(void) {struct timeval tv;long long ust;gettimeofday(&tv, NULL);ust = ((long long)tv.tv_sec)*1000000;ust += tv.tv_usec;return ust;
}static long long mstime(void) {return ustime()/1000;
}static void cliRefreshPrompt(void) {if (config.eval_ldb) return;sds prompt = sdsempty();if (config.hostsocket != NULL) {prompt = sdscatfmt(prompt,"redis %s",config.hostsocket);} else {char addr[256];anetFormatAddr(addr, sizeof(addr), config.hostip, config.hostport);prompt = sdscatlen(prompt,addr,strlen(addr));}/* Add [dbnum] if needed */if (config.dbnum != 0)prompt = sdscatfmt(prompt,"[%i]",config.dbnum);/* Add TX if in transaction state*/if (config.in_multi)  prompt = sdscatlen(prompt,"(TX)",4);/* Copy the prompt in the static buffer. */prompt = sdscatlen(prompt,"> ",2);snprintf(config.prompt,sizeof(config.prompt),"%s",prompt);sdsfree(prompt);
}/* Return the name of the dotfile for the specified 'dotfilename'.* Normally it just concatenates user $HOME to the file specified* in 'dotfilename'. However if the environment variable 'envoverride'* is set, its value is taken as the path.** The function returns NULL (if the file is /dev/null or cannot be* obtained for some error), or an SDS string that must be freed by* the user. */
static sds getDotfilePath(char *envoverride, char *dotfilename) {char *path = NULL;sds dotPath = NULL;/* Check the env for a dotfile override. */path = getenv(envoverride);if (path != NULL && *path != '\0') {if (!strcmp("/dev/null", path)) {return NULL;}/* If the env is set, return it. */dotPath = sdsnew(path);} else {char *home = getenv("HOME");if (home != NULL && *home != '\0') {/* If no override is set use $HOME/<dotfilename>. */dotPath = sdscatprintf(sdsempty(), "%s/%s", home, dotfilename);}}return dotPath;
}/* URL-style percent decoding. */
#define isHexChar(c) (isdigit(c) || (c >= 'a' && c <= 'f'))
#define decodeHexChar(c) (isdigit(c) ? c - '0' : c - 'a' + 10)
#define decodeHex(h, l) ((decodeHexChar(h) << 4) + decodeHexChar(l))static sds percentDecode(const char *pe, size_t len) {const char *end = pe + len;sds ret = sdsempty();const char *curr = pe;while (curr < end) {if (*curr == '%') {if ((end - curr) < 2) {fprintf(stderr, "Incomplete URI encoding\n");exit(1);}char h = tolower(*(++curr));char l = tolower(*(++curr));if (!isHexChar(h) || !isHexChar(l)) {fprintf(stderr, "Illegal character in URI encoding\n");exit(1);}char c = decodeHex(h, l);ret = sdscatlen(ret, &c, 1);curr++;} else {ret = sdscatlen(ret, curr++, 1);}}return ret;
}/* Parse a URI and extract the server connection information.* URI scheme is based on the the provisional specification[1] excluding support* for query parameters. Valid URIs are:*   scheme:    "redis://"*   authority: [[<username> ":"] <password> "@"] [<hostname> [":" <port>]]*   path:      ["/" [<db>]]**  [1]: https://www.iana.org/assignments/uri-schemes/prov/redis */
static void parseRedisUri(const char *uri) {const char *scheme = "redis://";const char *tlsscheme = "rediss://";const char *curr = uri;const char *end = uri + strlen(uri);const char *userinfo, *username, *port, *host, *path;/* URI must start with a valid scheme. */if (!strncasecmp(tlsscheme, curr, strlen(tlsscheme))) {
#ifdef USE_OPENSSLconfig.tls = 1;curr += strlen(tlsscheme);
#elsefprintf(stderr,"rediss:// is only supported when redis-cli is compiled with OpenSSL\n");exit(1);
#endif} else if (!strncasecmp(scheme, curr, strlen(scheme))) {curr += strlen(scheme);} else {fprintf(stderr,"Invalid URI scheme\n");exit(1);}if (curr == end) return;/* Extract user info. */if ((userinfo = strchr(curr,'@'))) {if ((username = strchr(curr, ':')) && username < userinfo) {config.user = percentDecode(curr, username - curr);curr = username + 1;}config.auth = percentDecode(curr, userinfo - curr);curr = userinfo + 1;}if (curr == end) return;/* Extract host and port. */path = strchr(curr, '/');if (*curr != '/') {host = path ? path - 1 : end;if ((port = strchr(curr, ':'))) {config.hostport = atoi(port + 1);host = port - 1;}config.hostip = sdsnewlen(curr, host - curr + 1);}curr = path ? path + 1 : end;if (curr == end) return;/* Extract database number. */config.input_dbnum = atoi(curr);
}static uint64_t dictSdsHash(const void *key) {return dictGenHashFunction((unsigned char*)key, sdslen((char*)key));
}static int dictSdsKeyCompare(void *privdata, const void *key1,const void *key2)
{int l1,l2;DICT_NOTUSED(privdata);l1 = sdslen((sds)key1);l2 = sdslen((sds)key2);if (l1 != l2) return 0;return memcmp(key1, key2, l1) == 0;
}static void dictSdsDestructor(void *privdata, void *val)
{DICT_NOTUSED(privdata);sdsfree(val);
}void dictListDestructor(void *privdata, void *val)
{DICT_NOTUSED(privdata);listRelease((list*)val);
}/* _serverAssert is needed by dict */
void _serverAssert(const char *estr, const char *file, int line) {fprintf(stderr, "=== ASSERTION FAILED ===");fprintf(stderr, "==> %s:%d '%s' is not true",file,line,estr);*((char*)-1) = 'x';
}

这篇关于漫话Redis源码之二十八的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/683905

相关文章

redis群集简单部署过程

《redis群集简单部署过程》文章介绍了Redis,一个高性能的键值存储系统,其支持多种数据结构和命令,它还讨论了Redis的服务器端架构、数据存储和获取、协议和命令、高可用性方案、缓存机制以及监控和... 目录Redis介绍1. 基本概念2. 服务器端3. 存储和获取数据4. 协议和命令5. 高可用性6.

Redis的数据过期策略和数据淘汰策略

《Redis的数据过期策略和数据淘汰策略》本文主要介绍了Redis的数据过期策略和数据淘汰策略,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录一、数据过期策略1、惰性删除2、定期删除二、数据淘汰策略1、数据淘汰策略概念2、8种数据淘汰策略

Redis存储的列表分页和检索的实现方法

《Redis存储的列表分页和检索的实现方法》在Redis中,列表(List)是一种有序的数据结构,通常用于存储一系列元素,由于列表是有序的,可以通过索引来访问元素,因此可以很方便地实现分页和检索功能,... 目录一、Redis 列表的基本操作二、分页实现三、检索实现3.1 方法 1:客户端过滤3.2 方法

Python中操作Redis的常用方法小结

《Python中操作Redis的常用方法小结》这篇文章主要为大家详细介绍了Python中操作Redis的常用方法,文中的示例代码简洁易懂,具有一定的借鉴价值,有需要的小伙伴可以了解一下... 目录安装Redis开启、关闭Redisredis数据结构redis-cli操作安装redis-py数据库连接和释放增

redis防止短信恶意调用的实现

《redis防止短信恶意调用的实现》本文主要介绍了在场景登录或注册接口中使用短信验证码时遇到的恶意调用问题,并通过使用Redis分布式锁来解决,具有一定的参考价值,感兴趣的可以了解一下... 目录1.场景2.排查3.解决方案3.1 Redis锁实现3.2 方法调用1.场景登录或注册接口中,使用短信验证码场

Redis 多规则限流和防重复提交方案实现小结

《Redis多规则限流和防重复提交方案实现小结》本文主要介绍了Redis多规则限流和防重复提交方案实现小结,包括使用String结构和Zset结构来记录用户IP的访问次数,具有一定的参考价值,感兴趣... 目录一:使用 String 结构记录固定时间段内某用户 IP 访问某接口的次数二:使用 Zset 进行

解读Redis秒杀优化方案(阻塞队列+基于Stream流的消息队列)

《解读Redis秒杀优化方案(阻塞队列+基于Stream流的消息队列)》该文章介绍了使用Redis的阻塞队列和Stream流的消息队列来优化秒杀系统的方案,通过将秒杀流程拆分为两条流水线,使用Redi... 目录Redis秒杀优化方案(阻塞队列+Stream流的消息队列)什么是消息队列?消费者组的工作方式每

Redis如何使用zset处理排行榜和计数问题

《Redis如何使用zset处理排行榜和计数问题》Redis的ZSET数据结构非常适合处理排行榜和计数问题,它可以在高并发的点赞业务中高效地管理点赞的排名,并且由于ZSET的排序特性,可以轻松实现根据... 目录Redis使用zset处理排行榜和计数业务逻辑ZSET 数据结构优化高并发的点赞操作ZSET 结

Redis的Zset类型及相关命令详细讲解

《Redis的Zset类型及相关命令详细讲解》:本文主要介绍Redis的Zset类型及相关命令的相关资料,有序集合Zset是一种Redis数据结构,它类似于集合Set,但每个元素都有一个关联的分数... 目录Zset简介ZADDZCARDZCOUNTZRANGEZREVRANGEZRANGEBYSCOREZ

Go中sync.Once源码的深度讲解

《Go中sync.Once源码的深度讲解》sync.Once是Go语言标准库中的一个同步原语,用于确保某个操作只执行一次,本文将从源码出发为大家详细介绍一下sync.Once的具体使用,x希望对大家有... 目录概念简单示例源码解读总结概念sync.Once是Go语言标准库中的一个同步原语,用于确保某个操