Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Download Microsoft EdgeMore info about Internet Explorer and Microsoft Edge
Table of contentsExit editor mode

Quickstart: Use Azure Cache for Redis in Java with Jedis Redis client

  • Applies to: ✅ Azure Cache for Redis, ✅ Azure Managed Redis
Feedback

In this article

In this quickstart, you incorporate Azure Cache for Redis into a Java app using theJedis Redis client. Your cache is a secure, dedicated cache that is accessible from any application within Azure.

Skip to the code on GitHub

Clone the repoJava quickstart on GitHub.

Prerequisites

Create an Azure Managed Redis instance

  1. To create an Azure Managed Redis instance, sign in to the Azure portal and selectCreate a resource.

  2. On theCreate a resource page, typeAzure Managed Redis in the search box.

  3. Select theAzure Managed Redis tile and selectCreate.

  4. On theCreate Azure Managed Redis instance pane, configure the settings for a new cache on theBasics tab.

    SettingChoose a valueDescription
    SubscriptionDrop down and select your subscription.The subscription under which to create this new Azure Managed Redis instance.
    Resource groupDrop down and select a resource group, or selectCreate 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.
    NameEnter a name that is unique in the region.The cache name must be a string between 1 and 63 characters whencombined with the cache's region name that contain only numbers, letters, or hyphens. (If the cache name is fewer than 45 characters long it should work in all currently available regions.) The name must start and end with a number or letter, and can't contain consecutive hyphens. Your cache instance'shost name is\<DNS name\>.\<Azure region\>.redis.azure.net.
    RegionDrop down and select a location.Azure Managed Redis is available in selected Azure regions.
    Data tierSelect eitherIn-memory for high-performance, orFlash for lower performance cachesThe in-memory tiers includeBalanced,Memory Optimized, andCompute Optimized. Use theFlash tier to use in-memory (RAM) and on-disk (SSD) data storage.
    Cache SizeDrop down and select a size.Cache size depends on tier. The smallest size is a Balanced tier. The size largest in-memory tier is a Memory Optimized tier.
    PerformanceDrop down and select a performance preference.Performance depends on the number of vCPUs. Number of vCPU varies with tier. Compute Optimized has the most vCPUs.

    For guidance on choosing the right performance tier, seeChoosing the right tier.

    Important

    All in-memory tiers that use over 235 GB of storage are in Public Preview, including Memory Optimized M350 and higher; Balanced B350 and higher; and Compute Optimized X350 and higher. All these tiers and higher are in Public Preview.

    All Flash Optimized tiers are in Public Preview.

  5. SelectNext: Networking , and select either aDisable public access and use private access orEnable public access from all networks.

  6. SelectNext: Active geo-replication. To use active geo-replication it must be enabled during provisioning. Caches without active geo-replication can't be added to or join active geo-replication groups later. For more information, seeConfigure active geo-replication for Azure Managed Redis instances.

  7. Select theNext: Advanced tab.

    Configure anyRedis modules you want to add to the instance.

    SetClustering policy:

    • UseEnterprise in order to use RedisSearch or other modules
    • UseOSS for a clustered cache.
    • UseNon-clustered (Preview) for a non-clustered cache.

    For more information on choosingClustering policy, seeCluster policy.

    By default, for a new managed cache:

    • Microsoft Entra ID is enabled.
    • Access Keys Authentication is disabled for security reasons.

    Important

    You can't change modules after you create a cache instance. Modules must be enabled at the time you create an Azure Managed Redis instance. There is no option to enable the configuration of a module after you create a cache.

    Important

    For optimal security, we recommend that you use Microsoft Entra ID with managed identities to authorize requests against your cache if possible. Authorization by using Microsoft Entra ID and managed identities provides superior security and ease of use over shared access key authorization. For more information about using managed identities with your cache, seeUse Microsoft Entra ID for cache authentication.

    Important

    You can't change the clustering policy of an Azure Managed Redis instance after you create it. If you're usingRediSearch, the Enterprise cluster policy is required, andNoEviction is the only eviction policy supported.

    Important

    If you're using this cache instance in a geo-replication group, eviction policies cannot be changed after the instance is created. Be sure to know the eviction policies of your primary nodes before you create the cache. For more information on active geo-replication, seeActive geo-replication prerequisites.

  8. SelectNext: Tags and skip.

  9. SelectNext: Review + create.

  10. Review the settings and selectCreate.

    It takes several minutes for the Redis instance to create. You can monitor progress on the Azure Managed RedisOverview page. WhenStatus shows asRunning, the cache is ready to use.

