Spring整合Ehcache緩存

新建一個maven項目。 項目結構圖以下:<br> 輸入圖片說明<br> 核心jar包:git

<dependency>
      <groupId>net.sf.ehcache</groupId>
      <artifactId>ehcache</artifactId>
      <version>2.8.3</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>3.2.8.RELEASE</version>
    </dependency>
    <dependency>

手動引入spring-context-support包避免由於版本的問題出錯(被坑過)<br>github

下面對關鍵的代碼進行解析:經過Java類來配置Ehcache,@EnableCaching註解來啓用緩存,而且通知Spring容器建立EhCacheManager,而且指定本地的ehcachel.xml文件spring

@Configuration
@EnableCaching
public class CachingConfig {
    [@Bean](https://my.oschina.net/bean)
    public EhCacheCacheManager ehCacheCacheManager(CacheManager cm) {
        return new EhCacheCacheManager(cm);
    }

    [@Bean](https://my.oschina.net/bean)
    public EhCacheManagerFactoryBean ehCacheManagerFactoryBean() {
        EhCacheManagerFactoryBean ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean();

        ehCacheManagerFactoryBean.setConfigLocation(new ClassPathResource("ehcache.xml"));
        return ehCacheManagerFactoryBean;
    }
}

ehcache.xml文件:緩存

<ehcache>
    <defaultCache
            maxElementsInMemory="10000"
            maxElementsOnDisk="100000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="true"
            diskSpoolBufferSizeMB="30"
            maxElementsOnDisk="10000000"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
    <cacheEventListenerFactory
            class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"/>
    <cache name="userListCache" maxBytesLocalHeap="50m" timeToLiveSeconds="100">
    </cache>
</ehcache>

ehcache.xml文件中幾個關鍵屬性: name:緩存的名稱;<br> maxElementsInMemory:內存中緩存element最大數量<br> maxElementsOnDisk:磁盤上緩存的最大數量<br> eternal:設定緩存是否永不過時<br> overflowToDisk:緩存超過內存限制是否緩存到磁盤上<br> timeToIdleSeconds:對象的空閒時間,多久沒有被訪問到就會失效<br> timeToLiveSeconds:對象的存活時間<br> memoryStoreEvictionPolicy:緩存超過指定內存的大小向磁盤緩存的策略,主要有三種FIFO,LFU,LRU (FIFO:先進先出,不做過多解釋,LFU:最少使用(緩存元素有個hit屬性,hit最小的就是最少使用的),LRU:最近最少被使用)<br>app

下面來進行業務邏輯的開發,對用戶信息進行查詢和修改:<br> UserMapper.xmlmaven

<select id="getUserList" resultType="com.spark.cache.model.User">
        select id as id,username as userName, password as password,age as age from user;
    </select>

    <update id="updateUser" parameterType="User">
        update `user` set id=#{id}
        <if test="userName!=null">
            ,username = #{userName}
        </if>
        <if test="password!=null">
            ,password = #{password}
        </if>
        <if test="age!=null">
            ,age = #{age}
        </if>
        where id = #{id}
    </update>

service層方法的實現:ide

@Cacheable(value = "userListCache")
    @Override
    public List<User> getUserList() {
        return userDao.getUserList();
    }

    @CacheEvict(value = "userListCache")
    @Override
    public int updateUser(User user) {
        return userDao.updateUser(user);
    }

介紹一下緩存中經常使用的註解:<br> @Cacheable : 代表在Spring調用方法以前,先在緩存中查找方法的返回值,若是可以找到,返回緩存中的值,不然,這個方法就會被調用,返回值放到緩存中。<br> @CachePut: 代表應該將該方法的返回值放到緩存中,方法調用以前不會檢查緩存,該方法始終會被調用。<br> @CacheEvict: 代表Spring應該在緩存中清空一個或者多個條目(緩存的value值)<br> @Caching:是一個分組的註解,可以同時應用多個其餘的緩存註解。測試

controller層處理:spa

@RequestMapping("/list")
    @ResponseBody
    public List<User> list() {
        return userService.getUserList();
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public User update(User user) {
        int result = userService.updateUser(user);
        if (result > 1) {
            return user;
        }
        return null;
    }

下面咱們來驗證一下:<br> 輸入圖片說明 看一下打印的日誌: 輸入圖片說明 再次請求: 輸入圖片說明 日誌沒有重複打印,說明咱們配置的緩存起做用了。.net

咱們來測試一下修改: 輸入圖片說明

再進行請求用戶列表接口,而後看一下日誌: 輸入圖片說明 執行了一次更新操做,還有一次查詢操做,說明咱們的緩存配置沒有問題。

若有不足之處,還請指出。

項目源碼:https://github.com/YunDongTeng/SpringEhCache/tree/master/springcache

相關文章
相關標籤/搜索