快速入門:在 Java 中使用 Azure Cache for Redis

在本快速入門中,您會使用 Jedis Redis 用戶端將 Azure Cache for Redis 納入 Java 應用程式。 您的快取是安全且專用的快取,可從 Azure 內的任何應用程式存取。

跳至 GitHub 上的程式碼

在 GitHub 上複製存放庫 Java 快速入門

必要條件

建立 Azure Cache for Redis

  1. 若要建立快取,請登入 Azure 入口網站,然後選取 [建立資源]。

    Create a resource is highlighted in the left navigation pane.

  2. 在 [新增] 頁面上,選取 [資料庫],然後選取 [Azure Cache for Redis]。

    On New, Databases is highlighted, and Azure Cache for Redis is highlighted.

  3. 在 [ 新增 Redis 快 取] 頁面上,設定新快取的設定。

    設定 選擇值 描述
    訂用帳戶 下拉式清單並選取您的訂用帳戶。 用來建立這個新 Azure Cache for Redis 實例的訂用帳戶。
    資源群組 下拉式清單並選取資源群組,或選取 [ 新建 ],然後輸入新的資源組名。 要在其中建立快取和其他資源的資源群組名稱。 藉由將所有應用程式資源放在一個資源群組中,您可以輕鬆地一起管理或刪除它們。
    DNS 名稱 輸入唯一名稱。 快取名稱必須是介於 1 到 63 個字元之間的字串,只包含數位、字母或連字元。 名稱必須以數位或字母開頭和結尾,且不能包含連續連字元。 快取實例的主機名<DNS name.redis.cache.windows.net>
    地點 下拉式清單並選取位置。 選取靠近使用快取之其他服務的區域
    快取類型 下拉式清單並選取階層 階層會決定快取可用的大小、效能和功能。 如需詳細資訊,請參閱 Azure Cache for Redis 概觀
  4. 選取 [ 網络] 索引 標籤,或選取頁面底部的 [ 網络] 按鈕。

  5. 在 [ 網络] 索引標籤中 ,選取您的連線方法。

  6. 選取 [ 下一步:進階 ] 索引標籤,或選取 頁面底部的 [下一步:進階 ] 按鈕,以查看 [ 進階 ] 索引卷標。

    Screenshot showing the Advanced tab in the working pane and the available option to select.

    • 針對 [基本] 或 [標準快取],切換非 TLS 埠的選取範圍。 如果您要啟用 Microsoft Entra Authentication,也可以選取 。
    • 針對 進階版 快取,請設定非 TLS 埠、叢集、受控識別和數據持續性的設定。 如果您要啟用 Microsoft Entra Authentication,也可以選取 。
  7. 選取 [ 下一步:標記 ] 索引標籤,或選取頁面底部的 [ 下一步:標記 ] 按鈕。

  8. 或者,如果您想要分類資源,請在 [ 標記 ] 索引標籤中輸入名稱和值。

  9. 選取 [檢閱 + 建立]。 系統會帶您前往 Azure 驗證設定的 [檢閱 + 建立] 索引標籤。

  10. 綠色 [驗證通過的訊息] 出現之後,選取 [ 建立]。

快取需要一段時間才能建立。 您可以在 Azure Cache for Redis 概觀 頁面上監視進度。 當 [狀態] 顯示為 [執行中],快取已準備好使用。

從 Azure 入口網站 擷取主機名、埠和存取密鑰

若要連線 Azure Cache for Redis 伺服器,快取用戶端需要快取的主機名、埠和密鑰。 有些用戶端可能會以稍微不同的名稱來參考這些專案。 您可以從 Azure 入口網站 取得主機名、埠和金鑰

  • 若要取得存取金鑰,請從快取左側導覽中 選取 [存取密鑰]。

    Azure Cache for Redis keys

  • 若要取得主機名和埠,請從快取左側導覽中選取 [ 屬性]。 主機名的格式為 DNS name.redis.cache.windows.net>。<

    Azure Cache for Redis properties

設定工作環境

根據您的作業系統,新增 您先前記下之 主機名和 主要存取密鑰 的環境變數。 開啟命令提示字元或終端機視窗,並設定下列值:

export REDISCACHEHOSTNAME=<your-host-name>.redis.cache.windows.net
export REDISCACHEKEY=<your-primary-access-key>

以下欄值取代佔位元:

  • <your-host-name>:D NS 主機名,取自 Azure 入口網站 中 Azure Cache for Redis 資源的 [屬性] 區段。
  • <your-primary-access-key>:主要存取密鑰,可從 Azure 入口網站 中 Azure Cache for Redis 資源的 [存取密鑰] 區段取得。

瞭解 Java 範例

