导航:首页 > 编程语言 > hbasejava客户端编程

hbasejava客户端编程

发布时间:2022-12-21 15:53:36

⑴ 如何使用java API操作Hbase

写了个Hbase新的api的增删改查的工具类,以供参考,直接拷贝代码就能用,散仙觉得基础的功能,都有了,代码如下:

package com.dhgate.hbase.test;

import java.util.ArrayList;
import java.util.List;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.filter.PageFilter;
import org.apache.hadoop.hbase.filter.PrefixFilter;
import org.apache.hadoop.hbase.util.Bytes;

/**
* 基于新的API
* Hbase0.96版本
* 写的工具类
*
* @author qindongliang
* 大数据技术交流群: 376932160
*
* **/
public class HbaseCommons {

static Configuration conf=HBaseConfiguration.create();
static String tableName="";

public static void main(String[] args)throws Exception {

//String tableName="test";
//createTable(tableName, null);

}

/**
* 批量添加数据
* @param tableName 标名字
* @param rows rowkey行健的集合
* 本方法仅作示例,其他的内容需要看自己义务改变
*
* **/
public static void insertList(String tableName,String rows[])throws Exception{
HTable table=new HTable(conf, tableName);
List<Put> list=new ArrayList<Put>();
for(String r:rows){
Put p=new Put(Bytes.toBytes(r));
//此处示例添加其他信息
//p.add(Bytes.toBytes("family"),Bytes.toBytes("column"), 1000, Bytes.toBytes("value"));
list.add(p);
}
table.put(list);//批量添加
table.close();//释放资源
}

/**
* 创建一个表
* @param tableName 表名字
* @param columnFamilys 列簇
*
* **/
public static void createTable(String tableName,String[] columnFamilys)throws Exception{
//admin 对象
HBaseAdmin admin=new HBaseAdmin(conf);
if(admin.tableExists(tableName)){
System.out.println("此表,已存在!");
}else{
//旧的写法
//HTableDescriptor tableDesc=new HTableDescriptor(tableName);
//新的api
HTableDescriptor tableDesc=new HTableDescriptor(TableName.valueOf(tableName));

for(String columnFamily:columnFamilys){
tableDesc.addFamily(new HColumnDescriptor(columnFamily));
}

admin.createTable(tableDesc);
System.out.println("建表成功!");

}
admin.close();//关闭释放资源

}

/**
* 删除一个表
* @param tableName 删除的表名
* */
public static void deleteTable(String tableName)throws Exception{
HBaseAdmin admin=new HBaseAdmin(conf);
if(admin.tableExists(tableName)){
admin.disableTable(tableName);//禁用表
admin.deleteTable(tableName);//删除表
System.out.println("删除表成功!");
}else{
System.out.println("删除的表不存在!");
}
admin.close();
}

/**
* 插入一条数据
* @param tableName 表明
* @param columnFamily 列簇
* @param column 列
* @param value 值
*
* ***/
public static void insertOneRow(String tableName,String rowkey,String columnFamily,String column,String value)throws Exception{

HTable table=new HTable(conf, tableName);
Put put=new Put(Bytes.toBytes(rowkey));
put.add(Bytes.toBytes(columnFamily), Bytes.toBytes(column), Bytes.toBytes(value));
table.put(put);//放入表
table.close();//释放资源

}

/**
* 删除一条数据
* @param tableName 表名
* @param row rowkey行键
*
* */
public static void deleteOneRow(String tableName,String row)throws Exception{

HTable table=new HTable(conf, tableName);
Delete delete=new Delete(Bytes.toBytes(row));
table.delete(delete);
table.close();
}

/**
* 删除多条数据
* @param tableName 表名
* @param rows 行健集合
*
* **/
public static void deleteList(String tableName,String rows[])throws Exception{
HTable table=new HTable(conf, tableName);
List<Delete> list=new ArrayList<Delete>();
for(String row:rows){
Delete del=new Delete(Bytes.toBytes(row));
list.add(del);
}
table.delete(list);
table.close();//释放资源

}

/**
* 获取一条数据,根据rowkey
* @param tableName 表名
* @param row 行健
*
* **/
public static void getOneRow(String tableName,String row)throws Exception{
HTable table=new HTable(conf, tableName);
Get get=new Get(Bytes.toBytes(row));
Result result=table.get(get);
printRecoder(result);//打印记录
table.close();//释放资源
}

/**
* 查看某个表下的所有数据
*
* @param tableName 表名
* */
public static void showAll(String tableName)throws Exception{
HTable table=new HTable(conf, tableName);
Scan scan=new Scan();
ResultScanner rs=table.getScanner(scan);
for(Result r:rs){
printRecoder(r);//打印记录
}
table.close();//释放资源
}

/**
* 查看某个表下的所有数据
*
* @param tableName 表名
* @param rowKey 行健
* */
public static void ScanPrefixByRowKey(String tableName,String rowKey)throws Exception{
HTable table=new HTable(conf, tableName);
Scan scan=new Scan();
scan.setFilter(new PrefixFilter(Bytes.toBytes(rowKey)));
ResultScanner rs=table.getScanner(scan);
for(Result r:rs){
printRecoder(r);//打印记录
}
table.close();//释放资源
}

/**
* 查看某个表下的所有数据
*
* @param tableName 表名
* @param rowKey 行健扫描
* @param limit 限制返回数据量
* */
public static void ScanPrefixByRowKeyAndLimit(String tableName,String rowKey,long limit)throws Exception{
HTable table=new HTable(conf, tableName);
Scan scan=new Scan();
scan.setFilter(new PrefixFilter(Bytes.toBytes(rowKey)));
scan.setFilter(new PageFilter(limit));
ResultScanner rs=table.getScanner(scan);
for(Result r:rs){
printRecoder(r);//打印记录
}
table.close();//释放资源
}

/**
* 根据rowkey扫描一段范围
* @param tableName 表名
* @param startRow 开始的行健
* @param stopRow 结束的行健
* **/
public void scanByStartAndStopRow(String tableName,String startRow,String stopRow)throws Exception{
HTable table=new HTable(conf, tableName);
Scan scan=new Scan();
scan.setStartRow(Bytes.toBytes(startRow));
scan.setStopRow(Bytes.toBytes(stopRow));
ResultScanner rs=table.getScanner(scan);
for(Result r:rs){
printRecoder(r);
}
table.close();//释放资源

}
/**
* 扫描整个表里面具体的某个字段的值
* @param tableName 表名
* @param columnFalimy 列簇
* @param column 列
* **/
public static void getValueDetail(String tableName,String columnFalimy,String column)throws Exception{

HTable table=new HTable(conf, tableName);
Scan scan=new Scan();
ResultScanner rs=table.getScanner(scan);
for(Result r:rs){
System.out.println("值: " +new String(r.getValue(Bytes.toBytes(columnFalimy), Bytes.toBytes(column))));
}
table.close();//释放资源

}

/**
* 打印一条记录的详情
*
* */
public static void printRecoder(Result result)throws Exception{
for(Cell cell:result.rawCells()){
System.out.print("行健: "+new String(CellUtil.cloneRow(cell)));
System.out.print("列簇: "+new String(CellUtil.cloneFamily(cell)));
System.out.print(" 列: "+new String(CellUtil.cloneQualifier(cell)));
System.out.print(" 值: "+new String(CellUtil.cloneValue(cell)));
System.out.println("时间戳: "+cell.getTimestamp());
}
}

}

