公司的项目有用到hbase数据库,而我正好负责hbase客户端的接口代码编写工作;实际就是为hbase中的各个表,提供增,删,改,查的功能。
前段时间,同事对接口进行测试时,跟我反馈:在使用visualVM在查看线程运行状态时,发现hbase客户端的线程很多,具体干什么不清楚,但其中很多线程处于等待状态。起初,没时间就没在意。这段时间,功能差不多了,就也用visualvm来查看线程状态。
一,使用visualvm来查看线程状态
从图片可以看到,有256个名称为“hconnection-0x14ba9a2-shared-pool12-tX”的线程;其中很多线程是处于等待状态,只有位为数不多的线程在执行客户端对hbase数据库的操作。这里应该是可以进行优化的。
先说一下,我们项目大概是如何使用hbase客户端的。代码类似如下:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
从代码中,可以看到并没有涉及到以上的线程数配置。只好从源代码上,查看有没有相关的配置。
关键的代码在类HConnectionImplementation:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
从以上代码可以看到,在创建一个线程池时,用到了三个关键配置项,分别是:
1.hbase.hconnection.threads.max 线程池维护线程的最大数量
2.hbase.hconnection.threads.core 线程池维护线程的最少数量
3.hbase.hconnection.threads.keepalivetime 线程池维护线程所允许的空闲时间
因此,我们就可以按照需要来配置了。修改后的代码如下:
“`
String tableName = “TableName”;
Configuration c = new Configuration();
Configuration hbaseConfiguration = HBaseConfiguration.create(c);
//在这里,我们重新hbase客户端的线程池变量
hbaseConfiguration.setInt(“hbase.hconnection.threads.max”, 512);
//最大数量改为512
hbaseConfiguration.setInt(“hbase.hconnection.threads.core”, 32);
//最少数量改为32
hbaseConfiguration.setLong(“hbase.hconnection.threads.keepalivetime”, 300);
//空闲时间改为300秒
hbaseConnection = HConnectionManager.createConnection(hbaseConfiguration);
HTableInterface table = hbaseConnection.getTable(tableName);
//do something here
table.close();
`前面两个
通过调节以上参数后,再次运行测试用例,结果如下:
可以看,确实只有32个线程在运行了。