简体   繁体   中英

How to cache ResponseEntity<Resource> in spring boot

I am trying to cache ResponseEntity in spring boot but unable to find a proper way to implement the same.

There are few examples where

        return ResponseEntity.ok()
            .cacheControl(CacheControl.maxAge(20, TimeUnit.SECONDS))
            .body(body);

But my problem here is that I am using an external library that returns

ResponseEntity<Resource>

and I wanted to cache that response. so it should be like

ResponseEntity<Resource> getResource() {
     
       ResponseEntity<Resource> resource = getResourceFromExternalFunction();
       // wanted to cache this resource
       return cachedResource
}

If I apply above technique for my code, it would be like

ResponseEntity<Resource> getResource() {
     
       ResponseEntity<Resource> resource = getResourceFromExternalFunction();
       return ResponseEntity.ok()
            .cacheControl(CacheControl.maxAge(20, TimeUnit.SECONDS))
            .body(resource );
}

it would return

ResourceEntity<ResourceEntity<Resource>> 

which is not expected. Can some one help here please

Always be on the look out for SpringBoot libraries that already exist before you try and reinvent the wheel. Lucky for you, the Spring community already has such a caching library which should make your life much easier, you can find a tutorial on it here:

Baeldung: A Guide to Caching in Spring

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM