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

在本快速入門中,您會使用 Jedis Redis 用戶端將 Azure Cache for Redis 納入 Java 應用程式中,以便存取可從 Azure 內的任何應用程式存取的安全、專用快取。In this quickstart, you incorporate Azure Cache for Redis into a Java app using the Jedis Redis client to have access to a secure, dedicated cache that is accessible from any application within Azure.

PrerequisitesPrerequisites

建立 Azure Cache for RedisCreate an Azure Cache for Redis

  1. 若要建立快取,請登入 Azure 入口網站,然後選取 [建立資源] 。To create a cache, sign in to the Azure portal and select Create a resource.

    [建立資源] 在左側導覽窗格中反白顯示。

  2. 在 [新增] 頁面上選取 [資料庫] ,然後選取 [Azure Cache for Redis] 。On the New page, select Databases and then select Azure Cache for Redis.

    在 [新增] 上,[資料庫] 和 [Azure Cache for Redis] 會反白顯示。

  3. 在 [新的 Redis 快取] 頁面上,設定新快取的設定。On the New Redis Cache page, configure the settings for your new cache.

    設定Setting 建議的值Suggested value 描述Description
    DNS 名稱DNS name 輸入全域唯一名稱。Enter a globally unique name. 快取名稱必須是 1 到 63 個字元的字串,且只能包含數字、字母或連字號。The cache name must be a string between 1 and 63 characters that contains only numbers, letters, or hyphens. 名稱的開頭和結尾必須是數字或字母,且不可包含連續的連字號。The name must start and end with a number or letter, and can't contain consecutive hyphens. 您的快取執行個體 主機名稱 將是 <DNS name>.redis.cache.windows.netYour cache instance's host name will be <DNS name>.redis.cache.windows.net.
    訂用帳戶Subscription 下拉並選取您的訂用帳戶。Drop down and select your subscription. 這個新的 Azure Cache for Redis 執行個體建立所在的訂用帳戶。The subscription under which to create this new Azure Cache for Redis instance.
    資源群組Resource group 下拉並選取資源群組,或選取 [新建] 並輸入新的資源群組名稱。Drop down and select a resource group, or select Create new and enter a new resource group name. 用來建立快取和其他資源的資源群組名稱。Name for the resource group in which to create your cache and other resources. 將所有的應用程式資源放在一個資源群組中,您將可輕鬆地一併管理或刪除這些資源。By putting all your app resources in one resource group, you can easily manage or delete them together.
    位置Location 下拉並選取位置。Drop down and select a location. 選取其他將使用快取的服務附近的區域Select a region near other services that will use your cache.
    定價層Pricing tier 下拉並選取 定價層Drop down and select a Pricing tier. 快取的可用大小、效能和功能取決於定價層。The pricing tier determines the size, performance, and features that are available for the cache. 如需詳細資訊,請參閱 Azure Cache for Redis 概觀For more information, see Azure Cache for Redis Overview.
  4. 選取 [網路] 索引標籤,或按一下頁面底部的 [網路] 按鈕。Select the Networking tab or click the Networking button at the bottom of the page.

  5. 在 [網路功能] 索引標籤中,選取您的連線方法。In the Networking tab, select your connectivity method.

  6. 選取頁面底部的 [下一步:進階] 索引標籤,或按一下頁面底部的 [下一步:進階] 按鈕。Select the Next: Advanced tab or click the Next: Advanced button on the bottom of the page.

  7. 在基本或標準快取執行個體的 [進階] 索引標籤中,如果您想要啟用非 TLS 連接埠,請選取啟用切換。In the Advanced tab for a basic or standard cache instance, select the enable toggle if you want to enable a non-TLS port. 您也可以選擇要使用 Redis 版本 4 或 (預覽) 6。You can also select which Redis version you would like use, either 4 or (PREVIEW) 6.

    Redis 版本 4 或 6。

  8. 在高階快取執行個體的 [進階] 索引標籤中,設定非 TLS 連接埠、叢集和資料持續性的設定。In the Advanced tab for premium cache instance, configure the settings for non-TLS port, clustering, and data persistence. 您也可以選擇要使用 Redis 版本 4 或 (預覽) 6。You can also select which Redis version you would like use, either 4 or (PREVIEW) 6.

  9. 選取頁面底部的 [下一步:標記] 索引標籤,或按一下頁面底部的 [下一步:標記] 按鈕。Select the Next: Tags tab or click the Next: Tags button at the bottom of the page.

  10. 在 [標記] 索引標籤中,如果您想要分類資源,可以選擇性地輸入名稱和值。Optionally, in the Tags tab, enter the name and value if you wish to categorize the resource.

  11. 選取 [檢閱 + 建立]。Select Review + create. 您會移至 [檢閱 + 建立] 索引標籤,其中 Azure 會驗證您的組態。You're taken to the Review + create tab where Azure validates your configuration.

  12. 出現綠色的「通過驗證」訊息之後,請選取 [建立]。After the green Validation passed message appears, select Create.

