一、HBase部署安装

1.HBase下载地址:Apache HBase – Apache HBase Downloads

2.解压启动(进入压缩包bin目录),本次演示的是macOS系统启动演示(windows系统启动命令:./start-hbase.cmd)

./start-hbase.sh

 

3. 浏览器访问http://IP:16010/master-status出现如下页面表示启动成功

 

 4.HBase控制台操作

4.1进入控制台:

1. 进入HBase安装包的bin目录
2. ./hbase shell

4.2.Hbase控制台常用命令总结如下

1.进入hbase shell命令行: ./hbase shell  (bin目录下执行)
2.扫描全表全部数据: scan '表名'
3.查看连接的用户: whomi
4.创建表: create ‘表名’,’列族名1’,’列族名2’
5.查看数据库中全部的表: list
6.describe查看表结构: describe '表名'
7.删除表: drop '表名'
8.插入数据: put ‘表名’,’列族名1:列名1’,’值’
9.get获取数据: get '表名',行,列族,列
10.count计算表的行数: count '表名'
11.删除整行数据: deleteall '表名','行号' 
12.删除全表数据: truncate '表名'

 4.3.HBase表结构以及参数说明

/**
 * @param tableName    表名
 * @param rowKey       行主键
 * @param columnFamily 列族
 * @param column       列名
 * @param value        列值
 */

 5.代码如下

5.1.maven依赖(本项目引用的Springboot版本是2.5.6)

 <dependency>
     <groupId>org.apache.hbase</groupId>
     <artifactId>hbase-client</artifactId>
     <version>2.2.3</version>
 </dependency>
  <!--添加Swagger3依赖-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>
        <!--knife4j(接口文档)-->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-spring-boot-starter</artifactId>
            <version>3.0.3</version>
        </dependency>

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

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.68</version>
        </dependency>

        <!-- hutool工具类-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.3.2</version>
        </dependency>

yml配置


server:
  port: 8081
#swagger文档开启/关闭
springfox:
  documentation:
    auto-startup: true
#knife4j
knife4j:
  production: false # 开启/屏蔽文档资源

#HBase
hbase:
  config:
    hbase:
      zookeeper:
        property:
          clientPort: 2181
        quorum: 127.0.0.1

5.2基础配置

import org.apache.hadoop.conf.Configuration;
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 java.io.IOException;
import java.util.Map;

/**
 * @author :jerry
 * @date :Created in 2022/11/7 09:54
 * @description:
 * @version: V1.1
 */
@EnableConfigurationProperties(HbaseProperties.class)
@org.springframework.context.annotation.Configuration
public class HbaseConfig {
    private final HbaseProperties prop;

    public HbaseConfig(HbaseProperties properties) {
        this.prop = properties;
    }

    @Bean
    public Configuration configuration() {
        Configuration configuration = HBaseConfiguration.create();
        Map<String, String> config = prop.getConfig();
        config.forEach(configuration::set);
        return configuration;
    }

    @Bean
    public Connection getConnection() throws IOException {
        return ConnectionFactory.createConnection(configuration());
    }
}

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

import java.util.Map;

/**
 * @author :jerry
 * @date :Created in 2022/11/7 09:52
 * @description:
 * @version: V1.1
 */
@ConfigurationProperties(prefix = "hbase")
public class HbaseProperties {
    private Map<String, String> config;

    public Map<String, String> getConfig() {
        return config;
    }

    public void setConfig(Map<String, String> config) {
        this.config = config;
    }
}

swagger配置

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
/**
 * @author :jerry
 * @date :Created in 2022/5/28 10:30
 * @description:
 * @version: V1.1
 *  *Swagger3API文档的配置
 *  knife4j文档地址(端口号根据自己项目配置): http://localhost:8081/doc.html#
 *  swagger文档地址(端口号根据自己项目配置):http://localhost:8081/swagger-ui/index.html#/
 */
@Configuration
@EnableOpenApi
@EnableKnife4j
public class Swagger3Config {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.OAS_30)
//                .groupName("webApi")
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.cetc.controller"))
                .paths(PathSelectors.any())
                .build();
    }


    @Bean
    public ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("SwaggerUI接口文档")
                .description("接口文档Swagger-Bootstrap版")
                .termsOfServiceUrl("http://localhost:8081/swagger-ui/index.html#/")
                .contact(new Contact("jerry","http://localhost:8081/doc.html#", "13258239832@163.com"))
                .version("1.0")
                .license("jerry")
                .build();
    }
}