在此範例中,您會使用 Maven 來執行快速入門應用程式。

  1. 變更為新的 重新設定 項目目錄。

  2. 開啟pom.xml檔案。 在檔案中,您會看到 Jedis相依性:

    <dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>4.1.0</version>
      <type>jar</type>
      <scope>compile</scope>
    </dependency>
    
  3. 關閉pom.xml檔案。

  4. 開啟 App.java ,並使用下列程式代碼查看程式代碼:

    package example.demo;
    
    import redis.clients.jedis.DefaultJedisClientConfig;
    import redis.clients.jedis.Jedis;
    
    /**
     * Redis test
     *
     */
    public class App 
    {
        public static void main( String[] args )
        {
    
            boolean useSsl = true;
            String cacheHostname = System.getenv("REDISCACHEHOSTNAME");
            String cachekey = System.getenv("REDISCACHEKEY");
    
            // Connect to the Azure Cache for Redis over the TLS/SSL port using the key.
            Jedis jedis = new Jedis(cacheHostname, 6380, DefaultJedisClientConfig.builder()
                .password(cachekey)
                .ssl(useSsl)
                .build());
    
            // Perform cache operations using the cache connection object...
    
            // Simple PING command
            System.out.println( "\nCache Command  : Ping" );
            System.out.println( "Cache Response : " + jedis.ping());
    
            // Simple get and put of integral data types into the cache
            System.out.println( "\nCache Command  : GET Message" );
            System.out.println( "Cache Response : " + jedis.get("Message"));
    
            System.out.println( "\nCache Command  : SET Message" );
            System.out.println( "Cache Response : " + jedis.set("Message", "Hello! The cache is working from Java!"));
    
            // Demonstrate "SET Message" executed as expected...
            System.out.println( "\nCache Command  : GET Message" );
            System.out.println( "Cache Response : " + jedis.get("Message"));
    
            // Get the client list, useful to see if connection list is growing...
            System.out.println( "\nCache Command  : CLIENT LIST" );
            System.out.println( "Cache Response : " + jedis.clientList());
    
            jedis.close();
        }
    }
    

    此程式代碼會示範如何使用快取主機名和密鑰環境變數連線到 Azure Cache for Redis 實例。 程序代碼也會在快取中儲存和擷取字串值。 PING也會執行和 CLIENT LIST 命令。

  5. 關閉App.java

建置並執行應用程式

  1. 首先,如果您尚未這麼做,您必須將環境變數設定為先前所述。

    export REDISCACHEHOSTNAME=<your-host-name>.redis.cache.windows.net
    export REDISCACHEKEY=<your-primary-access-key>
    
  2. 執行下列 Maven 命令來建置並執行應用程式:

    mvn compile
    mvn exec:java -D exec.mainClass=example.demo.App
    

在下列輸出中,您可以看到 Message 索引鍵先前有快取的值。 值已使用 jedis.set更新為新的值。 應用程式也會執行 PINGCLIENT LIST 命令。

Cache Command  : Ping
Cache Response : PONG

Cache Command  : GET Message
Cache Response : Hello! The cache is working from Java!

Cache Command  : SET Message
Cache Response : OK

Cache Command  : GET Message
Cache Response : Hello! The cache is working from Java!

Cache Command  : CLIENT LIST
Cache Response : id=777430 addr=             :58989 fd=22 name= age=1 idle=0 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=0 qbuf-free=32768 obl=0 oll=0 omem=0 ow=0 owmem=0 events=r cmd=client numops=6

清除資源

如果您繼續使用快速入門程序代碼,您可以保留在本快速入門中建立的資源,並重複使用它們。

否則,如果您已完成快速入門範例應用程式,您可以刪除本快速入門中建立的 Azure 資源,以避免產生費用。

重要

刪除資源群組是無法復原的,而且資源群組及其中的所有資源都會永久刪除。 請確定您不會不小心刪除錯誤的資源群組或資源。 如果您已建立資源,以將這個範例裝載於包含您想要保留之資源的現有資源群組內,您可以個別刪除每個資源,而不是刪除資源群組。

  1. 登入 Azure 入口網站,然後選取 [資源群組]。

  2. 在 [ 依名稱 篩選] 文本框中,輸入資源群組的名稱。 本文的指示使用了名為 TestResources 的資源群組。 在結果清單中的資源群組上,選取 [...],然後刪除資源群組

    Screenshot of the Azure portal that shows the Resource groups page with the Delete resource group button highlighted.

  3. 輸入資源群組的名稱以確認刪除,然後選取 [ 刪除]。

幾分鐘后,資源群組及其所有自主資源都會被刪除。

下一步

在本快速入門中,您已瞭解如何從 Java 應用程式使用 Azure Cache for Redis。 請繼續進行下一個快速入門,以搭配 ASP.NET Web 應用程式使用 Azure Cache for Redis。