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