Share via


搭配 適用於 PostgreSQL 的 Azure 資料庫 使用 Spring Data JDBC

本教學課程示範如何使用 Spring Data JDBC,將數據儲存在 適用於 PostgreSQL 的 Azure 資料庫 資料庫中。

JDBC 是連線到傳統關係資料庫的標準 Java API。

在本教學課程中,我們包含兩種驗證方法:Microsoft Entra 驗證和 PostgreSQL 驗證。 [無密碼] 索引標籤會顯示 Microsoft Entra 驗證,而 [密碼] 索引標籤會顯示 PostgreSQL 驗證。

Microsoft Entra 驗證是使用 Microsoft Entra 識別碼中定義的身分識別連線到 適用於 PostgreSQL 的 Azure 資料庫 的機制。 透過 Microsoft Entra 驗證,您可以在集中的位置管理資料庫使用者的身分識別和其他 Microsoft 服務,從而簡化權限管理。

PostgreSQL 驗證會使用儲存在 PostgreSQL 中的帳戶。 如果您選擇使用密碼作為帳戶的認證,則這些認證會儲存在 user 資料表中。 因為這些密碼會儲存在PostgreSQL中,因此您必須自行管理密碼的輪替。

必要條件

  • PostgreSQL 命令行用戶端

  • 如果您沒有 Spring Boot 應用程式,請使用 Spring Initializr 建立 Maven 專案。 請務必選取 Maven 專案,然後在 [相依性] 底下新增 Spring WebSpring Data JDBCPostgreSQL 驅動程式相依性,然後選取 [Java 第 8 版] 或更新版本。

  • 如果您沒有實例,請建立名為 postgresqlflexibletest 的 適用於 PostgreSQL 的 Azure 資料庫 彈性伺服器實例,以及名為demo的資料庫。 如需指示,請參閱快速入門:在 Azure 入口網站 中建立 適用於 PostgreSQL 的 Azure 資料庫 - 彈性伺服器。

請參閱範例應用程式

在本教學課程中,您將撰寫範例應用程式的程序代碼。 如果您想要更快速地執行,此應用程式已編碼,且可在取得 https://github.com/Azure-Samples/quickstart-spring-data-jdbc-postgresql

設定 PostgreSQL 伺服器的防火牆規則

適用於 PostgreSQL 的 Azure 資料庫 實例預設會受到保護。 其防火牆不允許任何連入連線。

若要能夠使用您的資料庫,請開啟伺服器的防火牆,以允許本機 IP 位址存取資料庫伺服器。 如需詳細資訊,請參閱 適用於 PostgreSQL 的 Azure 資料庫 - 彈性伺服器的防火牆規則。

如果您要從 Windows 電腦上的 Windows 子系統 Linux 版 (WSL) 連線到 PostgreSQL 伺服器,您必須將 WSL 主機標識元新增至防火牆。

建立 PostgreSQL 非系統管理員使用者並授與許可權

接下來,建立非系統管理員使用者,並授與資料庫的所有權限。

您可以使用下列方法來建立使用無密碼連線的非系統管理員使用者。

  1. 使用下列命令來安裝 Azure CLI 的服務 連線 或無密碼擴充功能:

     az extension add --name serviceconnector-passwordless --upgrade
    
  2. 使用下列命令來建立 Microsoft Entra 非系統管理員使用者:

      az connection create postgres-flexible \
           --resource-group <your_resource_group_name> \
           --connection postgres_conn \
           --target-resource-group <your_resource_group_name> \
           --server postgresqlflexibletest \
           --database demo \
           --user-account \
           --query authInfo.userName \
           --output tsv
    

    當命令完成時,記下主控台輸出中的用戶名稱。

從 適用於 PostgreSQL 的 Azure 資料庫 儲存數據

現在您已擁有 適用於 PostgreSQL 的 Azure 資料庫 彈性伺服器實例,您可以使用 Spring Cloud Azure 來儲存數據。

若要安裝 Spring Cloud Azure Starter JDBC PostgreSQL 模組,請將下列相依性新增至您的 pom.xml 檔案:

  • Spring Cloud Azure 材料帳單(BOM):

    <dependencyManagement>
      <dependencies>
        <dependency>
          <groupId>com.azure.spring</groupId>
          <artifactId>spring-cloud-azure-dependencies</artifactId>
          <version>5.12.0</version>
          <type>pom</type>
          <scope>import</scope>
        </dependency>
      </dependencies>
    </dependencyManagement>
    

    注意

    如果您使用 Spring Boot 2.x,請務必將 spring-cloud-azure-dependencies 版本設定為 4.18.0。 此材料帳單 (BOM) 應該在<dependencyManagement>pom.xml檔案的 區段中設定。 這可確保所有 Spring Cloud Azure 相依性都使用相同的版本。 如需此 BOM 所用版本的詳細資訊,請參閱 應該使用哪個版本的 Spring Cloud Azure。

  • Spring Cloud Azure Starter JDBC PostgreSQL 成品:

    <dependency>
      <groupId>com.azure.spring</groupId>
      <artifactId>spring-cloud-azure-starter-jdbc-postgresql</artifactId>
    </dependency>
    

