這篇博文是借鑑別人的,主要怕之後找不着了,本身只是照抄,轉載自http://www.pianshen.com/article/264026969/。mysql
項目組的後臺數據庫出了些問題,致使Mysql和Redis緩存之間出現了數據不一致,所以須要同步一下他倆。因而乎我從網上找了這篇文章,這種方法只是短時間同步,並非實時地進行同步的方式。redis
首先,熟悉下管道的格式sql
1 *4 #表示有4個參數 2 $4 #表示「參數」有三個字節("HSET"字符串爲4個字節) 3 hset #redis的設置命令 4 $8 # key有 8個字節 5 myTopic #key對應的值 6 $6 #field對應的長度 7 client.id #field對應的值 8 $12 # value的長度 9 hkid #value的值 10 # 一條語句結束 11 每行默認以 \r\n 結尾
而後,編寫Sql語句拼成要執行的Redis命令shell
1 select 2 'HSET' AS redis_cmd, CONCAT('topic:',topic_name) AS redis_key, 3 'client.id' AS hkey1, client_id AS hval1 4 FROM topic 5 union 6 SELECT 7 'HSET' AS redis_cmd, CONCAT('topic:',topic_name) AS redis_key, 8 'zk.host' AS hkey1, zk_host AS hval1 9 FROM topic
每一行就是一個完整的redis命令;數據庫
接着,編寫mysql_to_redis.sql文件緩存
1 SELECT CONCAT( 2 "*4\r\n", 3 '$', LENGTH(t.redis_cmd), '\r\n', 4 t.redis_cmd, '\r\n', 5 '$', LENGTH(t.redis_key), '\r\n', 6 t.redis_key, '\r\n', 7 '$', LENGTH(t.hkey1), '\r\n', 8 t.hkey1, '\r\n', 9 '$', LENGTH(t.hval1), '\r\n', 10 t.hval1, '\r' 11 ) as redissql 12 FROM ( 13 select 14 'HSET' AS redis_cmd, CONCAT('topic:',topic_name) AS redis_key, 15 'client.id' AS hkey1, client_id AS hval1 16 FROM topic 17 union 18 SELECT 19 'HSET' AS redis_cmd, CONCAT('topic:',topic_name) AS redis_key, 20 'zk.host' AS hkey1, zk_host AS hval1 21 FROM topic 22 ) AS t
最後,執行命令ui
1 mysql –h127.0.0.1 -uroot -pzhy123456 -Drui --skip-column-names --raw </usr/local/rui/shell/mysql_to_redis.sql |redis-cli -h 127.0.0.1 -p 6379 --pipe
-D 後面跟上Mysql數據庫名稱,redis-cli加-n,後邊能夠跟Redis庫。spa