Conteúdo do Curso
Introduction to Redis
Introduction to Redis
Annotations for Working with Cache
Instead of manually handling caching, you can use annotations that automatically manage the process. Let's take a look at the annotations available.
Caching Results
The @Cacheable
annotation is applied to methods whose results should be cached. When the method is called again with the same parameters, the result is retrieved from the cache.
In this example, the getUserById
method caches the result of a user query by their ID
in a cache named "usersCache"
. If the method is called again with the same userId
, the data is retrieved from the cache instead of executing the query against the database.
Updating the Cache
The @CachePut
annotation updates the cache every time the method is executed, regardless of whether the result was cached previously.
The @CachePut
annotation is used to update the cache each time the updateUser
method is called. This is useful when the data changes and you need to synchronize the cache with the changes in the database. The cache is updated with the key corresponding to the user ID.
Clearing the Cache
The @CacheEvict
annotation is used to remove data from the cache, such as when a user is deleted from the database.
In this example, the deleteUser
method removes the entry from the cache with the key equal to userId
.
Combined Cache Operations
The @Caching
annotation allows multiple caching operations to be performed within a single method, combining @CachePut
and @CacheEvict
.
In this example, the updateUser
method simultaneously updates the cache with the new state of the user using @CachePut
and removes the old entry from the cache using @CacheEvict
. This is useful when you need to perform multiple cache operations at the same time.
1. When would you use @CacheEvict
?
2. What is the purpose of the @CachePut
annotation?
Obrigado pelo seu feedback!