问题三:如何把redis的数据同步到MySQL

问题三:如何把redis的数据同步到MySQL?
解决:
使用开源的redis同步工具:https://github.com/leonchen83/redis-replicator
例如 如下代码:

package com.couchbase.devguide;

import com.moilioncircle.redis.replicator.RedisReplicator;
import com.moilioncircle.redis.replicator.Replicator;
import com.moilioncircle.redis.replicator.cmd.Command;
import com.moilioncircle.redis.replicator.cmd.impl.SetCommand;
import com.moilioncircle.redis.replicator.event.Event;
import com.moilioncircle.redis.replicator.event.EventListener;
import com.moilioncircle.redis.replicator.event.PostRdbSyncEvent;
import com.moilioncircle.redis.replicator.io.RawByteListener;
import com.moilioncircle.redis.replicator.rdb.dump.datatype.DumpKeyValuePair;

import java.io.*;
import java.util.concurrent.atomic.AtomicInteger;

public class redis {
    public static void main(String[] args) throws Exception {
        final OutputStream out = new BufferedOutputStream(new FileOutputStream(new File("a.aof")));
        final RawByteListener rawByteListener = new RawByteListener() {
            public void handle(byte... rawBytes) {
                try {
                    out.write(rawBytes);
                } catch (IOException ignore) {
                }
            }
        };

        //save 1000 records commands
        Replicator replicator = new RedisReplicator("redis://127.0.0.1:6379?authPassword=123456");
        final AtomicInteger acc = new AtomicInteger(0);
        replicator.addEventListener(new EventListener() {
            public void onEvent(Replicator replicator, Event event) {
                if (event instanceof PostRdbSyncEvent) {
                    replicator.addRawByteListener(rawByteListener);
                }
                if (event instanceof SetCommand) {
                    System.out.println(new String(((SetCommand) event).getValue()));
                    if (acc.incrementAndGet() == 10) {
                        try {
                            out.close();
                            replicator.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });

        replicator.open();

        //check aof file
        replicator = new RedisReplicator("redis:./a.aof");
        replicator.addEventListener(new EventListener() {
            public void onEvent(Replicator replicator, Event event) {
                System.out.println(event);
            }
        });
        replicator.open();
    }
}

你可能感兴趣的:(问题三:如何把redis的数据同步到MySQL)