zoukankan      html  css  js  c++  java
  • spring3.2+ehcache 注解使用

    通过spring 拦截,实现颗粒度比较细,容易控制的缓存。了解了下,spring 3.0 以后,应该从3.1 以后吧,注解方式的缓存就已经实现,下面是我自己做的例子,分享给大家:

    例子内容介绍:

    1.没用数据库,用的集合里面的数据,也就没事务之类的,完成的一个CRUD操作

    2.主要测试内容,包括第一次查询,和反复查询,缓存是否生效,更新之后数据同步的问题

    3.同时含有一些常用参数绑定等东西 

    4.为了内容简单,我没有使用接口,就是User,UserControl,UserServer,UserDao 几个类,以及xml 配置文件

    直接看类吧,源码文件,以及jar 都上传,方便大家下载:

    Java代码  收藏代码
    1. package com.se;  
    2.   
    3. public class User {  
    4.     public Integer id;  
    5.     public String name;  
    6.     public String password;  
    7.       
    8.     // 这个需要,不然在实体绑定的时候出错  
    9.     public User(){}  
    10.       
    11.     public User(Integer id, String name, String password) {  
    12.         super();  
    13.         this.id = id;  
    14.         this.name = name;  
    15.         this.password = password;  
    16.     }  
    17.       
    18.     public Integer getId() {  
    19.         return id;  
    20.     }  
    21.     public void setId(Integer id) {  
    22.         this.id = id;  
    23.     }  
    24.     public String getName() {  
    25.         return name;  
    26.     }  
    27.     public void setName(String name) {  
    28.         this.name = name;  
    29.     }  
    30.     public String getPassword() {  
    31.         return password;  
    32.     }  
    33.     public void setPassword(String password) {  
    34.         this.password = password;  
    35.     }  
    36.   
    37.     @Override  
    38.     public String toString() {  
    39.         return "User [id=" + id + ", name=" + name + ", password=" + password  
    40.                 + "]";  
    41.     }  
    42. }  
    Java代码  收藏代码
    1. package com.se;  
    2.   
    3. import java.util.ArrayList;  
    4. import java.util.List;  
    5.   
    6. import org.springframework.stereotype.Repository;  
    7.   
    8. /** 
    9.  * 静态数据,模拟数据库操作 
    10.  */  
    11. @Repository("userDao")  
    12. public class UserDao {  
    13.       
    14.     List<User> users = initUsers();  
    15.       
    16.     public User findById(Integer id){  
    17.         User user = null;  
    18.         for(User u : users){  
    19.             if(u.getId().equals(id)){  
    20.                 user = u;  
    21.             }  
    22.         }  
    23.         return user;  
    24.     }  
    25.       
    26.     public void removeById(Integer id){  
    27.         User user = null;  
    28.         for(User u : users){  
    29.             if(u.getId().equals(id)){  
    30.                 user = u;  
    31.                 break;  
    32.             }  
    33.         }  
    34.         users.remove(user);  
    35.     }  
    36.       
    37.     public void addUser(User u){  
    38.         users.add(u);  
    39.     }  
    40.       
    41.     public void updateUser(User u){  
    42.         addUser(u);  
    43.     }  
    44.       
    45.       
    46.     // 模拟数据库  
    47.     private List<User> initUsers(){  
    48.         List<User> users = new ArrayList<User>();  
    49.         User u1 = new User(1,"张三","123");  
    50.         User u2 = new User(2,"李四","124");  
    51.         User u3 = new User(3,"王五","125");  
    52.         users.add(u1);  
    53.         users.add(u2);  
    54.         users.add(u3);  
    55.         return users;  
    56.     }  
    57. }  
    Java代码  收藏代码
    1. package com.se;  
    2.   
    3. import java.util.List;  
    4.   
    5. import org.springframework.beans.factory.annotation.Autowired;  
    6. import org.springframework.cache.annotation.CacheEvict;  
    7. import org.springframework.cache.annotation.Cacheable;  
    8. import org.springframework.stereotype.Service;  
    9. /** 
    10.  * 业务操作, 
    11.  */  
    12. @Service("userService")  
    13. public class UserService {  
    14.       
    15.     @Autowired  
    16.     private UserDao userDao;  
    17.       
    18.     // 查询所有,不要key,默认以方法名+参数值+内容 作为key  
    19.     @Cacheable(value = "serviceCache")  
    20.     public List<User> getAll(){  
    21.         printInfo("getAll");  
    22.         return userDao.users;  
    23.     }  
    24.     // 根据ID查询,ID 我们默认是唯一的  
    25.     @Cacheable(value = "serviceCache", key="#id")  
    26.     public User findById(Integer id){  
    27.         printInfo(id);  
    28.         return userDao.findById(id);  
    29.     }  
    30.     // 通过ID删除  
    31.     @CacheEvict(value = "serviceCache", key="#id")  
    32.     public void removeById(Integer id){  
    33.         userDao.removeById(id);  
    34.     }  
    35.       
    36.     public void addUser(User u){  
    37.         if(u != null && u.getId() != null){  
    38.             userDao.addUser(u);  
    39.         }  
    40.     }  
    41.     // key 支持条件,包括 属性condition ,可以 id < 10 等等类似操作  
    42.     // 更多介绍,请看参考的spring 地址  
    43.     @CacheEvict(value="serviceCache", key="#u.id")  
    44.     public void updateUser(User u){  
    45.         removeById(u.getId());  
    46.         userDao.updateUser(u);  
    47.     }  
    48.       
    49.     // allEntries 表示调用之后,清空缓存,默认false,  
    50.     // 还有个beforeInvocation 属性,表示先清空缓存,再进行查询  
    51.     @CacheEvict(value="serviceCache",allEntries=true)  
    52.     public void removeAll(){  
    53.         System.out.println("清除所有缓存");  
    54.     }  
    55.       
    56.     private void printInfo(Object str){  
    57.         System.out.println("非缓存查询----------findById"+str);  
    58.     }  
    59.       
    60.       
    61. }  
    Java代码  收藏代码
    1. package com.se;  
    2.   
    3. import java.util.List;  
    4.   
    5. import org.springframework.beans.factory.annotation.Autowired;  
    6. import org.springframework.stereotype.Controller;  
    7. import org.springframework.ui.Model;  
    8. import org.springframework.web.bind.annotation.ModelAttribute;  
    9. import org.springframework.web.bind.annotation.PathVariable;  
    10. import org.springframework.web.bind.annotation.RequestMapping;  
    11.   
    12. @Controller  
    13. public class UserControl {  
    14.       
    15.     @Autowired  
    16.     private UserService userService;  
    17.       
    18.     // 提前绑定视图,提前绑定数据,方便查看数据变化  
    19.     @ModelAttribute("users")  
    20.     public List<User> cityList() {  
    21.         return userService.getAll();  
    22.     }   
    23.   
    24.     // 根据ID查询  
    25.     @RequestMapping("/get/{id}")  
    26.     public String getUserById(Model model,@PathVariable Integer id){  
    27.         User u = userService.findById(id);  
    28.         System.out.println("查询结果:"+u);  
    29.         model.addAttribute("user", u);  
    30.         return "forward:/jsp/edit";  
    31.     }  
    32.     // 删除  
    33.     @RequestMapping("/del/{id}")  
    34.     public String deleteById(Model model,@PathVariable Integer id){  
    35.         printInfo("删除-----------");  
    36.         userService.removeById(id);  
    37.         return "redirect:/jsp/view";  
    38.     }  
    39.     // 添加  
    40.     @RequestMapping("/add")  
    41.     public String addUser(Model model,@ModelAttribute("user") User user){  
    42.         printInfo("添加----------");  
    43.         userService.addUser(user);  
    44.         return "redirect:/jsp/view";  
    45.     }  
    46.     // 修改  
    47.     @RequestMapping("/update")  
    48.     public String update(Model model,@ModelAttribute User u){  
    49.         printInfo("开始更新---------");  
    50.         userService.updateUser(u);  
    51.         model.addAttribute("user", u);  
    52.         return "redirect:/jsp/view";  
    53.     }  
    54.     // 清空所有  
    55.     @RequestMapping("/remove-all")  
    56.     public String removeAll(){  
    57.         printInfo("清空-------------");  
    58.         userService.removeAll();  
    59.         return "forward:/jsp/view";  
    60.     }  
    61.     // JSP 跳转  
    62.     @RequestMapping("/jsp/{jspName}")  
    63.     public String toJsp(@PathVariable String jspName){  
    64.         System.out.println("JSP TO -->>" +jspName);  
    65.         return jspName;  
    66.     }  
    67.       
    68.     private void printInfo(String str){  
    69.         System.out.println(str);  
    70.     }  
    71. }  

    XML 配置:

    Java代码  收藏代码
    1. <?xml version="1.0" encoding="UTF-8"?>  
    2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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">  
    3.   <display-name>springEhcache</display-name>  
    4.   <servlet>    
    5.         <servlet-name>spring</servlet-name>    
    6.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    
    7.           <init-param>    
    8.             <param-name>contextConfigLocation</param-name>    
    9.             <param-value>classpath:com/config/springmvc-context.xml</param-value>    
    10.         </init-param>    
    11.         <load-on-startup>1</load-on-startup>    
    12.     </servlet>   
    13.        
    14.     <servlet-mapping>    
    15.         <servlet-name>spring</servlet-name>    
    16.         <url-pattern>/</url-pattern>    
    17.     </servlet-mapping>    
    18. </web-app>  
    Java代码  收藏代码
    1. <?xml version="1.0" encoding="UTF-8"?>    
    2. <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
    3. xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">    
    4. <!-- service 缓存配置 -->  
    5. <cache name="serviceCache"  
    6.     eternal="false"    
    7.     maxElementsInMemory="100"   
    8.     overflowToDisk="false"   
    9.     diskPersistent="false"    
    10.     timeToIdleSeconds="0"   
    11.     timeToLiveSeconds="300"    
    12.     memoryStoreEvictionPolicy="LRU" />   
    13. </ehcache>   
    Java代码  收藏代码
    1. <?xml version="1.0" encoding="UTF-8"?>  
    2. <beans xmlns="http://www.springframework.org/schema/beans"    
    3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
    4.     xmlns:context="http://www.springframework.org/schema/context"    
    5.     xmlns:oxm="http://www.springframework.org/schema/oxm"    
    6.     xmlns:mvc="http://www.springframework.org/schema/mvc"    
    7.     xmlns:cache="http://www.springframework.org/schema/cache"  
    8.     xmlns:aop="http://www.springframework.org/schema/aop"  
    9.     xsi:schemaLocation="http://www.springframework.org/schema/mvc   
    10.         http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd    
    11.         http://www.springframework.org/schema/beans   
    12.         http://www.springframework.org/schema/beans/spring-beans-3.2.xsd    
    13.         http://www.springframework.org/schema/context   
    14.         http://www.springframework.org/schema/context/spring-context-3.2.xsd  
    15.         http://www.springframework.org/schema/cache   
    16.         http://www.springframework.org/schema/cache/spring-cache.xsd">   
    17.   
    18.     <!-- 默认扫描 @Component @Repository  @Service @Controller -->  
    19.     <context:component-scan base-package="com.se" />  
    20.     <!-- 一些@RequestMapping 请求和一些转换 -->  
    21.     <mvc:annotation-driven />    
    22.       
    23.     <!-- 前后缀 -->  
    24.     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">    
    25.         <property name="prefix" value="/"/>    
    26.         <property name="suffix" value=".jsp"/>  
    27.     </bean>  
    28.     <!--  静态资源访问 的两种方式  -->  
    29.     <!-- <mvc:default-servlet-handler/>   -->  
    30.     <mvc:resources location="/*" mapping="/**" />   
    31.       
    32.       
    33.     <!--  缓存  属性-->  
    34.     <bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">    
    35.         <property name="configLocation"  value="classpath:com/config/ehcache.xml"/>   
    36.     </bean>   
    37.       
    38.     <!-- 支持缓存注解 -->  
    39.     <cache:annotation-driven cache-manager="cacheManager" />  
    40.       
    41.     <!-- 默认是cacheManager -->  
    42.     <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">    
    43.         <property name="cacheManager"  ref="cacheManagerFactory"/>    
    44.     </bean>    
    45. </beans>   

    JSP 配置:

    Java代码  收藏代码
    1. <%@ page language="java" contentType="text/html; charset=Utf-8" pageEncoding="Utf-8"%>  
    2. <html>  
    3. <head>  
    4. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
    5. <title>Insert title here</title>  
    6. </head>  
    7. <script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery-1.4.3.js"></script>  
    8. <body>  
    9. <strong>用户信息</strong><br>  
    10. 输入编号:<input id="userId">  
    11.   
    12. <a href="#" id="edit">编辑</a>  
    13.   
    14. <a href="#" id="del" >删除</a>  
    15.   
    16. <a href="<%=request.getContextPath()%>/jsp/add">添加</a>  
    17.   
    18. <a href="<%=request.getContextPath()%>/remove-all">清空缓存</a><br/>  
    19.   
    20.   
    21. <p>所有数据展示:<p/>  
    22. ${users }  
    23.   
    24.   
    25. <p>静态图片访问测试:</p>  
    26. <img style=" 110px;height: 110px" src="<%=request.getContextPath()%>/img/404cx.png"><br>  
    27. </body>  
    28. <script type="text/javascript">  
    29. $(document).ready(function(){  
    30.     $('#userId').change(function(){  
    31.         var userId = $(this).val();  
    32.         var urlEdit = '<%=request.getContextPath()%>/get/'+userId;  
    33.         var urlDel = '<%=request.getContextPath()%>/del/'+userId;  
    34.         $('#edit').attr('href',urlEdit);  
    35.         $('#del').attr('href',urlDel);  
    36.     });  
    37. });  
    38. </script>  
    39. </html>  
    Java代码  收藏代码
    1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
    2.     pageEncoding="UTF-8"%>  
    3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
    4. <html>  
    5. <head>  
    6. </head>  
    7. <script type="text/javascript" src="../js/jquery-1.4.3.js"></script>  
    8. <body>  
    9.     <strong>编辑</strong><br>  
    10.     <form id="edit" action="<%=request.getContextPath()%>/update" method="get">  
    11.         用户ID:<input id="id" name="id" value="${user.id}"><br>  
    12.         用户名:<input id="name" name="name" value="${user.name}"><br>  
    13.         用户密码:<input id="password" name="password" value="${user.password}"><br>  
    14.         <input value="更新" id="update" type="submit">  
    15.     </form>  
    16. </body>  
    17. </html>  
    Java代码  收藏代码
    1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
    2.     pageEncoding="UTF-8"%>  
    3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
    4. <html>  
    5. <head>  
    6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
    7. <title>Insert title here</title>  
    8. </head>  
    9. <script type="text/javascript" src="../js/jquery-1.4.3.js"></script>>  
    10. <body>  
    11.     <strong>添加</strong>  
    12.     <form action="<%=request.getContextPath()%>/add" method="post">  
    13.         用户ID:<input  name="id" ><br>  
    14.         用户名:<input  name="name" ><br>  
    15.         用户密码:<input  name="password"><br>  
    16.         <input value="添加" id="add" type="submit">  
    17.     </form>  
    18.     ${users }  
    19. </body>  
    20. </html>  

    关于测试方式:

    输入地址:http://localhost:8081/springEhcache/jsp/view

    然后根据ID 进行查询编辑, 还有添加,以及删除等操作,这里仅仅做简单实例,更多的需要大家自己做写。测试用例的我也导入了,业务可以自己写。

    里面用到了很多参考资料:

    比如:

    这个是google  弄的例子,实例项目类似,就不上传了

    http://blog.goyello.com/2010/07/29/quick-start-with-ehcache-annotations-for-spring/

    这个是涛ge,对spring cache 的一些解释

    http://jinnianshilongnian.iteye.com/blog/2001040

    还有就是spring 官网的一些资料,我是自己下的src ,里面文档都有,会上传

    自己路径的文件地址/spring-3.2.0.M2/docs/reference/htmlsingle/index.html

    关于Ehcache 的介绍,可以参考

    官网:http://www.ehcache.org/documentation/get-started/cache-topologies

    还有我缓存分类里面转的文章,关于几个主流缓存分类 以及区别的。

    小结:

            1.现在aop 和DI 用得很多了,也特别的方便,但是框架太多了,但是要核心源码搞清楚了才行

            2.上面的缓存机制还可以运用到类上,和事务差不多,反正里面东西挺多了, 我就不一一介绍了,可以自己进行扩展研究。

            3.感觉spring 的缓存,颗粒度还可以再细,精确到元素,或者可以提供对指定方法,指定内容的时间控制,而不是只能通过xml,也可以在方法上直接加参数,细化元素的缓存时间,关于这点的作用来说,我项目中,比如A 结果集,我想缓存10秒,B结果集想缓存50秒,就不用再次去配置缓存了。而且ehcache 是支持元素级的颗粒控制,各有想法吧。当然看自己喜欢用xml 方式拦截呢,还是注解使用,这里仅提供了注解方式,我比较喜欢~。~

            4.有问题的地方欢迎大家,多指正!

     不能超过10M,就分开传的,包括项目,以及文档介绍

  • 相关阅读:
    linux 、windows、mac、dns刷新
    Nginx日志切割及其各种服务日志随便切
    https是如何防劫持的
    梁启超-少年中国说
    mongodb-4.2-隋唐笔迹
    connection closed by foreign host
    磁盘类型查看
    魅力男神之解说
    jenkins 更新脚本之expect交互
    nginx 之特殊端口转目录访问
  • 原文地址:https://www.cnblogs.com/scwanglijun/p/3758229.html
Copyright © 2011-2022 走看看