SpringBoot-HBase,
演示的是阿里云的HBase
一.POM
<dependency>
<groupId>com.aliyun.hbase</groupId>
<artifactId>alihbase-client</artifactId>
<version>1.1.1</version>
</dependency>
二.
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Table;
public class HandlerHBase {
private static final String TABLE_NAME = "表名随便写";
private static final String ZK_ADDRESS = "地址1,地址2";
public static void main(String[] args) throws IOException {
createData("userId-1".getBytes(), "routeId-1".getBytes(), "drivingSpeed".getBytes(), "500km/h".getBytes());
System.out.println("=====================插入完毕==============");
System.out.println(getData("userId-1".getBytes(), "routeId-1".getBytes(), "drivingSpeed".getBytes()));
}
public static void createData(byte[] rowKey, byte[] family, byte[] colum, byte[] value) throws IOException {
Configuration config = HBaseConfiguration.create();
config.set(HConstants.ZOOKEEPER_QUORUM, ZK_ADDRESS);
TableName tn = TableName.valueOf(TABLE_NAME);
try (Connection connection = ConnectionFactory.createConnection(config);
Table table = connection.getTable(tn);) {
HTableDescriptor tableDescriptor = new HTableDescriptor(tn);
tableDescriptor.addFamily(new HColumnDescriptor(family));
Admin admin = connection.getAdmin();
if (!admin.tableExists(tn)) {
admin.createTable(tableDescriptor);
}
Put put = new Put(rowKey);
put.addColumn(family, colum, value);
table.put(put);
}
}
public static String getData(byte[] rowKey, byte[] family, byte[] colum) throws IOException {
Configuration config = HBaseConfiguration.create();
config.set(HConstants.ZOOKEEPER_QUORUM, ZK_ADDRESS);
TableName tn = TableName.valueOf(TABLE_NAME);
try (Connection connection = ConnectionFactory.createConnection(config);
Table table = connection.getTable(tn);) {
HTableDescriptor tableDescriptor = new HTableDescriptor(tn);
tableDescriptor.addFamily(new HColumnDescriptor(family));
Admin admin = connection.getAdmin();
if (!admin.tableExists(tn)) {
admin.createTable(tableDescriptor);
}
Get get = new Get(rowKey);
Result r = table.get(get);
byte[] value = r.getValue(family, colum);
return new String(value);
}
}
}
本站文章为和通数据库网友分享或者投稿,欢迎任何形式的转载,但请务必注明出处.
同时文章内容如有侵犯了您的权益,请联系QQ:970679559,我们会在尽快处理。