欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringBoot整合Hbase的实现示例

程序员文章站 2022-03-31 14:37:40
简介当单表数据量过大的时候,关系性数据库会出现性能瓶颈,这时候我们就可以用nosql,比如hbase就是一个不错的解决方案。接下来是用spring整合hbase的实际案例,且在最后会给出整合中可能会出...

简介

当单表数据量过大的时候,关系性数据库会出现性能瓶颈,这时候我们就可以用nosql,比如hbase就是一个不错的解决方案。接下来是用spring整合hbase的实际案例,且在最后会给出整合中可能会出现的问题,以及解决方案。这里我是用本地windows的idea,与局域网的伪分布hbase集群做的连接,其中hbase集群包括的组件有:jdk1.8、hadoop2.7.6、zookeeper3.4.10、hbase2.0.1,因为这里只是开发环境,所以做一个伪分布的就好,之后部署的时候再按生产环境要求来即可

整合步骤

目录结构

SpringBoot整合Hbase的实现示例

pom.xml

这里要导入hbase连接所需要包,需要找和你hbase版本一致的包

<dependency>
 <groupid>org.apache.hbase</groupid>
 <artifactid>hbase-client</artifactid>
 <version>2.0.1</version>
</dependency>

hbase-site.xml

我是用的配置文件连接方法,这个配置文件你在hbase的安装目录下的conf目录就可以找到,然后你直接把它复制到项目的resources目录下就好,当然你也可以用application.properties配置文件外加注入和代码的方式代替这个配置文件

hbaseconfig.java

这里因为只需连接hbase就没连接hadoop,如果要连接hadoop,windows下还要下载winutils.exe工具,后面会介绍

@configuration
public class hbaseconfig {
 @bean
 public hbaseservice gethbaseservice() {
  //设置临时的hadoop环境变量,之后程序会去这个目录下的\bin目录下找winutils.exe工具,windows连接hadoop时会用到
  //system.setproperty("hadoop.home.dir", "d:\\program files\\hadoop");
  //执行此步时,会去resources目录下找相应的配置文件,例如hbase-site.xml
  org.apache.hadoop.conf.configuration conf = hbaseconfiguration.create();
  return new hbaseservice(conf);
 }
}

hbaseservice.java

这是做连接后的一些操作可以参考之后自己写一下

public class hbaseservice {
 private logger log = loggerfactory.getlogger(hbaseservice.class);
 /**
  * 管理员可以做表以及数据的增删改查功能
  */
 private admin admin = null;
 private connection connection = null;
 public hbaseservice(configuration conf) {
  try {
   connection = connectionfactory.createconnection(conf);
   admin = connection.getadmin();
  } catch (ioexception e) {
   log.error("获取hbase连接失败!");
  }
 }
 /**
  * 创建表 create <table>, {name => <column family>, versions => <versions>}
  */
 public boolean creattable(string tablename, list<string> columnfamily) {
  try {
   //列族column family
   list<columnfamilydescriptor> cfdesc = new arraylist<>(columnfamily.size());
   columnfamily.foreach(cf -> {
    cfdesc.add(columnfamilydescriptorbuilder.newbuilder(
      bytes.tobytes(cf)).build());
   });
   //表 table
   tabledescriptor tabledesc = tabledescriptorbuilder
     .newbuilder(tablename.valueof(tablename))
     .setcolumnfamilies(cfdesc).build();
   if (admin.tableexists(tablename.valueof(tablename))) {
    log.debug("table exists!");
   } else {
    admin.createtable(tabledesc);
    log.debug("create table success!");
   }
  } catch (ioexception e) {
   log.error(messageformat.format("创建表{0}失败", tablename), e);
   return false;
  } finally {
   close(admin, null, null);
  }
  return true;
 }
 /**
  * 查询所有表的表名
  */
 public list<string> getalltablenames() {
  list<string> result = new arraylist<>();
  try {
   tablename[] tablenames = admin.listtablenames();
   for (tablename tablename : tablenames) {
    result.add(tablename.getnameasstring());
   }
  } catch (ioexception e) {
   log.error("获取所有表的表名失败", e);
  } finally {
   close(admin, null, null);
  }
  return result;
 }
 /**
  * 遍历查询指定表中的所有数据
  */
 public map<string, map<string, string>> getresultscanner(string tablename) {
  scan scan = new scan();
  return this.querydata(tablename, scan);
 }
 /**
  * 通过表名及过滤条件查询数据
  */
 private map<string, map<string, string>> querydata(string tablename, scan scan) {
  // <rowkey,对应的行数据>
  map<string, map<string, string>> result = new hashmap<>();
  resultscanner rs = null;
  //获取表
  table table = null;
  try {
   table = gettable(tablename);
   rs = table.getscanner(scan);
   for (result r : rs) {
    // 每一行数据
    map<string, string> columnmap = new hashmap<>();
    string rowkey = null;
    // 行键,列族和列限定符一起确定一个单元(cell)
    for (cell cell : r.listcells()) {
     if (rowkey == null) {
      rowkey = bytes.tostring(cell.getrowarray(), cell.getrowoffset(), cell.getrowlength());
     }
     columnmap.put(
       //列限定符
       bytes.tostring(cell.getqualifierarray(), cell.getqualifieroffset(), cell.getqualifierlength()),
       //列族
       bytes.tostring(cell.getvaluearray(), cell.getvalueoffset(), cell.getvaluelength()));
    }
    if (rowkey != null) {
     result.put(rowkey, columnmap);
    }
   }
  } catch (ioexception e) {
   log.error(messageformat.format("遍历查询指定表中的所有数据失败,tablename:{0}", tablename), e);
  } finally {
   close(null, rs, table);
  }
  return result;
 }
 /**
  * 为表添加或者更新数据
  */
 public void putdata(string tablename, string rowkey, string familyname, string[] columns, string[] values) {
  table table = null;
  try {
   table = gettable(tablename);
   putdata(table, rowkey, tablename, familyname, columns, values);
  } catch (exception e) {
   log.error(messageformat.format("为表添加 or 更新数据失败,tablename:{0},rowkey:{1},familyname:{2}", tablename, rowkey, familyname), e);
  } finally {
   close(null, null, table);
  }
 }
 private void putdata(table table, string rowkey, string tablename, string familyname, string[] columns, string[] values) {
  try {
   //设置rowkey
   put put = new put(bytes.tobytes(rowkey));
   if (columns != null && values != null && columns.length == values.length) {
    for (int i = 0; i < columns.length; i++) {
     if (columns[i] != null && values[i] != null) {
      put.addcolumn(bytes.tobytes(familyname), bytes.tobytes(columns[i]), bytes.tobytes(values[i]));
     } else {
      throw new nullpointerexception(messageformat.format(
        "列名和列数据都不能为空,column:{0},value:{1}", columns[i], values[i]));
     }
    }
   }
   table.put(put);
   log.debug("putdata add or update data success,rowkey:" + rowkey);
   table.close();
  } catch (exception e) {
   log.error(messageformat.format(
     "为表添加 or 更新数据失败,tablename:{0},rowkey:{1},familyname:{2}",
     tablename, rowkey, familyname), e);
  }
 }
 /**
  * 根据表名获取table
  */
 private table gettable(string tablename) throws ioexception {
  return connection.gettable(tablename.valueof(tablename));
 }

