DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Prompt Caching: Overriding Tokenization for Faster and More Cost-Effective AI
  • Five Layers Between Your AI Agent and a Production Outage
  • Why MCP Servers Lose Session State Behind Load Balancers
  • Security Is a Platform Property, Not a Pipeline Step

Trending

  • Giving AI Agents Safe Access to Legacy Systems: Introducing legacy2mcp
  • Delta Lake UniForm to Snowflake: Cross-Platform Table Access Without a Second Copy
  • Google Cloud KMS vs. AWS KMS: Java Encryption Guide
  • The Self-Hosting Math Changed While We Were Still Arguing About Sovereignty

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Software Design and Architecture
  3. Microservices
  4. How to Set Up Redis Properties Programmatically

How to Set Up Redis Properties Programmatically

Discussing an example of Redis configuration based on KeyspaceSettings for Spring application. Pros in comparison to other options for configuring Redis.

By 
Alexander Rumyantsev
·
Feb. 27, 25 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
3.9K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Redis is a high-performance NoSQL database that is usually used as an in-memory caching solution. However, it is very useful as the primary datastore solution. 

In this article, we will see how to set up Redis properties programmatically on the example of a Spring application. In many use cases, objects stored in Redis may be valid only for a certain amount of time. 

This is especially useful for persisting short-lived objects in Redis without having to remove them manually when they reach their end of life. We will look at how to configure time to live (TTL) for the app. TTL here is just an example of a Redis property. Other properties can be set up this way as well.

Implementation

Let’s consider a Spring application that stores CardInfoEntity in Redis. The entity contains sensitive information that can be stored for only five minutes. Here is what CardInfoEntity looks like:

Java
 
@Getter
@Setter
@ToString(exclude = "cardDetails")
@NoArgsConstructor
@AllArgsConstructor
@Builder
@RedisHash
public class CardInfoEntity {

   @Id
   private String id;
   private String cardDetails;
   private String firstName;
   private String lastName;
}


One needs to set TTL so that the objects will be deleted automatically. This can be achieved in three ways:

  • Using timeToLive property of the @RedisHash annotation (e.g. @RedisHash(timeToLive = 5*60))
  • Using the @TimeToLive annotation on either a numeric property or a method
  • Using KeyspaceConfiguration.KeyspaceSettings

The first two options have their flaws. In the first case, the value is hardcoded. There is no flexibility to change the value without rebuilding and redeploying the whole application. In the second case, we have to introduce a field that doesn’t relate to business logic.

The third option doesn’t have those problems. With this approach, we can use property in application.yml to set TTL and, if needed, other Redis properties. It’s also placed in a separate configuration file and doesn’t interfere with a business domain model.

We need to implement KeyspaceConfiguration and introduce custom KeyspaceSettings, which contains the Redis settings that we want to set up.

Java
 
@Configuration
@RequiredArgsConstructor
@EnableRedisRepositories(enableKeyspaceEvents = RedisKeyValueAdapter.EnableKeyspaceEvents.ON_STARTUP)
public class RedisConfiguration {
   private final RedisKeysProperties properties;

   @Bean
   public RedisMappingContext keyValueMappingContext() {
       return new RedisMappingContext(
               new MappingConfiguration(new IndexConfiguration(), new CustomKeyspaceConfiguration()));
   }

   public class CustomKeyspaceConfiguration extends KeyspaceConfiguration {

       @Override
       protected Iterable<KeyspaceSettings> initialConfiguration() {
           return Collections.singleton(customKeyspaceSettings(CardInfoEntity.class, CacheName.CARD_INFO));
       }

       private <T> KeyspaceSettings customKeyspaceSettings(Class<T> type, String keyspace) {
           final KeyspaceSettings keyspaceSettings = new KeyspaceSettings(type, keyspace);
           keyspaceSettings.setTimeToLive(properties.getCardInfo().getTimeToLive().toSeconds());
           return keyspaceSettings;
       }
   }

   @NoArgsConstructor(access = AccessLevel.PRIVATE)
   public static class CacheName {
       public static final String CARD_INFO = "cardInfo";
   }
}


To make Redis delete entities with TTL, one has to add enableKeyspaceEvents = RedisKeyValueAdapter.EnableKeyspaceEvents.ON_STARTUP to @EnableRedisRepositories annotation. I introduced CacheName class to use constants as entity names and to reflect that there can be multiple entities that can be configured differently if needed.

Conclusion

Redis has good integration with Spring, which provides several options for configuration. The approach provided in this article is not the most laconic and clear for someone who doesn’t have a lot of experience working with Spring. In many cases, just using annotations on top of entities is sufficient. 

However, if you have a more complex app with several different entities with different Redis properties, the option based on providing KeyspaceSettings can be preferable due to its clear structure and the above-mentioned advantages (using properties and keeping configuration outside business objects).

To view the full example application where AOP was used, as shown in this article, read my other article about creating a service for sensitive data with Spring and Redis.

The source code of the full version of this service is available on GitHub.

Time to live Property (programming) Redis (company)

Published at DZone with permission of Alexander Rumyantsev. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Prompt Caching: Overriding Tokenization for Faster and More Cost-Effective AI
  • Five Layers Between Your AI Agent and a Production Outage
  • Why MCP Servers Lose Session State Behind Load Balancers
  • Security Is a Platform Property, Not a Pipeline Step

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook