Hbase的相关学习

Hbase

简介(主要是介绍跟mysql不同)

1.mysql是关系型数据库,主键具有唯一性,Hbase是非关系型数据库

2.mysql底层是binlog( MySQL的二进制日志binlog可以说是MySQL最重要的日志,它记录了所有的DDL和DML语句(除了数据查询语句select),还有语句执行消耗的时间。binlog日志是二进制格式的,它不能使用查看文本工具的命令(比如,cat,vi等)查看,使用mysqlbinlog解析查看)

Hbase底层是hdfs(分布式文件存储)

3.mysql是行存储,hbase是列存储(我感觉有点抽象hhh,行存储的话可能会有很多字段是空的浪费空间,hbase就不会,他还可以多出几列来完全不影响hhh)

表格Hbase shell

jpsall查看所有进程

hbase shell 进去hbase

list 数据库表有哪些

create 'student','infor' 表名 + 列族名称

scan 表名 查询该表所有

(19条消息) HBase shell操作,看这一篇就够了莫叫石榴姐的博客-CSDN博客hbase shell 查询一条数据

 

表格api封装

HbaseCon.java

package com.atguigu;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;

import java.io.IOException;

public class HbaseCon {

  public static Connection Con = null;
  static {
      Configuration conf= new Configuration();

      conf.set("hbase.zookeeper.quorum","hadoop1,hadoop2,hadoop3");


      try {
          Con = ConnectionFactory.createConnection(conf);
      }catch (IOException e)
      {
          e.printStackTrace();
      }

  }

  public static void closeConn(){
      if(Con != null)
          try {
              Con.close();
          }catch (IOException e)
          {
              e.printStackTrace();
          }

  }

  public static void main(String[] args) {
      System.out.println(Con);

      closeConn();
  }
}

HbaseDDL.java

package com.atguigu;


import org.apache.hadoop.hbase.NamespaceDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;



public class HbaseDDL {

   public static Connection connection = HbaseCon.Con;

   /**
    * 创建命名空间
    * @param namespace
    * @throws IOException
    */
   public static void createNamespace(String namespace) throws IOException {
       //获取admin
       Admin admin = connection.getAdmin();


       //new NamespaceDescriptor()发现是一个私有的,我们考虑还有别的方法来获取对象,静态方法 ctrl + F12
       //建造者模式,手机需要加大内存,颜色,各种需求本质:丰富了构造器
       NamespaceDescriptor.Builder builder = NamespaceDescriptor.create(namespace);

       //添加需求
       builder.addConfiguration("user","aiguigu");

       //一个方法里面有多个异常,怎么处理,需要将不是本类的方法直接抛出去,是本类的单独写

       try {
           admin.createNamespace(builder.build());
      } catch (IOException e) {
           System.out.println("有相同的namespace");
           e.printStackTrace();
      }

       admin.close();
  }
   /**
    * 判断表格是否存在
    * @param namespace 命名空间名称
    * @param tableName 表格名称
    * @return 存不存在
    */
   public static boolean isTableExists(String namespace,String tableName) throws IOException {
       Admin admin = connection.getAdmin();

       boolean b = false;
       try {
           b = admin.tableExists(TableName.valueOf(namespace, tableName));
      } catch (IOException e) {
           System.out.println("");
           e.printStackTrace();
      }

       admin.close();

       return b;
  }

   /**
    * 创建表格
    * @param namespace 命名空间
    * @param tableName 表格名称
    * @param columnFamilys 列族
    */
   public static void createTable(String namespace,String tableName,String... columnFamilys) throws IOException {
       Admin admin = connection.getAdmin();

       //创建表格建造者
       TableDescriptorBuilder tableDescriptorBuilder = TableDescriptorBuilder.newBuilder(TableName.valueOf(namespace, tableName));

       //添加参数
       for(String c : columnFamilys)
      {
           ColumnFamilyDescriptorBuilder columnFamilyDescriptorBuilder = ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes(c));

           columnFamilyDescriptorBuilder.setMaxVersions(5);

           tableDescriptorBuilder.setColumnFamily(columnFamilyDescriptorBuilder.build());
      }

       try {
           admin.createTable(tableDescriptorBuilder.build());
      } catch (IOException e) {
           System.out.println("表格存在");
           e.printStackTrace();
      }

