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

具體關閉方法參考我之前寫的另一篇文章:

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM