Redis批量導入數據的示例:
1.準備一個redis protocol的文件,通過java程序來輸出的,代碼如下:
<<RedisBatchTest>>public class RedisBatchTest {
public static void main(String[] args) {
String outputFile = "d:\\temp\\redis_input.txt";
RedisBatchTest test = new RedisBatchTest();
test.generateFile(outputFile);
}
/**
* 格式化成輸入字符串
*
* @param args
* @return
*/
private String getString(String key, String value) {
StringBuilder sb = new StringBuilder();
sb.append("*3").append("\r\n");
sb.append("$3").append("\r\n");
sb.append("SET\r\n");
sb.append("$").append(key.getBytes().length).append("\r\n");
sb.append(key).append("\r\n");
sb.append("$").append(value.getBytes().length).append("\r\n");
sb.append(value).append("\r\n");
return sb.toString();
}
public void generateFile(String file) {
BufferedWriter w = null;
String key = null;
String value = null;
StringBuilder sb = new StringBuilder();
try {
w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));
for (int i = 1; i <= 380; i++) {
key = "test_batch_" + i;
value = "v_" + i + "注冊即送水電費ServiceTest"; // 這是key對應的value
sb.append(this.getString(key, value));
if (i % 10 == 0) {
w.write(sb.toString());
w.flush();
sb.delete(0, sb.length());
System.out.println("Current write: " + i);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
w.flush();
w.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2.執行java代碼后,會在d:\\temp目錄下生成一個文本文件,將這個文件上傳到要執行的機器上。
3.再通過終端控制臺執行以下命令將文件內容批量導入即可。
cat input/redis_input.txt | bin/redis-cli -p 6370 -a yourpasswd –pipe