hbase版本:0.98.5

hadoop版本:1.2.1

使用自带的zk

本文的内容是在集群中创建java项目调用api来操作hbase,主要涉及对hbase的创建表格,删除表格,插入数据,删除数据,查询一条数据,查询所有数据等操作。

具体流程如下:
1.创建项目
2.获取jar包到项目的lib目录下(这边试用的事hbase 0.98 lib目录下的所有jar包)
3.编写java程序
4.编写ant脚本

package test2;
import java.util.ArrayList;
import java.util.List; import org.apache.hadoop.fs.Path;
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.HConnection;
import org.apache.hadoop.hbase.client.HConnectionManager;
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; public class TestHBase { private HBaseAdmin admin = null;
private Configuration conf = null; public TestHBase() throws Exception
{
conf = HBaseConfiguration.create();
conf.addResource(new Path("/home/work/hbase_dev/test2/lib/hbase-site.xml"));
//conf.set("hbase.zookeeper.quorum", "10.57.90.19");
//conf.set("hbase.zookeeper.property.clientPort", "2181");
admin = new HBaseAdmin(conf);
} public void createTable (String tableName , String[] columnFamily) throws Exception
{
if (admin.tableExists(tableName))
{
System.out.println(tableName + "已存在");
return ;
//System.exit(0);
} HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf(tableName)); for (String colunm : columnFamily)
{
tableDescriptor.addFamily(new HColumnDescriptor(colunm));
} admin.createTable(tableDescriptor);
System.out.println("Create table successfully..");
} public boolean deleteTable (String tableName)
{
try {
if(admin.tableExists(tableName))
{
admin.disableTable(tableName);
admin.deleteTable(tableName);
System.out.println("drop table " + tableName);
}
return true;
} catch (Exception e) {
System.out.println("删除" + tableName + "失败");
return false;
}
} public List getAllTables()
{
List<String> tables = null;
if (admin != null)
{
try{
HTableDescriptor[] allTables = admin.listTables();
if(allTables.length > 0)
{
tables = new ArrayList<String>();
} for (HTableDescriptor tableDesc : allTables)
{
tables.add(tableDesc.getNameAsString());
System.out.println(tableDesc.getNameAsString());
}
}catch(Exception ex)
{
ex.printStackTrace();
}
} return tables;
} public boolean addOneRecord (String tableName , String key , String family , String column
, byte[] dataIn) throws Exception
{
HConnection connection = HConnectionManager.createConnection(conf);
//HTable table = new HTable(hbaseConf, tableName);
HTable table = (HTable)connection.getTable(tableName);
Put put = new Put(key.getBytes());
put.add(family.getBytes(), column.getBytes(), dataIn);
try {
table.put(put);
System.out.println("插入数据条 " + key + "成功");
return true;
} catch (Exception e) {
// TODO: handle exception
System.out.println("插入数据条 " + key + "失败");
return false;
}
} public void getValueFromKey (String tableName , String key)
{
try{
HConnection conn = HConnectionManager.createConnection(conf);
HTable table = (HTable) conn.getTable(tableName);
Get get = new Get(key.getBytes());
Result rs = table.get(get);
if (rs.rawCells().length == 0)
{
System.out.println("不存在关键字为" + key + "的行...");
}
else
{
for (Cell cell : rs.rawCells())
{
System.out.println(new String(CellUtil.cloneFamily(cell)) +
" " + new String(CellUtil.cloneQualifier(cell)) + " " + new String(CellUtil.cloneValue(cell)));
}
}
}
catch(Exception ex)
{
System.out.println("查询失败");
ex.printStackTrace();
}
} public void getAllData(String tableName) throws Exception
{
HConnection conn = HConnectionManager.createConnection(conf);
HTable table = (HTable) conn.getTable(tableName);
Scan scan = new Scan();
ResultScanner rs = table.getScanner(scan);
for (Result result : rs)
{
for (Cell cell : result.rawCells())
{
System.out.println("RowName: " + new String(CellUtil.cloneRow(cell)) + " ");
System.out.println("Timetamp: " + cell.getTimestamp() + " ");
System.out.println("Column family: " + new String(CellUtil.cloneFamily(cell)) + " ");
System.out.println("row name: " + new String(CellUtil.cloneQualifier(cell)) + " ");
System.out.println("value: " + new String(CellUtil.cloneValue(cell)) + " ");
}
}
} public void deleteRecord(String tableName , String key)
{
try
{
HConnection conn = HConnectionManager.createConnection(conf);
HTable table = (HTable)conn.getTable(tableName);
Delete delete = new Delete(key.getBytes()); table.delete(delete);
System.out.println("删除" + key +"成功...");
}
catch(Exception ex)
{
System.out.println("删除数据失败...");
ex.printStackTrace();
}
} public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
String[] column = {"family1" , "family2"};
try {
TestHBase hbase = new TestHBase();
hbase.deleteTable("students");
hbase.createTable("students", column);
//hbase.getAllData("scores");
hbase.addOneRecord("students", "id1", "family1", "name", "Jack".getBytes());
hbase.addOneRecord("students", "id1", "family1", "grade", "gaosan".getBytes());
//hbase.getAllTables();
//hbase.getAllData("students");
hbase.getValueFromKey("students", "id1");
hbase.deleteRecord("students", "id1");
hbase.addOneRecord("students", "id2", "family1", "name", "Holen".getBytes());
hbase.getValueFromKey("students", "id2");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} } }

