How to cache REST API response in java

thaveethu gce picture thaveethu gce · Apr 8, 2017 · Viewed 24.2k times · Source

I am building an app in java.I hit api more than 15000 times in loop and get the response ( response is static only )

Example

**
  username in for loop   
  GET api.someapi/username
  processing
  end loop
**

It is taking hours to complete all the calls. Suggest me any way (any cache technology) to reduce the call time.

P.S :

1) i am hitting api from java rest client(Spring resttemplate)

2) that api i am hitting is the public one, not developed by me

3) gonna deploy in heroku

Answer

dave0688 picture dave0688 · Aug 30, 2017

One very important note to that answer: If you ever plan to update those (cached) values, don't forget to use @CacheEvict on save() and delete() in the repositories. Else you will have problems fetching the new record when it is updated.

I have implemented my solution (with EhCache) this way (in the repository):

CurrencyRepository.java: // define a cacheable statement

@Cacheable("currencyByIdentifier")
public Currency findOneByIdentifier(String identifier);

CacheConfiguration.java: // Define that cache in EhCache Configuration

@Bean
public JCacheManagerCustomizer cacheManagerCustomizer() {
    return cm -> {
        cm.createCache("currencyByIdentifier", jcacheConfiguration);
        cm.createCache("sourceSystemByIdentifier", jcacheConfiguration);
    };
}

CurrencyRepository.java: // evict on save and delete by overriding the default method

@Override
@CacheEvict("currencyByIdentifier")
<S extends Currency> S save(S currency);

@Override
@CacheEvict("currencyByIdentifier")
void delete(Currency currency);

I hope that helps :)