In Spring Boot, you can leverage the @Cacheable
annotation to enable caching in your application. However, the @Cacheable
annotation itself does not provide a way to set an expiry time for cached items. To achieve this, you'll need to utilize the capabilities of your chosen caching provider.
Using Ehcache
If you're using Ehcache as your caching provider, you can specify the expiry time in your ehcache.xml
configuration file. Here's an example:
<?xml version="1.0" encoding="UTF-8"?> <ehcache> <defaultCache eternal="true" maxElementsInMemory="100" overflowToDisk="false" /> <cache name="forecast" maxElementsInMemory="1000" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="false" memoryStoreEvictionPolicy="LRU" /> </ehcache>
In this configuration, the forecast
cache is set with a timeToIdleSeconds
and timeToLiveSeconds
of 120 seconds each. This means that cached items will expire after 120 seconds of inactivity or 120 seconds after being created, whichever comes first.
Using Caffeine
If you're using Caffeine as your caching provider, you can set the expiry time using the spring.cache.caffeine.spec
property in your application.properties file:
spring.cache.caffeine.spec=expireAfterWrite=60m
In this example, the cached items will expire 60 minutes after being written to the cache.
Using Redis
When using Redis as your caching provider, you can set the expiry time using the spring.cache.redis.time-to-live
property in your application.properties file:
spring.cache.redis.time-to-live=60m
Similar to Caffeine, this configuration sets the expiry time for cached items to 60 minutes.
Remember that the specific configuration options available for setting expiry times may vary depending on the caching provider you're using. Always refer to the documentation of your chosen caching provider for more details.