Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Annotations for Working with Cache | Caching with Redis and Spring Boot
Introduction to Redis
course content

Course Content

Introduction to Redis

Introduction to Redis

1. Redis Fundamentals
2. The Essential Redis Commands
3. Data Types in Redis
4. Advanced Features and Security
5. Caching with Redis and Spring Boot

book
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?

When would you use `@CacheEvict`?

When would you use @CacheEvict?

Select the correct answer

What is the purpose of the `@CachePut` annotation?

What is the purpose of the @CachePut annotation?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 5. Chapter 3
We're sorry to hear that something went wrong. What happened?
some-alt