ant脚本

<?xml version="1.0"?>
<project name="HBaseProject" default="run" basedir=".">
<property name="src.dir" value="src" />
<property name="report.dir" value="report" />
<property name="classes.dir" value="classes" />
<property name="lib.dir" value="lib" />
<property name="dist.dir" value="dist" />
<property name="doc.dir" value="doc"/>
<path id="master-classpath">
<fileset file="${lib.dir}/*.jar" />
<pathelement path="${classes.dir}"/>
</path> <path id="run.path">
<path path="${classes.dir}"/>
<path refid="master-classpath" />
</path>
<target name="init" depends="clean">
<mkdir dir="${classes.dir}"/>
<mkdir dir="${dist.dir}"/>
</target>
<target name="compile" depends="init" description="compile the source files"> <javac srcdir="${src.dir}" destdir="${classes.dir}" target="1.6" includeantruntime="false">
<classpath refid="master-classpath"/>
</javac>
</target> <target name="run" depends="compile">
<java classname="test2.TestHBase" classpathref="run.path" fork="true" >
</java>
</target> <target name="pack" depends="compile" description="make .jar file">
<mkdir dir="${dist.dir}" />
<jar destfile="${dist.dir}/hbaseproject.jar" basedir="${classes.dir}">
<exclude name="**/*Test.*" />
<exclude name="**/Test*.*" />
</jar>
</target> <target name="clean" description="clean the project">
<delete dir="${classes.dir}"></delete>
<delete dir="${dist.dir}"></delete>
</target>
</project>

最后把项目放在集群中,进入项目的根目录,执行命令:ant run

即可运行!

