1

I have a service that searches the user by id, email, or username. Also, it can update or delete user by id.

@Service
public class UserService{


  public User getUserByEmail(String email) { ... }


  public User getUserByUsername(String usern) { ... }


  @Cacheable(cacheNames = "user", key = "#id")
  public User getUserById(Long id) { ... }


  @CachePut(cacheNames = "user", key = "#id")
  public User updateUser(Long id, String name, String phone) { ... }


  @CacheEvict(cacheNames = "user", key = "#id")
  public User deleteUserById(Long id) { ... }


}

The caching implementation works fine with this current implementation.

Now, what should I do to implement caching for getUserByEmail and getUserByUsername function as well? Since all of the getter functions point to the same cache table user, is there a way to maintain the cache table with multiple keys (id, email, and username) such that I can use any of the key to get cached data?

If possible, how would that affect my @CachePut and @CacheEvict?

paradox
  • 303
  • 3
  • 16
  • Have you read the section on (custom) key generation? https://docs.spring.io/spring/docs/current/spring-framework-reference/integration.html#cache-annotations-cacheable-key Perhaps you could pass the user object in full to these methods (so that the key can become `#user.id`, and then do user.getEmail() or user.getId() in the actual method? – user1884155 Apr 23 '20 at 10:08
  • @user1884155 I read the documentation. The problem is, if I use the user object in full as a key, how would I annotate the methods `getUserById`, `getUserByEmail`, and `getUserByUsername` where I will just have a single field of user available? I read the documentation but could not figure it out. You can put multiple keys using AND logic but could not find a way to use multiple keys using OR logic. – paradox Apr 24 '20 at 03:43

0 Answers0