Hbase-技术文档-spring-boot整合使用hbase--简单操作增删改查--提供封装高可用的模版类

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

使用spring-boot项目来整合使用hbase。

引入依赖

<dependency>
		<groupId>org.apache.hbase</groupId>
		<artifactId>hbase-client</artifactId>
		<version>2.4.3</version>
</dependency>

依赖声明表示将把Apache HBase客户端库的2.4.3版本添加到项目中。HBase是一个分布式、可扩展的大数据存储系统它基于Google的Bigtable模型并使用了Hadoop分布式文件系统作为底层存储。HBase客户端库是用于与HBase数据库进行交互的工具库提供了一组API用于执行CRUD创建、读取、更新、删除操作以及其他与HBase相关的功能。

通过在项目中添加这个依赖您将能够使用HBase客户端库的API来与HBase数据库进行通信执行数据的增删改查操作等。这样您就可以在Java应用程序中方便地使用HBase的功能了。

封装程度0.5在下面有一个高可用的封装模版类需要的向下直接看封装程度max!!!

书写配置文件

application.properties

hbase.config.hbase.zookeeper.quorum=ip地址
hbase.config.hbase.zookeeper.property.clientPort=2181

application.yml

hbase:
  config:
    hbase:
      zookeeper:
        quorum: ip地址
        property:
          clientPort: 2181

配置文件对应java类书写配置类HbaseProperties.java

import java.util.Map;
 
import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "hbase")
public class HbaseProperties {
	private Map<String,String> config;
	
	public void setConfig(Map<String, String> config) {
		this.config = config;
	}
	
	public Map<String, String> getConfig() {
		return config;
	}
}

配置文件HbaseConfig.java

import java.io.IOException;
import java.util.Map;
 
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
@EnableConfigurationProperties(HbaseProperties.class)
public class HbaseConfig {
	private final HbaseProperties props;
	
	public HbaseConfig(HbaseProperties props) {
		this.props = props;
	}
	
	@Bean
	public org.apache.hadoop.conf.Configuration configuration(){
		org.apache.hadoop.conf.Configuration conf = HBaseConfiguration.create();
		Map<String, String> config = props.getConfig();
		config.forEach(conf::set);
		return conf;
	}
	
	@Bean
	public Connection getConnection() throws IOException{
		return ConnectionFactory.createConnection(configuration());
	}
	
	@Bean
	public HBaseAdmin hBaseAdmin() throws IOException {
		return (HBaseAdmin) getConnection().getAdmin();
	}
}

创建一个Hbase的模版类用于执行与Hbase的交互操作

@Service
public class HBaseTemplate {
    @Autowired
    private Configuration configuration;

    private Connection connection;

    @PostConstruct
    public void init() {
        connection = ConnectionFactory.createConnection(configuration);
    }

    public void putData(Put put) throws IOException {
        Table table = connection.getTable(TableName.valueOf("table_name"));
        table.put(put);
        table.close();
    }
}

请将table_name替换为您要操作的HBase表的实际名称。 

使用封装好的模版类来使用进行操作

@Autowired
private HBaseTemplate hBaseTemplate;

public void doSomethingWithHBase() {
    // 创建Put对象包含要插入的数据...
    Put put = new Put(Bytes.toBytes("row_key"));
    // 设置要插入的列和值...
    hBaseTemplate.putData(put);
}

这是一个基本的整合示例可以根据您的具体需求进行调整和扩展。注意这只是一个基本的示例您可能还需要处理异常、关闭连接等其他操作。

高度封装max

注意

此方式不需要配置文件如果需要可以自己去写一个配置类即可配置类的写法在上面

1、导入依赖

<!--        hbase-->
        <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-client</artifactId>
            <version>2.4.3</version>
        </dependency>

2、封装模版类

模版类中有很详细的注解和说明

package com.adn.common.util;


import lombok.extern.log4j.Log4j2;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.filter.CompareFilter;
import org.apache.hadoop.hbase.filter.SingleColumnValueFilter;
import org.apache.hadoop.hbase.filter.SubstringComparator;
import org.apache.hadoop.hbase.util.Bytes;


import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Filter;

@Component
@Log4j2
public class HBaseTemplate {
    private Configuration configuration; // Hadoop配置对象用于创建HBase配置
    private Connection connection; // HBase连接对象用于与HBase建立连接


    /**
     * 如果需要就可以去写一个时加载的配置类读取配置中的数据
     * */
    @PostConstruct
    public void init() throws IOException {
        configuration = HBaseConfiguration.create();
        configuration.set("hbase.zookeeper.quorum", "部署hbase的ip地址");
        configuration.setInt("hbase.zookeeper.property.clientPort", 2181);
        // 等等其他HBase的配置设置
        connection = ConnectionFactory.createConnection(configuration);
    }
    /**
     * 插入数据
     * 注意如果向一个不存在的表中添加数据的时候会直接新建这个表
     * 所以在向有的表中进行添加数据的时候要确定表名是否存在
     * */
//    public void put(String tableName, String rowKey, String columnFamily, String column, String value) throws IOException {
//        // 对指定表执行插入数据操作
//        Table table = connection.getTable(TableName.valueOf(tableName)); // 获取指定表的Table对象
//        Put put = new Put(Bytes.toBytes(rowKey)); // 创建Put对象设置行键
//        put.addColumn(Bytes.toBytes(columnFamily), Bytes.toBytes(column), Bytes.toBytes(value)); // 设置列族、列和值
//        table.put(put); // 执行插入操作
//        table.close(); // 关闭表连接
//    }
    public void put(String tableName, String rowKey, String columnFamily, String column, String value)  {
        // 对指定表执行插入数据操作
        Table table = null; // 获取指定表的Table对象
        try {
            table = connection.getTable(TableName.valueOf(tableName));
        } catch (IOException e) {
            throw new RuntimeException("连接"+tableName+"表出现异常"+e);
        }
        Put put = new Put(Bytes.toBytes(rowKey)); // 创建Put对象设置行键
        put.addColumn(Bytes.toBytes(columnFamily), Bytes.toBytes(column), Bytes.toBytes(value)); // 设置列族、列和值
        try {
            table.put(put); // 执行插入操作
        } catch (IOException e) {
            try {
                log.info("新建表操作"+tableName);
                createTableIfNotExists(tableName, columnFamily);
                this.put(tableName,rowKey,columnFamily,column,value);
                //使用递归调用方法
                return;
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
        try {
            table.close(); // 关闭表连接
        } catch (IOException e) {
            throw new RuntimeException("关闭表连接出现错误"+e);
        }
    }
    /**
     * 新建表操作
     * */
    private void createTableIfNotExists(String tableName, String columnFamily) throws IOException {
        try (Admin admin = connection.getAdmin()) {
            TableName hbaseTable = TableName.valueOf(tableName);

            if (!admin.tableExists(hbaseTable)) {
                HTableDescriptor tableDescriptor = new HTableDescriptor(hbaseTable);
                tableDescriptor.addFamily(new HColumnDescriptor(Bytes.toBytes(columnFamily)));

                admin.createTable(tableDescriptor);
            }
        }
    }
    /**
     * 查找获取
     * */
    public String get(String tableName, String rowKey, String columnFamily, String column) {
        // 对指定表执行查找数据操作
        Table table = null; // 获取指定表的Table对象
        try {
            table = connection.getTable(TableName.valueOf(tableName));
        } catch (IOException e) {
            throw new RuntimeException("连接表出现异常"+e);
        }
        Get get = new Get(Bytes.toBytes(rowKey)); // 创建Get对象设置行键
        Result result = null; // 执行查找操作获取Result对象
        try {
            result = table.get(get);
        } catch (IOException e) {
            throw new RuntimeException("获取返回值出现异常"+e);
        }
        byte[] valueBytes = result.getValue(Bytes.toBytes(columnFamily), Bytes.toBytes(column)); // 获取指定列的值
        try {
            table.close(); // 关闭表连接
        } catch (IOException e) {
            throw new RuntimeException("关闭连接出现问题"+e);
        }
        return Bytes.toString(valueBytes); // 将值转换为字符串并返回
    }
    /**
     * 删除一条数据
     * */
    public void delete(String tableName, String rowKey) throws IOException {
        // 对指定表执行删除数据操作
        Table table = connection.getTable(TableName.valueOf(tableName)); // 获取指定表的Table对象
        Delete delete = new Delete(Bytes.toBytes(rowKey)); // 创建Delete对象设置行键
        table.delete(delete); // 执行删除操作
        table.close(); // 关闭表连接
    }
    /**
     * 删除表
     * */
    public void deleteTable(String tableName) throws IOException {
        Admin admin = connection.getAdmin(); // 获取 Admin 对象
        TableName table = TableName.valueOf(tableName); // 获取表名
        if (admin.tableExists(table)) { // 检查表是否存在
            admin.disableTable(table); // 禁用表
            admin.deleteTable(table); // 删除表
            System.out.println("成功删除表: " + tableName);
        } else {
            System.out.println("表 " + tableName + " 不存在");
        }
        admin.close(); // 关闭 Admin 连接
    }


    // 其他操作如 scan 方法等

    // 关闭连接的方法
    public void close() throws IOException {
        connection.close(); // 关闭HBase连接
    }

    /**
     * 条件查询方法根据指定的列族、列和值执行查询操作
     *
     * @param tableName    表名
     * @param columnFamily 列族名
     * @param column       列名
     * @param value        值
     * @return 匹配的行数据列表
     * @throws IOException 发生 IO 错误时抛出异常
     */
    public List<String> findbyConditions(String tableName, String columnFamily, String column, String value) throws IOException {
        List<String> results = new ArrayList<>(); // 创建结果列表
        Table table = connection.getTable(TableName.valueOf(tableName)); // 获取指定表的 Table 对象
        Filter filter = (Filter) new SingleColumnValueFilter(Bytes.toBytes(columnFamily), // 创建单列值过滤器
                Bytes.toBytes(column), CompareFilter.CompareOp.EQUAL, new SubstringComparator(value));
        Scan scan = new Scan(); // 创建扫描对象
        scan.setFilter((org.apache.hadoop.hbase.filter.Filter) filter); // 设置扫描过滤器
        ResultScanner scanner = table.getScanner(scan); // 获取结果扫描器
        for (Result result : scanner) {
            StringBuilder row = new StringBuilder(); // 创建字符串构建器
            row.append(Bytes.toString(result.getRow())).append(": "); // 拼接行键
            for (Cell cell : result.listCells()) {
                String family = Bytes.toString(cell.getFamilyArray(), cell.getFamilyOffset(), cell.getFamilyLength()); // 获取列族
                String qualifier = Bytes.toString(cell.getQualifierArray(), cell.getQualifierOffset(),
                        cell.getQualifierLength()); // 获取列名
                String cellValue = Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()); // 获取值
                row.append(family).append(":").append(qualifier).append("=").append(cellValue).append(", "); // 拼接行数据
            }
            results.add(row.toString()); // 将行数据添加到结果列表
        }
        table.close(); // 关闭表连接
        return results; // 返回结果列表
    }

    /**
     * 全表查询方法返回表中所有行的数据列表
     *
     * @param tableName 表名
     * @return 所有行的数据列表
     * @throws IOException 发生 IO 错误时抛出异常
     */
    public List<String> allTheTable(String tableName) throws IOException {
        List<String> rows = new ArrayList<>(); // 创建行列表
        Table table = connection.getTable(TableName.valueOf(tableName)); // 获取指定表的 Table 对象
        Scan scan = new Scan(); // 创建扫描对象
        ResultScanner scanner = table.getScanner(scan); // 获取结果扫描器
        for (Result result : scanner) {
            StringBuilder row = new StringBuilder(); // 创建字符串构建器
            row.append(Bytes.toString(result.getRow())).append(": "); // 拼接行键
            for (Cell cell : result.listCells()) {
                String family = Bytes.toString(cell.getFamilyArray(), cell.getFamilyOffset(), cell.getFamilyLength()); // 获取列族
                String qualifier = Bytes.toString(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength()); // 获取列名
                String value = Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()); // 获取值
                row.append(family).append(":").append(qualifier).append("=").append(value).append(", "); // 拼接行数据
            }
            rows.add(row.toString()); // 将行数据添加到行列表
        }
        table.close(); // 关闭表连接
        return rows; // 返回行列表
    }

}