Create an Azure Cache for Redis instance

  1. In theAzure portal, search for and selectAzure Cache for Redis.

  2. On theAzure Cache for Redis page, selectCreate >Azure Cache for Redis.

  3. On theBasics tab of theNew Redis Cache page, configure the following settings:

    • Subscription: Select the subscription to use.
    • Resource group: Select a resource group, or selectCreate new and enter a new resource group name. Putting all your app resources in the same resource group lets you easily manage or delete them together.
    • Name: Enter a cache name that's unique in the region. The name must:
      • Be a string of 1 to 63 characters.
      • Contain only numbers, letters, and hyphens.
      • Start and end with a number or letter.
      • Not contain consecutive hyphens.
    • Region: Select anAzure region near other services that use your cache.
    • Cache SKU: Select aSKU to determine the available sizes, performance, and features for your cache.
    • Cache size: Select a cache size. For more information, seeAzure Cache for Redis overview.

    Screenshot that shows the Basics tab of the New Redis Cache page.

  4. Select theNetworking tab, or selectNext: Networking.

  5. On theNetworking tab, select a connectivity method to use for the cache.Private Endpoint is recommended for security. If you selectPrivate Endpoint, selectAdd private endpoint and create the private endpoint.

  6. Select theAdvanced tab, or selectNext: Advanced.

  7. On theAdvanced pane, configure the following options:

    • SelectMicrosoft Entra Authentication orAccess Keys Authentication.Microsoft Entra Authentication is enabled by default.
    • Choose whether toEnable the non-TLS port.
    • For a Premium cache, you can configure or disableAvailability zones. You can't disable availability zones after the cache is created. For a Standard cache, availability zones are allocated automatically. Availability zones aren't available for Basic SKU.
    • For a Premium cache, configure the settings forReplica count,Clustering andShard count,System-assigned managed identity, andData persistence.

    The following image shows theAdvanced tab for the Standard SKU.

    Screenshot showing the Advanced pane for a Standard SKU cache.

    Important

    Use Microsoft Entra ID with managed identities to authorize requests against your cache if possible. Authorization using Microsoft Entra ID and managed identity provides better security and is easier to use than shared access key authorization. For more information about using managed identities with your cache, seeUse Microsoft Entra ID for cache authentication.

  8. Optionally, select theTags tab or selectNext: Tags, and enter tag names and values to categorize your cache resources.

  9. SelectReview + create, and once validation passes, selectCreate.

The new cache deployment takes several minutes. You can monitor deployment progress on the portal Azure Cache for Redis page. When the cacheStatus displaysRunning, the cache is ready to use.

Retrieve host name, ports, and access keys from the Azure portal

To connect your Azure Cache for Redis server, the cache client needs the host name, ports, and a key for the cache. Some clients might refer to these items by slightly different names. You can get the host name, ports, and keys from theAzure portal.

  • To get the host name and ports for your cache, selectOverview from theResource menu. The host name is of the form<DNS name>.redis.cache.windows.net.

    Screenshot showing Azure Cache for Redis properties.

  • To get the access keys, selectAuthentication from theResource menu. Then, select theAccess keys tab.

    Screenshot showing Azure Cache for Redis access keys.

Set up the working environment

The following steps show you how to set up the working environment for the Java app.

export REDIS_CACHE_HOSTNAME=<your-host-name>.redis.cache.windows.netexport REDIS_CACHE_PORT=10000
export REDIS_CACHE_HOSTNAME=<your-host-name>.redis.cache.windows.netexport REDIS_CACHE_PORT=6380

Replace the placeholders with the following values:

  • <your-host-name>: The DNS host name. To get the host name and ports for your cache, selectOverview from theResource menu. The host name is of the form<DNS name>.redis.cache.windows.net.

    Screenshot showing Azure Cache for Redis properties.

  • <your-client-id>: The application (client) ID of your Azure AD application registration.

  • <your-client-secret>: The client secret of your Azure AD application registration.

  • <your-tenant-id>: Your Azure Active Directory tenant ID.

    Note

    The above example uses client secret authentication. You can also configure theredis-authx-entraid library to use other authentication methods such as managed identity or client certificate by modifying theEntraIDTokenAuthConfigBuilder configuration in your code.