5.3.控制层代码

import com.cetc.dto.HBaseDto;
import com.cetc.service.HbaseService;
import com.cetc.util.CommonResultVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

/**
 * @author :jerry
 * @date :Created in 2022/11/7 10:39
 * @description:
 * @version: V1.1
 */
@Api(tags = "habse接口测试")
@RestController
@RequestMapping("/hbase")
public class HbaseController {
    @Autowired
    private HbaseService hbaseService;

    /**
     * 创建表
     * tableName:表名
     * columnFamilies:列族
     */
    @ApiOperation(value = "创建表")
    @GetMapping("/createTable")
    public CommonResultVo createTable(String tableName, String[] columnFamilies) throws IOException {
        return hbaseService.createTable(tableName, columnFamilies);
    }

    @ApiOperation(value = "新增/修改")
    @PostMapping("/saveOrUpdate")
    public CommonResultVo saveOrUpdate(@RequestBody List<HBaseDto> list) throws IOException {
        for (HBaseDto hBaseDto : list) {
            hbaseService.saveOrUpdate(hBaseDto);
        }
        return CommonResultVo.success();
    }

    @ApiOperation(value = "删除表/行/列族/列")
    @PostMapping("/deleteTable")
    public CommonResultVo deleteTable(@RequestBody HBaseDto hBaseDto) throws IOException {
        return hbaseService.deleteTable(hBaseDto);
    }


//    @ApiOperation(value = "判断表是否已经存在")
//    @GetMapping("/tableExists")
//    public CommonResultVo tableExists(String tableName) throws IOException {
//        boolean flag = hbaseService.tableExists(tableName);
//        return CommonResultVo.success(flag);
//    }

    @ApiOperation(value = "高级条件查询")
    @PostMapping("/scanRowData")
    public CommonResultVo scanRowData(@RequestBody HBaseDto hBaseDto) throws IOException {
        return hbaseService.scanRowData(hBaseDto);
    }

    @ApiOperation(value = "分页查询")
    @PostMapping("/scanPageRow")
    public CommonResultVo scanPageRow(@RequestBody HBaseDto hBaseDto) throws IOException {
        return hbaseService.scanPageRow(hBaseDto);
    }
//
//    @ApiOperation(value = "总行数")
//    @PostMapping("/countRow")
//    public CommonResultVo countRow(@RequestBody HBaseDto hBaseDto) throws IOException {
//        return CommonResultVo.success(hbaseService.countRow(hBaseDto));
//    }


}

5.4数据逻辑层代码

import com.cetc.dto.HBaseDto;
import com.cetc.util.CommonResultVo;

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

/**
 * @author :jerry
 * @date :Created in 2022/11/7 10:01
 * @description:
 * @version: V1.1
 */
public interface HbaseService {

    //创建表
    CommonResultVo createTable(String tableName, String... columnFamilies) throws IOException;

    void saveOrUpdate(HBaseDto hBaseDto) throws IOException;

    CommonResultVo deleteTable(HBaseDto hBaseDto) throws IOException;

    //判断表是否已经存在,这里使用间接的方式来实现
    boolean tableExists(String tableName) throws IOException;

    CommonResultVo scanRowData(HBaseDto hBaseDto) throws IOException;

    CommonResultVo scanPageRow(HBaseDto hBaseDto) throws IOException;

    long countRow(HBaseDto hBaseDto) throws IOException;

}
import com.cetc.config.HbaseConfig;
import com.cetc.dto.HBaseDto;
import com.cetc.service.HbaseService;
import com.cetc.util.CommonResultVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.filter.RowFilter;
import org.apache.hadoop.hbase.filter.SubstringComparator;
import org.apache.hadoop.hbase.util.Bytes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.*;

/**
 * @author :jerry
 * @date :Created in 2022/11/7 09:58
 * @description:
 * @version: V1.1
 */
@Service
@Slf4j
public class HbaseServiceImpl implements HbaseService {
    @Autowired
    private HbaseConfig config;

