添加jar包:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-hadoop</artifactId>
<version>2.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-client</artifactId>
<version>1.2.3</version>
<exclusions>
<exclusion>
<artifactId>jdk.tools</artifactId>
<groupId>*</groupId>
</exclusion>
<exclusion>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
</exclusion>
<exclusion>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
</exclusion>
</exclusions>
</dependency>
在spring配置文件中添加如下配置:
<
<hdp:configuration />
<hdp:hbase-configuration id="hbaseConfiguration" zk-quorum="xxx.xxx.xxx.xx:2181" zk-port="2181">
hbase.rpc.timeout=1000
hbase.client.operation.timeout=2000
hbase.client.retries.number=3
zookeeper.recovery.retry=10
zookeeper.recovery.retry.intervalmill=500
</hdp:hbase-configuration>
<!-- 配置HbaseTemplate -->
<bean id="htemplate" class="org.springframework.data.hadoop.hbase.HbaseTemplate">
<property name="configuration" ref="hbaseConfiguration"/>
</bean>
在java中实现代码:
@Autowired
private HbaseTemplate htemplate;
@Value("#{${server.db.hbase.trace.tablename}}")
private String tableName;
@Value("#{${server.db.hbase.trace.familyname}}")
private String familyName;
@Value("#{${server.db.hbase.trace.qualifier}}")
private String qualifier;
MessageTree msg = htemplate.get(tableName, rowKey, familyName, qualifier, new RowMapper<MessageTree>() {
@Override
public MessageTree mapRow(Result result, int rowNum) throws Exception {
Cell cell = result.getColumnLatestCell(familyName.getBytes(CHARSET), qualifier.getBytes(CHARSET));
// 如果获取不到内存直接返回
if (null == cell) {
logger.error("hbase can not find rowkey=" + rowKey);
return null;
}
byte[] bytes = CellUtil.cloneValue(cell);
ByteBuf buf = null;
MessageTree msg = null;
try {
buf = Unpooled.wrappedBuffer(bytes);
buf.markReaderIndex();
buf.readInt();
msg = codec.decode(buf);
msg.setBytes(bytes);
} catch (Exception e) {
logger.error("decoder data occured error!", e);
} finally {
if (buf != null) {
buf.release();
}
codec.reset();
}
return msg;
}
});
//main方法直接连接测试
public static void main(String[] args) throws MasterNotRunningException, ZooKeeperConnectionException, IOException {
Configuration cf=HBaseConfiguration.create();
cf.set(HConstants.ZOOKEEPER_QUORUM,"10.20.15.197,10.20.15.198,10.20.15.200");
cf.set(HConstants.ZOOKEEPER_ZNODE_PARENT, "/hbase1");
Connection connection = ConnectionFactory.createConnection(cf);
TableName name = TableName.valueOf("blog2");
Table table = connection.getTable(name);
Get get = new Get(Bytes.toBytes("rowkey1"));
Result result = table.get(get);
String conten =Bytes.toString(result.getValue(Bytes.toBytes("article"), Bytes.toBytes("conten")));
table.close();
connection.close();
logger.info(">>>>blog2查询数据为:" + conten);
}
}