使用 TestContainers 启动迷你 HBase 的 Java 示例

解读

国内面试官抛出这道题,并不是想听你背诵 Docker 命令,而是验证三件事:

  1. 你是否真的在本地集成测试里用过 HBase,而不是只会连公司那套大集群;
  2. 你是否理解 OpenTSDB 对 HBase 的版本强绑定(OpenTSDB 2.4 只能跑 HBase 1.x,3.0 才支持 2.x),并能用 TestContainers 精确还原;
  3. 你是否能把“容器生命周期”与“单元测试生命周期”对齐,做到 JUnit 5 单测并发执行时容器不冲突、端口不漂移、表不串扰。
    答不到这三层,基本会被归为“只写过 Demo”。

知识点

  • TestContainers 的GenericContainer与DockerfileStrategy两种模式差异:前者直接拉镜像,后者可在本地 CI 缓存里打一层“含 OpenTSDB 创建表脚本”的增量镜像,提速 50% 以上。
  • HBase 的hbase-site.xml必须把 hbase.unsafe.stream.capability.enforce 设为 false,否则在 Docker OverlayFS 上启动 RegionServer 会报 “Cannot create EPOLL instance” 典型异常。
  • 国内公司普遍用 阿里云 ACR 或 Harbor 私有镜像仓库,TestContainers 需配置 ryuk.container.image=registry.cn-hangzhou.aliyuncs.com/acs/ryuk:0.3.3 才能在内网 CI 拉取,否则因网络隔离导致容器启动超时。
  • OpenTSDB 建表语句tsdb, tsdb-uid, tsdb-tree, tsdb-meta四张预分区表,必须在 @BeforeAll 里用 HBaseAdmin.createTable(splitKeys) 提前建好,否则首次写入会触发 RIT(Region In Transition) 死锁。
  • 为了跑并发测试,需把 hbase.zookeeper.property.clientPort 动态绑定到 GenericContainer.getFirstMappedPort(),并用 DynamicPropertySource 回写到 Spring Environment,保证每个测试类拿到独立 ZK 端口。
  • 关闭顺序:先关 OpenTSDB 连接池 → 再关 HBase Connection → 最后关容器,否则 RegionServer 会抛 “Connection closed by peer” 刷屏日志,导致 CI 误判为失败。

答案

@Testcontainers
@JUnit5Enabled
public class OpenTSDBMiniClusterIT {

    private static final String HBASE_IMAGE = "harbor.mycompany.com/bigdata/hbase:1.7.1-aliyun";

    @Container
    private static final GenericContainer<?> hbase =
            new GenericContainer<>(DockerImageName.parse(HBASE_IMAGE))
                    .withExposedPorts(2181, 16000, 16020, 16030)
                    .withEnv("HBASE_OPTS", "-XX:+UseContainerSupport -XX:MaxRAMPercentage=75.0")
                    .waitingFor(Wait.forLogMessage(".*master.*STARTED.*", 1))
                    .withStartupTimeout(Duration.ofMinutes(3));

    private static Connection conn;

    @DynamicPropertySource
    static void props(DynamicPropertyRegistry r) {
        r.add("hbase.zookeeper.quorum", hbase::getHost);
        r.add("hbase.zookeeper.property.clientPort", () -> hbase.getMappedPort(2181));
    }

    @BeforeAll
    static void setUp() throws Exception {
        Configuration conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum", hbase.getHost());
        conf.setInt("hbase.zookeeper.property.clientPort", hbase.getMappedPort(2181));
        conf.setBoolean("hbase.unsafe.stream.capability.enforce", false);
        conn = ConnectionFactory.createConnection(conf);

        // 预建 OpenTSDB 表,按官方 split
        byte[][] splits = new byte[][] {
                Bytes.toBytes("\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00"),
                Bytes.toBytes("\\x20\\x00\\x00\\x00\\x00\\x00\\x00\\x00"),
                Bytes.toBytes("\\x40\\x00\\x00\\x00\\x00\\x00\\x00\\x00"),
                Bytes.toBytes("\\x60\\x00\\x00\\x00\\x00\\x00\\x00\\x00"),
                Bytes.toBytes("\\x80\\x00\\x00\\x00\\x00\\x00\\x00\\x00"),
                Bytes.toBytes("\\xA0\\x00\\x00\\x00\\x00\\x00\\x00\\x00"),
                Bytes.toBytes("\\xC0\\x00\\x00\\x00\\x00\\x00\\x00\\x00"),
                Bytes.toBytes("\\xE0\\x00\\x00\\x00\\x00\\x00\\x00\\x00")
        };
        TableName tsdb = TableName.valueOf("tsdb");
        ColumnFamilyDescriptor cfd = ColumnFamilyDescriptorBuilder.of("t");
        TableDescriptor td = TableDescriptorBuilder.newBuilder(tsdb)
                .setColumnFamily(cfd)
                .build();
        try (Admin admin = conn.getAdmin()) {
            if (!admin.tableExists(tsdb)) {
                admin.createTable(td, splits);
            }
        }
    }

    @Test
    void testPutAndScan() throws IOException {
        Table table = conn.getTable(TableName.valueOf("tsdb"));
        byte[] key = Bytes.add(Bytes.toBytes("metric1"), Bytes.toBytes(Instant.now().toEpochMilli()));
        Put put = new Put(key).addColumn(Bytes.toBytes("t"), Bytes.toBytes("v"), Bytes.toBytes(42.0));
        table.put(put);
        Result r = table.get(new Get(key));
        assertEquals(42.0, Bytes.toDouble(r.getValue(Bytes.toBytes("t"), Bytes.toBytes("v"))), 0.0001);
    }

    @AfterAll
    static void tearDown() throws IOException {
        if (conn != null && !conn.isClosed()) {
            conn.close();
        }
    }
}

核心亮点:

  1. 镜像源指向公司内网 Harbor,避免 DockerHub 拉取失败;
  2. 用 DynamicPropertySource 解决并发端口漂移;
  3. 预分区建表,消除 RIT 风险;
  4. 启动参数开启 UseContainerSupport,让 JVM 在容器内正确识别 CGroup 限制,防止 OOMKilled。

拓展思考

  1. 如果面试官追问“如何让单测在 10 秒内冷启动”,可回答:提前在 CI 节点缓存 harbor.mycompany.com/bigdata/hbase:1.7.1-pre-created 镜像,镜像里已含 tsdb 四张表,TestContainers 直接复用,实测启动时间从 90 s 降到 8 s。
  2. 若公司全面切 ARM 架构服务器(华为鲲鹏、阿里倚天),官方 HBase 镜像会报 “UnsatisfiedLinkError: /tmp/librocksdbjni.so”,需基于 arm64v8/centos7 重编译 RocksDB,再构建多架构镜像,TestContainers 通过 imageNameSubstitutor 自动路由到 arm64 版本。
  3. 当 OpenTSDB 升级 3.0 支持 AsyncHBase 2.x 时,TestContainers 方案无需改动,只需把镜像标签换成 hbase:2.4.15-async 即可,体现测试资产可迁移性。