测试环境:Hadoop-2.7.3集群,HBase-1.3.0,Idea2018(Linux版)
这里是对已经存在的表t1进行put与get操作。
代码:
package com.test;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import java.io.IOException;
/**
* @Author zhang
* @Date 18-6-5 下午1:54
*/
public class HbaseDemo {
public static void main(String[] args) throws IOException {
//put();
String val=get();
System.out.println(val);
}
public static void put() throws IOException {
//创建conf对象
Configuration configuration=HBaseConfiguration.create();
//创建连接
Connection connection= ConnectionFactory.createConnection(configuration);
//获取表t1
TableName tname=TableName.valueOf("ns1:t1");
//获取Table
Table table=connection.getTable(tname);
//通过bytes工具创建字节数组
byte[] rowid=Bytes.toBytes("row1");
//创建put对象
Put put=new Put(rowid);
//列族
byte[] f1=Bytes.toBytes("f1");
//列
byte[] col=Bytes.toBytes("name");
//值
byte[] val=Bytes.toBytes("李四");
//添加列
put.addColumn(f1,col,val);
//执行添加任务
table.put(put);
}
public static String get() throws IOException {
//创建conf对象
Configuration configuration=HBaseConfiguration.create();
//创建连接
Connection connection= ConnectionFactory.createConnection(configuration);
//获取表t1
TableName tname=TableName.valueOf("ns1:t1");
//获取Table
Table table=connection.getTable(tname);
//通过bytes工具创建字节数组
byte[] rowid=Bytes.toBytes("row1");
//创建get对象
Get get=new Get(rowid);
Result r=table.get(get);
byte[] bytes=r.getValue(Bytes.toBytes("f1"),Bytes.toBytes("name"));
return Bytes.toString(bytes);
}
}
同时将hbase-site.xml放到resources资源文件夹中。
整个工程截图:
源代码:
点此下载源代码:hbase-put-get.zip。
解压过后,有两个文件夹,只需要将root文件夹中的pom.xml文件以Maven工程的方式导入。