【问题标题】:Spring @Cacheable Not WorkingSpring @Cacheable 不工作
【发布时间】:2013-03-12 16:16:23
【问题描述】:

我有一个使用 @Cacheable 注释的 dao 方法,但它的缓存根本不起作用。我将日志消息放在方法中。

<cache:annotation-driven mode="proxy" proxy-target-class="true" cache-manager="cacheManager" />
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> 
        <property name="configLocation" value="WEB-INF/ehcache/ehcache.xml"></property>
        <property name="shared" value="true"></property>
    </bean>

<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
        <property name="cacheManager" ref="ehcache"></property>
    </bean>

@Controller
@RequestMapping(value = "/analytics")
public class AnalyticsController {

    @Autowired
    private ReportDao reportDao;

    /**
     * 
     */
    public AnalyticsController() {
    }

    @RequestMapping(value = "/lcr-report", method = RequestMethod.GET)
    public String viewCostReport(ModelMap map) {

        List<Country> countryList = reportDao.getAllCountry();

        map.put("countryList", countryList);

        return "lcrReport";
    }

}


@Repository
@Transactional(propagation=Propagation.REQUIRED, isolation=Isolation.DEFAULT, 
    rollbackFor={DataAccessException.class, SQLException.class, Exception.class})
public class ReportDao {

    @Autowired
    private JdbcTemplate dao;

    /**
     * 
     */
    public ReportDao() {
    }

    @Cacheable(value = {"reportDao"}/*, key= "T(Country).hash(#List<Country>)"*/)
    @Transactional(propagation=Propagation.REQUIRED, isolation=Isolation.DEFAULT, readOnly=true, 
            rollbackFor={DataAccessException.class, SQLException.class, Exception.class})
    public List<Country> getAllCountry() {
        List<Country> countryList =  null;
        BeanPropertyRowMapper<Country> mapper = new BeanPropertyRowMapper<Country>(Country.class);
        PreparedStatementCreator psc = new GenericPreparedStatementCreator("select c.country_code as countryCode, c.name as countryName from country c");
        System.out.println("Not from cache");
        countryList = dao.query(psc, mapper);

        return countryList;
    }

}

【问题讨论】:

  • 如何在方法上为 List 添加一个键?
  • 我认为您的ehcache.xml 有问题。也请张贴。

标签: spring ehcache


【解决方案1】:

您应该使用方法getAllCountry 的参数来创建密钥。在你的情况下它是空的,所以你可以这样做:

@Transactional(readOnly = true)
@Cacheable(value = CACHE_NAME, key = "'countries'")

并检查它是否使用地图缓存:

@Configuration
@EnableCaching(proxyTargetClass = true)
public class CacheProducer {

@Bean
public CacheManager cacheManager() {
        SimpleCacheManager result = new SimpleCacheManager();
        result.setCaches(Arrays.asList(new ConcurrentMapCache(DictionaryServiceImpl.CACHE_NAME)));
        return result;
    }
}

如果它有效 - 是时候检查你的 echache 配置了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-03
    • 2017-05-22
    • 2012-12-25
    相关资源
    最近更新 更多