Create a new Java app

  1. Use maven to generate a new quickstart app:

    mvn archetype:generate \    -DarchetypeGroupId=org.apache.maven.archetypes \    -DarchetypeArtifactId=maven-archetype-quickstart \    -DarchetypeVersion=1.3 \    -DinteractiveMode=false \    -DgroupId=example.demo \    -DartifactId=redis-jedis-test \    -Dversion=1.0
  2. Change to the newredis-jedis-test project directory.

  3. Open thepom.xml file. In the file, you see a dependency forJedis:

    Note

    Microsoft has entered into a partnership with Redis, Inc. As part of this collaboration, Microsoft Entra ID authentication support has been moved from Azure SDK to Redis Entra ID extensions. The newredis-authx-entraid library provides enhanced authentication capabilities and is the recommended approach for Microsoft Entra ID authentication with Azure Cache for Redis.

    <dependency>    <groupId>redis.clients.authentication</groupId>    <artifactId>redis-authx-entraid</artifactId>    <version>0.1.1-beta2</version></dependency><dependency>    <groupId>redis.clients</groupId>    <artifactId>jedis</artifactId>    <version>6.0.0</version> </dependency>
  4. Close thepom.xml file.

  5. OpenApp.java and see the code with the following code:

    package example.demo;import com.azure.identity.DefaultAzureCredentialBuilder;import redis.clients.authentication.core.TokenAuthConfig;import redis.clients.authentication.entraid.AzureTokenAuthConfigBuilder;import redis.clients.jedis.DefaultJedisClientConfig;import redis.clients.jedis.HostAndPort;import redis.clients.jedis.UnifiedJedis;import redis.clients.jedis.authentication.AuthXManager;import java.util.Set;/*** Redis test with Microsoft Entra ID authentication using redis-authx-entraid* For more information about Redis authentication extensions, see:* https://redis.io/docs/latest/develop/clients/jedis/amr/**/public class App{    public static void main( String[] args )    {        String REDIS_CACHE_HOSTNAME = System.getenv("REDIS_CACHE_HOSTNAME");        int REDIS_PORT = Integer.parseInt(System.getenv().getOrDefault("REDIS_CACHE_PORT", "10000"));        String SCOPES = "https://redis.azure.com/.default"; // The scope for Azure Cache for Redis        // Build TokenAuthConfig for Microsoft Entra ID authentication        TokenAuthConfig tokenAuthConfig = AzureTokenAuthConfigBuilder.builder()                .defaultAzureCredential(new DefaultAzureCredentialBuilder().build())                .scopes(Set.of(SCOPES))                .tokenRequestExecTimeoutInMs(2000)                .build();        DefaultJedisClientConfig config = DefaultJedisClientConfig.builder()                .authXManager(new AuthXManager(tokenAuthConfig))                .ssl(true)                .build();        UnifiedJedis jedis = new UnifiedJedis(                new HostAndPort(REDIS_CACHE_HOSTNAME, REDIS_PORT),                config);        // Test the connection        System.out.println(String.format("Database size is %d", jedis.dbSize()));        // 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"));        jedis.close();    }}

    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. ThePING commands are also executed.

  6. Close theApp.java file.

Build and run the app

Execute the following Maven command to build and run the app:

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

In the following output, you can see that theMessage key previously had a cached value. The value was updated to a new value usingjedis.set. The app also executed thePING commands.

Cache Command  : PingCache Response : PONGCache Command  : GET MessageCache Response : Hello! The cache is working from Java!Cache Command  : SET MessageCache Response : OKCache Command  : GET MessageCache Response : Hello! The cache is working from Java!

Clean up resources

If you plan to continue with the next tutorial, you can keep the resources created in this quickstart and reuse them.

Otherwise, if you're finished with the quickstart sample application, you can delete the Azure resources created in this quickstart to avoid charges.

Important

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 instead of deleting the resource group.

  1. Sign in to theAzure portal and selectResource groups.

  2. In theFilter by name textbox, type the name of your resource group. The instructions for this article used a resource group namedTestResources. On your resource group in the result list, selectTest Resources thenDelete resource group.

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

  3. Type the name of your resource group to confirm deletion and then selectDelete.

After a few moments, the resource group and all of its contained resources are deleted.

Next steps

In this quickstart, you learned how to use Azure Cache for Redis from a Java application. Continue to the next quickstart to use Azure Cache for Redis with an ASP.NET web app.


Feedback

Was this page helpful?

YesNoNo

Need help with this topic?

Want to try using Ask Learn to clarify or guide you through this topic?

Suggest a fix?

  • Last updated on

In this article

Was this page helpful?

YesNo
NoNeed help with this topic?

Want to try using Ask Learn to clarify or guide you through this topic?

Suggest a fix?