opuser1
opuser1

Reputation: 477

Spring cacheable annotation with multiple key

I have 2 ways to lookup a customer record (code below), customerGuid and customerId are 2 different fields in Customer object.

Suppose that i lookup customer by customerId once, is there a way for me to lookup customer by guid directly from cache without querying backend, Assuming both the methods return type is Customer.

public class CustomerLookup {
    @Cacheable("customerCache")
    public Customer getCustomerByGuid(final String customerGuid) {
        // some implementation here...
    }

    @Cacheable("customerCache")
    public Customer getCustomerByCustId(final String customerId) {
        // some implementation here...
    }
}

Upvotes: 0

Views: 1193

Answers (1)

akuma8
akuma8

Reputation: 4681

You can add a 2nd parameter to one method which will only serve as cache key. Example use customerId as key and proceed like this:

@Service
public class CustomerLookup {
   @Autowired
   @Lazy
   private CustomerLookup self;

   @CachePut("customerCache", key="#customerId")
   public Customer getCustomerByGuid(final String customerGuid, String customerId) {
     Customer customer = self.getCustomerByCustId(final String customerId);
     //......
   }
}

Note the self-injection of CustomerLookup if you don't do that the cache won't work when you call the getCustomerByCustId(final String customerId) method in getCustomerByGuid. Also note the @CachePut instead of @Cacheable on getCustomerByGuid, with this you are sure that this method will be called everytime.

Upvotes: 1

Related Questions