put向hbase中插入数据
package com.test.demo01;
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.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.mapreduce.Mapper;
public class HbaseDmlInsert {
static private HTable table = null;
static private Configuration conf = null;
static private Connection conn = null;
// 单条数据插入
public static void insertOnData() throws IOException {
// put对象,封装需要插入的数据,每一条数据--对应一个put对象
Put put = new Put("rk001".getBytes());
// 参数一、列族,参数二、列名,参数三、值
put.addColumn("zu01".getBytes(), "name".getBytes(), "wangming".getBytes());
table.put(put);
}
//多条数据插入、List集合、用list集合进行提交
public static void insertListDatas() throws IOException {
// 创建集合存放数据
List list = new ArrayList();
// 将1000条数据放入集合中
for (int i = 0; i < 1000; i++) {
Put pu = new Put((“rk” + i).getBytes());
pu.addColumn(“zu01”.getBytes(), “age”.getBytes(), (i + “岁”).getBytes());
list.add(pu);
}
// 用集合批量插入数据
table.put(list);
}
//用缓存批量插入数据
public static void insertBufferdatas() throws IOException {
/*
* 首先设置是否需要刷新提交put对象 默认的是true 默认一条数据提交一次 将参数值改为false 不会立即提交 达到我们设定值才会提交
*
*/
table.setAutoFlushTo(false);
// 设置插入数据的总条数1000条
for (int i = 0; i < 1000; i++) {
// put封装需要插入数据
Put pu = new Put(("rk" + i).getBytes());
pu.addColumn("zu01".getBytes(), "age".getBytes(), (i + "岁").getBytes());
// 此时不会提交 因为本地缓存中 没有连接 hbase Sever
table.put(pu);
// 设置提交值 两种方法选择一种久就可以了
// 设置文件大小
// table.setWriteBufferSize(10*1024*1024);
// 设置条数
if (i % 300 == 0) {
// 提交
table.flushCommits();
}
// 强制提交剩下的数据
table.flushCommits();
}
}
public static void main(String[] args) throws IOException {
//获取hbase的配置文件对象
conf = HBaseConfiguration.create();
//设置conf的zk访问路径
conf.set("hbase.zookeeper.quorum", "hadoop01:2181,hadoop02:2181,hadoop03:2181");
//创建hbase连接
conn = ConnectionFactory.createConnection(conf);
// 获取dml的句柄
// 一个Htable对象 -- 一个表
table = (HTable) conn.getTable(TableName.valueOf("student:test_teable"));
// 调用方法插入数据
//insertOnData();
//insertListDatas();
insertBufferdatas();
}
}