       admin.close();
  }


       /**
        * 修改表格中一个列族的版本
        * @param namespace 命名空间名称
        * @param tableName 表格名称
        * @param columnFamily 列族名称
        * @param version 版本
        */
       public static void modifyTable(String namespace ,String tableName,String columnFamily,int version) throws IOException {
       // 判断表格是否存在
       if (!isTableExists(namespace,tableName)){
           System.out.println("表格不存在无法修改");
           return;
      }
       // 1. 获取 admin
       Admin admin = connection.getAdmin();
       try {
           // 2. 调用方法修改表格
           // 2.0 获取之前的表格描述
           TableDescriptor descriptor =
                   admin.getDescriptor(TableName.valueOf(namespace, tableName));
           // 2.1 创建一个表格描述建造者
           // 如果使用填写 tableName 的方法 相当于创建了一个新的表格描述建造者 没有之前的信息
           // 如果想要修改之前的信息 必须调用方法填写一个旧的表格描述
           TableDescriptorBuilder tableDescriptorBuilder =
                   TableDescriptorBuilder.newBuilder(descriptor);
           // 2.2 对应建造者进行表格数据的修改
           ColumnFamilyDescriptor columnFamily1 =
                   descriptor.getColumnFamily(Bytes.toBytes(columnFamily));
           // 创建列族描述建造者
           // 需要填写旧的列族描述
           ColumnFamilyDescriptorBuilder
                   columnFamilyDescriptorBuilder =
                   ColumnFamilyDescriptorBuilder.newBuilder(columnFamily1);
           // 修改对应的版本
           columnFamilyDescriptorBuilder.setMaxVersions(version);

           tableDescriptorBuilder.modifyColumnFamily(columnFamilyDescriptorBuilder.build());
           admin.modifyTable(tableDescriptorBuilder.build());
      } catch (IOException e) {
           e.printStackTrace();
      }
       // 3. 关闭 admin
       admin.close();
  }

   /**
    * 删除表格
    * @param namespace 命名空间名称
    * @param tableName 表格名称
    * @return true 表示删除成功
    */
   public static boolean deleteTable(String namespace ,String
           tableName) throws IOException {
       // 1. 判断表格是否存在
       if (!isTableExists(namespace,tableName)){
           System.out.println("表格不存在 无法删除");
           return false;
      }
       // 2. 获取 admin
       Admin admin = connection.getAdmin();
       // 3. 调用相关的方法删除表格
       try {
           // HBase 删除表格之前 一定要先标记表格为不可以
           TableName tableName1 = TableName.valueOf(namespace,
                   tableName);
           admin.disableTable(tableName1);
           admin.deleteTable(tableName1);
      } catch (IOException e) {
           e.printStackTrace();
      }
       // 4. 关闭 admin
       admin.close();
       return true;
  }

   public static void main(String[] args) throws IOException {

       //创建链接名
       //createNamespace("aiguigu");

       //测试表格存在
       //System.out.println(isTableExists("bigdata", "student"));

       //测试创建表格
       //createTable("aiguigu","er","info","msg");

       //测试修改表格
       //modifyTable("aiguigu","student","oke",5);

       //测试删除表格
       //System.out.println(deleteTable("aiguigu", "student"));

       System.out.println(1);
  }



}

HbaseDML.java

package com.atguigu;


import com.atguigu.pojo.User;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.filter.CompareFilter;
import org.apache.hadoop.hbase.filter.Filter;
import org.apache.hadoop.hbase.filter.FilterList;
import org.apache.hadoop.hbase.filter.SingleColumnValueFilter;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

public class HbaseDML {


   public static Connection connection = com.atguigu.HbaseCon.Con;

   /**
    * 插入数据
    * @param namespace 命名空间名称
    * @param tableName 表格名称
    * @param rowKey 主键
    * @param columnFamily 列族名称
    * @param columnName 列名
    * @param value 值
    */
   public static void putCell(String namespace,String tableName,String rowKey, String columnFamily,String columnName,String value) throws IOException {
       // 1. 获取 table
       Table table = connection.getTable(TableName.valueOf(namespace, tableName));
       // 2. 调用相关方法插入数据
       // 2.1 创建 put 对象
       Put put = new Put(Bytes.toBytes(rowKey));
       // 2.2. 给 put 对象添加数据

       put.addColumn(Bytes.toBytes(columnFamily),Bytes.toBytes(columnName),Bytes.toBytes(value));
       // 2.3 将对象写入对应的方法
       try {
           table.put(put);
      } catch (IOException e) {
           e.printStackTrace();
      }
       // 3. 关闭 table
       table.close();
  }

