Spring緩衝機制執行個體代碼,spring緩衝執行個體

來源:互聯網
上載者:User

Spring緩衝機制執行個體代碼,spring緩衝執行個體

Spring的緩衝機制非常靈活,可以對容器中任意Bean或者Bean的方法進行緩衝,因此這種緩衝機制可以在JavaEE應用的任何層次上進行緩衝。

Spring緩衝底層也是需要藉助其他緩衝工具來實現,例如EhCache(Hibernate緩衝工具),上層則以統一API編程。

要使用Spring緩衝,需要以下三步

  • 1.向Spring設定檔匯入context:命名空間
  • 2.在Spring設定檔啟用緩衝,具體是添加 <cache:annotation-driven cache-manager="緩衝管理器ID" />
  • 3.配置緩衝管理器,不同的緩衝實現配置不同,如果是EhCache,需要先配置一個ehcache.xml

例如

<?xml version="1.0" encoding="UTF-8"?><ehcache>  <diskStore path="java.io.tmpdir" />  <!-- 配置預設的緩衝區 -->  <defaultCache    maxElementsInMemory="10000"    eternal="false"    timeToIdleSeconds="120"    timeToLiveSeconds="120"    maxElementsOnDisk="10000000"    diskExpiryThreadIntervalSeconds="120"    memoryStoreEvictionPolicy="LRU"/>  <!-- 配置名為users的緩衝區 -->  <cache name="users"    maxElementsInMemory="10000"    eternal="false"    overflowToDisk="true"    timeToIdleSeconds="300"    timeToLiveSeconds="600" /></ehcache>

上面的ehcache.xml配置了兩個緩衝區,Spring中的Bean將會緩衝在這些緩衝區中,一般的,Spring容器中有多少個Bean,就會在ehcache中定義多少個緩衝區。

接著在Spring設定檔中配置緩衝管理器如下,其中第一個Bean是一個工廠Bean,用來配置EhCache的CacheManager, 第二個Bean才是為Spring緩衝配置的緩衝管理器,所以將第一個Bean注入第二個Bean。

<cache:annotation-driven cache-manager="cacheManager" />  <!-- 配置EhCache的CacheManager  通過configLocation指定ehcache.xml檔案的位置 -->  <bean id="ehCacheManager"    class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"    p:configLocation="classpath:ehcache.xml"    p:shared="false" />  <!-- 配置基於EhCache的緩衝管理器  並將EhCache的CacheManager注入該緩衝管理器Bean -->  <bean id="cacheManager"    class="org.springframework.cache.ehcache.EhCacheCacheManager"    p:cacheManager-ref="ehCacheManager" >   </bean>

下面是一個完整的Spring配置,

<?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:p="http://www.springframework.org/schema/p"  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-4.0.xsd  http://www.springframework.org/schema/cache  http://www.springframework.org/schema/cache/spring-cache-4.0.xsd  http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-4.0.xsd">  <context:component-scan     base-package="com.service"/>      <cache:annotation-driven cache-manager="cacheManager" />  <!-- 配置EhCache的CacheManager  通過configLocation指定ehcache.xml檔案的位置 -->  <bean id="ehCacheManager"    class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"    p:configLocation="classpath:ehcache.xml"    p:shared="false" />  <!-- 配置基於EhCache的緩衝管理器  並將EhCache的CacheManager注入該緩衝管理器Bean -->  <bean id="cacheManager"    class="org.springframework.cache.ehcache.EhCacheCacheManager"    p:cacheManager-ref="ehCacheManager" >   </bean>  </beans>

下面將以@Cacheable為例,示範Spring基於EhCache緩衝的用法。 Cacheable用於修飾類或者方法,如果修飾類,則類中所有方法都會被緩衝。

類層級的緩衝

例如有如下Bean類,

@Service("userService")@Cacheable(value="users")public class UserServiceImpl implements UserService {  @Override  public User getUsersByNameAndAge(String name, int age) {    System.out.println("正在執行getUsersByNameAndAge()..");    return new User(name,age);  }  @Override  public User getAnotherUser(String name, int age) {    System.out.println("正在執行getAnotherUser()..");    return new User(name,age);  }}

基於類的緩衝,將會緩衝類中的所有方法,緩衝之後,程式調用該類執行個體的任何方法,只要傳入的參數相同,Spring將不會真正執行該方法,而是直接根據傳入的參數去尋找緩衝中的資料!

比如像下面這樣使用快取資料,