注意

自 版本 4.5.0以來,已支援無密碼連線。

將 Spring Boot 設定為使用 適用於 PostgreSQL 的 Azure 資料庫

若要使用 Spring Data JDBC 從 適用於 PostgreSQL 的 Azure 資料庫 儲存數據,請遵循下列步驟來設定應用程式:

  1. 將下列屬性新增至 application.properties 組態檔,以設定 適用於 PostgreSQL 的 Azure 資料庫 認證。

    logging.level.org.springframework.jdbc.core=DEBUG
    
    spring.datasource.url=jdbc:postgresql://postgresqlflexibletest.postgres.database.azure.com:5432/demo?sslmode=require
    spring.datasource.username=<your_postgresql_ad_non_admin_username>
    spring.datasource.azure.passwordless-enabled=true
    
    spring.sql.init.mode=always
    

    警告

    組態屬性 spring.sql.init.mode=always 表示 Spring Boot 會在每次啟動伺服器時,使用 您下次建立的schema.sql 檔案,自動產生資料庫架構。 這項功能非常適合用於測試,但請記住,它會在每次重新啟動時刪除您的數據,因此您不應該在生產環境中使用它。

請參閱範例應用程式

在本文中,您將撰寫範例應用程式的程序代碼。 如果您想要更快速地執行,此應用程式已編碼,且可在取得 https://github.com/Azure-Samples/quickstart-spring-data-jdbc-postgresql

設定 PostgreSQL 伺服器的防火牆規則

適用於 PostgreSQL 的 Azure 資料庫 實例預設會受到保護。 其防火牆不允許任何連入連線。

若要能夠使用您的資料庫,請開啟伺服器的防火牆,以允許本機 IP 位址存取資料庫伺服器。 如需詳細資訊,請參閱使用 Azure 入口網站 建立和管理 適用於 PostgreSQL 的 Azure 資料庫 - 單一伺服器的防火牆規則。

如果您要從 Windows 電腦上的 Windows 子系統 Linux 版 (WSL) 連線到 PostgreSQL 伺服器,您必須將 WSL 主機標識元新增至防火牆。

建立 PostgreSQL 非系統管理員使用者並授與許可權

接下來,建立非系統管理員使用者,並授與資料庫的所有權限。

您可以使用下列方法來建立使用無密碼連線的非系統管理員使用者。

  1. 使用下列命令來安裝 Azure CLI 的服務 連線 或無密碼擴充功能:

     az extension add --name serviceconnector-passwordless --upgrade
    
  2. 使用下列命令來建立 Microsoft Entra 非系統管理員使用者:

      az connection create postgres \
           --resource-group <your_resource_group_name> \
           --connection postgres_conn \
           --target-resource-group <your_resource_group_name> \
           --server postgresqlsingletest \
           --database demo \
           --user-account \
           --query authInfo.userName \
           --output tsv
    

    當命令完成時,記下主控台輸出中的用戶名稱。

從 適用於 PostgreSQL 的 Azure 資料庫 儲存數據

現在您已擁有 適用於 PostgreSQL 的 Azure 資料庫 單一伺服器實例,您可以使用 Spring Cloud Azure 來儲存數據。

若要安裝 Spring Cloud Azure Starter JDBC PostgreSQL 模組,請將下列相依性新增至您的 pom.xml 檔案:

  • Spring Cloud Azure 材料帳單(BOM):

    <dependencyManagement>
      <dependencies>
        <dependency>
          <groupId>com.azure.spring</groupId>
          <artifactId>spring-cloud-azure-dependencies</artifactId>
          <version>5.12.0</version>
          <type>pom</type>
          <scope>import</scope>
        </dependency>
      </dependencies>
    </dependencyManagement>
    

    注意

    如果您使用 Spring Boot 2.x,請務必將 spring-cloud-azure-dependencies 版本設定為 4.18.0。 此材料帳單 (BOM) 應該在<dependencyManagement>pom.xml檔案的 區段中設定。 這可確保所有 Spring Cloud Azure 相依性都使用相同的版本。 如需此 BOM 所用版本的詳細資訊,請參閱 應該使用哪個版本的 Spring Cloud Azure。

  • Spring Cloud Azure Starter JDBC PostgreSQL 成品:

    <dependency>
      <groupId>com.azure.spring</groupId>
      <artifactId>spring-cloud-azure-starter-jdbc-postgresql</artifactId>
    </dependency>
    

注意

自 版本 4.5.0以來,已支援無密碼連線。