示例service,不知道如何调用的课参考使用

package com.adn.service;

import com.adn.common.User;
import com.adn.common.util.HBaseTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
/**
 * 示例使用
 * */
@Component
public class UserHBaseRepository {
    @Autowired
    private HBaseTemplate  hbaseTemplate;

    /**
     * 表名
     * */
    private final String TABLE_NAME = "users";
    /**
     *列族
     * */
    private final String COLUMN_FAMILY = "info";

    public void createUser(String userId, String name, int age, String email) throws IOException {
        hbaseTemplate.put(TABLE_NAME, userId, COLUMN_FAMILY, "name", name);
        hbaseTemplate.put(TABLE_NAME, userId, COLUMN_FAMILY, "age", String.valueOf(age));
        hbaseTemplate.put(TABLE_NAME, userId, COLUMN_FAMILY, "email", email);
    }

    public User getUser(String userId) throws IOException {
        String name = hbaseTemplate.get(TABLE_NAME, userId, COLUMN_FAMILY, "name");
        String ageStr = hbaseTemplate.get(TABLE_NAME, userId, COLUMN_FAMILY, "age");
        int age = Integer.parseInt(ageStr);
        String email = hbaseTemplate.get(TABLE_NAME, userId, COLUMN_FAMILY, "email");

        // 构造User对象并返回
        return new User(userId, name, age, email);
    }

    public void updateUser(String userId, String name, int age, String email) throws IOException {
        hbaseTemplate.put(TABLE_NAME, userId, COLUMN_FAMILY, "name", name);
        hbaseTemplate.put(TABLE_NAME, userId, COLUMN_FAMILY, "age", String.valueOf(age));
        hbaseTemplate.put(TABLE_NAME, userId, COLUMN_FAMILY, "email", email);
    }

    public void deleteUser(String userId) throws IOException {
        hbaseTemplate.delete(TABLE_NAME, userId);
    }
}

实例controller

package com.adn.controller;

import com.adn.common.User;
import com.adn.service.UserHBaseRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
public class UserController {
    @Autowired
    UserHBaseRepository service;


    /**
     * 新增数据
     *String userId, String name, int age, String email
     */
    @GetMapping("new/{userId}/{name}/{age}/{email}")
    public void newuser(@PathVariable String userId,@PathVariable String name,@PathVariable int age,@PathVariable String email){
        try {
            service.createUser(userId,name,age,email);
        } catch (IOException e) {
            System.out.println("新增出现异常");
            throw new RuntimeException(e);
        }
    }

    /**
     * 查询数据根据id查看数据
     * */
    @GetMapping("findById/{userId}")
    public User findById(@PathVariable String userId){
        try {
            return service.getUser(userId);
        } catch (IOException e) {
            System.out.println("查询出现异常");
            throw new RuntimeException(e);
        }
    }

}

快去尝试一下8

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: Spring