在使用 MyBatis 和 Spring Boot 实现多数据源的基础上,我们可以通过以下步骤实现百万级数据插入到 Hive 中:

  1. 配置 Hive 数据源

在 'application.yaml' 中添加 Hive 数据源的配置,示例如下:

spring:
  datasource:
    hive:
      url: jdbc:hive2://localhost:10000/default
      username: hive
      password:
      driver-class-name: org.apache.hive.jdbc.HiveDriver
  1. 创建 Hive 表

使用 Hive 的 SQL 语句创建表,示例如下:

CREATE TABLE IF NOT EXISTS test(
  id int,
  name string
) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',';
  1. 编写 Mapper

在 Mapper 中编写插入数据的 SQL 语句,示例如下:

<insert id="insertBatch" parameterType="java.util.List">
  INSERT INTO test(id, name) VALUES
  <foreach collection="list" item="item" separator=",">
    (#{item.id}, #{item.name})
  </foreach>
</insert>
  1. 编写 Service

在 Service 中使用 'BatchExecutor' 来实现批量插入、多线程、异步的方式实现百万级数据插入 Hive 中,示例如下:

@Service
public class TestService {
  
  @Autowired
  private TestMapper testMapper;
  
  @Autowired
  @Qualifier("hiveDataSource")
  private DataSource hiveDataSource;
  
  public void insertBatch(List<Test> list) {
    int batchSize = 1000; // 每批次插入的数据量
    int threads = 5; // 并发线程数
    
    BatchExecutor executor = new BatchExecutor(hiveDataSource, batchSize);
    executor.execute(threads, list, (dataList) -> {
      testMapper.insertBatch(dataList);
    });
  }
  
}
  1. 调用 Service

在 Controller 中调用 Service 的插入方法,示例如下:

@RestController
public class TestController {
  
  @Autowired
  private TestService testService;
  
  @PostMapping("/insert")
  public String insert() {
    List<Test> list = new ArrayList<>();
    for (int i = 0; i < 1000000; i++) {
      Test test = new Test();
      test.setId(i);
      test.setName("test" + i);
      list.add(test);
    }
    testService.insertBatch(list);
    return "插入成功";
  }
  
}

以上就是使用 MyBatis + Spring Boot,在 application.yaml 中配置多数据源,在 service 中通过 BatchExecutor 来实现批量插入、多线程、异步的方式实现百万级数据插入 Hive 中的例子。

MyBatis + Spring Boot 多数据源配置 & 批量插入 Hive 实现百万级数据导入

原文地址: https://www.cveoy.top/t/topic/od6z 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录