⑵ hbase java端调用

这是缺少必要的类org/apache/hadoop/thirdparty/guava/common/primitives/UnsignedBytes
你可以到jarsearch上搜索含有这个类的jar包,然后把它放到classpath下就行了

⑶ 如何使用Java API操作Hbase

java API草错hbase举例如下:
例如输出表“users”的列族名称
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.util.Bytes;

public class ExampleClient {
public static void main(String[] args) throws IOException {

Configuration conf = HBaseConfiguration.create();
conf.set("hbase.zookeeper.quorum", "master");//使用eclipse时必须添加这个,否则无法定位
conf.set("hbase.zookeeper.property.clientPort", "2181");
HBaseAdmin admin = new HBaseAdmin(conf);// 新建一个数据库管理员
HTableDescriptor tableDescriptor = admin.getTableDescriptor(Bytes.toBytes("users"));
byte[] name = tableDescriptor.getName();
System.out.println("result:");

System.out.println("table name: "+ new String(name));
HColumnDescriptor[] columnFamilies = tableDescriptor
.getColumnFamilies();
for(HColumnDescriptor d : columnFamilies){
System.out.println("column Families: "+ d.getNameAsString());
}
}
}
输出结果:
2013-09-09 15:58:51,890 WARN conf.Configuration (Configuration.java:<clinit>(195)) - DEPRECATED: hadoop-site.xml found in the classpath. Usage of hadoop-site.xml is deprecated. Instead use core-site.xml, mapred-site.xml and hdfs-site.xml to override properties of core-default.xml, mapred-default.xml and hdfs-default.xml respectively
2013-09-09 15:58:55,031 INFO zookeeper.ZooKeeper (Environment.java:logEnv(100)) - Client environment:zookeeper.version=3.4.5-1392090, built on 09/30/2012 17:52 GMT
2013-09-09 15:58:55,031 INFO zookeeper.ZooKeeper (Environment.java:logEnv(100)) - Client environment:host.name=w253245.ppp.asahi-net.or.jp
2013-09-09 15:58:55,031 INFO zookeeper.ZooKeeper (Environment.java:logEnv(100)) - Client environment:java.version=1.6.0_10-rc2
2013-09-09 15:58:55,031 INFO zookeeper.ZooKeeper (Environment.java:logEnv(100)) - Client environment:java.vendor=Sun Microsystems Inc.
2013-09-09 15:58:55,031 INFO zookeeper.ZooKeeper (Environment.java:logEnv(100)) - Client environment:java.home=C:\Java\jre6
2013-09-09 15:58:55,031 INFO zookeeper.ZooKeeper (Environment.java:logEnv(100)) - Client environment:java.class.path
2013-09-09 15:58:55,031 INFO zookeeper.ZooKeeper (Environment.java:logEnv(100)) - Client environment:java.library.path=D:\workspace\Eclipse-jee\hadoop-1.1.21\lib\native;D:\workspace\Eclipse-jee\hadoop-1.1.21\lib\native
2013-09-09 15:58:55,031 INFO zookeeper.ZooKeeper (Environment.java:logEnv(100)) - Client environment:java.io.tmpdir=C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\
2013-09-09 15:58:55,031 INFO zookeeper.ZooKeeper (Environment.java:logEnv(100)) - Client environment:java.compiler=<NA>
2013-09-09 15:58:55,031 INFO zookeeper.ZooKeeper (Environment.java:logEnv(100)) - Client environment:os.name=Windows XP
2013-09-09 15:58:55,031 INFO zookeeper.ZooKeeper (Environment.java:logEnv(100)) - Client environment:os.arch=x86
2013-09-09 15:58:55,031 INFO zookeeper.ZooKeeper (Environment.java:logEnv(100)) - Client environment:os.version=5.1
2013-09-09 15:58:55,031 INFO zookeeper.ZooKeeper (Environment.java:logEnv(100)) - Client environment:user.name=hadoop
2013-09-09 15:58:55,031 INFO zookeeper.ZooKeeper (Environment.java:logEnv(100)) - Client environment:user.home=C:\Documents and Settings\Administrator
2013-09-09 15:58:55,031 INFO zookeeper.ZooKeeper (Environment.java:logEnv(100)) - Client environment:user.dir=D:\workspace\Eclipse-jee\Hadoop_APPs_U_tht
2013-09-09 15:58:55,031 INFO zookeeper.ZooKeeper (ZooKeeper.java:<init>(438)) - Initiating client connection, connectString=master:2181 sessionTimeout=180000 watcher=hconnection
2013-09-09 15:58:56,171 INFO zookeeper.RecoverableZooKeeper (RecoverableZooKeeper.java:<init>(104)) - The identifier of this process is 6032@tht
2013-09-09 15:58:56,234 INFO zookeeper.ClientCnxn (ClientCnxn.java:logStartConnect(966)) - Opening socket connection to server master/121.1.253.251:2181. Will not attempt to authenticate using SASL (无法定位登录配置)
2013-09-09 15:58:56,296 INFO zookeeper.ClientCnxn (ClientCnxn.java:primeConnection(849)) - Socket connection established to master/121.1.253.251:2181, initiating session
2013-09-09 15:58:56,484 INFO zookeeper.ClientCnxn (ClientCnxn.java:onConnected(1207)) - Session establishment complete on server master/121.1.253.251:2181, sessionid = 0x141011ad7db000e, negotiated timeout = 180000
result:
table name: users
column Families: address
column Families: info
column Families: user_id

