最新消息:

memcached专题三、数据导入导出

Linux ipcpu 4747浏览

memcached专题三、数据导入导出.md

概述

memcached数据默认是存放到内存里的,一旦服务重启,数据全部丢失。
尽管有memcachedb等数据持久化方案,但memcached使用依然非常广泛。

导出memcached数据

我们可以使用官方提供的memcached-tool来导出数据。命令如下

  1. [root@QYER-1-17 wetry]#memcached-tool 10.1.1.17:11211 dump > 17mem.data.txt
  2. [root@QYER-1-17 wetry]#head -4 17mem.data.txt
  3. add qel_1364630 0 1482557057 3
  4. abc
  5. add Ks3_1300915 0 1482557057 12
  6. 123456789012

也可以使用memdump导出key,然后写程序去获取key的值。

  1. [root@QYER-1-19 wetry]#memdump --servers=10.1.1.19:11211 > 19mem.data.txt
  2. [root@QYER-1-19 wetry]#head -4 19mem.data.txt
  3. flKs3_1289938
  4. ss3_1375972
  5. Ks3_1295452
  6. qel_1359186
  7. [root@QYER-1-17 wetry]#

上面的两个命令,在我的环境中,每次都只能导出21万左右的key(包括key的名字和Value,一共2M数据)。我的memcached版本为1.4.4。

所以每次只能导出一部分,删除一部分,然后继续导出、删除,如此往复。

我这里写了个脚本,来实现这个功能,如下

  1. #!/bin/bash
  2. MEMCACHED1="10.1.1.17:11211"
  3. MEMCACHED2="10.1.1.17 11211"
  4. ###init functions
  5. #get memcached stats
  6. function memstat() {
  7. memcached-tool $MEMCACHED1 > $1
  8. }
  9. #dump keys
  10. function dumpkey() {
  11. memcached-tool $MEMCACHED1 dump > $1.data.txt
  12. }
  13. #delete dumped keys
  14. function delkey() {
  15. for j in `cat $1.data.txt | grep -E "^add" |awk '{print $2}'`
  16. do
  17. echo "delete $j" | nc $MEMCACHED2 > /dev/null 2>&1
  18. echo $j >> $1.delete.txt
  19. done
  20. }
  21. ##record begin status
  22. memstat mem.stats.begin.txt
  23. #process in loop
  24. for i in `seq 1 2`
  25. do
  26. echo "serial is $i"
  27. dumpkey $i
  28. delkey $i
  29. done
  30. ##record end status
  31. memstat mem.stats.end.txt

导入数据到memcached

之前我们使用memcached-tool将数据导了出来,内容如下

  1. add flKel_1295456 0 1482557057 3
  2. abc

其中超时时间exptime字段被设置为1482557057,超出了30天最大值,因此是无效的,我们将其改为0,永不过期,实际导入时需要根据业务规则来定超时时间。
导入数据

  1. sed -i 's/1482557057 /0 /g' 1.data.txt
  2. cat 1.data.txt | nc 10.1.1.17 11211

参考资料

http://kikinote.net/article/194.html
http://www.cnblogs.com/shrewdlin/archive/2013/03/27/2985167.html
http://blog.sptty.com/2016/04/29/%E4%B8%8D%E8%83%BD%E8%8E%B7%E5%8F%96memcached%E6%89%80%E6%9C%89key%E7%9A%84%E9%97%AE%E9%A2%98%E5%A4%84%E7%90%86.html

转载请注明:IPCPU-网络之路 » memcached专题三、数据导入导出