    private static Connection connection = null;
    private static Admin admin = null;

    @PostConstruct
    private void init() {
        if (connection != null) {
            return;
        }
        try {
            connection = ConnectionFactory.createConnection(config.configuration());
            admin = connection.getAdmin();
        } catch (IOException e) {
            log.error("HBase create connection failed:", e);
        }
    }

    /**
     * 根据表名/列族创建表
     *
     * @param tableName      表名
     * @param columnFamilies 列族名
     * @throws IOException 异常
     */
    @Override
    public CommonResultVo createTable(String tableName, String... columnFamilies) throws IOException {
        try {
            TableName name = TableName.valueOf(tableName);
            boolean isExists = this.tableExists(tableName);
            if (isExists) {
                throw new TableExistsException(tableName + "is exists!");
            }
            TableDescriptorBuilder descriptorBuilder = TableDescriptorBuilder.newBuilder(name);
            List<ColumnFamilyDescriptor> columnFamilyList = new ArrayList<>();
            for (String columnFamily : columnFamilies) {
                ColumnFamilyDescriptor columnFamilyDescriptor = ColumnFamilyDescriptorBuilder
                        .newBuilder(columnFamily.getBytes()).build();
                columnFamilyList.add(columnFamilyDescriptor);
            }
            descriptorBuilder.setColumnFamilies(columnFamilyList);
            TableDescriptor tableDescriptor = descriptorBuilder.build();
            admin.createTable(tableDescriptor);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return CommonResultVo.success();
    }


    /**
     * 保存修改
     */
    @Override
    public void saveOrUpdate(HBaseDto dto) throws IOException {
        String tableName = dto.getTableName();  //表名
        String rowKey = dto.getRow();       //行主键
        String columnFamily = dto.getColumnFamily();        //列族
        String columns = dto.getColumn();        //列
        String value = dto.getValue();
        Long msgtimeUtime = dto.getMsgtimeUtime();

        Table table = connection.getTable(TableName.valueOf(tableName));
        Put put = new Put(Bytes.toBytes(rowKey));
        put.addColumn(Bytes.toBytes(columnFamily), Bytes.toBytes(columns), Bytes.toBytes(value));
        //设置时间戳
        put.setTimestamp(msgtimeUtime != null ? msgtimeUtime : System.currentTimeMillis());
        table.put(put);
    }


    /**
     * 删除
     * tableName    表名
     * rowKey       行主键
     * columnFamily 列族
     * column       列
     */
    @Override
    public CommonResultVo deleteTable(HBaseDto hBaseDto) throws IOException {
        boolean isExists = this.tableExists(hBaseDto.getTableName());
        if (!isExists) {
            return CommonResultVo.failed("表" + hBaseDto.getTableName() + "不存在");
        }
        String tableName = hBaseDto.getTableName();
        Table table = connection.getTable(TableName.valueOf(tableName));


        //删除列
        String columnFamily = hBaseDto.getColumnFamily();   //列族
        String row = hBaseDto.getRow();     //行主键
        String column = hBaseDto.getColumn();       //列
        if (StringUtils.isNotBlank(column) && StringUtils.isNotBlank(row)
                && StringUtils.isNotBlank(columnFamily) && StringUtils.isNotBlank(column)) {
            Delete delete = new Delete(row.getBytes());
            delete.addColumn(Bytes.toBytes(columnFamily), Bytes.toBytes(column));
            table.delete(delete);
            return CommonResultVo.success("列:" + column + "删除成功");
        }

        //删除列族
        if (StringUtils.isNotBlank(columnFamily) && StringUtils.isNotBlank(row)) {
            Delete delete = new Delete(row.getBytes());
            delete.addFamily(Bytes.toBytes(columnFamily));
            table.delete(delete);
            return CommonResultVo.success("列族:" + columnFamily + "删除成功");
        }

        //删除行主键
        if (StringUtils.isNotBlank(row)) {
            Delete delete = new Delete(row.getBytes());
            table.delete(delete);
        }

        //删除表
        if (StringUtils.isNotBlank(hBaseDto.getTableName())) {
            TableName name = TableName.valueOf(hBaseDto.getTableName());
            admin.disableTable(name);
            admin.deleteTable(name);
            return CommonResultVo.success("表:" + tableName + "删除成功");
        }

        return CommonResultVo.success();
    }

    /**
     * 判断表是否已经存在,这里使用间接的方式来实现
     *
     * @param tableName 表名
     * @return 真or假
     * @throws IOException 异常
     */
    @Override
    public boolean tableExists(String tableName) throws IOException {
        TableName[] tableNames = admin.listTableNames();
        if (tableNames != null && tableNames.length > 0) {
            for (int i = 0; i < tableNames.length; i++) {
                if (tableName.equals(tableNames[i].getNameAsString())) {
                    return true;
                }
            }
        }
        return false;
    }


    /**
     * 扫描指定列在指定行键范围的值
     */
    public CommonResultVo scanRowData(HBaseDto hBaseDto) throws IOException {
        List<Map<String, Object>> lis = new ArrayList<>();

        if (StringUtils.isBlank(hBaseDto.getTableName())) {
            CommonResultVo.failed("表名不能为null");
        }
        boolean flagStu = this.tableExists(hBaseDto.getTableName());
        if (!flagStu) {
            CommonResultVo.failed("表" + hBaseDto.getTableName() + "不存在");
        }
        Table table = connection.getTable(TableName.valueOf(hBaseDto.getTableName()));
        //指定起始行键和结束行键
        Scan scan = new Scan();
        //根据列族查询
        if (StringUtils.isNotBlank(hBaseDto.getColumnFamily())) {
            scan.addFamily(Bytes.toBytes(hBaseDto.getColumnFamily()));
        }
        //起始or结束行
        if (StringUtils.isNotBlank(hBaseDto.getStartRow()) || StringUtils.isNotBlank(hBaseDto.getStopRow())) {
            new Scan(Bytes.toBytes(hBaseDto.getStartRow()), Bytes.toBytes(hBaseDto.getStopRow()));
        }
        //指定行
        if (StringUtils.isNotBlank(hBaseDto.getRow())) {
            RowFilter rowFilter = new RowFilter(CompareOperator.EQUAL, new SubstringComparator(hBaseDto.getRow()));
            scan.setFilter(rowFilter);
        }
        //扫描指定的列
        if (StringUtils.isNotBlank(hBaseDto.getColumn())) {
            scan.addColumn(Bytes.toBytes(hBaseDto.getColumnFamily()), Bytes.toBytes(hBaseDto.getColumn()));
        }

        //时间戳精确查询
        if (!Objects.isNull(hBaseDto.getMsgtimeUtime())) {
            scan.setTimestamp(hBaseDto.getMsgtimeUtime());
        }

        //时间戳区间查询
        if ((!Objects.isNull(hBaseDto.getStartTime())) && (!Objects.isNull(hBaseDto.getEndTime()))) {
            scan.setTimeRange(hBaseDto.getStartTime(), hBaseDto.getEndTime());
        }
        ResultScanner resultScanner = table.getScanner(scan);

        for (Result result : resultScanner) {

            Map<String, Object> map = new HashMap<>();
            String flag = "0";
            for (Cell cell : result.rawCells()) {
                String rowVal = Bytes.toString(CellUtil.cloneRow(cell));
                if (!flag.equals(rowVal)) {
                    map = new HashMap<>();
                }
                flag = rowVal;
                String columns = Bytes.toString(CellUtil.cloneQualifier(cell));
                String value = Bytes.toString(CellUtil.cloneValue(cell));
                map.put(columns, value);
                map.put("row", rowVal);
                if (flag.equals(rowVal)) {
                    lis.remove(map);
                }
                lis.add(map);
//                System.out.println("行键:" + Bytes.toString(CellUtil.cloneRow(cell)) +
//                        ", 列簇:" + Bytes.toString(CellUtil.cloneFamily(cell)) +
//                        ", 列:" + Bytes.toString(CellUtil.cloneQualifier(cell)) +
//                        ", 值:" + Bytes.toString(CellUtil.cloneValue(cell)));
            }
        }
        return CommonResultVo.success(lis);
    }

    /**
     * 分页查询
     */
    @Override
    public CommonResultVo scanPageRow(HBaseDto hBaseDto) throws IOException {


        List<Map<String, Object>> lis = new ArrayList<>();

        if (StringUtils.isBlank(hBaseDto.getTableName())) {
            CommonResultVo.failed("表名不能为null");
        }
        boolean flagStu = this.tableExists(hBaseDto.getTableName());
        if (!flagStu) {
            CommonResultVo.failed("表" + hBaseDto.getTableName() + "不存在");
        }
        Table table = connection.getTable(TableName.valueOf(hBaseDto.getTableName()));
        //指定起始行键和结束行键
        Scan scan = new Scan();
        //根据列族查询
        if (StringUtils.isNotBlank(hBaseDto.getColumnFamily())) {
            scan.addFamily(Bytes.toBytes(hBaseDto.getColumnFamily()));
        }
        //起始or结束行
        if (StringUtils.isNotBlank(hBaseDto.getStartRow()) || StringUtils.isNotBlank(hBaseDto.getStopRow())) {
            new Scan(Bytes.toBytes(hBaseDto.getStartRow()), Bytes.toBytes(hBaseDto.getStopRow()));
        }
        //指定行
        if (StringUtils.isNotBlank(hBaseDto.getRow())) {
            RowFilter rowFilter = new RowFilter(CompareOperator.EQUAL, new SubstringComparator(hBaseDto.getRow()));
            scan.setFilter(rowFilter);
        }
        //扫描指定的列
        if (StringUtils.isNotBlank(hBaseDto.getColumn())) {
            scan.addColumn(Bytes.toBytes(hBaseDto.getColumnFamily()), Bytes.toBytes(hBaseDto.getColumn()));
        }

        //时间戳精确查询
        if (!Objects.isNull(hBaseDto.getMsgtimeUtime())) {
            scan.setTimestamp(hBaseDto.getMsgtimeUtime());
        }

        //时间戳区间查询
        if ((!Objects.isNull(hBaseDto.getStartTime())) && (!Objects.isNull(hBaseDto.getEndTime()))) {
            scan.setTimeRange(hBaseDto.getStartTime(), hBaseDto.getEndTime());
        }

        //current 当前页     pageSize:条数
        scan.setCaching(hBaseDto.getPageSize() * hBaseDto.getCurrent() > 6000 ? 6000 : hBaseDto.getPageSize() * hBaseDto.getCurrent());


        ResultScanner resultScanner = table.getScanner(scan);
        Result[] results;
        int pageCount = 0;
        while ((results = resultScanner.next(hBaseDto.getPageSize())).length != 0) {
            pageCount++;
            if (pageCount < hBaseDto.getCurrent()) {
                continue;
            }
            for (Result rs : results) {
                //在此处解析获取数据
//                alls.add(rs);
                Map<String, Object> map = new HashMap<>();
                String flag = "0";
                for (Cell cell : rs.rawCells()) {
                    String rowVal = Bytes.toString(CellUtil.cloneRow(cell));
                    if (!flag.equals(rowVal)) {
                        map = new HashMap<>();
                    }
                    flag = rowVal;
                    String columns = Bytes.toString(CellUtil.cloneQualifier(cell));
                    String value = Bytes.toString(CellUtil.cloneValue(cell));
                    map.put(columns, value);
                    map.put("row", rowVal);
                    if (flag.equals(rowVal)) {
                        lis.remove(map);
                    }
                    lis.add(map);
//                System.out.println("行键:" + Bytes.toString(CellUtil.cloneRow(cell)) +
//                        ", 列簇:" + Bytes.toString(CellUtil.cloneFamily(cell)) +
//                        ", 列:" + Bytes.toString(CellUtil.cloneQualifier(cell)) +
//                        ", 值:" + Bytes.toString(CellUtil.cloneValue(cell)));
                }
            }
            break;
        }
        return CommonResultVo.success(lis);
    }

    /**
     * 获取HBase的总行数
     */
    @Override
    public long countRow(HBaseDto hBaseDto) throws IOException {

        Table table = connection.getTable(TableName.valueOf(hBaseDto.getTableName()));
        Scan scan = new Scan();
        scan.setCaching(20);
        scan.addFamily(Bytes.toBytes(hBaseDto.getColumnFamily()));
        ResultScanner scanner = table.getScanner(scan);
        long rowCount = 0;

        Result[] results;
        while ((results = scanner.next(hBaseDto.getPageSize())).length != 0) {
            rowCount+=results.length;
        }
        return rowCount;
    }

}

5.5.封装的实体对象

import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

/**
 * @author :jerry
 * @date :Created in 2022/11/7 15:50
 * @description:结果集封装
 * @version: V1.1
 */
@Data
public class HBaseDto {
    /**
     * @param tableName    表名
     * @param rowKey       行主键
     * @param columnFamily 列族
     * @param column       列
     * @param value        值
     * @throws
     */
    @ApiModelProperty("行")
    private String row;