⑷ 如何使用Java API操作Hbase

使用Linux的shell命令,就可以非常轻松的操作Hbase,例如一些建表,建列簇,插值,显示所有表,统计数量等等,但有时为了提高灵活性,我们也需要使用编程语言来操作Hbase
当然Hbase通过Thrift接口提供了对大多数主流编程语言的支持,例如C++,PHP,Python,Ruby等等,那么本篇,散仙给出的例子是基于Java原生的API操作Hbase,相比其他的一些编程语言,使用Java操作Hbase,会更加高效一些,因为Hbase本身就是使用Java语言编写的。

⑸ 如何使用Java API操作Hbase

HBase提供了对HBase进行一系列的管理涉及到对表的管理、数据的操作java api。
常用的API操作有:
1、 对表的创建、删除、显示以及修改等,可以用HBaseAdmin,一旦创建了表,那么可以通过HTable的实例来访问表,每次可以往表里增加数据。
2、 插入数据
创建一个Put对象,在这个Put对象里可以指定要给哪个列增加数据,以及当前的时间戳等值,然后通过调用HTable.put(Put)来提交操作,子猴在这里提请注意的是:在创建Put对象的时候,你必须指定一个行(Row)值,在构造Put对象的时候作为参数传入。
3、 获取数据
要获取数据,使用Get对象,Get对象同Put对象一样有好几个构造函数,通常在构造的时候传入行值,表示取第几行的数据,通过HTable.get(Get)来调用。
4、 浏览每一行
通过Scan可以对表中的行进行浏览,得到每一行的信息,比如列名,时间戳等,Scan相当于一个游标,通过next()来浏览下一个,通过调用HTable.getScanner(Scan)来返回一个ResultScanner对象。HTable.get(Get)和HTable.getScanner(Scan)都是返回一个Result。Result是一个
KeyValue的链表。
5、 删除
使用Delete来删除记录,通过调用HTable.delete(Delete)来执行删除操作。(注:删除这里有些特别,也就是删除并不是马上将数据从表中删除。)
6、 锁
新增、获取、删除在操作过程中会对所操作的行加一个锁,而浏览却不会。
7、 簇的访问
客户端代码通过ZooKeeper来访问找到簇,也就是说ZooKeeper quorum将被使用,那么相关的类(包)应该在客户端的类(classes)目录下,即客户端一定要找到文件hbase-site.xml。
下面是一个例子程序:

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.MasterNotRunningException;
import org.apache.hadoop.hbase.ZooKeeperConnectionException;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.Bytes;

