zoukankan      html  css  js  c++  java
  • SpringBoot 使用Phoenix操作HBase教程1(使用标准JDBC)

      我在之前的文章中介绍了如何在 Java 项目中通过 hbase-client 来操作 HBase 数据库。而借助 Apache Phoenix,可以让我们能够使用标准 SQL 和 JDBC 接口来操作 HBase。下面通过样例进行演示。

    一、使用标准的 JDBC 来操作 HBase

    1,准备工作

    (1)服务器除了要安装 HBase 外,还需要安装 Phoenix,具体参考我之前写的文章:

    (2)编辑项目的 pom.xml 文件,添加 Phoenix 相关依赖(高亮部分):

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <!-- 去掉springboot默认日志配置 -->
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
     
        <!-- 引入log4j2依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>
     
        <!-- phoenix相关依赖配置 -->
        <dependency>
            <groupId>org.apache.phoenix</groupId>
            <artifactId>phoenix-core</artifactId>
            <version>5.0.0-HBase-2.0</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>joda-time</groupId>
                    <artifactId>joda-time</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.google.code.gson</groupId>
                    <artifactId>gson</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-common</artifactId>
            <version>2.9.2</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.google.code.gson</groupId>
                    <artifactId>gson</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.3</version>
        </dependency>
    </dependencies>

    2,编写代码

    (1)下面通过标准的 JDBC 来对表以及表数据进行增删改查操作:
    1,表名为什么加引号?
    • 在 phoenix 中,默认情况下,库名,表名,字段名等会自动转换为大写,若要小写,使用双引号,如"student"。
    2,是否需要 Phoenix JDBC 连接池?
    • 答案是不需要缓存 Phoenix JDBC 连接池。由于 HBase 的特殊性,Phoenix 连接对象有别于其他常规的 JDBC 连接。Phoenix 连接被设计为 thin 对象,创建它的代价很小。如果使用连接池来重用 HBase 连接,前一个用户的非正常退出可能会导致连接处于错误状态。因此最好每次创建一个新的连接。
    • 如果实在需要使用连接池,可以对 Phoenix 连接做简单的代理,每次需要从池中获取连接的时候初始化一个就好,而将连接归还到连接池之后就把它关闭掉。
    @RestController
    public class HelloController {
     
        //phoenix驱动
        private String phoenixDriver = "org.apache.phoenix.jdbc.PhoenixDriver";
        //zookeeper地址
        private String phoenixURL = "jdbc:phoenix:192.168.60.133:2181";
     
        @GetMapping("/test")
        public void test() throws Exception {
            // 创建表
            System.out.println("\n--- 开始创建 student 表 ---");
            createTable();
     
            // 获取Phoenix中的表(系统表除外)
            System.out.println("\n--- 获取Phoenix中的表(系统表除外) ---");
            List<String> tables = getTables();
            System.out.println(tables);
     
            // 插入数据
            System.out.println("\n--- 开始插入数据 ---");
            insertData();
     
            // 删除数据
            System.out.println("\n--- 开始删除数据 ---");
            deleteData();
     
            // 查询数据
            System.out.println("\n--- 开始查询数据 ---");
            List<Map<String, String>> list = getData("\"student\"");
            System.out.println(list);
     
            //删除表
            System.out.println("\n--- 开始删除 student 表 ---");
            dropTable();
        }
     
        // 获取连接
        public Connection getConnection() throws Exception {
            Class.forName(phoenixDriver);
            return DriverManager.getConnection(phoenixURL);
        }
     
        // 创建表
        public void createTable() throws Exception {
                //获取连接
                Connection connection = getConnection();
                // 创建Statement对象
                String sql = "CREATE TABLE IF NOT EXISTS \"student\"(" +
                        "id VARCHAR primary key," +
                        "name VARCHAR," +
                        "age VARCHAR)";
                PreparedStatement statement = connection.prepareStatement(sql);
                // 执行sql操作
                statement.execute();
                // 关闭
                statement.close();
                connection.close();
        }
     
        // 获取Phoenix中的表(系统表除外)
        public List<String> getTables() throws Exception {
            //获取连接
            Connection connection = getConnection();
            List<String> tables = new ArrayList<>();
            DatabaseMetaData metaData = connection.getMetaData();
            String[] types = {"TABLE"}; //"SYSTEM TABLE"
            ResultSet resultSet = metaData.getTables(null, null, null, types);
            while (resultSet.next()) {
                tables.add(resultSet.getString("TABLE_NAME"));
            }
            return tables;
        }
     
        // 删除表
        public void dropTable() throws Exception {
            //获取连接
            Connection connection = getConnection();
            // 创建Statement对象
            String sql = "DROP TABLE \"student\"";
            PreparedStatement statement = connection.prepareStatement(sql);
            // 执行sql操作
            statement.execute();
            // 关闭
            statement.close();
            connection.close();
        }
     
        // 插入数据
        public void insertData() throws Exception {
            //获取连接
            Connection connection = getConnection();
     
            //获取Statement对象,并进行数据插入
            Statement statement = connection.createStatement();
            statement.executeUpdate("upsert into \"student\" values('1001','大刘','20')");
            statement.executeUpdate("upsert into \"student\" values('1002','小星','22')");
            connection.commit();
            statement.close();
     
            //获取PreparedStatement对象,并进行数据插入
            PreparedStatement preparedStatement = connection.prepareStatement(
                    "upsert into \"student\" values(?,?,?)");
            //给参数赋值
            preparedStatement.setString(1,"1003");
            preparedStatement.setString(2,"hangge");
            preparedStatement.setString(3,"1000");
            //执行插入
            preparedStatement.execute();
            connection.commit();
            preparedStatement.close();
     
            connection.close();
        }
     
        // 删除数据
        public void deleteData() throws Exception {
            //获取连接
            Connection connection = getConnection();
     
            //获取Statement对象,并进行数据删除
            Statement statement = connection.createStatement();
            statement.execute("delete from \"student\" where id = '1002'");
            connection.commit();
            statement.close();
            connection.close();
        }
     
        // 查询数据(获取表中的所有数据)
        public List<Map<String, String>> getData(String tableName) throws Exception {
            //获取连接
            Connection connection = getConnection();
            String sql = "SELECT * FROM " + tableName;
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            ResultSet resultSet = preparedStatement.executeQuery();
            ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
            List<Map<String, String>> resultList = new ArrayList<>();
            while (resultSet.next()) {
                Map<String, String> result = new HashMap<>();
                for (int i = 1, len = resultSetMetaData.getColumnCount(); i <= len; i++) {
                    result.put(resultSetMetaData.getColumnName(i), resultSet.getString(i));
                }
                resultList.add(result);
            }
            return resultList;
        }
    }

    (2)启动项目,使用浏览器访问 /test 接口可以看到控制台输出如下,说明数据库操作成功:

    如果 Phoenix 开启了 SCHEMA,建议将其关闭,否则连接时会报如下错误:

    • ava.sql.SQLException: ERROR 726 (43M10): Inconsistent namespace mapping properties. Cannot initiate connection as SYSTEM:CATALOG is found but client does not have phoenix.schema.isNamespaceMappingEnabled enabled

    具体关闭方法参考我之前写的另一篇文章:

     

  • 相关阅读:
    SpringMVC视图解析器
    JavaEE PO VO BO DTO POJO DAO 整理总结
    Android Studio JNI开发入门教程
    javah的使用
    右键“在此处打开命令行窗口”的一个小秘密
    URL和URI的区别
    自学使用
    Ribbon使用
    Eureka集群搭建
    ssm常见面试题
  • 原文地址:https://www.cnblogs.com/shanheyongmu/p/15661006.html
Copyright © 2011-2022 走看看