ehcache整合spring注解方式


一、簡介

  在hibernate中就是用到了ehcache 充當緩存。spring對ehcache也提供了支持,使用也比較簡單,只需在spring的配置文件中將ehcache的ehcache.xml文件配置進去即可。在spring中使用ehcache有兩種方式,一種是使用spring提供的封裝,使用注解的方式配置在某個方法上面,第一次調用該方法的時候,將該方法執行返回的數據緩存,當再次執行的時候如果時間沒有變,就直接沖緩存獲取,該方法不執行;另一種方式是獲取到ehcache本地接口,直接使用ehcache本地接口進行數據緩存。第一種的方式使用簡單,代碼簡潔,但靈活度不高,而第二種方式靈活度高,但是代碼就比較到,需要自己去判斷數據是否緩存,如何沒有緩存就去獲取上海並本放入緩;如果緩存了,就直接去緩存中獲取。本例子是用的是第一種方式。

  工程使用maven構建,需要的依賴如下:

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>3.2.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache-core</artifactId>
            <version>2.4.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.2.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>3.2.6.RELEASE</version>
        </dependency>

二、示例代碼

   ehcache.xml代碼如下:

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
    updateCheck="false">

    <!-- 默認緩存配置 ,緩存名稱為 default -->
    <defaultCache maxElementsInMemory="50" eternal="false"
        overflowToDisk="false" memoryStoreEvictionPolicy="LFU" />
    <!-- 自定義緩存,名稱為lt.ehcache -->
    <cache name="lt.ecache" maxElementsInMemory="50" eternal="false"
        overflowToDisk="false" memoryStoreEvictionPolicy="LFU" />
</ehcache>  

  Spring-config-ehcache.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: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.0.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <cache:annotation-driven />
    <context:component-scan base-package="com.ehcache.test" /> <!-- 注解掃描路徑 -->
        
    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
        <property name="cacheManager" ref="ehcache" />
    </bean>
    
    <bean id="ehcache"
        class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
        <property name="configLocation" value="classpath:ehcache.xml" />
    </bean>
    
</beans>

  ehcache.xml與Spring-config-ehcache.xml存放在系統目錄下。

  相關代碼如下:

  實體Employee.java

 1 package com.ehcache.test;
 2 
 3 import java.io.Serializable;
 4 
 5 public class Employee implements Serializable {
 6     private static final long serialVersionUID = -6534180255882276966L;
 7     private int id;
 8     private String name;
 9     private String designation;
10 
11     public Employee(int id, String name, String designation) {
12         super();
13         this.id = id;
14         this.name = name;
15         this.designation = designation;
16     }
17 
18     public int getId() {
19         return id;
20     }
21 
22     public void setId(int id) {
23         this.id = id;
24     }
25 
26     @Override
27     public String toString() {
28         return "Employee [id=" + id + ", name=" + name + ", designation=" + designation + "]";
29     }
30 
31     public String getName() {
32         return name;
33     }
34 
35     public void setName(String name) {
36         this.name = name;
37     }
38 
39     public String getDesignation() {
40         return designation;
41     }
42 
43     public void setDesignation(String designation) {
44         this.designation = designation;
45     }
46 }

  EmployeeDAO.java

   

 1 package com.ehcache.test;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 import org.springframework.cache.annotation.CacheEvict;
 7 import org.springframework.cache.annotation.CachePut;
 8 import org.springframework.cache.annotation.Cacheable;
 9 import org.springframework.stereotype.Component;
10 
11 @Component("employeeDAO")
12 public class EmployeeDAO {
13     
14     // key 當前類,緩存對象為返回值list
15     @Cacheable(value = {"lt.ecache"}, key = "#root.targetClass")
16     public List<Employee> getEmployees() {
17         System.out.println("*** getEmployees() 已經調用   ***");
18         List<Employee> list = new ArrayList<Employee>(5);
19         list.add(new Employee(1, "Ben", "Architect"));
20         list.add(new Employee(2, "Harley", "Programmer"));
21         list.add(new Employee(3, "Peter", "BusinessAnalyst"));
22         list.add(new Employee(4, "Sasi", "Manager"));
23         list.add(new Employee(5, "Abhi", "Designer"));
24         return list;
25     }
26 
27     // key id,緩存數據為返回值Employee對象
28     @Cacheable(value = "lt.ecache", key = "#id")
29     public Employee getEmployee(int id, List<Employee> employees) {
30         System.out.println("***  getEmployee(): " + id + " ***");
31         Employee emp = null;
32         for (Employee employee : employees) {
33             if (employee.getId() == id) {
34                 emp = employee;
35             }
36         }
37         return emp;
38     }
39 
40     // @CachePut會去替換緩存中的Employee對象為當前id對應的對象
41     @CachePut(value = "lt.ecache", key = "#id")
42     public Employee updateEmployee(int id, String designation, List<Employee> employees) {
43         System.out.println("*** updateEmployee()  " + id + " ***");
44         Employee emp = null;
45         int i = 0;
46         for (Employee employee : employees) {
47             if (employee.getId() == id) {
48                 employee.setDesignation(designation);
49                 emp = employee;
50             }
51         }
52         System.out.println(emp);
53         return emp;
54     }
55 
56     //key為參數中Employee對象的id,緩存指定id對應的Employee對象
57     @Cacheable(value = "lt.ecache", key = "#employee.id")
58     public Employee addEmployee(Employee employee, List<Employee> employees) {
59         System.out.println("*** addEmployee() : " + employee.getId() + " ***");
60         employees.add(employee);
61         System.out.println(employee);
62         return employee;
63     }
64 
65     //key為參數中的id,移除緩存,移除指定id對應的Employee對象
66     @CacheEvict(value = "lt.ecache", key = "#id")
67     public Employee removeEmployee(int id, List<Employee> employees) {
68         System.out.println("*** removeEmployee()  : " + id + " ***");
69         Employee emp = null;
70         int i = 0;
71         for (Employee employee : employees) {
72             if (employee.getId() == id) {
73                 emp = employee;
74             } else {
75                 i++;
76             }
77         }
78         employees.remove(i);
79         return emp;
80     }
81 
82     //key為當前類,移除緩存,移除employees列表對象
83     @CacheEvict(value = "lt.ecache", key = "#root.targetClass")
84     public List<Employee> removeAllEmployee(List<Employee> employees) {
85         System.out.println("*** removeAllEmployee()  :  ***");
86         employees.clear();
87         System.out.println(employees.size());
88         return employees;
89     }
90 
91 }

  lt.ecache為ehcache.xml中配置的緩存名稱。對於要使用到緩存的方法必須使用@注解,同時還要將緩存對象在方法的最后return,否則會報錯。

  類中使用到了Spring Expression Language(SpEL),其中相關說明如下

#root.methodName 被執行方法的名稱
#root.method.name 被執行的方法
#root.target 被執行的目標對象 
#root.targetClass 被執行的目標對象的class
#root.args[0] 調用目標方法的時候目標方法里面的參數(可將參數列表類比成對象數組)的第一個
#root.caches[0].name 獲取當前執行方法的緩存

Main.java

 1 package com.ehcache.test;
 2 
 3 import java.util.List;
 4 
 5 import org.springframework.context.ApplicationContext;
 6 import org.springframework.context.support.ClassPathXmlApplicationContext;
 7 
 8 
 9 public class Main {
10 
11     public static void main(String[] args) {
12         
13         ApplicationContext context = new ClassPathXmlApplicationContext("spring-config-ehcache.xml");
14 
15         EmployeeDAO dao = (EmployeeDAO) context.getBean("employeeDAO"); 
16 
17         System.out.println("-----------------------第1次調用----------------------------");
18         List<Employee> employees = dao.getEmployees(); 
19         System.out.println(employees.toString()); 
20         System.out.println("------------------------第2次調用---------------------------");
21         employees = dao.getEmployees();
22         System.out.println(employees.toString()); 
23         System.out.println("------------------------第3次調用---------------------------");
24         employees = dao.getEmployees();
25         System.out.println(employees.toString()); 
26 
27         
28         System.out.println("-------------------------第1次調用--------------------------");
29         Employee employee = dao.getEmployee(1, employees);
30         System.out.println(employee.toString());
31         System.out.println("-------------------------第2次調用--------------------------");
32         employee = dao.getEmployee(1, employees);
33         System.out.println(employee.toString());
34         
35         
36         System.out.println("------------------------- 對象更新--------------------------"); 
37         dao.updateEmployee(1, "已經更新的對象", employees); 
38         System.out.println("-------------------------第1次調用--------------------------");
39         employee = dao.getEmployee(1, employees);
40         System.out.println(employee.toString());
41         System.out.println("-------------------------第2次調用--------------------------");
42         employee = dao.getEmployee(1, employees);
43         System.out.println(employee.toString());
44         
45         
46         System.out.println("------------------------- 添加對象--------------------------");
47         dao.addEmployee(new Employee(6, "555", "Designer5555"),employees);
48         System.out.println("-------------------------第1次調用--------------------------");
49         employee = dao.getEmployee(6, employees);
50         System.out.println(employee);
51         System.out.println("-------------------------第2次調用--------------------------");
52         employee = dao.getEmployee(6, employees);
53         System.out.println(employee.toString());
54         
55         
56         System.out.println("------------------------- 清除一個對象--------------------------");
57         System.out.println(employees.size());
58         employee = dao.removeEmployee(6, employees);
59         System.out.println("-------------------------第1次調用--------------------------");
60         employees = dao.getEmployees();
61         System.out.println(employees);
62         System.out.println(employees.size());
63         System.out.println("-------------------------第2次調用--------------------------");
64         employees = dao.getEmployees();
65         System.out.println(employees); 
66         
67         
68         System.out.println("------------------------- 清除所有--------------------------");
69         System.out.println(employees.size());
70         employees = dao.removeAllEmployee(employees);
71         System.out.println("-------------------------第1次調用--------------------------");
72         employees = dao.getEmployees();
73         System.out.println(employees); 
74         System.out.println("-------------------------第2次調用--------------------------");
75         employees = dao.getEmployees();
76         System.out.println(employees); 
77     }
78 }

  當對象緩存之后方法就不會執行,而是直接從緩存中獲取。 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM