栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

使用Java操作HBase(增,删,改,查操作)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Java操作HBase(增,删,改,查操作)

目录

在这里我用的是idea操作的

一、配置

1.首先确保HBase集群已经开启

2.配置hosts文件

 3、创建maven项目,在pom.xml文件中添加如下依赖项

4.配置log4j.properties文件

二、连接增删改查

1.连接测试类

 2.创建表

3.添加数据

4.查询指定行键数据

5.查询全表数据

6.查询表的行数

 7.查询已存在表

8.删除指定行数据

9.删除表


在这里我用的是idea操作的

一、配置

1.首先确保HBase集群已经开启
[root@hadoop ~]# jps
2761 HQuorumPeer
2137 ResourceManager
7114 Jps
2858 HMaster
1691 NameNode
1789 DataNode
2237 NodeManager
2943 HRegionServer
1983 SecondaryNameNode

上面所有节点都有

2.配置hosts文件

在你所在电脑配置你的hadoop集群信息,所以需要找到并修改hosts文件:

hosts的目录:C:WindowsSystem32driversetc

在这里我的伪分布式下的,修改hosts文件时需要打开所有权限,才能保存

使用记事本打开,修改后并保存

在文档最后一行加上IP空格主机名

任务管理器中输入ping 主机名

C:Users>ping hadoop
192.168.171.151 的 Ping 统计信息:
    数据包: 已发送 = 4,已接收 = 4,丢失 = 0 (0% 丢失),
往返行程的估计时间(以毫秒为单位):
    最短 = 0ms,最长 = 1ms,平均 = 0ms

 3、创建maven项目,在pom.xml文件中添加如下依赖项


    4.0.0

    com.lenovo
    0406
    1.0-SNAPSHOT

    
        8
        8
    

    
  
     jdk.tools   
     jdk.tools  
     1.8  
     system  
     C:/Program Files/Java/jdk1.8.0_91/lib/tools.jar  
  
  
  
   
     org.apache.hadoop
     hadoop-common
     2.7.3
 
  
   
     org.apache.hbase
     hbase-it
     1.3.1
     pom
 
    

4.配置log4j.properties文件

将log4j.properties文件拷贝到src/main/resources目录下,这样方便我们看到执行过程

log4j.properties文件路径在hadoop安装包里面:hadoop-2.7.3etchadooplog4j.properties

二、连接增删改查

1.连接测试类
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.junit.Test;