linux 下通过过 hbase 的Java api 操作hbase的更多相关文章

  1. HBase 6、用Phoenix Java api操作HBase

    开发环境准备:eclipse3.5.jdk1.7.window8.hadoop2.2.0.hbase0.98.0.2.phoenix4.3.0 1.从集群拷贝以下文件:core-site.xml.hb ...

  2. Hbase框架原理及相关的知识点理解、Hbase访问MapReduce、Hbase访问Java API、Hbase shell及Hbase性能优化总结

    转自:http://blog.csdn.net/zhongwen7710/article/details/39577431 本blog的内容包含: 第一部分:Hbase框架原理理解 第二部分:Hbas ...

  3. Java API 操作HBase Shell

    HBase Shell API 操作 创建工程 本实验的环境实在ubuntu18.04下完成,首先在改虚拟机中安装开发工具eclipse. 然后创建Java项目名字叫hbase-test 配置运行环境 ...

  4. HBase的Java Api连接失败的问题及解决方法

    分布式方式部署的HBase,启动正常,Shell操作正常,使用HBase的Java Api操作时总是连接失败,信息如下: This server is in the failed servers li ...

  5. hadoop2-HBase的Java API操作

    Hbase提供了丰富的Java API,以及线程池操作,下面我用线程池来展示一下使用Java API操作Hbase. 项目结构如下: 我使用的Hbase的版本是 hbase-0.98.9-hadoop ...

  6. 5 hbase-shell + hbase的java api

    本博文的主要内容有 .HBase的单机模式(1节点)安装 .HBase的单机模式(1节点)的启动 .HBase的伪分布模式(1节点)安装  .HBase的伪分布模式(1节点)的启动    .HBase ...

  7. hbase-shell + hbase的java api

    本博文的主要内容有 .HBase的单机模式(1节点)安装 .HBase的单机模式(1节点)的启动 .HBase的伪分布模式(1节点)安装   .HBase的伪分布模式(1节点)的启动    .HBas ...

  8. Linux 下报错:A Java RunTime Environment (JRE) or Java Development Kit (JDK) must解决方案

    一.报错环境:在Linux mint下,前几天还用得很好的的eclipse,今天开机不知为什么这样. Linux 下报错:A Java RunTime Environment (JRE) or Jav ...

  9. MongoDB Java API操作很全的整理

    MongoDB 是一个基于分布式文件存储的数据库.由 C++ 语言编写,一般生产上建议以共享分片的形式来部署. 但是MongoDB官方也提供了其它语言的客户端操作API.如下图所示: 提供了C.C++ ...

随机推荐

  1. 解决图片浮动调节不了的问题(使用vertical-align属性)

    vertical-align: middle; vertical-align 属性设置元素的垂直对齐方式. baseline  默认.元素放置在父元素的基线上.sub 垂直对齐文本的下标.super ...

  2. unity批量设置图片为etc2格式或者astc格式

    网上找了半天,没一个能用的,干脆自己写个,直接拷贝这个脚本就行 这个是ios版本的,安卓的话写在注释里面,去掉注释就能用了 现在ios支持一种新格式叫astc比原本的pvrtc压缩比更高,而且质量更高 ...

  3. ThreadPoolExecutor 异常

    通过execute提交的任务,能将该任务抛出的异常交给未捕获异常处理器处理,而通过submit提交的任务,无论是抛出的未检查异常还是已检查异常,都将被认为是任务返回状态的一部分.如果一个由submit ...

  4. 剑指offer(41-45)编程题

    41.入一个递增排序的数组和一个数字S,在数组中查找两个数,是的他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的. class Solution { public: vector&l ...

  5. Weblogic Maven

    从weblogic 10.3.4开始支持maven deploy部署   步骤如下: 1.构建weblogic-maven-plugin jar 在D:\oracle\Middleware\wlser ...

  6. 搭建nginx代理,为前端页面跨域调用接口

    前端同学因开发需要,本地搭建的服务需要调用其它域名的接口,在帮助正确配置后,已能正常使用. 这里写一篇博客,记录一下. 前端页面地址为127.0.0.1:9813/a.html 接口地址http:// ...

  7. Android组件--意图(Intent)

    1. 隐示调用和显示调用 参考资料:http://blog.csdn.net/harvic880925/article/details/38399723 1.概念 1). 显式意图: 能从intent ...

  8. JavaScript的柯里化函数

    柯里化,或者说部分应用,是一种函数式编程的技术,对于熟悉以传统方式编写 JavaScript 代码的人来说可能会很费解.但如果使用得当,它可以使你的 JavaScript 函数更具可读性. 更具可读性 ...

  9. Docker学习(五): 仓库与数据管理

    特别声明: 博文主要是学习过程中的知识整理,以便之后的查阅回顾.部分内容来源于网络(如有摘录未标注请指出).内容如有差错,也欢迎指正! =============系列文章============= 1 ...

  10. 七、curator recipes之阻塞队列SimpleDistributedQueue

    简介 Java在单机环境实现了BlockQueue阻塞队列,与之类似的curator实现了分布式场景下的阻塞队列,SimpleDistributedQueue 官方文档:http://curator. ...