Spring學習-緩存
阿新 • • 發佈:2017-09-25
一個 實現 .get xmlns 今天 cat tag -i web
提到緩存,能想到什麽?一級緩存、二級緩存、web緩存、redis。所有的緩存無非在宣揚一個優勢,那就是快,無需反復查詢等。今天講講Spring緩存如何實現。
如何實現?
1、聲明啟用緩存,添加緩存管理器
1 <beans xmlns="http://www.springframework.org/schema/beans" 2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xmlns:cache="http://www.springframework.org/schema/cache" 4 xmlns:p="http://www.springframework.org/schema/p" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans.xsd 7 http://www.springframework.org/schema/cache 8 http://www.springframework.org/schema/cache/spring-cache.xsd"> 9 10 <cache:annotation-driven /> 1112 <bean id="personService" class="com.jackie.service.PersonService" /> 13 14 <!-- generic cache manager --> 15 <bean id="cacheManager" 16 class="org.springframework.cache.support.SimpleCacheManager"> 17 <property name="caches"> 18 <set> 19 <bean 20 class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" 21 p:name="default" /> 22 23 <bean 24 class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" 25 p:name="personCache" /> 26 </set> 27 </property> 28 </bean> 29 </beans>
第10行作用:啟用緩存。
15~28行:添加緩存管理器。
編寫需要緩存的方法:1、創建一個測試bean Person對象 2、準備需要緩存的接口方法
1 @Component 2 public class Person { 3 4 private int id; 5 private int age; 6 private String name; 7 8 public int getId() { 9 return id; 10 } 11 12 public void setId(int id) { 13 this.id = id; 14 } 15 16 public int getAge() { 17 return age; 18 } 19 20 public void setAge(int age) { 21 this.age = age; 22 } 23 24 public String getName() { 25 return name; 26 } 27 28 public void setName(String name) { 29 this.name = name; 30 } 31 32 @Override 33 public String toString() { 34 return "Person{" + 35 "id=" + id + 36 ", age=" + age + 37 ", name=‘" + name + ‘\‘‘ + 38 ‘}‘; 39 } 40 }
準備需要緩存的接口方法
1 @Service("personService") 2 public class PersonService { 3 4 @Cacheable(value = "personCache") 5 public Person findPerson(int i) { 6 System.out.println("real query person object info"); 7 8 Person person = new Person(); 9 person.setId(i); 10 person.setAge(18); 11 person.setName("Jackie"); 12 return person; 13 } 14 15 }
@Cacheable:主要用來配置方法,能夠根據方法和請求參數對結果進行緩存,當調用相同參數的方法時,本身不會被調用,取而代之的是直接從返回中找到並返回,簡言之,就是緩存中有就取出,沒有就執行方法。
既然有緩存的過程,就有刪除緩存的過程。@CacheEvict
1 @CacheEvict(value = "personCache", key = "#person.getId()") 2 public void updatePerson(Person person) { 3 System.out.println("update: " + person.getName()); 4 } 5 6 @CacheEvict(value = "personCache", allEntries = true) 7 public void reload() { 8 9 }
第1行的意思是:當updatePerson被調用時,會根據key來取出相應的緩存記錄,並刪除。
第6行的意思是:在調用reload方法時,會清空所有的緩存記錄。
Spring學習-緩存