ehcache-core)Maven 依賴:
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.6.11</version>
</dependency>
<beans ... xmlns:cache="https://www.springframework.org/schema/cache"
xsi:schemaLocation="... https://www.springframework.org/schema/cache/spring-cache.xsd">
<!-- 數據源、MyBatis 配置省略 -->
<!-- 啟用緩存注解 -->
<cache:annotation-driven cache-manager="cacheManager"/>
<!-- EhCacheManagerFactoryBean 加載 ehcache.xml -->
<bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache.xml"/>
</bean>
<!-- Spring CacheManager 適配器 -->
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="cacheManagerFactory"/>
</bean>
<mvc:annotation-driven/>
<context:component-scan base-package="com.example.controller, com.example.service"/>
</beans>
<ehcache xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://ehcache.org/ehcache.xsd"> <!-- 修正 xsd 路徑 -->
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="false"/>
<cache name="myCache"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="0"
timeToLiveSeconds="0"
memoryStoreEvictionPolicy="LFU"/>
</ehcache>
注意:timeToIdleSeconds="0" 表示無閒置超時,timeToLiveSeconds="0" 表示永不過期 (配合 LFU 淘汰)。
@Service
public class UserService {
@Autowired UserDao userDao;
@Cacheable(value = "myCache", key = "'allUsers'")
public List<User> listAllUsers() {
System.out.println(">>> Querying database...");
return userDao.listAllUsers();
}
}
首次調用打印 "Querying database...",後續調用直接返回緩存,無日誌輸出。
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired UserService userService;
@RequestMapping("/index")
public ModelAndView index() {
System.out.println("Size: " + userService.listAllUsers().size());
return new ModelAndView("index");
}
}
/user/index → 控制台打印查詢日誌。