將 Spring Boot 應用程式連線到 Azure Cache for Redis

這個教學展示了如何使用 Azure Cache for Redis 在 Spring Boot 應用程式中儲存和檢索資料。 透過使用 Azure Cache for Redis,您可以提升高度依賴後端資料儲存的應用程式的效能與可擴展性。

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

Microsoft Entra 驗證是一種機制,可使用在 Microsoft Entra ID 中定義的身份用於連接 Azure Cache for Redis。 透過Microsoft Entra 驗證,您可以在集中位置管理資料庫使用者身分識別和其他Microsoft服務,以簡化許可權管理。

Redis 驗證會在 Redis 中使用密碼。 如果您選擇使用密碼作為認證,則必須自行管理密碼。

先決條件

在 Azure Cache for Redis 中快取資料

透過使用 Azure Cache for Redis 實例,你可以用 Spring Cloud Azure 快取資料。

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

<dependencies>
 <dependency>
   <groupId>com.azure.spring</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
 </dependency>
 <dependency>
   <groupId>com.azure.spring</groupId>
   <artifactId>spring-cloud-azure-starter-data-redis-lettuce</artifactId>
 </dependency>
 <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-redis</artifactId>
 </dependency>
</dependencies>

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

備註

請在 <dependencyManagement>pom.xml 檔案的區塊中設定此物料清單(BOM)。 此配置確保所有 Spring Cloud Azure 相依套件使用相同版本。 如需此 BOM 所用版本的詳細資訊,請參閱 應該使用哪個版本的 Spring Cloud Azure

撰寫應用程式程序代碼

若要使用 Redis 快取來儲存和擷取數據,請使用下列步驟來設定應用程式:

  1. application.properties 組態檔中設定 Redis 快取認證,如下列範例所示。

    spring.data.redis.host=<your-redis-name>.redis.cache.windows.net
    spring.data.redis.port=10000
    spring.data.redis.username=<your-redis-username>
    spring.data.redis.ssl.enabled=true
    spring.data.redis.azure.passwordless-enabled=true
    
    spring.data.redis.host=<your-redis-name>.redis.cache.windows.net
    spring.data.redis.port=6380
    spring.data.redis.username=<your-redis-username>
    spring.data.redis.ssl.enabled=true
    spring.data.redis.azure.passwordless-enabled=true
    

    備註

    若要取得 username 的值,請遵循 使用 Microsoft Entra ID 進行快取驗證中的 啟用 Microsoft Entra ID 驗證部分所提供的指示,並複製 使用者名稱 的值。

  2. 編輯啟動類別檔案以顯示下列內容。 此程式代碼會儲存和擷取數據。

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.data.redis.core.StringRedisTemplate;
    import org.springframework.data.redis.core.ValueOperations;
    
    @SpringBootApplication
    public class DemoCacheApplication implements CommandLineRunner {
    
        private static final Logger LOGGER = LoggerFactory.getLogger(DemoCacheApplication.class);
    
        @Autowired
        private StringRedisTemplate template;
    
        public static void main(String[] args) {
            SpringApplication.run(DemoCacheApplication.class, args);
        }
    
        @Override
        public void run(String... args) {
            ValueOperations<String, String> ops = this.template.opsForValue();
            String key = "testkey";
            if(!this.template.hasKey(key)){
                ops.set(key, "Hello World");
                LOGGER.info("Add a key is done");
            }
            LOGGER.info("Return the value from the cache: {}", ops.get(key));
        }
    
    }
    

然後,啟動應用程式。 應用程式會從 Redis 快取擷取數據。 您應該會看到類似下列範例的記錄:

Add a key is done
Return the value from the cache: Hello World

部署至 Azure Spring 應用程式

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

後續步驟

若要深入瞭解 Spring 和 Azure,請繼續前往 Azure 上的 Spring 檔中心。