將 Spring Boot 設定為使用 適用於 PostgreSQL 的 Azure 資料庫

若要使用 Spring Data JDBC 從 適用於 PostgreSQL 的 Azure 資料庫 儲存數據,請遵循下列步驟來設定應用程式:

  1. 將下列屬性新增至 application.properties 組態檔,以設定 適用於 PostgreSQL 的 Azure 資料庫 認證。

    logging.level.org.springframework.jdbc.core=DEBUG
    
    spring.datasource.url=jdbc:postgresql://postgresqlsingletest.postgres.database.azure.com:5432/demo?sslmode=require
    spring.datasource.username=<your_postgresql_ad_non_admin_username>@postgresqlsingletest
    spring.datasource.azure.passwordless-enabled=true
    
    spring.sql.init.mode=always
    

    警告

    組態屬性 spring.sql.init.mode=always 表示 Spring Boot 會在每次啟動伺服器時,使用 您下次建立的schema.sql 檔案,自動產生資料庫架構。 這項功能非常適合用於測試,但請記住,它會在每次重新啟動時刪除您的數據,因此您不應該在生產環境中使用它。

  1. 建立 src/main/resources/schema.sql 組態檔來設定資料庫架構,然後新增下列內容。

    DROP TABLE IF EXISTS todo;
    CREATE TABLE todo (id SERIAL PRIMARY KEY, description VARCHAR(255), details VARCHAR(4096), done BOOLEAN);
    
  1. 建立新的 Todo Java 類別。 這個類別是對應到 Spring Boot 自動建立之數據表的 todo 網域模型。 下列程式代碼會 getters 忽略和 setters 方法。

    import org.springframework.data.annotation.Id;
    
    public class Todo {
    
        public Todo() {
        }
    
        public Todo(String description, String details, boolean done) {
            this.description = description;
            this.details = details;
            this.done = done;
        }
    
        @Id
        private Long id;
    
        private String description;
    
        private String details;
    
        private boolean done;
    
    }
    
  2. 編輯啟動類別檔案以顯示下列內容。

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.context.event.ApplicationReadyEvent;
    import org.springframework.context.ApplicationListener;
    import org.springframework.context.annotation.Bean;
    import org.springframework.data.repository.CrudRepository;
    
    import java.util.stream.Stream;
    
    @SpringBootApplication
    public class DemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
        }
    
        @Bean
        ApplicationListener<ApplicationReadyEvent> basicsApplicationListener(TodoRepository repository) {
            return event->repository
                .saveAll(Stream.of("A", "B", "C").map(name->new Todo("configuration", "congratulations, you have set up correctly!", true)).toList())
                .forEach(System.out::println);
        }
    
    }
    
    interface TodoRepository extends CrudRepository<Todo, Long> {
    
    }
    

    提示

    在本教學課程中,組態或程式代碼中沒有任何驗證作業。 不過,連線到 Azure 服務需要驗證。 若要完成驗證,您需要使用 Azure Identity。 Spring Cloud Azure 使用 DefaultAzureCredential,Azure 身分識別連結庫會提供它來協助您取得認證,而不需要變更任何程序代碼。

    DefaultAzureCredential 支援多種驗證方法,並在執行階段判斷應使用的方法。 這種方法可讓您的應用程式在不同的環境中使用不同的驗證方法(例如本機和生產環境),而不需要實作環境特定的程序代碼。 如需詳細資訊,請參閱 DefaultAzureCredential

    若要在本機開發環境中完成驗證,您可以使用 Azure CLI、Visual Studio Code、PowerShell 或其他方法。 如需詳細資訊,請參閱 Java 開發環境中的 Azure 驗證。 若要在 Azure 裝載環境中完成驗證,建議您使用使用者指派的受控識別。 如需詳細資訊,請參閱什麼是 Azure 資源受控識別?

  3. 啟動應用程式。 應用程式會將資料儲存至資料庫。 您會看到類似下列範例的記錄:

    2023-02-01 10:22:36.701 DEBUG 7948 --- [main] o.s.jdbc.core.JdbcTemplate : Executing prepared SQL statement [INSERT INTO todo (description, details, done) VALUES (?, ?, ?)]    
    com.example.demo.Todo@4bdb04c8
    

部署至 Azure Spring Apps

現在您已在本機執行 Spring Boot 應用程式,現在可以將其移至生產環境。 Azure Spring Apps 可讓您輕鬆地將 Spring Boot 應用程式部署至 Azure,而不需要變更任何程式代碼。 服務會管理 Spring 應用程式的基礎結構,讓開發人員可以專注於處理程式碼。 Azure Spring 應用程式提供生命週期管理,使用全方位的監視和診斷、組態管理、服務探索、持續整合與持續傳遞的整合、藍綠部署等等。 若要將應用程式部署至 Azure Spring Apps,請參閱 將第一個應用程式部署至 Azure Spring Apps

下一步