 /**
  * 关闭流
  */
 private void close(admin admin, resultscanner rs, table table) {
  if (admin != null) {
   try {
    admin.close();
   } catch (ioexception e) {
    log.error("关闭admin失败", e);
   }
   if (rs != null) {
    rs.close();
   }
   if (table != null) {
    rs.close();
   }
   if (table != null) {
    try {
     table.close();
    } catch (ioexception e) {
     log.error("关闭table失败", e);
    }
   }
  }
 }
}

hbaseapplicationtests.java

@runwith(springjunit4classrunner.class)
@springboottest
class hbaseapplicationtests {
 @resource
 private hbaseservice hbaseservice;
 //测试创建表
 @test
 public void testcreatetable() {
  hbaseservice.creattable("test_base", arrays.aslist("a", "back"));
 }
 //测试加入数据
 @test
 public void testputdata() {
  hbaseservice.putdata("test_base", "000001", "a", new string[]{
    "project_id", "varname", "coefs", "pvalues", "tvalues",
    "create_time"}, new string[]{"40866", "mob_3", "0.9416",
    "0.0000", "12.2293", "null"});
  hbaseservice.putdata("test_base", "000002", "a", new string[]{
    "project_id", "varname", "coefs", "pvalues", "tvalues",
    "create_time"}, new string[]{"40866", "idno_prov", "0.9317",
    "0.0000", "9.8679", "null"});
  hbaseservice.putdata("test_base", "000003", "a", new string[]{
    "project_id", "varname", "coefs", "pvalues", "tvalues",
    "create_time"}, new string[]{"40866", "education", "0.8984",
    "0.0000", "25.5649", "null"});
 }
 //测试遍历全表
 @test
 public void testgetresultscanner() {
  map<string, map<string, string>> result2 = hbaseservice.getresultscanner("test_base");
  system.out.println("-----遍历查询全表内容-----");
  result2.foreach((k, value) -> {
   system.out.println(k + "--->" + value);
  });
 }
}

运行结果

hbase数据库查询结果

SpringBoot整合Hbase的实现示例

idea的遍历结果

SpringBoot整合Hbase的实现示例

报错与解决方案

报错一

SpringBoot整合Hbase的实现示例

解决方案:

这是参数配置的有问题,如果你是用hbase-site.xml配置文件配置的参数,那么检查它,用代码配置就检查代码参数

报错二

SpringBoot整合Hbase的实现示例

解决方案:

更改windows本地hosts文件,c:\windows\system32\drivers\etc\hosts,添加hbase服务所在主机地址与主机名称,这里你如果保存不了hosts文件,把它拉出到桌面改好再拉回即可

报错三

SpringBoot整合Hbase的实现示例

解决方案:

这是因为在windows下连接hadoop需要一个叫winutils.exe的工具,并且从源代码可知,它会去读你windows下的环境变量,如果你不想在本地设置,可以用方法system.setproperty()设置实时环境变量,另外,如果你只用hbase,其实这个报错并不影响你使用hbase服务

代码地址

https://github.com/xiaoxiamo/springboot_hbase

到此这篇关于springboot整合hbase的实现示例的文章就介绍到这了,更多相关springboot整合hbase内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!