   /**
    * 读取数据 读取对应的一行中的某一列
    *
    * @param namespace 命名空间名称
    * @param tableName 表格名称
    * @param rowKey 主键
    * @param columnFamily 列族名称
    * @param columnName 列名
    */
   public static void getCells(String namespace, String tableName,String rowKey, String columnFamily, String columnName) throws IOException {
       // 1. 获取 table
       Table table = connection.getTable(TableName.valueOf(namespace, tableName));
       // 2. 创建 get 对象
       Get get = new Get(Bytes.toBytes(rowKey));
       // 如果直接调用 get 方法读取数据 此时读一整行数据
       // 如果想读取某一列的数据 需要添加对应的参数
       get.addColumn(Bytes.toBytes(columnFamily),Bytes.toBytes(columnName));
       // 设置读取数据的版本
       get.readAllVersions();
       try {
           // 读取数据 得到 result 对象
           Result result = table.get(get);
           // 处理数据
           Cell[] cells = result.rawCells();
           // 测试方法: 直接把读取的数据打印到控制台
           // 如果是实际开发 需要再额外写方法 对应处理数据
           for (Cell cell : cells) {
               // cell 存储数据比较底层
               String value = Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength());

               System.out.println(value);
          }
      } catch (IOException e) {
           e.printStackTrace();
      }
       // 关闭 table
       table.close();
  }

   /**
    * 删除 column 数据
    *
    * @param nameSpace
    * @param tableName
    * @param rowKey
    * @param family
    * @param column
    * @throws IOException
    */
   public static void deleteColumn(String nameSpace, String tableName, String rowKey, String family, String column) throws IOException {
       // 1.获取 table
       Table table = connection.getTable(TableName.valueOf(nameSpace,
               tableName));
       // 2.创建 Delete 对象
       Delete delete = new Delete(Bytes.toBytes(rowKey));
       // 3.添加删除信息
       // 3.1 删除单个版本
       delete.addColumn(Bytes.toBytes(family),Bytes.toBytes(column));
       // 3.2 删除所有版本
       delete.addColumns(Bytes.toBytes(family),
               Bytes.toBytes(column));
       // 3.3 删除列族
// delete.addFamily(Bytes.toBytes(family));
       // 3.删除数据
       table.delete(delete);
       // 5.关闭资源
       table.close();
  }

   public static void add(User user) throws IOException {

       long time=new Date().getTime();
       Date dates=new Date(time);
       SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddhhmmss");
       String times=sdf.format(dates);

       putCell("aiguigu","er",times,"info","institutions",user.getInstitutions());
       putCell("aiguigu","er",times,"info","manager",user.getManager());
       putCell("aiguigu","er",times,"info","addrress",user.getAddress());
       putCell("aiguigu","er",times,"info","region",user.getRegion());

       putCell("aiguigu","er",times,"msg","content",user.getContent());
       putCell("aiguigu","er",times,"msg","attribute",user.getAttribute());
  }

   public static List<User> getDate(String nameSpace,String tableName,String columnFamily,Map<String,String> coulmnAndValue) throws IOException {
       Table table = connection.getTable(TableName.valueOf(nameSpace,tableName));
       Scan scan = new Scan();
       List<Filter> filters = new ArrayList<Filter>();
       coulmnAndValue.forEach((k,v)->{
           Filter filter = new SingleColumnValueFilter(Bytes.toBytes(columnFamily),Bytes.toBytes(k),
                   CompareFilter.CompareOp.EQUAL,Bytes.toBytes(v));
           filters.add(filter);
      });
       FilterList filterList = new FilterList(filters);
       scan.setFilter(filterList);
       List<User> list=new ArrayList<>();
       User bean=null;
       try {
           // 读取多行数据 获得 scanner
           ResultScanner scanner = table.getScanner(scan);
           // result 来记录一行数据 cell 数组
           // ResultScanner 来记录多行数据 result 的数组
           for (Result result : scanner) {
               Cell[] cells = result.rawCells();
               List<String> lvalue=new ArrayList<>();
               for (Cell cell : cells){

                   String value = Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength());
                   lvalue.add(value);
              }
               bean =new User(lvalue.get(1),lvalue.get(2),lvalue.get(0),lvalue.get(3),lvalue.get(4),lvalue.get(5));
               System.out.println(bean.toString());
               list.add(bean);
          }
      } catch (IOException e) {
           e.printStackTrace();
      }
       // 3. 关闭 table
       table.close();


       /*ResultScanner results = table.getScanner(scan);
       Map<String,Result> map = new HashMap<>();
       for(Result result:results){
           String key = new String(result.getRow());
           map.put(key,result);
       }
       List<Map.Entry> list = new ArrayList<>();
       list.addAll(map.entrySet());*/
       return list;
  }



   public static void main(String[] args) throws IOException {
       //测试添加数据
       /*putCell("aiguigu","er","2004","info","institutions","石家庄铁道大学3");
       putCell("aiguigu","er","2004","info","manager","软工3");
       putCell("aiguigu","er","2004","info","addrress","胜利北接到3");
       putCell("aiguigu","er","2004","info","region","长安区3");

       putCell("aiguigu","er","2004","msg","content","大飒飒打撒3");
       putCell("aiguigu","er","2004","msg","attribute","企业3");*/

       //测试查找数据
       //getCells("aiguigu","er","2001","info","manager");

       //测试删除
       //deleteColumn("aiguigu","er","6001","msg","attribute");

       //测试查询
       Map<String, String> map = new HashMap<String, String>();
       map.put("institutions","石家庄铁道大学2");
       map.put("manager","软工2");
       List<User> date = getDate("aiguigu","er", "info", map);
       System.out.println(date.size());
       System.out.println(date);

       System.out.println(11);

       com.atguigu.HbaseCon.closeConn();
  }


}

 

