spring - 为什么 Spring 消息转换器仍然在 @Cachable 方法中被调用

标签 spring caching optimization

假设我的 Controller 中有两种方法来支持 json 和 xml。

@RequestMapping(value = "/get/response.json", method = RequestMethod.GET)
@Cacheable(JSON_CACHE)
public @ResponseBody JSONResponse getJsonResponse(){
    return responseService.getJsonResponse();
}
@RequestMapping(value = "/get/response.xml", method = RequestMethod.GET)
@Cacheable(XML_CACHE)
public  @ResponseBody XMLResponse getXmlResponse(){
    return responseService.getXmlResponse();
}

还有两个消息转换器,将我的对象编码为合适的响应。

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="jsonConverter"/>
            <ref bean="xmlConverter" />
        </list>
    </property>
</bean>

问题在于 Spring 3.1,即使方法使用 @Cachable 进行注释,仍然会为每次调用调用 marshaller。它在编码之前缓存对象的状态。 这是 Not Acceptable ,因为性能在这里至关重要,而编码对我来说太昂贵了。我希望 Spring 在这种情况下缓存最终响应。我在这里做错了什么吗?

最佳答案

为了避免此问题,可以使用 ehcache Web 缓存:http://www.ehcache.org/documentation/user-guide/web-caching

它的工作原理是简单地向 web.xml 添加过滤器并提供 HTTP 响应的缓存。

<filter>
    <filter-name>SimpleCachingHeadersPageCachingFilter</filter-name>
    <filter-class>net.sf.ehcache.constructs.web.filter.SimpleCachingHeadersPageCachingFilter
    </filter-class>
    <init-param>
        <param-name>suppressStackTrace</param-name>
        <param-value>false</param-value>
    </init-param>
    <init-param>
        <param-name>cacheName</param-name>
        <param-value>CachedPage2Cache</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>SimpleCachingHeadersPageCachingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

关于spring - 为什么 Spring 消息转换器仍然在 @Cachable 方法中被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11001180/

相关文章:

java - 创建 Spring boot Web 服务而不使用 main 方法

spring - HTTP 状态 404 -/gwtspring/com.javacodegeeks.gwtspring.Application/Application.html

python - 使用 Flask-Cache 缓存 lxml.html 对象

java - Infinispan-10.0.1.Final : No marshaller registered for Java type java. util.UUID

mysql - 海量数据库和mysql

java - Mockito when() 方法不起作用并出现空指针异常

java - 配置spring security后出现未授权调用

java - 可以持久保存到磁盘的 memcached 的替代品

javascript - 什么是 CavalryLogger,我需要它吗?

Java压缩一些代码