import java.io.IOException;

    
public class Demo {
    @Test
    public void test(){
        //获取配置对象
        Configuration con = new Configuration();
        con.set("hbase.zookeeper.quorum","IP地址");
        //获取连接
        try {
            Connection conn = ConnectionFactory.createConnection(con);
            System.out.println(conn);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

运行结果

 2.创建表
public static void main(String[] args) {
    new Demo().createTable("demo","userinfo");
    }
public void createTable(String tableName, String familyName) {
        //获取配置对象
        Configuration con = new Configuration();
        con.set("hbase.zookeeper.quorum", "ip地址");
        //获取连接
        Connection conn = null;
        Admin admin = null;
        try {
            conn = ConnectionFactory.createConnection(con);
            //拿到admin
            admin = conn.getAdmin();
            //获取表格描述器
            HTableDescriptor hTableDescriptor = new HTableDescriptor(TableName.valueOf(tableName));
            //添加列簇
            hTableDescriptor.addFamily(new HColumnDescriptor(familyName));
            //执行创建操作
            admin.createTable(hTableDescriptor);
            //关流

            System.out.println("创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                admin.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                conn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

运行结果:

  

HBase中的结果:

hbase(main):001:0> list
TABLE                                                                                                                                                          
demo                                                                                                                                                                  
1 row(s) in 0.3300 seconds
=> ["demo"]

3.添加数据
  
public static void main(String[] args) {
        boolean result = new Demo().addOneData("demo", "张三", "753159");//1001的数据
//        boolean result = new Demo().addOneData("demo", "lisi", "752159");//1002的数据
//        boolean result = new Demo().addOneData("demo", "王五", "762159");//1003的数据
        System.out.println(result);
    }
public boolean addOneData(String tableName,String userName,String passWord){
        //获取配置对象
        Configuration con = new Configuration();
        con.set("hbase.zookeeper.quorum","IP地址");
        Connection conn = null;
        Table table = null;
        //获取连接
        try {
            conn = ConnectionFactory.createConnection(con);
            //获取表的信息
            table = conn.getTable(TableName.valueOf(tableName));
            //设置行键
            Put put = new Put("1001".getBytes());
            //设置列的标识 以及列值
            put.addColumn("userinfo".getBytes(),"username".getBytes(),userName.getBytes());
            put.addColumn("userinfo".getBytes(),"password".getBytes(),passWord.getBytes());
            //执行添加
            table.put(put);
            //关流
            table.close();
            conn.close();

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                table.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                conn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

运行结果:

  

HBase中的结果:

hbase(main):003:0> scan 'demo'
ROW                                 COLUMN+CELL                                                                                          
 1001                               column=userinfo:name, timestamp=1650476863233, value=xE5xBCxA0xE4xB8x89                        
 1001                               column=userinfo:password, timestamp=1650476863233, value=753159                                      
1 row(s) in 0.0230 seconds

4.查询指定行键数据
  
@Test
    //获取全部的数据
    public void getAllData2(){
        //获取配置对象
        Configuration con= new Configuration();
        con.set("hbase.zookeeper.quorum","ip地址");
        Connection conn = null;
        Table user = null;
        try {
            //获取连接
            conn = ConnectionFactory.createConnection(con);
            user = conn.getTable(TableName.valueOf("demo"));
            //创建get
            Get get = new Get("1001".getBytes());
            //获取所有列
            Result result = user.get(get);
            Cell[] cells = result.rawCells();
            for (Cell cell : cells) {
                //获取行键
                byte[] rowKey = result.getRow();
                String s = new String(rowKey);
                //获取列名
                byte[] qualifier = cell.getQualifier();
                String columnName = new String(qualifier);
                //获取值
                byte[] value = cell.getValue();
                String value2 = new String(value);
                System.out.println("行键:"+s+"列名:"+columnName+"值:"+value2);
            }



        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                user.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                conn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

运行结果:

HBase中的结果:

hbase(main):007:0> get 'demo','1001'
COLUMN                              CELL                                                                                                 
 userinfo:name                      timestamp=1650477242603, value=xE7x8Ex8BxE4xBAx94                                              
 userinfo:password                  timestamp=1650477242603, value=762159                                                                
1 row(s) in 0.0780 seconds

5.查询全表数据
 
@Test
    public void sacnAllData() {
        Configuration con = new Configuration();
        con.set("hbase.zookeeper.quorum", "IP地址");
        //获取连接
        Connection conn = null;
        Table user = null;
        try {
            conn = ConnectionFactory.createConnection(con);
            user = conn.getTable(TableName.valueOf("demo"));
            Scan scan = new Scan();
            scan.setStartRow("1001".getBytes());
            scan.setStopRow("1004".getBytes());//小一位
            ResultScanner scanner = user.getScanner(scan);
            for (Result result : scanner) {
                List cells = result.listCells();
                for (Cell cell : cells) {
                    byte[] rowKey = result.getRow();
                    String s = new String(rowKey);
                    byte[] qualifier = cell.getQualifier();
                    String columnName = new String(qualifier);
                    byte[] value = cell.getValue();
                    String value2 = new String(value);
                    System.out.println("行键:" + s + "列名:" + columnName + "值:" + value2);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                user.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                conn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

运行结果:

 HBase中的结果:

hbase(main):008:0> scan 'demo'
ROW                                 COLUMN+CELL                                                                                          
 1001                               column=userinfo:name, timestamp=1650477242603, value=xE7x8Ex8BxE4xBAx94                        
 1001                               column=userinfo:password, timestamp=1650477242603, value=762159                                      
 1002                               column=userinfo:name, timestamp=1650477294338, value=lisi                                            
 1002                               column=userinfo:password, timestamp=1650477294338, value=752159                                      
 1003                               column=userinfo:name, timestamp=1650477429031, value=xE5xBCxA0xE4xB8x89                        
 1003                               column=userinfo:password, timestamp=1650477429031, value=753159                                      
3 row(s) in 0.0280 seconds

6.查询表的行数
@Test
    public void countRows(){
        Configuration con = new Configuration();
        con.set("hbase.zookeeper.quorum", "IP地址");
        //获取连接
        Connection conn = null;
        Table student = null;
        try {
            conn = ConnectionFactory.createConnection(con);
            student = conn.getTable(TableName.valueOf("demo"));
            Scan scan = new Scan();
            ResultScanner scanner = student.getScanner(scan);
            int num = 0;
            for(Result result = scanner.next();result!=null;result=scanner.next()) {
                num++;
            }
            System.out.println("行数:"+num);

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                student.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                conn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

运行结果:

  HBase中的结果:

hbase(main):009:0> count 'demo'
3 row(s) in 0.0280 seconds

=> 3

 7.查询已存在表
@Test
    public void listTables(){
        Configuration con = new Configuration();
        con.set("hbase.zookeeper.quorum", "ip地址");
        //获取连接
        Connection conn = null;
        Admin admin = null;
        try {
            conn = ConnectionFactory.createConnection(con);
            //拿到admin
            admin = conn.getAdmin();
            HTableDescriptor[] hTableDescriptors = admin.listTables();
            for (HTableDescriptor hTableDescriptor : hTableDescriptors) {
                System.out.println(hTableDescriptor.getNameAsString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                admin.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                conn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

运行结果:

 HBase中的结果:

hbase(main):011:0> list
TABLE                                                                                                                                    
demo                                                                                                                                     
helloWorld                                                                                                                               
student                                                                                                                                  
user                                                                                                                                     
year                                                                                                                                     
5 row(s) in 0.0330 seconds

=> ["demo", "helloWorld", "student", "user", "year"]

8.删除指定行数据
@Test
    public void deleteDataData() {
        Configuration con = new Configuration();
        con.set("hbase.zookeeper.quorum", "ip地址");
        //获取连接
        Connection conn = null;
        Table helloWorld = null;

        try {
            conn = ConnectionFactory.createConnection(con);
            helloWorld = conn.getTable(TableName.valueOf("demo"));
            Delete delete = new Delete("1001".getBytes());
            helloWorld.delete(delete);
            System.out.println("删除成功");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                helloWorld.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                conn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

运行结果:

 HBase中的结果:

hbase(main):012:0> scan 'demo'
ROW                                 COLUMN+CELL                                                                                          
 1002                               column=userinfo:name, timestamp=1650477294338, value=lisi                                            
 1002                               column=userinfo:password, timestamp=1650477294338, value=752159                                      
 1003                               column=userinfo:name, timestamp=1650477429031, value=xE5xBCxA0xE4xB8x89                        
 1003                               column=userinfo:password, timestamp=1650477429031, value=753159                                      
2 row(s) in 0.0230 seconds

9.删除表
@Test
    public void deleteTable(){
        Configuration con = new Configuration();
        con.set("hbase.zookeeper.quorum", "IP地址");
        //获取连接
        Connection conn = null;
        Admin admin = null;
        Table student = null;

        try {
            conn = ConnectionFactory.createConnection(con);
            //拿到admin
            admin = conn.getAdmin();
            student = conn.getTable(TableName.valueOf("demo"));
            admin.disableTable(TableName.valueOf("demo"));
            admin.deleteTable(TableName.valueOf("demo"));
            System.out.println("删除表成功");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                student.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                admin.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                conn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

运行结果:

  HBase中的结果:

hbase(main):013:0> list
TABLE                                                                                                                                    
helloWorld                                                                                                                               
student                                                                                                                                  
user                                                                                                                                     
year                                                                                                                                     
4 row(s) in 0.0480 seconds

=> ["helloWorld", "student", "user", "year"]

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/820588.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号