How to cache REST API response in java

I am creating an application in java.I hit the api over 15000 times in a loop and get a response (response is static only)

Example

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

      

It takes several hours to complete all calls. Please suggest me any way (any caching technology) to reduce the call time.

PS:

1) I am pushing api from java rest client (Spring resttemplate)

2) that api I am public, not developed by me

3) is about to unfold into a hero

+3


source to share


2 answers


Try to use a cache abstraction Springs, https://docs.spring.io/spring/docs/current/spring-framework-reference/html/cache.html

.

You can use this abstraction in a method that has a restTemplate call.

Any response to method calls can be cached using this abstraction with the method parameters as keys and the return type as the response.



@Cacheable("username")
public UserResponse getUser(String username){
   // Code to call your rest api
}

      

This creates a Spring AOP advice around the method. Every time the method is called, it checks if data is available in the cache for this key (username), if so, it returns a response from the cache and does not call the actual method. If the data is not available in the cache then it calls the actual method and caches the data in the cache, so the next time the same method is called with one key, the data can be fetched from the cache.

This cache abstraction can be supported by simple JVM caches like Guava or more complex cache implementations like EHCache, Redis, HazelCast.

+5


source


It's very important to note this answer: if you ever plan on updating these (cached) values, don't forget to use @CacheEvict to save () and delete () to the repos. Otherwise, you will have trouble getting a new record when you update it.

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

CurrencyRepository.java: // define the cache code

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

      

CacheConfiguration.java: // Define this cache in the EhCache config



@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);

      

Hope it helps :)

+3


source







All Articles