码迷,mamicode.com
首页 > 编程语言 > 详细

ehcache整合spring注解方式

时间:2014-11-23 18:46:19      阅读:306      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   io   ar   color   os   使用   

一、简介

  在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 }

  当对象缓存之后方法就不会执行,而是直接从缓存中获取。 

ehcache整合spring注解方式

标签:des   style   blog   http   io   ar   color   os   使用   

原文地址:http://www.cnblogs.com/always-online/p/4116771.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!