I have a One Spring Hibernate Application. In my application, Recently i am implemented Spring data Redis.
spring-servlet.xml
<!-- redis connection factory -->
<bean id="jedisConnFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" p:use-pool="true"/>
<!-- redis template definition -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
p:connection-factory-ref="jedisConnFactory"/>
And this redisTemplate
use in my ServiceImpl class.
RedisServiceImpl
@Autowired
private RedisTemplate<String, T> redisTemplate;
public RedisTemplate<String, T> getRedisTemplate() {
return redisTemplate;
}
public void setRedisTemplate(RedisTemplate<String, T> redisTemplate) {
this.redisTemplate = redisTemplate;
}
Now I added data in redisServer like this
public void putData(String uniqueKey, String key, Object results) {
redisTemplate.opsForHash().put(uniqueKey, key, results);
}
Now i want to remove Expire key.
I search in Google, But in google all are saying like this
redisTemplate.expire(key, timeout, TimeUnit);
In this expire method, We need to provide uniqueKey
instead of key
.
But I need to Expire key
instead of uniqueKey
.
So Please help me what can i do for expire Key
?
To create a Redis with an expiration time, use the SET command and the EX option to set the expiration time. The EX option takes a number in seconds and sets the number of seconds the key is valid until expiration. You can also use PX to specify the expiration time in Milliseconds.
Spring Data Redis, part of the larger Spring Data family, provides easy configuration and access to Redis from Spring applications. It offers both low-level and high-level abstractions for interacting with the store, freeing the user from infrastructural concerns.
I am using Spring Data Redis.
I am using @Redishash(timeToLive=300)
annotation to expire my Entities after 300 seconds.
Here is the excerpt from my pom.xml
...
...
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
...
...
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
...
...
My RedisConfig.class
@Configuration
@Log4j2
@EnableRedisRepositories(basePackageClasses = ConsentOTP.class)
public class RedisConfig {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private Integer port;
@Value("${spring.redis.password}")
private String password;
@Bean
JedisConnectionFactory jedisConnectionFactory() {
log.info("=================================================================");
log.info("redis config : {} : {} ", host, port);
log.info("=================================================================");
RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(host, port);
config.setPassword(RedisPassword.of(password));
return new JedisConnectionFactory(config);
}
}
And my entity class ConsentOtp.class
@RedisHash(value = "ConsentOTP", timeToLive = 300)
@Data
@NoArgsConstructor
public class ConsentOTP implements Serializable {
private static final long serialVersionUID = 1708925807375596799L;
private String id;
private LocalDateTime timestamp;
private String otp;
public ConsentOTP(String personId, LocalDateTime timestamp, String otp) {
this.id = personId;
this.timestamp = timestamp;
this.otp = otp;
}
}
Here is my Redis repository
public interface ConsentOtpRepository extends CrudRepository<ConsentOTP, String> {
}
I am using Redis Version 3.2.100.
Instead of redis template ,Use Redis Cache Manager, pass redistemplate to cacheManager and use its set expires property to which is basically map of String & Long , you can add cache name and set its expiry time i.e time to live (TTL).
You can use setDefaultExpiration method of cacheManager to set same expiry time to all the cache.
@SuppressWarnings({ "rawtypes", "unused" })
@Configuration
@EnableCaching(proxyTargetClass = true, mode = AdviceMode.ASPECTJ, order = 1)
@PropertySource("classpath:/application.properties")
public class CacheConfigImpl extends CachingConfigurerSupport {
private @Value("${redis.ip}") String redisHost;
private @Value("${redis.port}") int redisPort;
private static final Map<String, Long> cacheMap = new HashMap<String, Long>();
static {
cacheMap.put("method1cache", 600L);
cacheMap.put("method2cache", 600L);
cacheMap.put("method3cache", 800L);
}
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
@Bean
public JedisConnectionFactory redisConnectionFactory() {
JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory();
redisConnectionFactory.setHostName(CustomPropertyLoader.getProperty("redis.ip"));
redisConnectionFactory.setPort(Integer.parseInt(CustomPropertyLoader.getProperty("redis.port")));
return redisConnectionFactory;
}
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
@Bean(name = "RCacheManager")
public CacheManager cacheManager(RedisTemplate redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
cacheManager.setExpires(cacheMap);
cacheManager.setUsePrefix(true);
final String redis_client_name = CustomPropertyLoader.getProperty("redis.client.name");
cacheManager.setCachePrefix(new RedisCachePrefix() {
private final RedisSerializer<String> serializer = new StringRedisSerializer();
private final String delimiter = ":";
public byte[] prefix(String cacheName) {
return this.serializer
.serialize(redis_client_name.concat(this.delimiter).concat(cacheName).concat(this.delimiter));
}
});
return cacheManager;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With