zoukankan      html  css  js  c++  java
  • Redis批量导入数据的方法

    有时候,我们需要给redis库中插入大量的数据,如做性能测试前的准备数据。遇到这种情况时,偶尔可能也会懵逼一下,这里就给大家介绍一个批量导入数据的方法。

    先准备一个redis protocol的文件(redis protocol可以参考这里:https://redis.io/topics/protocol),这里是用java程序来输出的,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(" ");
            sb.append("$3").append(" ");
            sb.append("SET ");

            sb.append("$").append(key.getBytes().length).append(" ");
            sb.append(key).append(" ");

            sb.append("$").append(value.getBytes().length).append(" ");
            sb.append(value).append(" ");

            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();
                }

            }
        }

    }

    执行以上代码,就会在d:\temp目录下生成一个文本文件,格式如下:

     

    以上就是redis protocol格式的文件了,请上传到要执行的机器上。然后使用以下命令来执行它:

    cat input/redis_input.txt | bin/redis-cli -p 6370 -a yourpasswd –pipe

    如果执行成功的话,你就可以看到如下信息了:

     

    从以上输出可以看出,380条数全部插入到redis服务器上啦。

    更详细的信息,可以参考:https://redis.io/topics/mass-insert

  • 相关阅读:
    Vue.config.productionTip = false;
    Node学习笔记
    Redux学习笔记------容器组件与展示组件分离
    Redux学习笔记------数据流
    Redux学习笔记------store
    Redux学习笔记------reducer
    Redux学习笔记------action
    Redux学习笔记------基础介绍
    过滤emoji表情
    textarea自适应高度
  • 原文地址:https://www.cnblogs.com/lightarc/p/redisbatch.html
Copyright © 2011-2022 走看看