歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Redis通信協議優化

Redis通信協議優化

日期:2017/3/1 10:14:23   编辑:Linux編程

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

關鍵函數strcasecmp比較的時候,是先將s1和s2中的對應字符轉化為小寫再比較的。

Copyright © Linux教程網 All Rights Reserved