    @ApiModelProperty("列族")
    private String columnFamily;

    @ApiModelProperty("列")
    private String column;

    @ApiModelProperty("列值")
    private String value;

    @ApiModelProperty("表名")
    private String tableName;

    @ApiModelProperty("开始行")
    private String startRow;

    @ApiModelProperty("结束行")
    private String stopRow;

    @ApiModelProperty("报文时间")
    private Long msgtimeUtime;

    @ApiModelProperty("开始时间")
    private Long startTime;

    @ApiModelProperty("结束时间")
    private Long endTime;

    @ApiModelProperty("页码")
    private Integer current;

    @ApiModelProperty("条数")
    private Integer pageSize;
}

5.6.工具类:

import lombok.Builder;
import lombok.Getter;
import lombok.Setter;

/**
 * @author dudycoco
 * @version 1.0.0
 * @ClassName CommonResultVo.java
 * @Description 结果返回公共类
 * @createTime 2022年09月19日 00:16
 */
@Getter
@Setter
@Builder
public class CommonResultVo<T> {

    private int code;
    private String message;
    private T data;

    protected CommonResultVo() {
    }

    protected CommonResultVo(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    /**
     * 成功返回结果
     *
     */
    public static <T> CommonResultVo<T> success() {
        return new CommonResultVo<T>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), null);
    }

