求助,HBASE不能hbase 创建数据库表

lifuxiangcaohui
package org.
import java.io.IOE
import java.text.DateF
import java.text.SimpleDateF
import java.util.ArrayL
import java.util.D
import java.util.HashS
import java.util.L
import java.util.NavigableM
import java.util.S
import java.util.V
import org.apache.hadoop.conf.C
import org.apache.hadoop.hbase.HBaseC
import org.apache.hadoop.hbase.HColumnD
import org.apache.hadoop.hbase.HTableD
import org.apache.hadoop.hbase.KeyV
import org.apache.hadoop.hbase.MasterNotRunningE
import org.apache.hadoop.hbase.ZooKeeperConnectionE
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.B
&* tab_global &param:userid
&* tab_user2id info:id
&* tab_id2user info:username, info:password
&* tab_users user:follow user:followd user:inbox user:sent
&* tab_post post:content
//hbase接口类
public class HbaseIf {
public static HbaseIf ghbase =
public static HbaseIf getInstance(){
if(ghbase == null)
ghbase = new HbaseIf();
HbaseIf() {
conf = HBaseConfiguration.create();
//创建表的方法
public void create_table(String name, String col, int version)
throws Exception {
HBaseAdmin admin = new HBaseAdmin(conf);
//先检查表是否存在
if (admin.tableExists(name)) {
admin.disableTable(name);
admin.deleteTable(name);
HTableDescriptor tableDesc = new HTableDescriptor(name);
HColumnDescriptor hd = new HColumnDescriptor(col);
hd.setMaxVersions(version);
tableDesc.addFamily(hd);
admin.createTable(tableDesc);
admin.close();
public List&Post& getPost(String username) throws Exception{
List&Post& list = new ArrayList&Post&();
long id = this.getIdByUsername(username);
//byte[] begin = Bytes.add(Bytes.toBytes(id), Bytes.toBytes(Long.MAX_VALUE-Long.MAX_VALUE));
byte[] begin = Bytes.toBytes(id);
//byte[] end = Bytes.add(Bytes.toBytes(id), Bytes.toBytes(Long.MAX_VALUE));
byte[] end = Bytes.toBytes(id+1);
Scan s = new Scan();
s.setStartRow(begin);
s.setStopRow(end);
HTable tab_post = new HTable(conf, &tab_post&);
HTable tab_inbox = new HTable(conf, &tab_inbox&);
ResultScanner ss = tab_inbox.getScanner(s);
for (Result r : ss) {
byte[] postid = r.getValue(Bytes.toBytes(&postid&), null);
get = new Get(postid);
Result rs = tab_post.get(get);
String post_username = Bytes.toString(rs.getValue(Bytes.toBytes(&post&), Bytes.toBytes(&username&)));
String post_content = &Bytes.toString(rs.getValue(Bytes.toBytes(&post&), Bytes.toBytes(&content&)));
String post_ts = & & & Bytes.toString(rs.getValue(Bytes.toBytes(&post&), Bytes.toBytes(&ts&)));
p = new Post(post_username, post_content, post_ts);
list.add(0,p);
public boolean post(String username, String content)
throws Exception {
HTable tab_global = new HTable(conf, &tab_global&);
HTable tab_post = new HTable(conf, &tab_post&);
long id = tab_global.incrementColumnValue(Bytes.toBytes(&row_postid&),
Bytes.toBytes(&param&), Bytes.toBytes(&postid&), 1);
byte[] postid = Bytes.toBytes(id);
// insert record in tab_post
Put put = new Put(postid);
DateFormat dateFormat = new SimpleDateFormat(&yyyy-MM-dd HH:mm:ss&);
String ts = dateFormat.format(new Date());
put.add(Bytes.toBytes(&post&), Bytes.toBytes(&username&), username.getBytes());
put.add(Bytes.toBytes(&post&), Bytes.toBytes(&content&), content.getBytes());
put.add(Bytes.toBytes(&post&), Bytes.toBytes(&ts&), ts.getBytes());
tab_post.put(put);
tab_global.close();
tab_post.close();
// send the post
long senderid = this.getIdByUsername(username);
System.out.println(&sender id:& + senderid);
byte[] begin = Bytes.add(Bytes.toBytes(senderid), Bytes.toBytes(Long.MAX_VALUE-Long.MAX_VALUE));
byte[] end = Bytes.add(Bytes.toBytes(senderid), Bytes.toBytes(Long.MAX_VALUE));
Scan s = new Scan();
s.setStartRow(begin);
s.setStopRow(end);
HTable tab_followed = new HTable(conf, &tab_followed&);
HTable tab_inbox = new HTable(conf, &tab_inbox&);
ResultScanner ss = tab_followed.getScanner(s);
put = new Put(Bytes.add(Bytes.toBytes(senderid), postid));
put.add(Bytes.toBytes(&postid&), null, postid);
tab_inbox.put(put);
for (Result r : ss) {
byte[] did = r.getValue(Bytes.toBytes(&userid&), null);
put = new Put(Bytes.add(did, postid));
put.add(Bytes.toBytes(&postid&), null, postid);
tab_inbox.put(put);
tab_followed.close();
tab_inbox.close();
//执行创建表方法
public void createTables() throws Exception {
// create tag_global and initialization
create_table(&tab_global&, &param&, 1);
HTable ht = new HTable(conf, &tab_global&);
Put put = new Put(Bytes.toBytes(&row_userid&));
long id = 0;
put.add(Bytes.toBytes(&param&), Bytes.toBytes(&userid&),
Bytes.toBytes(id));
ht.put(put);
put = new Put(Bytes.toBytes(&row_postid&));
put.add(Bytes.toBytes(&param&), Bytes.toBytes(&postid&),
Bytes.toBytes(id));
ht.put(put);
// create tab_user2id
create_table(&tab_user2id&, &info&, 1);
// create tab_id2user
create_table(&tab_id2user&, &info&, 1);
* tab_follow rowkey:userid CF:name:userid =& username version =& 1
create_table(&tab_follow&, &name&, 1);
* tab_followed rowkey:userid_{userid} CF:userid =& userid
create_table(&tab_followed&, &userid&, 1);
* tab_post
* rowkey:postid
* CF:content
create_table(&tab_post&, &post&, 1);
* tab_inbox
* rowkey:userid+postid
* CF:postid
create_table(&tab_inbox&, &postid&, 1);
& & //获取所有用户
public Set&String& getAllUser() throws Exception {
Set&String& set = new HashSet&String&();
HTable tab_user2id = new HTable(conf, &tab_user2id&);
Scan s = new Scan();
ResultScanner ss = tab_user2id.getScanner(s);
for (Result r : ss) {
String name = new String(r.getRow());
set.add(name);
System.out.print(name);
public Set&String& getFollow(String username) throws Exception {
long id = this.getIdByUsername(username);
Set&String& set = new HashSet&String&();
HTable tab_follow = new HTable(conf, &tab_follow&);
Get get = new Get(Bytes.toBytes(id));
Result rs = tab_follow.get(get);
for (KeyValue kv : rs.raw()) {
String s = new String(kv.getValue());
set.add(s);
System.out.println(s);
tab_follow.close();
public boolean alreadyFollow(long oid, long did) throws Exception {
HTable tab_users = new HTable(conf, &tab_users&);
Get get = new Get(Bytes.toBytes(oid));
get.setMaxVersions(500);
Result rs = tab_users.get(get);
List&KeyValue& list = rs.getColumn(Bytes.toBytes(&user&),
Bytes.toBytes(&follow&));
tab_users.close();
for (KeyValue kv : list) {
if (did == Bytes.toLong(kv.getValue()))
public boolean follow(String oname, String dname) throws Exception {
long oid = this.getIdByUsername(oname);
long did = this.getIdByUsername(dname);
if (oid == 0 || did == 0 || oid == did)
* tab_follow rowkey:userid CF:name:userid =& username version =& 1
HTable tab_follow = new HTable(conf, &tab_follow&);
Put put = new Put(Bytes.toBytes(oid));
put.add(Bytes.toBytes(&name&), Bytes.toBytes(did), dname.getBytes());
tab_follow.put(put);
tab_follow.close();
* tab_followed rowkey:userid_{userid} CF:userid =& userid
HTable tab_followed = new HTable(conf, &tab_followed&);
put = new Put(Bytes.add(Bytes.toBytes(did), Bytes.toBytes(oid)));
put.add(Bytes.toBytes(&userid&), null, Bytes.toBytes(oid));
tab_followed.put(put);
tab_followed.close();
public boolean unfollow(String oname, String dname) throws Exception {
long oid = this.getIdByUsername(oname);
long did = this.getIdByUsername(dname);
if (oid == 0 || did == 0 || oid == did)
* tab_follow rowkey:userid CF:name:userid =& username version =& 1
HTable tab_follow = new HTable(conf, &tab_follow&);
Delete del = new Delete(Bytes.toBytes(oid));
del.deleteColumns(Bytes.toBytes(&name&), Bytes.toBytes(did));
tab_follow.delete(del);
tab_follow.close();
* tab_followed rowkey:userid_{userid} CF:userid =& userid
HTable tab_followed = new HTable(conf, &tab_followed&);
del = new Delete(Bytes.add(Bytes.toBytes(did), Bytes.toBytes(oid)));
tab_followed.delete(del);
tab_followed.close();
public boolean deleteUser(long id) throws Exception {
String username = getNameById(id);
if (username.equals(&&))
HTable tab_user2id = new HTable(conf, &tab_user2id&);
HTable tab_id2user = new HTable(conf, &tab_id2user&);
Delete del = new Delete(username.getBytes());
tab_user2id.delete(del);
del = new Delete(Bytes.toBytes(id));
tab_id2user.delete(del);
tab_user2id.close();
tab_id2user.close();
//添加用户
public boolean createNewUser(String name, String password)
throws IOException {
HTable tab_global = new HTable(conf, &tab_global&);
HTable tab_user2id = new HTable(conf, &tab_user2id&);
HTable tab_id2user = new HTable(conf, &tab_id2user&);
if (tab_user2id.exists(new Get(name.getBytes())))
long id = tab_global.incrementColumnValue(Bytes.toBytes(&row_userid&),
Bytes.toBytes(&param&), Bytes.toBytes(&userid&), 1);
// insert record in tab_user2id
Put put = new Put(name.getBytes());
put.add(Bytes.toBytes(&info&), Bytes.toBytes(&id&), Bytes.toBytes(id));
tab_user2id.put(put);
// insert record in tab_id2user
put = new Put(Bytes.toBytes(id));
put.add(Bytes.toBytes(&info&), Bytes.toBytes(&username&),
Bytes.toBytes(name));
put.add(Bytes.toBytes(&info&), Bytes.toBytes(&password&),
Bytes.toBytes(password));
tab_id2user.put(put);
tab_global.close();
tab_user2id.close();
tab_id2user.close();
  //通过id获取用户用户名
public String getNameById(long id) {
HTable tab_id2user = new HTable(conf, &tab_id2user&);
Result rs = tab_id2user.get(new Get(Bytes.toBytes(id)));
//获取最新一列
KeyValue kv = rs.getColumnLatest(Bytes.toBytes(&info&),
Bytes.toBytes(&username&));
return Bytes.toString(kv.getValue());
} catch (Exception e) {
return &&;
public long getIdByUsername(String username) {
HTable tab_user2id = new HTable(conf, &tab_user2id&);
Result rs = searchByRowKey(tab_user2id, username);
KeyValue kv = rs.getColumnLatest(Bytes.toBytes(&info&),
Bytes.toBytes(&id&));
byte[] bid = kv.getValue();
return Bytes.toLong(bid);
} catch (Exception e) {
// return 0:not matched &0:match
public long checkPassword(String name, String password) throws Exception {
HTable tab_user2id = new HTable(conf, &tab_user2id&);
HTable tab_id2user = new HTable(conf, &tab_id2user&);
if (!tab_user2id.exists(new Get(name.getBytes())))
Result rs = searchByRowKey(tab_user2id, name);
KeyValue kv = rs.getColumnLatest(Bytes.toBytes(&info&),
Bytes.toBytes(&id&));
byte[] bid = kv.getValue();
Get get = new Get(bid);
rs = tab_id2user.get(get);
kv = rs.getColumnLatest(Bytes.toBytes(&info&),
Bytes.toBytes(&password&));
String passwordInDb = Bytes.toString(kv.getValue());
// System.out.println(passwordInDb);
if (!password.equals(passwordInDb))
long id = Bytes.toLong(bid);
public Result searchByRowKey(HTable ht, String rk) throws Exception {
Get get = new Get(rk.getBytes());
Result rs = ht.get(get);
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
HbaseIf hbase = new HbaseIf();
// hbase.createTables();
* h.createTables(); if(h.createNewUser(&robby1&, &robby&))
* System.out.println(&add user success&); else
* System.out.println(&add user failed&);
hbase.createTables();
hbase.createNewUser(&user1&, &pwd1&);
hbase.createNewUser(&user2&, &pwd1&);
hbase.createNewUser(&user3&, &pwd1&);
hbase.createNewUser(&user4&, &pwd1&);
hbase.createNewUser(&user5&, &pwd1&);
hbase.follow(&user1&, &user2&);
hbase.follow(&user3&, &user2&);
hbase.follow(&user4&, &user2&);hbase简单程序实例
HBaseConfiguration是用来配置HBase的对象。
意思是把HBase的配置文件添加到配置信息中,这个类继承自org.apache.hadoop.conf.Configuration,
他只有两个过时的构造方法,这里不讲。他还有两个静态的创造配置文件的方法,
()&和(org.apache.hadoop.conf.Configuration&that)&
无参数的是创建一个新的与Hbase的资源配置,带参数的是创建一个资源配置的副本。
资源配置创建好了,我们还需要手动设置配置的位置。
用Confguration的set方法:
Configuration conf =
HBaseConfiguration.create();
conf.set("hbase.zookeeper.quorum",
"服务器地址");
配置搞定。
使用HBaseAdmin
它提供了一个接口来管理HBase的数据库表的元数据。使用HBaseAdmin可以创建,删除,查看,启用和禁用表。它也使用添加和删除表列的字段。
它提供了(&desc)&这个方法,HTableDescriptor包含HBase的表的所有列描述符的详细信息,是一个目录表,表的根,提供的方法中比较有用的有:
setMaxFileSize,指定最大的region
setMemStoreFlushSize
指定memstore flush到HDFS上的文件大小
如果要增加列,通过(&family)&增加一个列字段。
指一个列,一个列的版本,它提供的方法比较常用的有
setTimeToLive:指定最大的TTL,单位是ms,过期数据会被自动删除。
setInMemory:指定是否放在内存中,对小表有用,可用于提高效率。默认关闭
setBloomFilter:指定是否使用BloomFilter,可提高随机查询效率。默认关闭
setCompressionType:设定数据压缩类型。默认无压缩。
setMaxVersions:指定数据最大保存的版本个数。默认为3。
一个简单的例子:
&public static void creatTable() {
&&HBaseAdmin admin = new
HBaseAdmin(conf);
&&if (admin.tableExists("table"))
&&&admin.disableTable("table");
&&&admin.deleteTable("table");
&&HTableDescriptor
tableDescripter = new HTableDescriptor("table".getBytes());
&&tableDescripter.addFamily(new
HColumnDescriptor("one"));
tableDescripter.addFamily(new HColumnDescriptor("two"));
tableDescripter.addFamily(new HColumnDescriptor("three"));
admin.createTable(tableDescripter);
删除表也是通过HBaseAdmin来操作,删除表之前首先要disable表。这是一个非常耗时的操作,所以不建议频繁删除表。
disableTable和deleteTable分别用来disable和delete表。
HBaseAdmin hAdmin = new HBaseAdmin(hbaseConfig);
if (hAdmin.tableExists(tableName)) {
&hAdmin.disableTable(tableName);
&hAdmin.deleteTable(tableName);
查询分为单条随机查询和批量查询。
单条查询是通过rowkey在table中查询某一行的数据。HTable提供了get方法来完成单条查询。
批量查询是通过制定一段rowkey的范围来查询。HTable提供了个getScanner方法来完成批量查询。
public Result get(final Get get)
public ResultScanner getScanner(final Scan scan)
Get对象包含了一个Get查询需要的信息。它的构造方法有两种:
& public Get(byte [] row)
& public Get(byte [] row, RowLock rowLock)
Rowlock是为了保证读写的原子性,你可以传递一个已经存在Rowlock,否则HBase会自动生成一个新的rowlock。
Scan对象提供了默认构造函数,一般使用默认构造函数。
Get/Scan的常用方法有:
addFamily/addColumn:指定需要的family或者column,如果没有调用任何addFamily或者Column,会返回所有的columns.
setMaxVersions:指定最大的版本个数。如果不带任何参数调用setMaxVersions,表示取所有的版本。如果不掉用setMaxVersions,只会取到最新的版本。
setTimeRange:指定最大的时间戳和最小的时间戳,只有在此范围内的cell才能被获取。
setTimeStamp:指定时间戳。
setFilter:指定Filter来过滤掉不需要的信息
Scan特有的方法:
setStartRow:指定开始的行。如果不调用,则从表头开始。
setStopRow:指定结束的行(不含此行)。
setBatch:指定最多返回的Cell数目。用于防止一行中有过多的数据,导致OutofMemory错误。
ResultScanner是Result的一个容器,每次调用ResultScanner的next方法,会返回Result.
public Result next() throws IOE
public Result [] next(int nbRows) throws IOE
Result代表是一行的数据。常用方法有:
getRow:返回rowkey
raw:返回所有的key value数组。
getValue:按照column来获取cell的值
Scan s = new Scan();
s.setMaxVersions();
ResultScanner ss = table.getScanner(s);
for(Result r:ss){
& & System.out.println(new
String(r.getRow()));
& & for(KeyValue
kv:r.raw()){
&System.out.println(new
String(kv.getValue()));
HTable通过put方法来插入数据。
public void put(final Put put) throws IOException
public void put(final List&Put& puts)
throws IOException
可以传递单个批Put对象或者List put对象来分别实现单条插入和批量插入。
Put提供了3种构造方式:
public Put(byte [] row)
public Put(byte [] row, RowLock rowLock)
public Put(Put putToCopy)
Put常用的方法有:
add:增加一个Cell
setTimeStamp:指定所有cell默认的timestamp,如果一个Cell没有指定timestamp,就会用到这个值。如果没有调用,HBase会将当前时间作为未指定timestamp的cell的timestamp.
setWriteToWAL: WAL是Write Ahead
Log的缩写,指的是HBase在插入操作前是否写Log。默认是打开,关掉会提高性能,但是如果系统出现故障(负责插入的Region
Server挂掉),数据可能会丢失。
另外HTable也有两个方法也会影响插入的性能
setAutoFlash: AutoFlush指的是在每次调用HBase的Put操作,是否提交到HBase
Server。默认是true,每次会提交。如果此时是单条插入,就会有更多的IO,从而降低性能.
setWriteBufferSize: Write Buffer
Size在AutoFlush为false的时候起作用,默认是2MB,也就是当插入数据超过2MB,就会自动提交到Server
HTable table = new HTable(hbaseConfig, tableName);
table.setAutoFlush(autoFlush);
List&Put& lp = new
ArrayList&Put&();
int count = 10000;
byte[] buffer = new byte[1024];
Random r = new Random();
for (int i = 1; i &= ++i) {
&Put p = new Put(String.format(“row
d”,i).getBytes());
&r.nextBytes(buffer);
&p.add(“f1&P.getBytes(), null, buffer);
&p.add(“f2&P.getBytes(), null, buffer);
&p.add(“f3&P.getBytes(), null, buffer);
&p.add(“f4&P.getBytes(), null, buffer);
&p.setWriteToWAL(wal);
&lp.add(p);
&if(i00==0){
&table.put(lp);
&lp.clear();
HTable 通过delete方法来删除数据。
& public void delete(final Delete delete)
Delete构造方法有:
public Delete(byte [] row)
public Delete(byte [] row, long timestamp, RowLock rowLock)
public Delete(final Delete d)
Delete常用方法有
deleteFamily/deleteColumns:指定要删除的family或者column的数据。如果不调用任何这样的方法,将会删除整行。
注意:如果某个Cell的timestamp高于当前时间,这个Cell将不会被删除,仍然可以查出来。
HTable table = new HTable(hbaseConfig, “mytest”);
Delete d = new Delete(“row1&P.getBytes());
table.delete(d)
HBaseAdmin提供split方法来将table 进行split.
public void split(final String tableNameOrRegionName)
如果提供的tableName,那么会将table所有region进行如果提供的region
Name,那么只会split这个region.
由于split是一个异步操作,我们并不能确切的控制region的个数。
public void split(String tableName,int number,int timeout) throws
Exception {
& & Configuration HBASE_CONFIG =
new Configuration();
HBASE_CONFIG.set(“hbase.zookeeper.quorum”,
GlobalConf.ZOOKEEPER_QUORUM);
HBASE_CONFIG.set(“hbase.zookeeper.property.clientPort”,
GlobalConf.ZOOKEEPER_PORT);
& & HBaseConfiguration cfg = new
HBaseConfiguration(HBASE_CONFIG);
& & HBaseAdmin hAdmin = new
HBaseAdmin(cfg);
& & HTable hTable = new
HTable(cfg,tableName);
& & int oldsize = 0;
&System.currentTimeMillis();
& & while(true){
&int size = hTable.getRegionsInfo().size();
&<(“the region number=”+size);
&if(size&=number )
&if(size!=oldsize){
&hAdmin.split(hTable.getTableName());
& & &oldsize =
if(System.currentTimeMillis()-t&timeout){
&Thread.sleep(1000*10);
已投稿到:
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。求助,HBASE不能创建表_百度知道
求助,HBASE不能创建表
提问者采纳
否则一直是这种只读模式.999. leave - 强制NameNode离开安全模式3.pct(缺省值0您好. get -
返回安全模式是否开启的信息4:hadoop dfsadmin -safemode leave然后我分别进入 hive 和 hbase create 就可以 顺利的执行了。如果设为1则HDFS永远是处于SafeMode。namenode在启动的时候首先进入安全模式.pct为一个比较小的值。(2)hadoop dfsadmin -safemode leave命令强制离开用户可以通过dfsadmin -safemode value
来操作安全模式,请点击【追问】希望我的回答对您有所帮助.safemode.safemode. wait - 等待。进入hadoop 的bin目录,如若还有问题,很高兴为您解答. enter - 进入安全模式2,如果DataNode上报的block个数达到了元数据记录的block个数的0.999f)表示HDFS启动的时候,缺省是0。有两个方法离开这种安全模式(1)修改dfs,望采纳:1,请点击右侧【采纳答案】。dfs,参数value的说明如下,一直到安全模式结束。如若满意,执行。我采取的办法是 强制离开安全模式,如果datanode丢失的block达到一定的比例,则系统会一直处于安全模式状态即只读状态.threshold.threshold.999倍才可以离开安全模式
来自团队:
其他类似问题
等待您来回答
为您推荐:
下载知道APP
随时随地咨询
出门在外也不愁Java操作Hbase进行建表、删表以及对数据进行增删改查,条件查询 - JavaCrazyer的)技术博客 - ITeye技术网站
博客分类:
1、搭建环境
新建JAVA项目,添加的包有:
有关Hadoop的hadoop-core-0.20.204.0.jar
有关Hbase的hbase-0.90.4.jar、hbase-0.90.4-tests.jar以及Hbase资源包中lib目录下的所有jar包
2、主要程序
package com.wujintao.hbase.
import java.io.IOE
import java.util.ArrayL
import java.util.L
import org.apache.hadoop.conf.C
import org.apache.hadoop.hbase.HBaseC
import org.apache.hadoop.hbase.HColumnD
import org.apache.hadoop.hbase.HTableD
import org.apache.hadoop.hbase.KeyV
import org.apache.hadoop.hbase.MasterNotRunningE
import org.apache.hadoop.hbase.ZooKeeperConnectionE
import org.apache.hadoop.hbase.client.D
import org.apache.hadoop.hbase.client.G
import org.apache.hadoop.hbase.client.HBaseA
import org.apache.hadoop.hbase.client.HT
import org.apache.hadoop.hbase.client.HTableP
import org.apache.hadoop.hbase.client.P
import org.apache.hadoop.hbase.client.R
import org.apache.hadoop.hbase.client.ResultS
import org.apache.hadoop.hbase.client.S
import org.apache.hadoop.hbase.filter.F
import org.apache.hadoop.hbase.filter.FilterL
import org.apache.hadoop.hbase.filter.SingleColumnValueF
import org.apache.hadoop.pareOp;
import org.apache.hadoop.hbase.util.B
public class JinTaoTest {
public static Configu
configuration = HBaseConfiguration.create();
configuration.set("hbase.zookeeper.property.clientPort", "2181");
configuration.set("hbase.zookeeper.quorum", "192.168.1.100");
configuration.set("hbase.master", "192.168.1.100:600000");
public static void main(String[] args) {
// createTable("wujintao");
// insertData("wujintao");
// QueryAll("wujintao");
// QueryByCondition1("wujintao");
// QueryByCondition2("wujintao");
//QueryByCondition3("wujintao");
//deleteRow("wujintao","abcdef");
deleteByCondition("wujintao","abcdef");
* @param tableName
public static void createTable(String tableName) {
System.out.println("start create table ......");
HBaseAdmin hBaseAdmin = new HBaseAdmin(configuration);
if (hBaseAdmin.tableExists(tableName)) {// 如果存在要创建的表,那么先删除,再创建
hBaseAdmin.disableTable(tableName);
hBaseAdmin.deleteTable(tableName);
System.out.println(tableName + " is exist,detele....");
HTableDescriptor tableDescriptor = new HTableDescriptor(tableName);
tableDescriptor.addFamily(new HColumnDescriptor("column1"));
tableDescriptor.addFamily(new HColumnDescriptor("column2"));
tableDescriptor.addFamily(new HColumnDescriptor("column3"));
hBaseAdmin.createTable(tableDescriptor);
} catch (MasterNotRunningException e) {
e.printStackTrace();
} catch (ZooKeeperConnectionException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
System.out.println("end create table ......");
* 插入数据
* @param tableName
public static void insertData(String tableName) {
System.out.println("start insert data ......");
HTablePool pool = new HTablePool(configuration, 1000);
HTable table = (HTable) pool.getTable(tableName);
Put put = new Put("112233bbbcccc".getBytes());// 一个PUT代表一行数据,再NEW一个PUT表示第二行数据,每行一个唯一的ROWKEY,此处rowkey为put构造方法中传入的值
put.add("column1".getBytes(), null, "aaa".getBytes());// 本行数据的第一列
put.add("column2".getBytes(), null, "bbb".getBytes());// 本行数据的第三列
put.add("column3".getBytes(), null, "ccc".getBytes());// 本行数据的第三列
table.put(put);
} catch (IOException e) {
e.printStackTrace();
System.out.println("end insert data ......");
* 删除一张表
* @param tableName
public static void dropTable(String tableName) {
HBaseAdmin admin = new HBaseAdmin(configuration);
admin.disableTable(tableName);
admin.deleteTable(tableName);
} catch (MasterNotRunningException e) {
e.printStackTrace();
} catch (ZooKeeperConnectionException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
* 根据 rowkey删除一条记录
* @param tablename
* @param rowkey
public static void deleteRow(String tablename, String rowkey)
HTable table = new HTable(configuration, tablename);
List list = new ArrayList();
Delete d1 = new Delete(rowkey.getBytes());
list.add(d1);
table.delete(list);
System.out.println("删除行成功!");
} catch (IOException e) {
e.printStackTrace();
* 组合条件删除
* @param tablename
* @param rowkey
public static void deleteByCondition(String tablename, String rowkey)
//目前还没有发现有效的API能够实现 根据非rowkey的条件删除 这个功能能,还有清空表全部数据的API操作
* 查询所有数据
* @param tableName
public static void QueryAll(String tableName) {
HTablePool pool = new HTablePool(configuration, 1000);
HTable table = (HTable) pool.getTable(tableName);
ResultScanner rs = table.getScanner(new Scan());
for (Result r : rs) {
System.out.println("获得到rowkey:" + new String(r.getRow()));
for (KeyValue keyValue : r.raw()) {
System.out.println("列:" + new String(keyValue.getFamily())
+ "====值:" + new String(keyValue.getValue()));
} catch (IOException e) {
e.printStackTrace();
* 单条件查询,根据rowkey查询唯一一条记录
* @param tableName
public static void QueryByCondition1(String tableName) {
HTablePool pool = new HTablePool(configuration, 1000);
HTable table = (HTable) pool.getTable(tableName);
Get scan = new Get("abcdef".getBytes());// 根据rowkey查询
Result r = table.get(scan);
System.out.println("获得到rowkey:" + new String(r.getRow()));
for (KeyValue keyValue : r.raw()) {
System.out.println("列:" + new String(keyValue.getFamily())
+ "====值:" + new String(keyValue.getValue()));
} catch (IOException e) {
e.printStackTrace();
* 单条件按查询,查询多条记录
* @param tableName
public static void QueryByCondition2(String tableName) {
HTablePool pool = new HTablePool(configuration, 1000);
HTable table = (HTable) pool.getTable(tableName);
Filter filter = new SingleColumnValueFilter(Bytes
.toBytes("column1"), null, CompareOp.EQUAL, Bytes
.toBytes("aaa")); // 当列column1的值为aaa时进行查询
Scan s = new Scan();
s.setFilter(filter);
ResultScanner rs = table.getScanner(s);
for (Result r : rs) {
System.out.println("获得到rowkey:" + new String(r.getRow()));
for (KeyValue keyValue : r.raw()) {
System.out.println("列:" + new String(keyValue.getFamily())
+ "====值:" + new String(keyValue.getValue()));
} catch (Exception e) {
e.printStackTrace();
* 组合条件查询
* @param tableName
public static void QueryByCondition3(String tableName) {
HTablePool pool = new HTablePool(configuration, 1000);
HTable table = (HTable) pool.getTable(tableName);
List&Filter& filters = new ArrayList&Filter&();
Filter filter1 = new SingleColumnValueFilter(Bytes
.toBytes("column1"), null, CompareOp.EQUAL, Bytes
.toBytes("aaa"));
filters.add(filter1);
Filter filter2 = new SingleColumnValueFilter(Bytes
.toBytes("column2"), null, CompareOp.EQUAL, Bytes
.toBytes("bbb"));
filters.add(filter2);
Filter filter3 = new SingleColumnValueFilter(Bytes
.toBytes("column3"), null, CompareOp.EQUAL, Bytes
.toBytes("ccc"));
filters.add(filter3);
FilterList filterList1 = new FilterList(filters);
Scan scan = new Scan();
scan.setFilter(filterList1);
ResultScanner rs = table.getScanner(scan);
for (Result r : rs) {
System.out.println("获得到rowkey:" + new String(r.getRow()));
for (KeyValue keyValue : r.raw()) {
System.out.println("列:" + new String(keyValue.getFamily())
+ "====值:" + new String(keyValue.getValue()));
rs.close();
} catch (Exception e) {
e.printStackTrace();
注意:可能大家没看到更新数据的操作,其实更新的操作跟添加完全一致,只不过是添加呢rowkey不存在,更新呢rowkey已经存在,并且timstamp相同的情况下,还有就是目前好像还没办法实现hbase数据的分页查询,不知道有没有人知道怎么做
HBase性能优化建议:
针对前面的代码,有很多不足之处,在此我就不修改上面的代码了,只是提出建议的地方,大家自己加上
当你调用create方法时将会加载两个配置文件:hbase-default.xml and hbase-site.xml,利用的是当前的java类路径, 代码中configuration设置的这些配置将会覆盖hbase-default.xml和hbase-site.xml中相同的配置,如果两个配置文件都存在并且都设置好了相应参上面的属性下面的属性即可
2)关于建表
public void createTable(HTableDescriptor desc)
HTableDescriptor 代表的是表的schema, 提供的方法中比较有用的有
setMaxFileSize,指定最大的region size
setMemStoreFlushSize 指定memstore flush到HDFS上的文件大小
增加family通过 addFamily方法
public void addFamily(final HColumnDescriptor family)
代表的是column的schema,提供的方法比较常用的有
setTimeToLive:指定最大的TTL,单位是ms,过期数据会被自动删除。
setInMemory:指定是否放在内存中,对小表有用,可用于提高效率。默认关闭
setBloomFilter:指定是否使用BloomFilter,可提高随机查询效率。默认关闭
setCompressionType:设定数据压缩类型。默认无压缩。
setMaxVersions:指定数据最大保存的版本个数。默认为3。
注意的是,一般我们不去setInMemory为true,默认是关闭的
3)关于入库
table.setAutoFlush(false); //数据入库之前先设置此项为false
table.setflushCommits();//入库完成后,手动刷入数据
在入库过程中,put.setWriteToWAL(true/flase);
关于这一项如果不希望大量数据在存储过程中丢失,建议设置为true,如果仅是在测试演练阶段,为了节省入库时间建议设置为false
4)关于获取表实例
HTablePool pool = new HTablePool(configuration, Integer.MAX_VALUE);
HTable table = (HTable) pool.getTable(tableName);
建议用表连接池的方式获取表,具体池有什么作用,我想用过数据库连接池的同学都知道,我就不再重复
不建议使用new HTable(configuration,tableName);的方式获取表
5)关于查询
建议每个查询语句都放入try catch语句块,并且finally中要进行关闭ResultScanner实例以及将不使用的表重新放入到HTablePool中的操作,具体做法如下
public static void QueryAll(String tableName) {
HTablePool pool = new HTablePool(configuration, Integer.MAX_VALUE);
HTable table =
ResultScanner rs =
Scan scan = new Scan();
table = (HTable) pool.getTable(tableName);
rs = table.getScanner(scan);
for (Result r : rs) {
System.out.println("获得到rowkey:" + new String(r.getRow()));
for (KeyValue keyValue : r.raw()) {
System.out.println("列:" + new String(keyValue.getFamily())
+ "====值:" + new String(keyValue.getValue()));
} catch (IOException e) {
e.printStackTrace();
rs.close();// 最后还得关闭
pool.putTable(table); //实际应用过程中,pool获取实例的方式应该抽取为单例模式的,不应在每个方法都重新获取一次(单例明白?就是抽取到专门获取pool的逻辑类中,具体逻辑为如果pool存在着直接使用,如果不存在则new)
所以,以上代码有缺陷的地方,感兴趣的同学可以针对优化建议作出相应修改
浏览 56655
楼主,请教个问题。最近学习hbase,版本是0.90.4。使用Standalone模式启动成功,用shell也是可以操作数据库的。可是我想通过java的api远程访问,但始终都是失败。netstat一下hbase进程,60000端口根本没有起来。我的问题是Standalone模式下,不支持远程访问吗?楼主的例子采取是Standalone模式下调试吗?这个问题经过各种原因是ipv6导致的所以要在host配置如下信息127.0.0.1& localhost ::1&&&& ip6-localhost ip6-loopback& fe00::0 ip6-localnet& ff00::0 ip6-mcastprefix& ff02::1 ip6-allnodes& ff02::2 ip6-allrouters& ff02::3 ip6-allhosts 192.168.159.2 master master192.168.159.3 save1& save1192.168.159.4 save2& save2192.168.159.5 save3& save3
楼主,请教个问题。最近学习hbase,版本是0.90.4。使用Standalone模式启动成功,用shell也是可以操作数据库的。可是我想通过java的api远程访问,但始终都是失败。netstat一下hbase进程,60000端口根本没有起来。我的问题是Standalone模式下,不支持远程访问吗?楼主的例子采取是Standalone模式下调试吗?standalone模式也可以的,不管采用哪种模式,使用java都可以远程访问的.其模式可以分为单机模式,伪分布式,分布式,感兴趣的可以一起研究
JavaCrazyer
浏览: 1779914 次
来自: 河南
因为java所以java 写道请教一下啊,那么拦截器和jdk的 ...
楼主,我也碰到了下载问题
[color=violet][/color]我[size=me ...
spring mvc demo教程源代码下载:http://w ...
例子挺齐全的,谢谢。学习了}

我要回帖

更多关于 hbase表结构设计 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信