快速入门:将 Azure Redis 缓存与 Java 配合使用Quickstart: Use Azure Cache for Redis with Java

在本快速入门中,会使用 Jedis Redis 客户端将 Azure 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.

先决条件Prerequisites

创建 Azure Redis 缓存Create 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.chinacloudapi.cnYour cache instance's host name will be <DNS name>.redis.cache.chinacloudapi.cn.
    订阅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. 有关详细信息,请参阅用于 Redis 的 Azure 缓存概述For more information, see Azure Cache for Redis Overview.
  4. 选择“创建” 。Select Create.

    创建 Azure Redis 缓存

    备注

    缓存预配大约需要 15 到 20 分钟。You can expect the provisioning of the Cache to take around 15 to 20 minutes.

    可以在 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 Redis 缓存

从 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 Redis 缓存密钥

  • 若要获取主机名和端口,请在缓存的左侧导航栏中选择“属性”。 To get the host name and ports, from your cache left navigation, select Properties. 主机名的格式为 <DNS 名称>.redis.cache.chinacloudapi.cn 。The host name is of the form <DNS name>.redis.cache.chinacloudapi.cn.

    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.chinacloudapi.cn
set REDISCACHEKEY=<YOUR_PRIMARY_ACCESS_KEY>
export REDISCACHEHOSTNAME=<YOUR_HOST_NAME>.redis.cache.chinacloudapi.cn
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 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.javaSave 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 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 Redis 缓存。In this quickstart, you learned how to use Azure Cache for Redis from a Java application. 请继续学习下一个快速入门,将 Azure Redis 缓存与 ASP.NET Web 应用配合使用。Continue to the next quickstart to use Azure Cache for Redis with an ASP.NET web app.