java使用Hbase时的连接池实现以及查询操作

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

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.Get;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Table;

public class HBasePoolUtils {
	private static Configuration conf = null;
	// 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
	private static ExecutorService executor = null;
	private static Connection conn = null;

	static {
		try {
			conf = HBaseConfiguration.create();
			conf.set("hbase.zookeeper.quorum", "hadoop-80-01,hadoop-80-01,hadoop-80-01,hadoop-80-01,hadoop-80-01");
			conf.set("hbase.zookeeper.property.clientPort", "2181");
			conf.set("hbase.defaults.for.version.skip", "true");
			executor = Executors.newFixedThreadPool(20);
			conn = ConnectionFactory.createConnection(conf, executor);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static Connection getConn() {
		return conn;
	}
	/**
	 * 查询操作
	 * @tableName 表名
	 * @index 索引
	 * @author zhouzp 
	 * @date 2019年1月8日
	 */
	@SuppressWarnings({ "unchecked"})
	public static Map<String, Object> queryData(String tableName, String index) {
		Table table = null;
		try {
			table = conn.getTable(TableName.valueOf(tableName));
			Get get = new Get(MD5Util.encodeMD5(index).getBytes());
			Result rst = table.get(get);
			byte[] value = rst.getValue("fbase".getBytes(), "data".getBytes());
			if (value != null && value.length > 0) {
				return (Map<String, Object>) JsonUtil.toObject(new String(value), Map.class);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (table != null)
					table.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
}

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值