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

这篇具有很好参考价值的文章主要介绍了Hbase-技术文档-spring-boot整合使用hbase--简单操作增删改查--提供封装高可用的模版类。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

使用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!!!!文章来源地址https://www.toymoban.com/news/detail-727391.html

到了这里,关于Hbase-技术文档-spring-boot整合使用hbase--简单操作增删改查--提供封装高可用的模版类的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包赞助服务器费用

相关文章

  • HBase--技术文档--基本概念--《快速扫盲》

    HBase--技术文档--基本概念--《快速扫盲》

    Apache HBase – Apache HBase™ Home 阿里云hbase 云数据库HBase_大数据存储_订单风控_数据库-阿里云 云数据库 HBase-阿里云帮助中心         HBase是一种分布式、可扩展、支持海量数据存储的NoSQL数据库。它基于 Hadoop ,采用列式存储方式,可以提供实时计算和分布式访问。HBase的数

    2024年02月11日
    浏览(10)
  • Hbase--技术文档--单机docker基础安装(非高可用)

    Hbase--技术文档--单机docker基础安装(非高可用)

    配置Linux服务器华为云耀云服务器之docker安装,以及环境变量安装 java (虚拟机一样适用)_docker配置java环境变量_一单成的博客-CSDN博客 说明:         本文章安装方式为学习使用的单体hbase项目。主要是 学习!学习!         在docker中直接拉取镜像运行,将端口映射出来

    2024年02月11日
    浏览(8)
  • Java技术-接口文档-Swagger2&Swagger3&接口文档UI整合

    Java技术-接口文档-Swagger2&Swagger3&接口文档UI整合

    目录 一、Swagger2完整用法 1.POM依赖 2.接口类 3.实现类 4.托管静态资源 5.接口文档配置 6.生产环境关闭接口文档 7.Swagger3页面效果 二、Swagger3完整用法 三、Swagger整合Knife4jUi 1.POM依赖 2.接口类 3.实现类 4.托管静态资源 5.接口文档配置 6.生产环境关闭接口文档 四、注释和参数讲解

    2024年02月16日
    浏览(13)
  • Hbase-技术文档-java.net.UnknownHostException: 不知道这样的主机。 (e64682f1b276)

    Hbase-技术文档-java.net.UnknownHostException: 不知道这样的主机。 (e64682f1b276)

            在使用spring-boot操作habse的时候,在对habse进行操作的时候出现这个问题。。 报错信息如下: java.net.UnknownHostException: e64682f1b276 错误 java.net.UnknownHostException: 不知道这样的主机 (e64682f1b276) 意味着你的程序无法解析对应的主机名 (host name)。这可能是因为你提供的主机名无

    2024年02月11日
    浏览(7)
  • websocket--技术文档--spring后台+vue基本使用

    websocket--技术文档--spring后台+vue基本使用

            给大家分享一个可以用来进行测试websocket的网页,个人觉得还是挺好用的. WebSocket在线测试工具 还有一个小家伙 ApiPost也可以进行使用websocket的测试。 在Spring Boot中使用WebSocket建立服务端,可以按照以下步骤进行: 确保的Spring Boot项目已经创建并配置好。 在项目的

    2024年02月09日
    浏览(26)
  • 首选Spring MVC实战架构文档:GitHub上率先发布,引领技术革新

    首选Spring MVC实战架构文档:GitHub上率先发布,引领技术革新

    Spring MVC是一个基于Java的Web框架,它遵循MVC设计模式,实现了请求驱动类型的轻量级架构。通过将Model、View和Controller分离,Spring MVC将Web层的职责进行了清晰的划分,使得复杂的Web应用程序变得结构清晰、易于开发和维护。 其中,DispatcherServlet是Spring MVC框架的核心组件。作为

    2024年02月02日
    浏览(9)
  • Spring Boot整合Spring Fox生成Swagger文档

    Spring Boot整合Spring Fox生成Swagger文档

    Springfox是一个用于在Spring应用程序中生成Swagger文档的开源库。它提供了一组注解和工具,可以将你的API代码和文档整合在一起,方便生成和展示API的Swagger文档。 使用Springfox,你可以在Spring Boot项目中集成Swagger,并通过Swagger UI查看和测试API。它提供了一些注解,如 @Api 、 @

    2024年02月08日
    浏览(5)
  • 【Java核心知识】spring boot整合Mybatis plus + Phoenix 访问Hbase与使用注意

    为什么Phoenix能让开发者通过SQL访问Hbase而不必使用原生的方式?引用Phoenix官网上的一句话:SQL is just a way of expressing what you want to get not how you want to get it . 即SQL不是一种数据操作技术,而是一种特殊的表达方式。只是表示你需要什么而不是你如何获得。 一个集成了Phoenix的Hb

    2024年02月15日
    浏览(12)
  • 【Spring Boot】SpringBoot 优雅整合Swagger Api 自动生成文档

    【Spring Boot】SpringBoot 优雅整合Swagger Api 自动生成文档

    Swagger 是一套 RESTful API 文档生成工具,可以方便地生成 API 文档并提供 API 调试页面。 而 Spring Boot 是一款非常优秀的 Java Web 开发框架,它可以非常方便地构建 Web 应用程序。 在本文中,我们将介绍如何使用 Swagger 以及如何在 Spring Boot 中整合 Swagger 。 首先,在 pom.xml 文件中添

    2023年04月22日
    浏览(10)
  • Flutter--常用技术文档

    配置 清华大学flutter镜像 export PUB_HOSTED_URL=https://mirrors.tuna.tsinghua.edu.cn/dart-pub export FLUTTER_STORAGE_BASE_URL=https://mirrors.tuna.tsinghua.edu.cn/flutter 社区镜象 export PUB_HOSTED_URL=https://pub.flutter-io.cn export FLUTTER_STORAGE_BASE_URL=https://storage.flutter-io.cn 混合开发 问题 解决 iOS、Flutter混合开发 ➜ Na

    2024年01月16日
    浏览(19)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包