建立快取需要一些時間。It takes a while for the cache to create. 您可以在 Azure Cache for Redis 的 [概觀] 頁面上監視進度。You can monitor progress on the Azure Cache for Redis Overview page. 當 [狀態] 顯示為 [執行中] 時,表示快取已可供使用。When Status shows as Running, the cache is ready to use.

從 Azure 入口網站擷取主機名稱、連接埠和存取金鑰Retrieve host name, ports, and access keys from the Azure portal

若要連線至 Azure Cache for Redis 執行個體,快取用戶端需要主機名稱、連接埠和快取金鑰。To connect to an Azure Cache for Redis instance, cache clients need the host name, ports, and a key for the cache. 某些用戶端可能會以稍有不同的名稱來參考這些項目。Some clients might refer to these items by slightly different names. 您可以從 Azure 入口網站取得主機名稱、連接埠和金鑰。You can get the host name, ports, and keys from the Azure portal.

  • 若要取得存取金鑰,請從快取的左側導覽中選取 [存取金鑰] 。To get the access keys, from your cache left navigation, select Access keys.

    Azure Cache for Redis 金鑰

  • 若要取得主機名稱和連接埠,請從快取的左側導覽中選取 [屬性] 。To get the host name and ports, from your cache left navigation, select Properties. 主機名稱的格式為 <DNS name>.redis.cache.windows.netThe host name is of the form <DNS name>.redis.cache.windows.net.

    Azure Redis 快取屬性

設定工作環境Setting up the working environment

根據您的作業系統,為 主機名稱主要存取金鑰 新增環境變數。Depending on your operating system, add environment variables for your Host name and Primary access key. 開啟命令提示字元或終端機視窗,然後設定下列值:Open a command prompt, or a terminal window, and set up the following values:

set REDISCACHEHOSTNAME=<YOUR_HOST_NAME>.redis.cache.windows.net
set REDISCACHEKEY=<YOUR_PRIMARY_ACCESS_KEY>
export REDISCACHEHOSTNAME=<YOUR_HOST_NAME>.redis.cache.windows.net
export REDISCACHEKEY=<YOUR_PRIMARY_ACCESS_KEY>

以下列值取代預留位置:Replace the placeholders with the following values:

  • <YOUR_HOST_NAME>:在 Azure 入口網站中,從 Azure Cache for Redis 資源的「屬性」區段取得的 DNS 主機名稱。<YOUR_HOST_NAME>: The DNS host name, obtained from the Properties section of your Azure Cache for Redis resource in the Azure portal.
  • <YOUR_PRIMARY_ACCESS_KEY>:在 Azure 入口網站中,從 Azure Cache for Redis 資源的「存取金鑰」區段取得的主要存取金鑰。<YOUR_PRIMARY_ACCESS_KEY>: The primary access key, obtained from the Access keys section of your Azure Cache for Redis resource in the Azure portal.

建立新的 Java 應用程式Create a new Java app

使用 Maven 產生新的快速入門應用程式:Using Maven, generate a new quickstart app:

mvn archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.3 -DgroupId=example.demo -DartifactId=redistest -Dversion=1.0

變更為新的 redistest 專案目錄。Change to the new redistest project directory.