代码学习

1.封装,hbaseDML封装好了,但是操作的时候有namespace,tablename,cloumnfamily,cloumn等等,好多东西,

public static void putCell
(String namespace,String tableName,String rowKey, String columnFamily,String columnName,String value)
   
   
public static void add(User user) throws IOException {

       long time=new Date().getTime();
       Date dates=new Date(time);
       SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddhhmmss");
       String times=sdf.format(dates);

       putCell("aiguigu","er",times,"info","institutions",user.getInstitutions());
       putCell("aiguigu","er",times,"info","manager",user.getManager());
       putCell("aiguigu","er",times,"info","addrress",user.getAddress());
       putCell("aiguigu","er",times,"info","region",user.getRegion());

       putCell("aiguigu","er",times,"msg","content",user.getContent());
       putCell("aiguigu","er",times,"msg","attribute",user.getAttribute());
  }

将这个转化成我们熟悉的类,而不是单纯的一条条插入,你如果写到servlet中那肯定是不行滴,就像Control层,就是跳转页面接受参数的,方法要在Service层写好

2.layui组件的查询在下面显示表格

//servlet方法
public  void search(HttpServletRequest request, HttpServletResponse response) throws IOException {
       //1.格式
       request.setCharacterEncoding("utf-8");
       response.setContentType("text/html;charset=UTF-8");

       //2.获取前端值
       String institutions = request.getParameter("institutions");
       String manager = request.getParameter("manager");
       String address = request.getParameter("address");
       String region = request.getParameter("region");
       //System.out.println("institutions:"+institutions+"manager:"+manager+"region:"+region+"address:"+address);

       //3.检验过程
       Map<String, String> map = new HashMap<String, String>();
       if(institutions != "")
       map.put("institutions",institutions);

       if(manager != "")
       map.put("manager",manager);

       if(address != "")
       map.put("address",address);

       if(region != "")
       map.put("region",region);

       //System.out.println("1111111111111111");
       List<User> date = HbaseDML.getDate("aiguigu", "er", "info", map);
       //System.out.println("222222222222");
       //System.out.println(date.size());
       
       //4.将后台数据放前端
       JSONArray json = new JSONArray();
       for (int i = 0; i < date.size(); i ++)
      {
           JSONObject ob = new JSONObject();
           ob.put("institutions",date.get(i).getInstitutions());
           ob.put("manager",date.get(i).getManager());
           ob.put("address",date.get(i).getAddress());
           ob.put("region",date.get(i).getRegion());
           ob.put("attribute",date.get(i).getAttribute());
           ob.put("content",date.get(i).getContent());
           json.add(ob);
      }
       JSONObject ob=new JSONObject();
       ob.put("code", 0);
       ob.put("msg", "");
       ob.put("count",date.size());
       ob.put("data",json);
       PrintWriter out = response.getWriter();
       out.write(ob.toString());

  }
 
 
一些小点:ctrl +F12查看所有方法
shift + shift 也可以查找
ctrl alt t test方法
posted @   爽爽子的秃头生活  阅读(8)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示