yongguangl
yongguangl

Reputation: 87

How to set the cache time in springboot

enter image description hereI used the springboot to send the verification code. The valid time for setting the verification code was two minutes, and it will expire in two minutes later. Can I do this by setting up the cache? Or other ways. Who can help me?

Upvotes: 1

Views: 3287

Answers (2)

Anthony Dahanne
Anthony Dahanne

Reputation: 5053

You can try ehcache3, it was designed for such use cases !

Have a look at the documentation, in particular, the part about expiry.

Then, hack your project together, there are many ehcache3 + spring boot examples out there, there, and there, with the added benefit that you can just rely on the Java EE official caching spec, JSR-107, and not be vendor dependent.

Upvotes: 1

tryingToLearn
tryingToLearn

Reputation: 11663

You can use Redis for this purpose.

Redis is an open source in-memory data structure store that can be used as a cache. It provides a way to add expiry time to your keys. After the expiry time, keys will be invalidated/removed from Redis automatically.

In your maven, give the following dependency:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

In your SpringBoot application, you need to define just following properties:

spring.redis.host=
spring.redis.port=

And you can set the expiry time like:

public void put(final T key, final T hashKey, final Object value, final long exiryInMilliseconds) {
        hashOps.put(key, hashKey, value);
        if (exiryInMilliseconds > 0) {
            redisTemplate.expire(key, exiryInMilliseconds, TimeUnit.MILLISECONDS);
        }

    }

Both RedisTemplate & HashOperations are provided by Redis core package. You can either inject them using Spring like these or use them by creating instances yourself.

@Resource
private RedisTemplate<T, T> redisTemplate;

@Resource(name = "redisTemplate")
private  <T, T, Object> hashOps;

At the time of retrieval, if you do this:

hashOps.get(key, hashKey);

it will return null if expiry time has elapsed / or key does not exist. else you will get your object.

Upvotes: 1

Related Questions