    /**
     * 成功返回结果
     *
     * @param data 获取的数据
     */
    public static <T> CommonResultVo<T> success(T data) {
        return new CommonResultVo<T>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), data);
    }

    /**
     * 成功返回结果
     *
     * @param data 获取的数据
     * @param  message 提示信息
     */
    public static <T> CommonResultVo<T> success(T data, String message) {
        return new CommonResultVo<T>(ResultCode.SUCCESS.getCode(), message, data);
    }

    /**
     * 失败返回结果
     * @param resultCode 错误码
     */
    public static <T> CommonResultVo<T> failed(ResultCode resultCode) {
        return new CommonResultVo<T>(resultCode.getCode(), resultCode.getMessage(), null);
    }

    /**
     * 失败返回结果
     * @param resultCode 错误码
     * @param message 错误信息
     */
    public static <T> CommonResultVo<T> failed(ResultCode resultCode, String message) {
        return new CommonResultVo<T>(resultCode.getCode(), message, null);
    }

    /**
     * 失败返回结果
     * @param message 提示信息
     */
    public static <T> CommonResultVo<T> failed(String message) {
        return new CommonResultVo<T>(ResultCode.FAILED.getCode(), message, null);
    }

    /**
     * 失败返回结果
     */
    public static <T> CommonResultVo<T> failed() {
        return failed(ResultCode.FAILED);
    }
}

import lombok.Getter;
import lombok.Setter;

/**
 * @author dudycoco
 * @version 1.0.0
 * @ClassName ResultCode.java
 * @Description 返回值code
 * @createTime 2022年09月19日 00:22
 */

public enum ResultCode {
    SUCCESS(0, "操作成功"),
    FAILED(-1, "操作失败"),
    VALIDATE_FAILED(404, "参数检验失败"),
    UNAUTHORIZED(401, "暂未登录或token已经过期"),
    FORBIDDEN(403, "没有相关权限");

    @Setter
    @Getter
    private int code;

    @Setter
    @Getter
    private String message;

    private ResultCode(int code, String message) {
        this.code = code;
        this.message = message;
    }


}

更多HBase知识点可以查看:Hbase 入门详解_Se7en_InfoQ写作社区

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