- application.yml添加配置
hbase:
zookeeper:
quorum: zkip
parent: /hbase(默认)
client:
username:用户名
password:密码
- 创建config
@org.springframework.context.annotation.Configuration
public class HbaseConfig {
private static final Logger log = LoggerFactory.getLogger(HbaseConfig.class);
private static Configuration conf = null;
// 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
private static Connection conn = null;
private static String threadPoolName = "hbasePool";// 线程池名称
private static int corePoolSize = 10; // 核心线程数
private static int maximumPoolSize = 20; //最大线程数
private static int queueSize = 50; //队列容量
private static ExecutorService executor = null;
@Value("${hbase.zookeeper.quorum}")
private String quorum;
@Value("${hbase.zookeeper.parent}")
private String parent;
@Value("${hbase.client.username}")
private String username;
@Value("${hbase.client.password}")
private String password;
@PostConstruct
public void initHbase() {
log.error("Hbase初始化->开始初始化Hbase连接,quorum:{},parent:{},username:{},password:{}", quorum, parent,username,password);
try {
conf = HBaseConfiguration.create();
conf.set("hbase.zookeeper.quorum", quorum);
conf.set("zookeeper.znode.parent", parent);
conf.set("hbase.cluster.distributed", "true");
conf.set("hbase.client.username", username);
conf.set("hbase.client.password", password);
executor = ThreadPoolConfig.getExecutorService(threadPoolName, corePoolSize, maximumPoolSize, queueSize);
conn = ConnectionFactory.createConnection(conf, executor);
log.error("Hbase初始化->初始化Hbase连接成功,quorum:{},parent:{},username:{},password:{}", quorum, parent,username,password);
} catch (IOException e) {
e.printStackTrace();
log.error("Hbase初始化->初始化Hbase连接成功失败,quorum:{},parent:{},username:{},password:{}", quorum, parent,username,password);
}
}
public static Connection getConn() {
return conn;
}
- 创建工具类
@Configuration
public class HbaseUtil {
private static final Logger log = LoggerFactory.getLogger(HbaseUtil.class);
public Connection getConn() {
Connection connection = null;
try {
connection = HbaseConfig.getConn();
admin = connection.getAdmin();
} catch (Exception e) {
e.printStackTrace();
log.error("创建hbase连接异常", e);
}
return connection;
}
//查询所有表
public TableName[] showTables() throws Exception {
//实例化HBaseAdmin对象
TableName[] tableNames = admin.listTableNames();
return tableNames;
}
}
4.controller层进行查询
@Resource
private HbaseUtil hbaseUtil;
@RequestMapping("/test")
public String test() {
TableName[] tableNames = hbaseUtil.showTables();
for (TableName tableName : tableNames) {
System.out.println(tableName.getNameAsString());
}}
最后运行项目就可以得到查询结果
|