打开intellj
创建一个hbase Module模块
右击Add_FrameWork_Support添加Maven依赖
添加hbase的client包依赖,client的版本需要与实际的hbase版本一致。之后IDEA将会自动下载依赖包,可以在External Libraries中查看下载的依赖包。
<dependencies> <dependency> <groupId>org.apache.hbase</groupId> <artifactId>hbase-client</artifactId> <version>1.2.1</version> </dependency> </dependencies>
等依赖下载好之后,在src/main/resources目录下新建一个hbase-site.xml文件,把hbase集群的配置文件内容粘贴过去。
在src/test/java目录下新建一个java文件:
package com.yzd.hbase; 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 org.junit.Test; import java.io.IOException; public class test { @Test public void put() throws Exception{ // 创建conf对象 Configuration configuration = HBaseConfiguration.create(); // 通过连接工厂创建连接对象 Connection conn = ConnectionFactory.createConnection(configuration); // 通过连接查询table对象 TableName tname = TableName.valueOf("ns1:t1"); // 获得表 Table table = conn.getTable(tname); // 通过bytes类创建字节数组 byte[] rowid = Bytes.toBytes("row3"); // 创建put对象 Put put = new Put(rowid); put.addColumn(Bytes.toBytes("f1"),Bytes.toBytes("id"), Bytes.toBytes(120)); put.addColumn(Bytes.toBytes("f1"),Bytes.toBytes("name"),Bytes.toBytes("lucy")); put.addColumn(Bytes.toBytes("f1"),Bytes.toBytes("age"),Bytes.toBytes(20)); put.addColumn(Bytes.toBytes("f2"),Bytes.toBytes("hobby"),Bytes.toBytes("reading_books")); put.addColumn(Bytes.toBytes("f2"),Bytes.toBytes("addr"),Bytes.toBytes("Beijing")); table.put(put); System.out.println("插入成功"); } /* 查询数据 */ @Test public void testGet() throws IOException { // 创建conf对象 Configuration conf = HBaseConfiguration.create(); // 通过连接工厂创建连接对象 Connection conn = ConnectionFactory.createConnection(conf); // 创建TableName对象 TableName tname = TableName.valueOf("ns1:t1"); // 传入TableName对象获取表 Table table = conn.getTable(tname); // new一个get对象,传入rowkey Get get = new Get(Bytes.toBytes("row3")); // 获取数据,传入get对象 Result result = table.get(get); byte[] id_value = result.getValue(Bytes.toBytes("f1"),Bytes.toBytes("id")); System.out.println(Bytes.toInt(id_value)); } }
然后运行testGet方法,输出如下信息:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。