springmvc+ehcache簡單例子

jopen 10年前發布 | 115K 次閱讀 Spring MVC Web框架 Ehcache

springmvc+ehcache簡單例子

這里采用的是spring3.2、ehcache2.7、tomcat7.0(必須)

1.web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <!-- SpringMVC核心分發器 -->
    <servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

2.applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:cache="http://www.springframework.org/schema/cache"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
                        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd  
                        http://www.springframework.org/schema/mvc  
                        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd  
                        http://www.springframework.org/schema/cache  
                        http://www.springframework.org/schema/cache/spring-cache-3.2.xsd  
                        http://www.springframework.org/schema/context  
                        http://www.springframework.org/schema/context/spring-context-3.2.xsd">
    <context:component-scan base-package="com" />
    <!-- 緩存配置 -->
    <!-- 啟用緩存注解功能(請將其配置在Spring主配置文件中) -->
    <cache:annotation-driven cache-manager="cacheManager" />
    <!-- Spring自己的基于java.util.concurrent.ConcurrentHashMap實現的緩存管理器(該功能是從Spring3.1開始提供的) -->
    <!-- <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager"> 
        <property name="caches"> <set> <bean name="myCache" class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"/> 
        </set> </property> </bean> -->
    <!-- 若只想使用Spring自身提供的緩存器,則注釋掉下面的兩個關于Ehcache配置的bean,并啟用上面的SimpleCacheManager即可 -->
    <!-- Spring提供的基于的Ehcache實現的緩存管理器 -->
    <bean id="cacheManagerFactory"
        class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
        <property name="configLocation" value="classpath:ehcache.xml" />
    </bean>
    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
        <property name="cacheManager" ref="cacheManagerFactory" />
    </bean>
</beans>

3.ehcache.xml

<!-- Ehcache2.x的變化(取自https://github.com/springside/springside4/wiki/Ehcache) -->  
<!-- 1)最好在ehcache.xml中聲明不進行updateCheck -->  
<!-- 2)為了配合BigMemory和Size Limit,原來的屬性最好改名 -->  
<!--   maxElementsInMemory->maxEntriesLocalHeap -->  
<!--   maxElementsOnDisk->maxEntriesLocalDisk -->  
<ehcache>  
    <diskStore path="java.io.tmpdir"/>  
    <defaultCache  
           maxElementsInMemory="1000"  
           eternal="false"  
           timeToIdleSeconds="120"  
           timeToLiveSeconds="120"  
           overflowToDisk="false"/>  
    <cache name="myCache"  
           maxElementsOnDisk="20000"  
           maxElementsInMemory="2000"  
           eternal="true"  
           overflowToDisk="true"  
           diskPersistent="true"/>  
</ehcache>  
<!--  
<diskStore>==========當內存緩存中對象數量超過maxElementsInMemory時,將緩存對象寫到磁盤緩存中(需對象實現序列化接口)  
<diskStore path="">==用來配置磁盤緩存使用的物理路徑,Ehcache磁盤緩存使用的文件后綴名是*.data和*.index  
name=================緩存名稱,cache的唯一標識(ehcache會把這個cache放到HashMap里)  
maxElementsOnDisk====磁盤緩存中最多可以存放的元素數量,0表示無窮大  
maxElementsInMemory==內存緩存中最多可以存放的元素數量,若放入Cache中的元素超過這個數值,則有以下兩種情況  
                     1)若overflowToDisk=true,則會將Cache中多出的元素放入磁盤文件中  
                     2)若overflowToDisk=false,則根據memoryStoreEvictionPolicy策略替換Cache中原有的元素  
eternal==============緩存中對象是否永久有效,即是否永駐內存,true時將忽略timeToIdleSeconds和timeToLiveSeconds  
timeToIdleSeconds====緩存數據在失效前的允許閑置時間(單位:秒),僅當eternal=false時使用,默認值是0表示可閑置時間無窮大,此為可選屬性  
                     即訪問這個cache中元素的最大間隔時間,若超過這個時間沒有訪問此Cache中的某個元素,那么此元素將被從Cache中清除  
timeToLiveSeconds====緩存數據在失效前的允許存活時間(單位:秒),僅當eternal=false時使用,默認值是0表示可存活時間無窮大  
                     即Cache中的某元素從創建到清楚的生存時間,也就是說從創建開始計時,當超過這個時間時,此元素將從Cache中清除  
overflowToDisk=======內存不足時,是否啟用磁盤緩存(即內存中對象數量達到maxElementsInMemory時,Ehcache會將對象寫到磁盤中)  
                     會根據標簽中path值查找對應的屬性值,寫入磁盤的文件會放在path文件夾下,文件的名稱是cache的名稱,后綴名是data  
diskPersistent=======是否持久化磁盤緩存,當這個屬性的值為true時,系統在初始化時會在磁盤中查找文件名為cache名稱,后綴名為index的文件  
                     這個文件中存放了已經持久化在磁盤中的cache的index,找到后會把cache加載到內存  
                     要想把cache真正持久化到磁盤,寫程序時注意執行net.sf.ehcache.Cache.put(Element element)后要調用flush()方法  
diskExpiryThreadIntervalSeconds==磁盤緩存的清理線程運行間隔,默認是120秒  
diskSpoolBufferSizeMB============設置DiskStore(磁盤緩存)的緩存區大小,默認是30MB  
memoryStoreEvictionPolicy========內存存儲與釋放策略,即達到maxElementsInMemory限制時,Ehcache會根據指定策略清理內存  
                                 共有三種策略,分別為LRU(最近最少使用)、LFU(最常用的)、FIFO(先進先出)  
-->

4.UserController.java

package com.controller;

import net.sf.ehcache.CacheManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.service.UserService;

@Controller
public class UserController
{

    @Autowired
    private UserService userService;
    @Autowired
    private CacheManager cacheManager;

    @RequestMapping(value = "test", method = RequestMethod.GET)
    public String test()
    {
        System.out.println(cacheManager.getCache("myCache").get("test"));
        userService.test();
        return "hello";
    }

}

6.UserService.java

package com.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.dao.UserDao;
import com.model.User;

@Service
public class UserService
{

    @Autowired
    private UserDao userDao;

    @Cacheable(value = "myCache", key = "'test'")
    public List<User> test()
    {
        System.out.println("select from db");
        return userDao.test();
    }

}

7.UserDao.java

package com.dao;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.model.User;

@Repository
public class UserDao
{
    private List<User> userlist;
    private User user;

    public UserDao()
    {
        userlist = new ArrayList<User>();
        user = new User();
        user.setId(0);
        userlist.add(user);
        user = new User();
        user.setId(1);
        userlist.add(user);
        user = new User();
        user.setId(2);
        userlist.add(user);
        user = new User();
        user.setId(3);
        userlist.add(user);
    }

    public List<User> test()
    {
        return userlist;
    }

}

8.User.java

package com.model;

import java.io.Serializable;

public class User implements Serializable
{

    /**
     * 
     */
    private static final long serialVersionUID = 5104855734772499069L;
    private int id;

    public int getId()
    {
        return id;
    }

    public void setId(int id)
    {
        this.id = id;
    }

    @Override
    public String toString()
    {
        return "User [id=" + id + "]";
    }

}

9.瀏覽器輸入http://localhost:8080/springcache/test,第一次輸出null,select from db,第二次輸出[cache.........]

PS:其實,你不會發現沒有 5. = =


 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!