public static void test2() {    ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");    UserService us = ctx.getBean("userService", UserService.class);    User u1 = us.getUsersByNameAndAge("張三", 50);    //由於第二次調用userService方法時,使用了相同參數,那麼真正的方法將不會執行,    //Spring將直接從緩衝按參數尋找資料    User u2 = us.getAnotherUser("張三", 50);    System.out.println(u1==u2);  }

輸出結果,

正在執行getUsersByNameAndAge()..
true

可以看到,上面的getAnotherUser()並沒有真正執行,因為傳入的參數與之前的方法傳入的參數相同,於是Spring直接從緩衝區資料了。

上面的Bean類中的註解@Cacheable除了必選屬性value之外,還有key, condition,, unless屬性,後面三個都是用來設定Spring儲存策略,對於基於類的緩衝來說,Spring預設以方法傳入的參數作為key去緩衝中尋找結果。

當然我們也可以修改key的策略,讓Spring按照其他標準,比如按照第一個參數是否相同來作為key,在緩衝中尋找結果。

將上面的Bean類修改如下,

@Service("userService")@Cacheable(value="users", key="#name")public class UserServiceImpl implements UserService {  @Override  public User getUsersByNameAndAge(String name, int age) {

意味著我們傳入相同的name,Spring就不會真正執行方法。只有name不同的時候,方法才會真正執行,例如下面,

public static void test2() {    ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");    UserService us = ctx.getBean("userService", UserService.class);    User u1 = us.getUsersByNameAndAge("張三", 50);    //將@Cacheable的key參數改為key="#name"之後,下面的方法將可以執行。    User u2 = us.getAnotherUser("李四", 50);    System.out.println(u1==u2);  }

可以看到這回getAnotherUser()方法得到執行了,

1 正在執行getUsersByNameAndAge()..
2 正在執行getAnotherUser()..
3 false

我們也可以設定condition屬性,例如,

@Service("userService")@Cacheable(value="users", condition="#age<100")public class UserServiceImpl implements UserService {  @Override  public User getUsersByNameAndAge(String name, int age) {

那麼對於下面的代碼來說,兩個方法都不會被緩衝,Spring每次都是執行真正的方法取結果,

public static void test2() {    ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");    UserService us = ctx.getBean("userService", UserService.class);    User u1 = us.getUsersByNameAndAge("張三", 500);    User u2 = us.getAnotherUser("李四", 500);    System.out.println(u1==u2);  }

執行結果,

正在執行getUsersByNameAndAge()..
正在執行getAnotherUser()..
false

方法層級的緩衝

方法層級的緩衝則只會對方法起作用了,不同的方法可以設定不用的緩衝區,例如下面這樣,

@Service("userService")public class UserServiceImpl implements UserService {  @Cacheable("users1")  @Override  public User getUsersByNameAndAge(String name, int age) {    System.out.println("正在執行getUsersByNameAndAge()..");    return new User(name,age);  }  @Cacheable("users2")  @Override  public User getAnotherUser(String name, int age) {    System.out.println("正在執行getAnotherUser()..");    return new User(name,age);  }}

使用下面的測試代碼,

public static void test2() {    ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");    UserService us = ctx.getBean("userService", UserService.class);    //第一次執行方法,方法將會真正執行並緩衝    User u1 = us.getUsersByNameAndAge("張三", 500);    //雖然下面方法傳入相同參數,但是因為這兩個方法在不同的緩衝區,所以無法使用快取資料    User u2 = us.getAnotherUser("張三", 500);    System.out.println(u1==u2);    //上面已經緩衝過,這裡不會真正執行,直接使用緩衝    User u3 = us.getAnotherUser("張三", 500);    System.out.println(u3==u2);  }

執行結果,

正在執行getUsersByNameAndAge()..
正在執行getAnotherUser()..
false
true

使用@CacheEvict清除緩衝

被@CacheEvict修飾的方法可以用來清除緩衝,使用@CacheEvict可以指定如下屬性。

allEntries, 是否清空整個緩衝區

beforeInvocation: 是否在執行方法之前清除緩衝。預設是方法執行成功之後才清除。

condiition以及key, 與@Cacheable中一樣的含義。

下面示範簡單用啊,

@Service("userService")@Cacheable("users")public class UserServiceImpl implements UserService {@Override  public User getUsersByNameAndAge(String name, int age) {System.out.println("正在執行getUsersByNameAndAge()..");return new User(name,age);}@Override  public User getAnotherUser(String name, int age) {System.out.println("正在執行getAnotherUser()..");return new User(name,age);}//指定根據name,age參數清楚緩衝@CacheEvict(value="users")  public void evictUser(String name, int age) {System.out.println("--正在清空"+name+","+age+"對應的緩衝--");}//指定清除user緩衝區所有緩衝的資料@CacheEvict(value="users", allEntries=true)  public void evictAll() {System.out.println("--正在清空整個緩衝--");}}

下面是測試類別,

public static void test2() {    ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");    UserService us = ctx.getBean("userService", UserService.class);    //系統會緩衝兩個方法    User u1 = us.getUsersByNameAndAge("張三", 500);    User u2 = us.getAnotherUser("李四",400);    //調用evictUser()方法清除緩衝區指定的資料    us.evictUser("李四", 400);    //前面清除了 李四, 400 的緩衝,下面的方法返回的資料將會再次被緩衝    User u3 = us.getAnotherUser("李四", 400);    System.out.println(us == u3);  //false    //前面已經緩衝了 張三, 500的資料,下面方法不會重新執行,直接取緩衝中的資料    User u4 = us.getAnotherUser("張三", 500);    System.out.println(u1==u4); //輸出true    //清空整個緩衝    us.evictAll();    //由於整個緩衝都已經被清空,下面的代碼都會被重新執行    User u5 = us.getAnotherUser("張三", 500);    User u6 = us.getAnotherUser("李四", 400);    System.out.println(u1==u5); //輸出false    System.out.println(u3==u6); //輸出false  }

執行結果,

正在執行getUsersByNameAndAge()..
正在執行getAnotherUser()..
--正在清空李四,400對應的緩衝--
正在執行getAnotherUser()..
false
true
--正在清空整個緩衝--
正在執行getAnotherUser()..
正在執行getAnotherUser()..
false
false

總結

以上就是本文關於Spring緩衝機制執行個體代碼的全部內容,希望對大家有所協助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.