Redis通信协议优化


1、命令简化
分析:redis通信协议中的命令,用的是原始的set、get、hset、hget等字符串,可以用0x01、0x02、0x03、0x04等单字节代替。
好处:节省网络传输流量,减少dump文件和aof文件的大小。
坏处:不易阅读(这个好象不是问题。。。)。

2、命令分隔符简化
分析:redis通信协议中的命令分隔符,用的是"\r\n",同HTTP协议,可以用"\r"或"\n"代替。
好处:节省网络传输流量,减少dump文件和aof文件的大小。
坏处:好象没有。

3、命令大小写优化(这与1有关,如果1做了,就不会有此条)
分析:redis通信协议文档中,并未说明协议中命令用大写好,还是小写好,但仔细阅读其源代码,会发现,用小写最好。
好处:减少大写转小写次数,加速命令查找。
坏处:无。
参考:

  1. // 以下代码来自redis.c   
  2.   
  3. /* A case insensitive version used for the command lookup table. */  
  4. int dictSdsKeyCaseCompare(void *privdata, const void *key1,  
  5.         const void *key2)  
  6. {  
  7.     DICT_NOTUSED(privdata);  
  8.   
  9.     return strcasecmp(key1, key2) == 0;  
  10. }  
  11.   
  12.   
  13. /* Command table. sds string -> command struct pointer. */  
  14. dictType commandTableDictType = {  
  15.     dictSdsCaseHash,           /* hash function */  
  16.     NULL,                      /* key dup */  
  17.     NULL,                      /* val dup */  
  18.     dictSdsKeyCaseCompare,     /* key compare */  
  19.     dictSdsDestructor,         /* key destructor */  
  20.     NULL                       /* val destructor */  
  21. };  
  22.   
  23. void initServerConfig() {  
  24.   
  25.     // ...   
  26.   
  27.     /* Command table -- we intiialize it here as it is part of the 
  28.      * initial configuration, since command names may be changed via 
  29.      * redis.conf using the rename-command directive. */  
  30.     server.commands = dictCreate(&commandTableDictType,NULL);  
  31.     populateCommandTable();  
  32.     server.delCommand = lookupCommandByCString("del");  
  33.     server.multiCommand = lookupCommandByCString("multi");  
  34.   
  35.     // ...   
  36. }  
  37.   
  38.   
  39. // 以下代码来自linux kernel 3.4.4内核中的lib/string.c文件   
  40.   
  41. #ifndef __HAVE_ARCH_STRCASECMP   
  42. int strcasecmp(const char *s1, const char *s2)  
  43. {  
  44.     int c1, c2;  
  45.   
  46.     do {  
  47.         c1 = tolower(*s1++);  
  48.         c2 = tolower(*s2++);  
  49.     } while (c1 == c2 && c1 != 0);  
  50.     return c1 - c2;  
  51. }  
  52. EXPORT_SYMBOL(strcasecmp);  
  53. #endif  

关键函数strcasecmp比较的时候,是先将s1和s2中的对应字符转化为小写再比较的。

相关内容