0

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... } } 

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer, however in mycase the caller of getCustomerByGuid() mayn't always know or have customerId. Thats one of the reason why there are 2 lookup methods.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.