Java – how to make spring cache store ResponseBody instead of intermediate object

I use spring cache and this method to return the query value as JSON:

@RequestMapping("/getById")
@ResponseBody
@Cacheable
public HugeValue getHugeValueFromSlowFoo( @RequestParam(value = "id",defaultValue = "") String id ) {
  return Foo.getById( id );
}

This works, and the hugevalue object is stored in the cache (hazelcast in this case) I want to improve further because it takes quite a long time to create JSON from hugevalue Can I tell spring cache to cache JSON object version objects?

I use Jackson with spring boot 1.2 and spring 4.1

Solution

Without really knowing your exact use case (I haven't been allowed to add comments to ask unfortunately), I try to summarize my ideas briefly They all assume that you use Jackson for JSON mapping, at least spring 3.1

As far as I know, there is no enableresponsebody caching function in spring MVC

The first alternative: use HTTP caching because you seem to want to cache the entire HTTP response Spring provides an intuitive global configuration method:

<mvc:interceptors>
    <bean id="webContentInterceptor"
          class="org.springframework.web.servlet.mvc.WebContentInterceptor">
        <property name="cacheSeconds" value="0"/>
        <property name="useExpiresHeader" value="true"/>
        <property name="useCacheControlHeader" value="true"/>
        <property name="useCacheControlNoStore" value="true"/>
    </bean>
</mvc:interceptors>

If you want to control each controller, inherit from the spring abstractcontroller and set the cacheseconds property according to Javadoc

Of course, the real function of HTTP caching comes with an HTTP proxy in front of your server

Second idea: implement your own mappingjackson2httpmessageconverter subclass In writeinternal (), you can add some logic to access the cache to retrieve the mapped version instead of mapping the input object This approach means that you will hit your service to retrieve the Java objects behind the JSON stream If this is good for you because there is a cache at some time, it's worth trying

The third idea: make a JSON mapping in the dedicated wrapper service, which provides the original JSON string / stream You can easily inject Jackson mapper (class name objectmapper) and gain full control of the mapping Annotate the service and then allow you to cache the results In your controller, you only provide a responseentity (string or some streams) of the type you like to use If there are cached results, this can prevent even deeper service access

Editor: maybe mappingjackson2jsonview can also be convenient To be honest, I've never used it before, so I can't really talk about its usage

Hope to be helpful and / or inspired! Cheers!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>