2013-03-12 86 views
1

我有一個dao方法用@Cacheable註解,但是它的緩存根本不起作用。我把日誌消息放在方法裏面。Spring @Cacheable不能正常工作

<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; 
    } 

} 
+0

如何在該方法上添加列表的密鑰? – peterwkc 2013-03-12 07:17:07

+0

我認爲你的'ehcache.xml'有問題。請張貼它。 – 2013-03-12 07:18:48

回答

2

您應該使用方法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配置。

+0

我使用記錄器測試了多個呼叫,它可以工作。 – peterwkc 2013-03-12 08:30:19