Doris数据同步:stream load Java工具类实现

导入原理自己百度吧,工具类需要引入一个依赖

<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>${httpcomponents.version}</version>
        </dependency>

工具类:

1.导入csv文件,文件格式如下:

1,2,,3,4

1,2,3,4,5

public class DorisStreamLoader {
    /**
     * 用户名
     */
    private final String user ;
    /**
     * 密码
     */
    private final String password;

    /**
     * doris stream load url
     */
    private final String loadUrl ;

    /**
     *
     * @param host FE ip地址
     * @param port FE 端口
     * @param database 数据库名
     * @param table 表名
     * @param user 用户名
     * @param password 密码
     */
    public DorisStreamLoader(String host, int port, String database, String table, String user, String password) {
        this.user = user;
        this.password = password;
        this.loadUrl = String.format("http://%s:%s/api/%s/%s/_stream_load", host, port, database, table);
    }

    /**
     * 构建HTTP客户端
     */
    private final static HttpClientBuilder httpClientBuilder = HttpClients
            .custom()
            .setRedirectStrategy(new DefaultRedirectStrategy() {
                @Override
                protected boolean isRedirectable(String method) {
                    // If the connection target is FE, you need to deal with 307 redirect。
                    return true;
                }
            });

    /**
     * 文件数据导入
     * @param inputStream 要导入的文件流
     * @throws Exception Exception
     */
    public void load(InputStream inputStream,String label ) throws Exception {
        try (CloseableHttpClient client = httpClientBuilder.build()) {
            HttpPut put = new HttpPut(loadUrl);
            put.removeHeaders(HttpHeaders.CONTENT_LENGTH);
            put.removeHeaders(HttpHeaders.TRANSFER_ENCODING);
            put.setHeader(HttpHeaders.EXPECT, "100-continue");
            put.setHeader(HttpHeaders.AUTHORIZATION, basicAuthHeader(user, password));

            // You can set stream load related properties in the Header, here we set label and column_separator.
            put.setHeader("label", label);
            put.setHeader("column_separator", ",");
            // Set up the import file. Here you can also use StringEntity to transfer arbitrary data.
            InputStreamEntity entity = new InputStreamEntity(inputStream);
            put.setEntity(entity);
            log.info("开始同步doris,url={},label={}",loadUrl,label);
            try (CloseableHttpResponse response = client.execute(put)) {
                String loadResult = "";
                if (response.getEntity() != null) {
                    loadResult = EntityUtils.toString(response.getEntity());
                }

                final int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode != 200) {
                    throw new IOException(String.format("Stream load failed. status: %s load result: %s", statusCode, loadResult));
                }
                log.info("Get load result: {}" , loadResult);
            }
        }
    }

    /**
     * JSON格式的数据导入
     * @param jsonData String
     * @throws Exception Exception
     */
    public void loadJson(String jsonData) throws Exception {
        try (CloseableHttpClient client = httpClientBuilder.build()) {
            HttpPut put = new HttpPut(loadUrl);
            put.removeHeaders(HttpHeaders.CONTENT_LENGTH);
            put.removeHeaders(HttpHeaders.TRANSFER_ENCODING);
            put.setHeader(HttpHeaders.EXPECT, "100-continue");
            put.setHeader(HttpHeaders.AUTHORIZATION, basicAuthHeader(user, password));

            // You can set stream load related properties in the Header, here we set label and column_separator.
            put.setHeader("label", UUID.randomUUID().toString());
            put.setHeader("column_separator", ",");
            put.setHeader("format", "json");

            // Set up the import file. Here you can also use StringEntity to transfer arbitrary data.
            StringEntity entity = new StringEntity(jsonData);
            put.setEntity(entity);

            try (CloseableHttpResponse response = client.execute(put)) {
                String loadResult = "";
                if (response.getEntity() != null) {
                    loadResult = EntityUtils.toString(response.getEntity());
                }

                final int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode != 200) {
                    throw new IOException(String.format("Stream load failed. status: %s load result: %s", statusCode, loadResult));
                }
                log.info("Get load result: {}" , loadResult);
            }
        }
    }

    /**
     * 封装认证信息
     * @param username String
     * @param password String
     * @return String
     */
    private String basicAuthHeader(String username, String password) {
        final String tobeEncode = username + ":" + password;
        byte[] encoded = Base64.encodeBase64(tobeEncode.getBytes(StandardCharsets.UTF_8));
        return "Basic " + new String(encoded);
    }


    public static void main(String[] args) throws Exception {
        DorisStreamLoader streamLoader = new DorisStreamLoader("zzxczxc", 8888, "database", "table", "user", "password");

    }
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Doris是一种分布式OLAP数据库,是由Apache Doris社区开发的开源项目。它基于列式存储和MPP架构,能够快速处理海量数据,并支持实时查询和高并发访问。Java作为一种流行的编程语言,可以通过Doris提供的JDBC驱动程序来进行数据查询和操作。用户可以在Java程序中使用JDBC API来连接Doris数据库,执行SQL语句并获取结果集。以下是Java查询Doris的示例代码: ```java import java.sql.*; public class DorisQuery { public static void main(String[] args) { // JDBC连接参数 String url = "jdbc:mysql://<doris-host>:<doris-port>/<database-name>"; String user = "<doris-username>"; String password = "<doris-password>"; // SQL查询语句 String sql = "SELECT * FROM <table-name> LIMIT 10"; try { // 加载JDBC驱动程序 Class.forName("com.mysql.jdbc.Driver"); // 建立数据库连接 Connection conn = DriverManager.getConnection(url, user, password); // 创建Statement对象 Statement stmt = conn.createStatement(); // 执行SQL查询语句 ResultSet rs = stmt.executeQuery(sql); // 处理查询结果集 while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); double price = rs.getDouble("price"); System.out.println("ID: " + id + ", Name: " + name + ", Price: " + price); } // 关闭资源 rs.close(); stmt.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` 在上面的示例中,需要替换以下参数: - `<doris-host>`:Doris数据库的主机名或IP地址。 - `<doris-port>`:Doris数据库的端口号,默认为9080。 - `<database-name>`:Doris数据库数据库名称。 - `<doris-username>`:连接Doris数据库的用户名。 - `<doris-password>`:连接Doris数据库的密码。 - `<table-name>`:要查询的表名。 以上是Java查询Doris的简单示例,用户可以根据实际需求进行修改和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值