# redis-replicator **Repository Path**: davidmr/redis-replicator ## Basic Information - **Project Name**: redis-replicator - **Description**: Redis-replicator是一款用java写的redis rdb以及命令解析软件. 它可以实时解析,过滤,广播rdb以及command事件 支持redis2.8+,内部采用psync命令同步数据 支持rdb version 6,rdb version 7 支持注册命令解析器. - **Primary Language**: Java - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 2 - **Forks**: 48 - **Created**: 2017-04-07 - **Last Updated**: 2020-12-18 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README Table of Contents([中文说明](./README.zh_CN.md)) ================= * [1. Redis-replicator](#1-redis-replicator) * [1.1. Brief introduction](#11-brief-introduction) * [1.2. QQ group](#12-qq-group) * [1.3. Contract author](#13-contract-author) * [2. Install](#2-install) * [2.1. Requirements](#21-requirements) * [2.2. Maven dependency](#22-maven-dependency) * [2.3. Install from source code](#23-install-from-source-code) * [3. Simple usage](#3-simple-usage) * [3.1. Replication via socket](#31-replication-via-socket) * [3.2. Read rdb file](#32-read-rdb-file) * [3.3. Read aof file](#33-read-aof-file) * [3.4. Read mixed file](#34-read-mixed-file) * [3.4.1. Mixed file format](#341-mixed-file-format) * [3.4.2. Mixed file redis configuration](#342-mixed-file-redis-configuration) * [3.4.3. Using replicator read mixed file](#343-using-replicator-read-mixed-file) * [3.5. Backup remote rdb snapshot](#35-backup-remote-rdb-snapshot) * [3.6. Backup remote commands](#36-backup-remote-commands) * [4. Advanced topics](#4-advanced-topics) * [4.1. Command extension](#41-command-extension) * [4.1.1. Write a command](#411-write-a-command) * [4.1.2. Write a command parser](#412-write-a-command-parser) * [4.1.3. Register this parser](#413-register-this-parser) * [4.1.4. Handle command event](#414-handle-command-event) * [4.2. Module extension](#42-module-extension) * [4.2.1. Compile redis test modules](#421-compile-redis-test-modules) * [4.2.2. Open comment in redis.conf](#422-open-comment-in-redisconf) * [4.2.3. Write a module parser](#423-write-a-module-parser) * [4.2.4. Write a command parser](#424-write-a-command-parser) * [4.2.5. Register this module parser and command parser and handle event](#425-register-this-module-parser-and-command-parser-and-handle-event) * [4.3. Write your own rdb parser](#43-write-your-own-rdb-parser) * [5. Other topics](#5-other-topics) * [5.1. Built-in command parser](#51-built-in-command-parser) * [5.2. EOFException](#52-eofexception) * [5.3. Trace event log](#53-trace-event-log) * [5.4. SSL connection](#54-ssl-connection) * [5.5. Auth](#55-auth) * [5.6. Avoid full sync](#56-avoid-full-sync) * [5.7. FullSyncEvent](#57-fullsyncevent) * [5.8. Handle raw bytes](#58-handle-raw-bytes) * [6. Contributors](#6-contributors) * [7. References](#7-references) # 1. Redis-replicator ## 1.1. Brief introduction [![Join the chat at https://gitter.im/leonchen83/redis-replicator](https://badges.gitter.im/leonchen83/redis-replicator.svg)](https://gitter.im/leonchen83/redis-replicator?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Build Status](https://travis-ci.org/leonchen83/redis-replicator.svg?branch=master)](https://travis-ci.org/leonchen83/redis-replicator) [![Coverage Status](https://coveralls.io/repos/github/leonchen83/redis-replicator/badge.svg?branch=master)](https://coveralls.io/github/leonchen83/redis-replicator?branch=master) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.moilioncircle/redis-replicator/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.moilioncircle/redis-replicator) [![Javadoc](https://javadoc-emblem.rhcloud.com/doc/com.moilioncircle/redis-replicator/badge.svg)](http://www.javadoc.io/doc/com.moilioncircle/redis-replicator) [![Hex.pm](https://img.shields.io/hexpm/l/plug.svg?maxAge=2592000)](https://github.com/leonchen83/redis-replicator/blob/master/LICENSE) Redis Replicator is a redis rdb and command parser written in java. It can parse,filter,broadcast the rdb and command events in a real time manner. It also can synchronize redis data to your local cache or to database. The below I mentioned `Command` which means `Write Command` in redis and excludes `Read Command`(e.g. `get`,`hmget`) ## 1.2. QQ group **479688557** ## 1.3. Contract author **chen.bao.yi@gmail.com** # 2. Install ## 2.1. Requirements jdk 1.7+ maven-3.2.3+ redis 2.4 - 4.0-rc2 ## 2.2. Maven dependency ```java com.moilioncircle redis-replicator 2.0.0-rc3 ``` ## 2.3. Install from source code ``` $mvn clean install package -Dmaven.test.skip=true ``` # 3. Simple usage ## 3.1. Replication via socket ```java Replicator replicator = new RedisReplicator("127.0.0.1", 6379, Configuration.defaultSetting()); replicator.addRdbListener(new RdbListener.Adaptor() { @Override public void handle(Replicator replicator, KeyValuePair kv) { System.out.println(kv); } }); replicator.addCommandListener(new CommandListener() { @Override public void handle(Replicator replicator, Command command) { System.out.println(command); } }); replicator.open(); ``` ## 3.2. Read rdb file ```java Replicator replicator = new RedisReplicator(new File("dump.rdb"), FileType.RDB, Configuration.defaultSetting()); replicator.addRdbListener(new RdbListener.Adaptor() { @Override public void handle(Replicator replicator, KeyValuePair kv) { System.out.println(kv); } }); replicator.open(); ``` ## 3.3. Read aof file ```java Replicator replicator = new RedisReplicator(new File("appendonly.aof"), FileType.AOF, Configuration.defaultSetting()); replicator.addCommandListener(new CommandListener() { @Override public void handle(Replicator replicator, Command command) { System.out.println(command); } }); replicator.open(); ``` ## 3.4. Read mixed file ### 3.4.1. Mixed file format ```java [RDB file][AOF tail] ``` ### 3.4.2. Mixed file redis configuration ```java aof-use-rdb-preamble yes ``` ### 3.4.3. Using replicator read mixed file ```java final Replicator replicator = new RedisReplicator(new File("appendonly.aof"), FileType.MIXED, Configuration.defaultSetting()); replicator.addRdbListener(new RdbListener.Adaptor() { @Override public void handle(Replicator replicator, KeyValuePair kv) { System.out.println(kv); } }); replicator.addCommandListener(new CommandListener() { @Override public void handle(Replicator replicator, Command command) { System.out.println(command); } }); replicator.open(); ``` ## 3.5. Backup remote rdb snapshot ```java final FileOutputStream out = new FileOutputStream(new File("./dump.rdb")); final RawByteListener rawByteListener = new RawByteListener() { @Override public void handle(byte... rawBytes) { try { out.write(rawBytes); } catch (IOException ignore) { } } }; //save rdb from remote server Replicator replicator = new RedisReplicator("127.0.0.1", 6379, Configuration.defaultSetting()); replicator.addRdbListener(new RdbListener() { @Override public void preFullSync(Replicator replicator) { replicator.addRawByteListener(rawByteListener); } @Override public void handle(Replicator replicator, KeyValuePair kv) { } @Override public void postFullSync(Replicator replicator, long checksum) { replicator.removeRawByteListener(rawByteListener); try { out.close(); replicator.close(); } catch (IOException ignore) { } } }); replicator.open(); //check rdb file replicator = new RedisReplicator(new File("./dump.rdb"), FileType.RDB, Configuration.defaultSetting()); replicator.addRdbListener(new RdbListener.Adaptor() { @Override public void handle(Replicator replicator, KeyValuePair kv) { System.out.println(kv); } }); replicator.open(); ``` ## 3.6. Backup remote commands ```java final FileOutputStream out = new FileOutputStream(new File("./appendonly.aof")); final RawByteListener rawByteListener = new RawByteListener() { @Override public void handle(byte... rawBytes) { try { out.write(rawBytes); } catch (IOException ignore) { } } }; //save 1000 records commands Replicator replicator = new RedisReplicator("127.0.0.1", 6379, Configuration.defaultSetting()); replicator.addRdbListener(new RdbListener() { @Override public void preFullSync(Replicator replicator) { } @Override public void handle(Replicator replicator, KeyValuePair kv) { } @Override public void postFullSync(Replicator replicator, long checksum) { replicator.addRawByteListener(rawByteListener); } }); final AtomicInteger acc = new AtomicInteger(0); replicator.addCommandListener(new CommandListener() { @Override public void handle(Replicator replicator, Command command) { if (acc.incrementAndGet() == 1000) { try { out.close(); replicator.close(); } catch (IOException e) { e.printStackTrace(); } } } }); replicator.open(); //check aof file replicator = new RedisReplicator(new File("./appendonly.aof"), FileType.AOF, Configuration.defaultSetting()); replicator.addCommandListener(new CommandListener() { @Override public void handle(Replicator replicator, Command command) { System.out.println(command); } }); replicator.open(); ``` # 4. Advanced topics ## 4.1. Command extension ### 4.1.1. Write a command ```java public static class YourAppendCommand implements Command { private final String key; private final String value; public YourAppendCommand(String key, String value) { this.key = key; this.value = value; } public String getKey() { return key; } public String getValue() { return value; } @Override public String toString() { return "YourAppendCommand{" + "key='" + key + '\'' + ", value='" + value + '\'' + '}'; } } } ``` ### 4.1.2. Write a command parser ```java public class YourAppendParser implements CommandParser { @Override public YourAppendCommand parse(Object[] command) { return new YourAppendCommand((String) command[1], (String) command[2]); } } ``` ### 4.1.3. Register this parser ```java Replicator replicator = new RedisReplicator("127.0.0.1",6379,Configuration.defaultSetting()); replicator.addCommandParser(CommandName.name("APPEND"),new YourAppendParser()); ``` ### 4.1.4. Handle command event ```java replicator.addCommandListener(new CommandListener() { @Override public void handle(Replicator replicator, Command command) { if(command instanceof YourAppendCommand){ YourAppendCommand appendCommand = (YourAppendCommand)command; // your code goes here } } }); ``` ## 4.2. Module extension ### 4.2.1. Compile redis test modules ```java $cd /path/to/redis-4.0-rc2/src/modules $make ``` ### 4.2.2. Open comment in redis.conf ```java loadmodule /path/to/redis-4.0-rc2/src/modules/hellotype.so ``` ### 4.2.3. Write a module parser ```java public class HelloTypeModuleParser implements ModuleParser { @Override public HelloTypeModule parse(RedisInputStream in) throws IOException { DefaultRdbModuleParser parser = new DefaultRdbModuleParser(in); int elements = (int) parser.loadUnSigned(); long[] ary = new long[elements]; int i = 0; while (elements-- > 0) { ary[i++] = parser.loadSigned(); } return new HelloTypeModule(ary); } } public class HelloTypeModule implements Module { private final long[] value; public HelloTypeModule(long[] value) { this.value = value; } public long[] getValue() { return value; } @Override public String toString() { return "HelloTypeModule{" + "value=" + Arrays.toString(value) + '}'; } } ``` ### 4.2.4. Write a command parser ```java public class HelloTypeParser implements CommandParser { @Override public HelloTypeCommand parse(Object[] command) { String key = (String) command[1]; long value = Long.parseLong((String) command[2]); return new HelloTypeCommand(key, value); } } public class HelloTypeCommand implements Command { private final String key; private final long value; public long getValue() { return value; } public String getKey() { return key; } public HelloTypeCommand(String key, long value) { this.key = key; this.value = value; } @Override public String toString() { return "HelloTypeCommand{" + "key='" + key + '\'' + ", value=" + value + '}'; } } ``` ### 4.2.5. Register this module parser and command parser and handle event ```java public static void main(String[] args) throws IOException { RedisReplicator replicator = new RedisReplicator("127.0.0.1", 6379, Configuration.defaultSetting()); replicator.addCommandParser(CommandName.name("hellotype.insert"), new HelloTypeParser()); replicator.addModuleParser("hellotype", 0, new HelloTypeModuleParser()); replicator.addRdbListener(new RdbListener.Adaptor() { @Override public void handle(Replicator replicator, KeyValuePair kv) { if (kv instanceof KeyStringValueModule) { System.out.println(kv); } } }); replicator.addCommandListener(new CommandListener() { @Override public void handle(Replicator replicator, Command command) { if (command instanceof HelloTypeCommand) { System.out.println(command); } } }); replicator.open(); } ``` ## 4.3. Write your own rdb parser * extends `RdbVisitor` * register your `RdbVisitor` to `Replicator` using `setRdbVisitor` method. # 5. Other topics ## 5.1. Built-in command parser |**commands**|**commands** | **commands** |**commands**|**commands** | **commands** | | ---------- | ------------ | ---------------| ---------- | ------------ | ---------------| | **PING** | **APPEND** | **SET** | **SETEX** | **MSET** | **DEL** | | **SADD** | **HMSET** | **HSET** | **LSET** | **EXPIRE** | **EXPIREAT** | | **GETSET** | **HSETNX** | **MSETNX** | **PSETEX** | **SETNX** | **SETRANGE** | | **HDEL** | **UNLINK** | **SREM** | **LPOP** | **LPUSH** | **LPUSHX** | | **LRem** | **RPOP** | **RPUSH** | **RPUSHX** | **ZREM** | **RENAME** | | **INCR** | **DECR** | **INCRBY** |**PERSIST** | **SELECT** | **FLUSHALL** | |**FLUSHDB** | **HINCRBY** | **ZINCRBY** | **MOVE** | **SMOVE** | **PFADD** | |**PFCOUNT** | **PFMERGE** | **SDIFFSTORE** |**RENAMENX**| **PEXPIREAT**|**SINTERSTORE** | |**ZADD** | **BITFIELD** |**SUNIONSTORE** |**RESTORE** | **LINSERT** |**ZINTERSTORE** | |**GEOADD** | **PEXPIRE** |**ZUNIONSTORE** |**EVAL** | **SCRIPT** |**BRPOPLPUSH** | |**PUBLISH** | **BITOP** |**SETBIT** | | | | ## 5.2. EOFException * adjust redis server setting below.more details please refer to [redis.conf](https://raw.githubusercontent.com/antirez/redis/3.0/redis.conf) ```java client-output-buffer-limit slave 0 0 0 ``` **WARNNING: this setting may run out of memory of redis server in some cases.** ## 5.3. Trace event log * set log level to **debug** * if you are using log4j2,add logger below: ```xml ``` ```java Configuration.defaultSetting().setVerbose(true); ``` ## 5.4. SSL connection ```java System.setProperty("javax.net.ssl.trustStore", "/path/to/truststore"); System.setProperty("javax.net.ssl.trustStorePassword", "password"); System.setProperty("javax.net.ssl.trustStoreType", "your_type"); Configuration.defaultSetting().setSsl(true); //optional setting Configuration.defaultSetting().setSslSocketFactory(sslSocketFactory); Configuration.defaultSetting().setSslParameters(sslParameters); Configuration.defaultSetting().setHostnameVerifier(hostnameVerifier); ``` ## 5.5. Auth ```java Configuration.defaultSetting().setAuthPassword("foobared"); ``` ## 5.6. Avoid full sync * adjust redis server setting below ```java repl-backlog-size repl-backlog-ttl repl-ping-slave-period ``` `repl-ping-slave-period` **MUST** less than `Configuration.getReadTimeout()` default `Configuration.getReadTimeout()` is 30 seconds ## 5.7. FullSyncEvent ```java Replicator replicator = new RedisReplicator("127.0.0.1", 6379, Configuration.defaultSetting()); final long start = System.currentTimeMillis(); final AtomicInteger acc = new AtomicInteger(0); replicator.addRdbListener(new RdbListener() { @Override public void preFullSync(Replicator replicator) { System.out.println("pre full sync"); } @Override public void handle(Replicator replicator, KeyValuePair kv) { acc.incrementAndGet(); } @Override public void postFullSync(Replicator replicator, long checksum) { long end = System.currentTimeMillis(); System.out.println("time elapsed:" + (end - start)); System.out.println("rdb event count:" + acc.get()); } }); replicator.open(); ``` ## 5.8. Handle raw bytes * when kv.getValueRdbType() == 0, you can get the raw bytes of value. In some cases(e.g. HyperLogLog),this is very useful. ```java Replicator replicator = new RedisReplicator("127.0.0.1", 6379, Configuration.defaultSetting()); replicator.addRdbListener(new RdbListener.Adaptor() { @Override public void handle(Replicator replicator, KeyValuePair kv) { if (kv instanceof KeyStringValueString) { KeyStringValueString ksvs = (KeyStringValueString) kv; System.out.println(Arrays.toString(ksvs.getRawBytes())); } } }); replicator.open(); ``` # 6. Contributors * Leon Chen * Adrian Yao # 7. References * [rdb.c](https://github.com/antirez/redis/blob/unstable/src/rdb.c) * [Redis RDB File Format](https://github.com/sripathikrishnan/redis-rdb-tools/wiki/Redis-RDB-Dump-File-Format) * [Redis Protocol specification](http://redis.io/topics/protocol) * [Redis Replication](http://redis.io/topics/replication)