public class HBaseTest {

private static Configuration conf = null;

/**
* 初始化配置
*/
static {
Configuration HBASE_CONFIG = new Configuration();
//与hbase/conf/hbase-site.xml中hbase.zookeeper.quorum配置的值相同
HBASE_CONFIG.set("hbase.zookeeper.quorum", "10.1.1.1");
//与hbase/conf/hbase-site.xml中hbase.zookeeper.property.clientPort配置的值相同
HBASE_CONFIG.set("hbase.zookeeper.property.clientPort", "2181");
conf = HBaseConfiguration.create(HBASE_CONFIG);
}

/**
* 创建一张表
*/
public static void creatTable(String tableName, String[] familys) throws Exception {
HBaseAdmin admin = new HBaseAdmin(conf);
if (admin.tableExists(tableName)) {
System.out.println("table already exists!");
} else {
HTableDescriptor tableDesc = new HTableDescriptor(tableName);
for(int i=0; i<familys.length; i++){
tableDesc.addFamily(new HColumnDescriptor(familys[i]));
}
admin.createTable(tableDesc);
System.out.println("create table " + tableName + " ok.");
}
}

/**
* 删除表
*/
public static void deleteTable(String tableName) throws Exception {
try {
HBaseAdmin admin = new HBaseAdmin(conf);
admin.disableTable(tableName);
admin.deleteTable(tableName);
System.out.println("delete table " + tableName + " ok.");
} catch (MasterNotRunningException e) {
e.printStackTrace();
} catch (ZooKeeperConnectionException e) {
e.printStackTrace();
}
}

/**
* 插入一行记录
*/
public static void addRecord (String tableName, String rowKey, String family, String qualifier, String value)
throws Exception{
try {
HTable table = new HTable(conf, tableName);
Put put = new Put(Bytes.toBytes(rowKey));
put.add(Bytes.toBytes(family),Bytes.toBytes(qualifier),Bytes.toBytes(value));
table.put(put);
System.out.println("insert recored " + rowKey + " to table " + tableName +" ok.");
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* 删除一行记录
*/
public static void delRecord (String tableName, String rowKey) throws IOException{
HTable table = new HTable(conf, tableName);
List list = new ArrayList();
Delete del = new Delete(rowKey.getBytes());
list.add(del);
table.delete(list);
System.out.println("del recored " + rowKey + " ok.");
}

/**
* 查找一行记录
*/
public static void getOneRecord (String tableName, String rowKey) throws IOException{
HTable table = new HTable(conf, tableName);
Get get = new Get(rowKey.getBytes());
Result rs = table.get(get);
for(KeyValue kv : rs.raw()){
System.out.print(new String(kv.getRow()) + " " );
System.out.print(new String(kv.getFamily()) + ":" );
System.out.print(new String(kv.getQualifier()) + " " );
System.out.print(kv.getTimestamp() + " " );
System.out.println(new String(kv.getValue()));
}
}

/**
* 显示所有数据
*/
public static void getAllRecord (String tableName) {
try{
HTable table = new HTable(conf, tableName);
Scan s = new Scan();
ResultScanner ss = table.getScanner(s);
for(Result r:ss){
for(KeyValue kv : r.raw()){
System.out.print(new String(kv.getRow()) + " ");
System.out.print(new String(kv.getFamily()) + ":");
System.out.print(new String(kv.getQualifier()) + " ");
System.out.print(kv.getTimestamp() + " ");
System.out.println(new String(kv.getValue()));
}
}
} catch (IOException e){
e.printStackTrace();
}
}

public static void main (String [] agrs) {
try {
String tablename = "scores";
String[] familys = {"grade", "course"};
HBaseTest.creatTable(tablename, familys);

//add record zkb
HBaseTest.addRecord(tablename,"zkb","grade","","5");
HBaseTest.addRecord(tablename,"zkb","course","","90");
HBaseTest.addRecord(tablename,"zkb","course","math","97");
HBaseTest.addRecord(tablename,"zkb","course","art","87");
//add record baoniu
HBaseTest.addRecord(tablename,"baoniu","grade","","4");
HBaseTest.addRecord(tablename,"baoniu","course","math","89");

System.out.println("===========get one record========");
HBaseTest.getOneRecord(tablename, "zkb");

System.out.println("===========show all record========");
HBaseTest.getAllRecord(tablename);

System.out.println("===========del one record========");
HBaseTest.delRecord(tablename, "baoniu");
HBaseTest.getAllRecord(tablename);

System.out.println("===========show all record========");
HBaseTest.getAllRecord(tablename);
} catch (Exception e) {
e.printStackTrace();
}
}
}

⑹ 北大青鸟java培训:Hbase知识点总结

hbase概念:非结构化的分布式的面向列存储非关系型的开源的数据库,根据谷歌的三大论文之一的bigtable高宽厚表作用:为了解决大规模数据集合多重数据种类带来的挑战,尤其是大数据应用难题。
能干什么:存储大量结果集数据,低延迟的随机查询。
sql:结构化查询语言nosql:非关系型数据库,列存储和文档存储(查询低延迟),hbase是nosql的一个种类,其特点是列式存储。
非关系型数据库--列存储(hbase)非关系型数据库--文档存储(MongoDB)非关系型数据库--内存式存储(redis)非关系型数据库--图形模型(graph)hive和hbase区别?Hive的定位是数据仓库,虽然也有增删改查,但其删改查对应的是整张表而不是单行数据,查询的延迟较高。
其本质是更加方便的使用mr的威力来进行离线分析的一个数据分析工具。
HBase的定位是hadoop的数据库,电脑培训http://www.kmbdqn.cn/发现是一个典型的Nosql,所以HBase是用来在大量数据中进行低延迟的随机查询的。
hbase运行方式:standalonedistrubited单节点和伪分布式?单节点:单独的进程运行在同一台机器上hbase应用场景:存储海量数据低延迟查询数据hbase表由多行组成hbase行一行在hbase中由行健和一个或多个列的值组成,按行健字母顺序排序的存储。

⑺ 如何使用Java API操作Hbase

写了个Hbase新的api的增删改查的工具类,以供参考,代码如下:
package com.dhgate.hbase.test;

import java.util.ArrayList;
import java.util.List;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.filter.PageFilter;
import org.apache.hadoop.hbase.filter.PrefixFilter;
import org.apache.hadoop.hbase.util.Bytes;
/**
* 基于新的API
* Hbase0.96版本
* 写的工具类
*
* **/
public class HbaseCommons {

static Configuration conf=HBaseConfiguration.create();
static String tableName="";

public static void main(String[] args)throws Exception {

//String tableName="test";
//createTable(tableName, null);

}

/**
* 批量添加数据
* @param tableName 标名字
* @param rows rowkey行健的集合
* 本方法仅作示例,其他的内容需要看自己义务改变
*
* **/
public static void insertList(String tableName,String rows[])throws Exception{
HTable table=new HTable(conf, tableName);
List<Put> list=new ArrayList<Put>();
for(String r:rows){
Put p=new Put(Bytes.toBytes(r));
//此处示例添加其他信息
//p.add(Bytes.toBytes("family"),Bytes.toBytes("column"), 1000, Bytes.toBytes("value"));
list.add(p);
}
table.put(list);//批量添加
table.close();//释放资源
}

/**
* 创建一个表
* @param tableName 表名字
* @param columnFamilys 列簇
*
* **/
public static void createTable(String tableName,String[] columnFamilys)throws Exception{
//admin 对象
HBaseAdmin admin=new HBaseAdmin(conf);
if(admin.tableExists(tableName)){
System.out.println("此表,已存在!");
}else{
//旧的写法
//HTableDescriptor tableDesc=new HTableDescriptor(tableName);
//新的api
HTableDescriptor tableDesc=new HTableDescriptor(TableName.valueOf(tableName));

for(String columnFamily:columnFamilys){
tableDesc.addFamily(new HColumnDescriptor(columnFamily));
}

admin.createTable(tableDesc);
System.out.println("建表成功!");

}
admin.close();//关闭释放资源

}

/**
* 删除一个表
* @param tableName 删除的表名
* */
public static void deleteTable(String tableName)throws Exception{
HBaseAdmin admin=new HBaseAdmin(conf);
if(admin.tableExists(tableName)){
admin.disableTable(tableName);//禁用表
admin.deleteTable(tableName);//删除表
System.out.println("删除表成功!");
}else{
System.out.println("删除的表不存在!");
}
admin.close();
}

/**
* 插入一条数据
* @param tableName 表明
* @param columnFamily 列簇
* @param column 列
* @param value 值
*
* ***/
public static void insertOneRow(String tableName,String rowkey,String columnFamily,String column,String value)throws Exception{

HTable table=new HTable(conf, tableName);
Put put=new Put(Bytes.toBytes(rowkey));
put.add(Bytes.toBytes(columnFamily), Bytes.toBytes(column), Bytes.toBytes(value));
table.put(put);//放入表
table.close();//释放资源

}

/**
* 删除一条数据
* @param tableName 表名
* @param row rowkey行键
*
* */
public static void deleteOneRow(String tableName,String row)throws Exception{

HTable table=new HTable(conf, tableName);
Delete delete=new Delete(Bytes.toBytes(row));
table.delete(delete);
table.close();
}

/**
* 删除多条数据
* @param tableName 表名
* @param rows 行健集合
*
* **/
public static void deleteList(String tableName,String rows[])throws Exception{
HTable table=new HTable(conf, tableName);
List<Delete> list=new ArrayList<Delete>();
for(String row:rows){
Delete del=new Delete(Bytes.toBytes(row));
list.add(del);
}
table.delete(list);
table.close();//释放资源

}

/**
* 获取一条数据,根据rowkey
* @param tableName 表名
* @param row 行健
*
* **/
public static void getOneRow(String tableName,String row)throws Exception{
HTable table=new HTable(conf, tableName);
Get get=new Get(Bytes.toBytes(row));
Result result=table.get(get);
printRecoder(result);//打印记录
table.close();//释放资源
}

/**
* 查看某个表下的所有数据
*
* @param tableName 表名
* */
public static void showAll(String tableName)throws Exception{
HTable table=new HTable(conf, tableName);
Scan scan=new Scan();
ResultScanner rs=table.getScanner(scan);
for(Result r:rs){
printRecoder(r);//打印记录
}
table.close();//释放资源
}

/**
* 查看某个表下的所有数据
*
* @param tableName 表名
* @param rowKey 行健
* */
public static void ScanPrefixByRowKey(String tableName,String rowKey)throws Exception{
HTable table=new HTable(conf, tableName);
Scan scan=new Scan();
scan.setFilter(new PrefixFilter(Bytes.toBytes(rowKey)));
ResultScanner rs=table.getScanner(scan);
for(Result r:rs){
printRecoder(r);//打印记录
}
table.close();//释放资源
}

/**
* 查看某个表下的所有数据
*
* @param tableName 表名
* @param rowKey 行健扫描
* @param limit 限制返回数据量
* */
public static void ScanPrefixByRowKeyAndLimit(String tableName,String rowKey,long limit)throws Exception{
HTable table=new HTable(conf, tableName);
Scan scan=new Scan();
scan.setFilter(new PrefixFilter(Bytes.toBytes(rowKey)));
scan.setFilter(new PageFilter(limit));
ResultScanner rs=table.getScanner(scan);
for(Result r:rs){
printRecoder(r);//打印记录
}
table.close();//释放资源
}

/**
* 根据rowkey扫描一段范围
* @param tableName 表名
* @param startRow 开始的行健
* @param stopRow 结束的行健
* **/
public void scanByStartAndStopRow(String tableName,String startRow,String stopRow)throws Exception{
HTable table=new HTable(conf, tableName);
Scan scan=new Scan();
scan.setStartRow(Bytes.toBytes(startRow));
scan.setStopRow(Bytes.toBytes(stopRow));
ResultScanner rs=table.getScanner(scan);
for(Result r:rs){
printRecoder(r);
}
table.close();//释放资源

}
/**
* 扫描整个表里面具体的某个字段的值
* @param tableName 表名
* @param columnFalimy 列簇
* @param column 列
* **/
public static void getValueDetail(String tableName,String columnFalimy,String column)throws Exception{

HTable table=new HTable(conf, tableName);
Scan scan=new Scan();
ResultScanner rs=table.getScanner(scan);
for(Result r:rs){
System.out.println("值: " +new String(r.getValue(Bytes.toBytes(columnFalimy), Bytes.toBytes(column))));
}
table.close();//释放资源

}

/**
* 打印一条记录的详情
*
* */
public static void printRecoder(Result result)throws Exception{
for(Cell cell:result.rawCells()){
System.out.print("行健: "+new String(CellUtil.cloneRow(cell)));
System.out.print("列簇: "+new String(CellUtil.cloneFamily(cell)));
System.out.print(" 列: "+new String(CellUtil.cloneQualifier(cell)));
System.out.print(" 值: "+new String(CellUtil.cloneValue(cell)));
System.out.println("时间戳: "+cell.getTimestamp());
}
}

}

⑻ 如何使用Java API操作Hbase

一般情况下,我们使用Linux的shell命令,就可以非常轻松的操作Hbase,例如一些建表,建列簇,插值,显示所有表,统计数量等等,但有时为了提高灵活性,我们也需要使用编程语言来操作Hbase,当然Hbase通过Thrift接口提供了对大多数主流编程语言的支持,例如C++,PHP,Python,Ruby等等,那么本篇,散仙给出的例子是基于Java原生的API操作Hbase,相比其他的一些编程语言,使用Java操作Hbase,会更加高效一些,因为Hbase本身就是使用Java语言编写的。转载
下面,散仙给出源码,以供参考:

package com.hbase;

import java.util.ArrayList;
import java.util.List;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.util.Bytes;

/**
* @author
*
* **/
public class Test {

static Configuration conf=null;
static{

conf=HBaseConfiguration.create();//hbase的配置信息
conf.set("hbase.zookeeper.quorum", "10.2.143.5"); //zookeeper的地址

}

public static void main(String[] args)throws Exception {

Test t=new Test();
//t.createTable("temp", new String[]{"name","age"});
//t.insertRow("temp", "2", "age", "myage", "100");
// t.getOneDataByRowKey("temp", "2");
t.showAll("temp");

}

/***
* 创建一张表
* 并指定列簇
* */
public void createTable(String tableName,String cols[])throws Exception{
HBaseAdmin admin=new HBaseAdmin(conf);//客户端管理工具类
if(admin.tableExists(tableName)){
System.out.println("此表已经存在.......");
}else{
HTableDescriptor table=new HTableDescriptor(tableName);
for(String c:cols){
HColumnDescriptor col=new HColumnDescriptor(c);//列簇名
table.addFamily(col);//添加到此表中
}

admin.createTable(table);//创建一个表
admin.close();
System.out.println("创建表成功!");
}
}

/**
* 添加数据,
* 建议使用批量添加
* @param tableName 表名
* @param row 行号
* @param columnFamily 列簇
* @param column 列
* @param value 具体的值
*
* **/
public void insertRow(String tableName, String row,
String columnFamily, String column, String value) throws Exception {
HTable table = new HTable(conf, tableName);
Put put = new Put(Bytes.toBytes(row));
// 参数出分别:列族、列、值
put.add(Bytes.toBytes(columnFamily), Bytes.toBytes(column),
Bytes.toBytes(value));

table.put(put);
table.close();//关闭
System.out.println("插入一条数据成功!");
}

/**
* 删除一条数据
* @param tableName 表名
* @param row rowkey
* **/
public void deleteByRow(String tableName,String rowkey)throws Exception{
HTable h=new HTable(conf, tableName);
Delete d=new Delete(Bytes.toBytes(rowkey));
h.delete(d);//删除一条数据
h.close();
}

/**
* 删除多条数据
* @param tableName 表名
* @param row rowkey
* **/
public void deleteByRow(String tableName,String rowkey[])throws Exception{
HTable h=new HTable(conf, tableName);

List<Delete> list=new ArrayList<Delete>();
for(String k:rowkey){
Delete d=new Delete(Bytes.toBytes(k));
list.add(d);
}
h.delete(list);//删除
h.close();//释放资源
}

/**
* 得到一条数据
*
* @param tableName 表名
* @param rowkey 行号
* ***/
public void getOneDataByRowKey(String tableName,String rowkey)throws Exception{
HTable h=new HTable(conf, tableName);

Get g=new Get(Bytes.toBytes(rowkey));
Result r=h.get(g);
for(KeyValue k:r.raw()){

System.out.println("行号: "+Bytes.toStringBinary(k.getRow()));
System.out.println("时间戳: "+k.getTimestamp());
System.out.println("列簇: "+Bytes.toStringBinary(k.getFamily()));
System.out.println("列: "+Bytes.toStringBinary(k.getQualifier()));
//if(Bytes.toStringBinary(k.getQualifier()).equals("myage")){
// System.out.println("值: "+Bytes.toInt(k.getValue()));
//}else{
String ss= Bytes.toString(k.getValue());
System.out.println("值: "+ss);
//}

}
h.close();

}

/**
* 扫描所有数据或特定数据
* @param tableName
* **/
public void showAll(String tableName)throws Exception{

HTable h=new HTable(conf, tableName);

Scan scan=new Scan();
//扫描特定区间
//Scan scan=new Scan(Bytes.toBytes("开始行号"),Bytes.toBytes("结束行号"));
ResultScanner scanner=h.getScanner(scan);
for(Result r:scanner){
System.out.println("==================================");
for(KeyValue k:r.raw()){

System.out.println("行号: "+Bytes.toStringBinary(k.getRow()));
System.out.println("时间戳: "+k.getTimestamp());
System.out.println("列簇: "+Bytes.toStringBinary(k.getFamily()));
System.out.println("列: "+Bytes.toStringBinary(k.getQualifier()));
//if(Bytes.toStringBinary(k.getQualifier()).equals("myage")){
// System.out.println("值: "+Bytes.toInt(k.getValue()));
//}else{
String ss= Bytes.toString(k.getValue());
System.out.println("值: "+ss);
//}

}
}
h.close();

}

}

显示所有数据的打印输出如下:

==================================
行号: 1
时间戳: 1385597699287
列簇: name
列: myname
值:
==================================
行号: 2
时间戳: 1385598393306
列簇: age
列: myage
值: 100
行号: 2
时间戳: 1385597723900
列簇: name
列: myname
值:

阅读全文

与hbasejava客户端编程相关的资料

热点内容
dvd光盘存储汉子算法 浏览:757
苹果邮件无法连接服务器地址 浏览:963
phpffmpeg转码 浏览:671
长沙好玩的解压项目 浏览:145
专属学情分析报告是什么app 浏览:564
php工程部署 浏览:833
android全屏透明 浏览:737
阿里云服务器已开通怎么办 浏览:803
光遇为什么登录时服务器已满 浏览:302
PDF分析 浏览:485
h3c光纤全工半全工设置命令 浏览:143
公司法pdf下载 浏览:382
linuxmarkdown 浏览:350
华为手机怎么多选文件夹 浏览:683
如何取消命令方块指令 浏览:349
风翼app为什么进不去了 浏览:778
im4java压缩图片 浏览:362
数据查询网站源码 浏览:150
伊克塞尔文档怎么进行加密 浏览:892
app转账是什么 浏览:163