源码:
package HbaseOperation; import com.alibaba.fastjson.JSON; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.*; import org.apache.hadoop.hbase.client.*; import org.apache.hadoop.hbase.util.Bytes; import org.springframework.stereotype.Service; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; @Service public class HbaseOperationServiceImpl implements HbaseOperationService { public static final String FAMILY_NAME = "f1"; public static final String FAMILY_NAME_F2 = "f2"; public static final byte[] CF = Bytes.toBytes(FAMILY_NAME); private static Connection connection = null; private static volatile HbaseOperationServiceImpl instance; private HbaseOperationServiceImpl() { String ip = "192.168.184.128"; String port = "2181"; try { Configuration conf = HBaseConfiguration.create(); conf.set("hbase.zookeeper.quorum", ip); conf.set("hbase.zookeeper.property.clientPort", port); connection = ConnectionFactory.createConnection(conf); System.out.println("创建connection!"); } catch (IOException e) { e.printStackTrace(); } } public static HbaseOperationServiceImpl getIstance() { // 定义一个共有的静态方法,返回该类型实例 if (instance == null) { // 对象实例化时与否判断(不使用同步代码块,instance不等于null时,直接返回对象,提高运行效率) synchronized (HbaseOperationServiceImpl.class) { // 同步代码块(对象未初始化时,使用同步代码块,保证多线程访问时对象在第一次创建后,不再重复被创建) if (instance == null) { // 未初始化,则初始instance变量 instance = new HbaseOperationServiceImpl(); } } } return instance; }
}
测试代码:
public class test_hbase_oper { public static void main(String args[]) { HbaseOperationServiceImpl hbaseOperationObj = HbaseOperationServiceImpl.getIstance(); }