springboot 整合hbase client

 

pom.xml引入依赖,核心内容如下

注意hbase 版本,跟你要连接的服务端保持一致


        org.springframework.boot
        spring-boot-starter-parent
        2.1.5.RELEASE
         




            org.apache.hbase
            hbase-shaded-client
            2.1.9

 

application.properties加入配置

##hbase所使用的zookeeper
hbase.config.hbase.zookeeper.quorum=host1,host2,host3
hbase.config.hbase.zookeeper.property.clientPort=2181

 

java配置

HBaseProperties.java

import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.Map;


@ConfigurationProperties(prefix = "hbase")
public class HBaseProperties {

    private Map config;

    public Map getConfig() {
        return config;
    }

    public void setConfig(Map config) {
        this.config = config;
    }
}

 

HBaseConfig.java


import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

@Configuration
@EnableConfigurationProperties(HBaseProperties.class)
public class HBaseConfig {

    private final HBaseProperties properties;

    public HBaseConfig(HBaseProperties properties) {
        this.properties = properties;
    }

    @Bean
    public Connection hbaseConnection() {
        Connection conn = null;
        try {
            conn = ConnectionFactory.createConnection(configuration());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        return conn;
    }


    public org.apache.hadoop.conf.Configuration configuration() {

        org.apache.hadoop.conf.Configuration configuration = HBaseConfiguration.create();

        Map config = properties.getConfig();
        Set keySet = config.keySet();
        for (String key : keySet) {
            configuration.set(key, config.get(key));
        }

        return configuration;
    }
}

 

如何使用

 

在需要操作hbase表的地方,注入hbaseConnection即可

@Autowired
private Connection hbaseConnection;


void dosomething(){

// 剩下的就是api的使用了,和shell命令都能对应上
Admin admin = hbaseConnection.getAdmin();
TableDescriptor tableDescriptor = TableDescriptorBuilder.newBuilder(...).build();
admin.createTable(tableDescriptor);

Table table = hbaseConnection.getTable(TableName.valueOf("tablename"));
table.put(put);
table.get(get);
table.getScanner(scan);

}

 

你可能感兴趣的:(大数据)