開啟 pom.xml 檔案,然後新增 Jedis 的相依性:Open the pom.xml file and add a dependency for Jedis:

    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>3.2.0</version>
        <type>jar</type>
        <scope>compile</scope>
    </dependency>

儲存 pom.xml 檔案。Save the pom.xml file.

開啟 App.java 檔案,並以下列程式碼取代其中的程式碼:Open App.java and replace the code with the following code:

package example.demo;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisShardInfo;

/**
 * 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.
        JedisShardInfo shardInfo = new JedisShardInfo(cacheHostname, 6380, useSsl);
        shardInfo.setPassword(cachekey); /* Use your access key. */
        Jedis jedis = new Jedis(shardInfo);      

        // 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 執行個體。This code shows you how to connect to an Azure Cache for Redis instance using the cache host name and key environment variables. 此程式碼也會將字串值儲存到快取中,以及擷取其中的字串值。The code also stores and retrieves a string value in the cache. PINGCLIENT LIST 命令也會執行。The PING and CLIENT LIST commands are also executed.

儲存 App.java。Save App.java.

建置並執行應用程式Build and run the app

執行下列 Maven 命令,以建置和執行應用程式:Execute the following Maven command to build and run the app:

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

在下列範例中,您會看到 Message 金鑰先前有快取值,此值是在 Azure 入口網站中使用 Redis 主控台所設定的。In the example below, you can see the Message key previously had a cached value, which was set using the Redis Console in the Azure portal. 應用程式更新了該快取值。The app updated that cached value. 應用程式也已執行 PINGCLIENT LIST 命令。The app also executed the PING and CLIENT LIST commands.

Azure Cache for Redis 應用程式已完成

清除資源Clean up resources

如果您準備繼續進行下一個教學課程,則可以保留在本快速入門中所建立的資源,並重複使用它們。If you will be continuing to the next tutorial, you can keep the resources created in this quickstart and reuse them.

否則,如果您已完成快速入門範例應用程式,便可以將在此快速入門中所建立的 Azure 資源刪除,以避免衍生費用。Otherwise, if you are finished with the quickstart sample application, you can delete the Azure resources created in this quickstart to avoid charges.

重要

刪除資源群組是無法回復的動作,資源群組和其內的所有資源將會永久刪除。Deleting a resource group is irreversible and that the resource group and all the resources in it are permanently deleted. 請確定您不會不小心刪除錯誤的資源群組或資源。Make sure that you do not accidentally delete the wrong resource group or resources. 如果您是在包含有需要保留之資源的現有資源群組內,建立用來裝載此範例的資源,則可以從每個資源各自的刀鋒視窗中個別刪除每個資源,而不必刪除正個資源群組。If you created the resources for hosting this sample inside an existing resource group that contains resources you want to keep, you can delete each resource individually from their respective blades instead of deleting the resource group.

  1. 登入 Azure 入口網站,然後選取 [資源群組] 。Sign in to the Azure portal and select Resource groups.

  2. 在 [依名稱篩選] 文字方塊中,輸入您的資源群組名稱。In the Filter by name textbox, type the name of your resource group. 本文的指示是使用名為 TestResources 的資源群組。The instructions for this article used a resource group named TestResources. 在結果清單中的目標資源群組上方,選取 ... ,然後按一下 [刪除資源群組] 。On your resource group in the result list, select ... then Delete resource group.

    Azure 資源群組已刪除

  3. 系統將會要求您確認是否刪除資源。You will be asked to confirm the deletion of the resource group. 輸入您資源群組的名稱以進行確認,然後選取 [刪除]。Type the name of your resource group to confirm, and select Delete.

片刻過後,系統便會刪除該資源群組及其所有內含的資源。After a few moments, the resource group and all of its contained resources are deleted.

後續步驟Next steps

在本快速入門中,您已了解如何從 Java 應用程式使用 Azure Cache for Redis。In this quickstart, you learned how to use Azure Cache for Redis from a Java application. 請繼續閱讀下一個快速入門,以搭配使用 Azure Cache for Redis 與 ASP.NET Web 應用程式。Continue to the next quickstart to use Azure Cache for Redis with an ASP.NET web app.