How to set the cache expiration time when using Redis annotations? Import Redis dependencies. Use ttl attributes annotated with @Cacheable and @CachePut. The ttl attribute specifies the cache expiration time in seconds.
Redis annotation sets cache expiration time
Question: How to use Redis annotation Set cache expiration time?
Answer:
To set the cache expiration time when using Redis annotations, you can use @Cacheable
and @CachePut
The ttl
attribute of the annotation.
Specific steps:
<code class="xml"><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency></code>
@Cacheable
Annotation: <code class="java">@Cacheable(value = "cacheName", key = "#key", ttl = 300) public Object get(Object key) { // 逻辑代码 }</code>
Where:
value
Specify the cache namekey
Specify the cache keyttl
Specify the cache expiration time in seconds@CachePut
Note: <code class="java">@CachePut(value = "cacheName", key = "#key", ttl = 300) public Object put(Object key, Object value) { // 逻辑代码 }</code>
In the above example, the get()
method gets the data in the cache. If there is no data in the cache, Then the logic code is executed and the results are cached for 5 minutes. The put()
method puts the data into the cache and sets the expiration time to 5 minutes.
Note:
ttl
The property can be set to any positive integer in seconds. ttl
attribute is not specified, the cache will never expire. The above is the detailed content of redis annotation sets cache expiration time. For more information, please follow other related articles on the PHP Chinese website!