资讯专栏INFORMATION COLUMN

Java call mongodump

ethernet / 2550人阅读

Note: the version just supports macOS and linux.
100% testing coverage, please feel free to use.

Usage
new MongoDump.Builder()
                .runtime(mockRuntime)
                .uri("mongodb://127.0.0.1:27017/gt_ut")
                .archive("dbname.archive")
                .commandPath("/usr/local/bin/mongodump")
                .build()
                .execute();
Source Code MongoDump.java
package learningops.mongo;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * @author learningops
 * @date 22/03/2018
 */
public class MongoDump {
    private static final Logger LOG = LoggerFactory.getLogger(MongoDump.class);

    private String uri;
    private String archive;
    private String commandPath;
    private Runtime runtime;

    public static class Builder {

        private String uri;
        private String archive;
        private String commandPath;
        private Runtime runtime;


        public Builder archive(String archive) {
            this.archive = archive;
            return this;
        }

        public Builder runtime(Runtime runtime) {
            this.runtime = runtime;
            return this;
        }

        public Builder commandPath(String commandPath) {
            this.commandPath = commandPath;
            return this;
        }

        public Builder uri(String uri) {
            this.uri = uri;
            return this;
        }

        public MongoDump build() {
            MongoDump result = new MongoDump();
            result.uri = checkNotNull(uri, "uri was null.");
            result.commandPath = checkNotNull(commandPath, "commandPath was null.");
            result.archive = checkNotNull(archive, "archive was null.");
            Runtime rt = runtime;
            if (rt == null) {
                rt = Runtime.getRuntime();
            }
            result.runtime = rt;
            return result;
        }
    }

    public String execute() {
        try {
            String command = String.format("%s --archive=%s --uri=%s", commandPath, archive, uri);
            LOG.debug("command: {}", command);
            Process runtimeProcess = runtime.exec(new String[]{"/bin/sh", "-c", command});
            int exitValue = runtimeProcess.waitFor();
            if (exitValue != 0) {
                InputStream error = runtimeProcess.getErrorStream();
                String errorMessage = IOUtils.toString(error, "UTF-8");
                throw new MongoDumpException(errorMessage);
            }
            InputStream message = runtimeProcess.getInputStream();
            return IOUtils.toString(message, "UTF-8");
        } catch (MongoDumpException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
MongoDumpException.java
package learningops.mongo;

/**
 * @author learningops
 * @date 22/03/2018
 */
public class MongoDumpException extends RuntimeException {
    public MongoDumpException(String message) {
        super(message);
    }
}
Unit Testing
package learningops.mongo;

import org.apache.commons.io.IOUtils;
import org.testng.annotations.Test;

import java.io.InputStream;

import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertEquals;

/**
 * @author learningops
 * @date 22/03/2018
 */
public class MongoDumpTest {

    @Test
    public void test() throws Exception {
        Runtime mockRuntime = mock(Runtime.class);
        Process mockProcess = mock(Process.class);
        when(mockProcess.getInputStream()).thenReturn(IOUtils.toInputStream("success message", "UTF-8"));
        when(mockRuntime.exec(new String[]{anyString()})).thenReturn(mockProcess);
        when(mockProcess.waitFor()).thenReturn(0);
        String result = new MongoDump.Builder()
                .runtime(mockRuntime)
                .uri("mongodb://127.0.0.1:27017/gt_ut")
                .archive("dbname.archive")
                .commandPath("/usr/local/bin/mongodump")
                .build()
                .execute();
        assertEquals(result, "success message");
    }

    @Test(expectedExceptions = {MongoDumpException.class}, expectedExceptionsMessageRegExp = "error message")
    public void unknownTermination() throws Exception {
        Runtime mockRuntime = mock(Runtime.class);
        Process mockProcess = mock(Process.class);
        when(mockRuntime.exec(new String[]{anyString()})).thenReturn(mockProcess);
        when(mockProcess.waitFor()).thenReturn(1);
        InputStream errorStream = IOUtils.toInputStream("error message", "UTF-8");
        when(mockProcess.getErrorStream()).thenReturn(errorStream);
        new MongoDump.Builder()
                .runtime(mockRuntime)
                .uri("mongodb://127.0.0.1:27017/dbname")
                .archive("dbname.archive")
                .commandPath("/usr/local/bin/mongodump")
                .build()
                .execute();
    }

    @Test(expectedExceptions = {RuntimeException.class})
    public void unknownException() throws Exception {
        Runtime mockRuntime = mock(Runtime.class);
        Process mockProcess = mock(Process.class);
        when(mockRuntime.exec(new String[]{anyString()})).thenReturn(mockProcess);
        InputStream errorStream = IOUtils.toInputStream("error message", "UTF-8");
        when(mockProcess.getErrorStream()).thenReturn(errorStream);
        new MongoDump.Builder()
                .runtime(mockRuntime)
                .uri("mongodb://127.0.0.1:27017/dbname")
                .archive("dbname.archive")
                .commandPath("/usr/local/bin/mongodump")
                .build()
                .execute();
    }

    @Test
    public void buildWithDefaultRuntime() {
        new MongoDump.Builder()
                .uri("mongodb://127.0.0.1:27017/dbname")
                .archive("dbname.archive")
                .commandPath("/usr/local/bin/mongodump")
                .build();
    }

}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/76355.html

相关文章

  • Java call mongodump

    Note: the version just supports macOS and linux. 100% testing coverage, please feel free to use. Usage new MongoDump.Builder() .runtime(mockRuntime) .uri(mongodb://127...

    Fourierr 评论0 收藏0
  • Simple Automated Backups for MongoDB Replica Sets

    There are a bunch of different methods you can use to back up your MongoDB data, but if you want to avoid downtime and/or potential performance degradation, the most common advice seems to be that you...

    iamyoung001 评论0 收藏0
  • Centos Mongodb离线安装&配置远程连接&数据迁移

    摘要:就是说,恢复后,备份后添加修改的数据都会被删除,慎用实例 Centos Mongodb离线安装&配置远程连接&数据迁移 笔者的之前的centos服务器满了,这次准备迁移数据.目的是,扩容更大的磁盘分区,避免一次又一次的挂载新的磁盘.由于机器无法联网本次为离线安装 下载Mongodb网址为https://www.mongodb.com/dr/fastdl.mongodb.org/lin...

    韩冰 评论0 收藏0
  • MongoDB备份与恢复

    摘要:一的导入与导出导出工具概念中的工具可以把一个导出成格式或格式的文件。可以通过参数指定导出的数据项,也可以根据指定的条件导出数据。恢复工具概念是从备份中恢复数据的工具,它主要用来获取的输出结果,并将备份的数据插入到运行的中。 一、Mongodb的导入与导出 1.1、导出工具:mongoexport 概念: mongoDB中的mongoexport工具可以把一个collection导出成J...

    2450184176 评论0 收藏0
  • 【mongoDB运维篇②】备份与恢复(导入与导出)

    摘要:导入导出可以操作的是本地的服务器也可以是远程的服务器所以都有如下通用选项主机端口用户名密码导出库名表名列名查询条件导出的文件名导出格式便于和传统数据库交换数据导出库下面的表从哪里导出导出的文档数导出库下 导入/导出可以操作的是本地的mongodb服务器,也可以是远程的服务器所以,都有如下通用选项: -h host 主机 --port port 端口 -u username 用...

    lakeside 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<