首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Spring MVC 4 整合 Ehcache 2.6 實現緩存實戰

     編輯:Java 綜合教學

環境與依賴

  • Spring MVC 4.x
  • Ehcache 2.6.11 (ehcache-core)
  • MyBatis + SQL Server (示例數據源)

Maven 依賴:

<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache-core</artifactId>
    <version>2.6.11</version>
</dependency>

Spring 配置 (springmvc-servlet.xml)

<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 配置 (ehcache.xml)

<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 層使用 @Cacheable

@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 調用

@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");
    }
}

驗證緩存生效

  1. 啟動項目,訪問 /user/index → 控制台打印查詢日誌。
  2. 再次訪問 → 無查詢日誌,直接返回視圖。
  3. 可通過 JMX / Ehcache 管理頁面監控緩存命中率。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved