`

ehCache+spring的简单使用

 
阅读更多

 1、最近在做一个贷款项目是城市分站的 分为贷款前台和贷款机构后台,这个两个平台的二级域名不一样,一个前台是cityname.xx.com,cityname是会地区的不同而变化的,如在 北京就是bj.xx.com,机构后台是loan.xx.com,在机构登录的时候 ,如果把登录信息放在session,会有一个问题,就是当切换到前台的时候,由于域名改变了,此时session就会改变,之前session保存的信 息就不存在了,也就是session跨域问题,最后想到了使用缓存才存储在线用户信息,这样就不存在session跨域的问题。

        2、ehCache介绍

       EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。

      下图是 Ehcache 在应用程序中的位置:

ehCache+spring的简单实用

 



       ehCache+spring的简单实用


     主要的特性有:
      1. 快速.
      2. 简单.
      3. 多种缓存策略
      4. 缓存数据有两级:内存和磁盘,因此无需担心容量问题
      5. 缓存数据会在虚拟机重启的过程中写入磁盘
      6. 可以通过RMI、可插入API等方式进行分布式缓存
      7. 具有缓存和缓存管理器的侦听接口
      8. 支持多缓存管理器实例,以及一个实例的多个缓存区域
      9. 提供Hibernate的缓存实现

下面说ehcache的使用

  ①下载??????ehcache.jar,自己去google下载地址

  ②随后,开始配置ehCache的属性,ehCache需要一个xml文件来设置ehCache相关的一些属性,如最大缓存数量、cache刷新的时间等等
??ehcache.xml放在你的classpath下.
   
<ehcache>
<!--<diskStore path="c:\\myapp\\cache"/> -->
    
    <defaultCache
        maxElementsInMemory="1000"
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        overflowToDisk="false"
        />
  <cache name="DEFAULT_CACHE"
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="300000"
        timeToLiveSeconds="600000"
        overflowToDisk="false"
        />
</ehcache>
<!--
1.必须要有的属性:
name: cache的名字,用来识别不同的cache,必须惟一。
maxElementsInMemory: 内存管理的缓存元素数量最大限值。
maxElementsOnDisk: 硬盘管理的缓存元素数量最大限值。默认值为0,就是没有限制。
eternal: 设定元素是否持久话。若设为true,则缓存元素不会过期。
overflowToDisk: 设定是否在内存填满的时候把数据转到磁盘上。
2.下面是一些可选属性:
timeToIdleSeconds: 设定元素在过期前空闲状态的时间,只对非持久性缓存对象有效。默认值为0,值为0意味着元素可以闲置至无限长时间。
timeToLiveSeconds: 设定元素从创建到过期的时间。其他与timeToIdleSeconds类似。
diskPersistent: 设定在虚拟机重启时是否进行磁盘存储,默认为false.(我的直觉,对于安全小型应用,宜设为true)。
diskExpiryThreadIntervalSeconds: 访问磁盘线程活动时间。
diskSpoolBufferSizeMB: 存入磁盘时的缓冲区大小,默认30MB,每个缓存都有自己的缓冲区。
memoryStoreEvictionPolicy: 元素逐出缓存规则。共有三种,Recently Used (LRU)最近最少使用,为默认。 First In First Out (FIFO),先进先出。Less Frequently Used(specified as LFU)最少使用
 -->
③用spring3拦截器检查缓存中是否有用户信息
   
package com.woaika.loan.front.common.filter;
 
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;
 
import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
 
import com.woaika.loan.front.loanuser.vo.LoginOrganVo;
import com.woaika.loan.ip.IPUtil;
import com.woaika.loan.po.LoanOrgan;
 
public class OrgMgtInterceptor implements HandlerInterceptor {
 
    private Logger log = Logger.getLogger(OrgMgtInterceptor.class);
    
    private Cache  ehCache;
    
    @Resource(name="ehCache")
    public void setEhCache(Cache ehCache) {
        this.ehCache = ehCache;
    }
    
    public void afterCompletion(HttpServletRequest arg0,
            HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        //log.info("==============执行顺序: 3、afterCompletion================");
 
    }
 
    
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
            Object arg2, ModelAndView arg3) throws Exception {
        //log.info("==============执行顺序: 2、postHandle================");
 
    }
 
    
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
            Object handler) throws Exception {
        // log.info("==============执行顺序: 1、preHandle================");
 
          String ip =  IPUtil.getRemortIP(request);
          Element elementIp = ehCache.get(ip); 
          if(null==elementIp){
              response.sendRedirect(com.woaika.loan.commons.constants.SiteConstant.JIGOU_URL+"/tologin");
              return false;
          }else{
              LoginOrganVo vo =(LoginOrganVo)elementIp.getObjectValue();
              if(vo!=null){
                  Element elementId = ehCache.get(vo.getId().toString());
                  if(elementId!=null){
                      String tempIp = (String)elementId.getObjectValue();
                      if(tempIp!=null && !"".equals(tempIp) && ip.equals(tempIp)){
                          request.setAttribute("currentOrgan", vo);
                          return true;
                      }
                    
                  }else{
                      response.sendRedirect(com.woaika.loan.commons.constants.SiteConstant.JIGOU_URL+"/tologin");
                      return false;
                      
                  }
              }
          }
          return true;
          
        /* String url=request.getRequestURL().toString();
            // if(url.matches(mappingURL)){
                    HttpSession session = request.getSession();
                    LoanOrgan org = (LoanOrgan)session.getAttribute("currentOrgan");
                    if(org!=null){
                        return true;
                    }else{
                        response.sendRedirect(com.woaika.loan.commons.constants.SiteConstant.JIGOU_URL+"/tologin");
                    }
                    return false; 
              //  }  
             //   return true;
         */  
 
    }
 
}
④将ehcache进行注入的配置applicationContext-ehCache.xml
   
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:p="http://www.springframework.org/schema/p"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd
      http://www.springframework.org/schema/tx
      http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
      http://www.springframework.org/schema/aop
      http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
      http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
    <!-- 引用ehCache的配置 --> 
    <bean id="defaultCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> 
      <property name="configLocation"> 
        <value>classpath:ehcache.xml</value> 
     </property> 
    </bean>
    
      <!-- 定义ehCache的工厂,并设置所使用的Cache name --> 
    <bean id="ehCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean"> 
      <property name="cacheManager"> 
        <ref local="defaultCacheManager"/> 
      </property> 
      <property name="cacheName"> 
          <value>DEFAULT_CACHE</value> 
      </property> 
    </bean>
    
</beans>
⑤登录的时候,验证用户名密码,正确放入缓存,这里只是提供一个简单的方法(用的spring的mvc)

   
@RequestMapping(value="/login")
    public String login(String organname, String pwd, HttpServletRequest request, HttpServletResponse response){
         judgmentCity.getCityInfo(request);
        LoanOrgan organ = loanOrganService.login(organname, pwd);
        if(organ==null){
            request.setAttribute("msg", "用户名或密码错误");
            return "forward:/jigou/tologin";
        }else{
            //将机构信息存在cache中,来进行跨域
            String ip =  IPUtil.getRemortIP(request);
             LoginOrganVo vo = new LoginOrganVo();
             vo.setId(organ.getId());
             vo.setOrganname(organ.getOrganname());
             Element elementip  = new  Element(ip, (Serializable) vo); 
             Element elementid  = new  Element(organ.getId().toString(), ip);
             //Element elementvo  = new  Element(organ.getId().toString(), (Serializable) vo);
             ehCache.put(elementip);//添加到缓存
             ehCache.put(elementid);
            // ehCache.put(elementvo);
            //request.getSession().setAttribute("currentOrgan", organ);
            return "redirect:/organmgt/index";
        }
    }
注销操作(用的spring的mvc):

//注销登录
   @RequestMapping(value="/logout")
   public String logout(HttpServletRequest request){
       String ip =  IPUtil.getRemortIP(request);
       Element elementIp = ehCache.get(ip);
       if(elementIp!=null){
           LoginOrganVo vo =(LoginOrganVo)elementIp.getObjectValue();
           if(vo!=null){
               ehCache.remove(vo.getId());
           }
       }
       ehCache.remove(ip);
       //request.getSession().removeAttribute("currentOrgan");
       return "redirect:/jigou/tologin";
   }
⑥spring3拦截器的配置文件
   
<mvc:interceptors>
       <mvc:interceptor>
          <mvc:mapping path="/organmgt/**" /><!-- 如果不配置或/*,将拦截所有的Controller -->
          <bean class="com.woaika.loan.front.common.filter.OrgMgtInterceptor">
          </bean>
       </mvc:interceptor>
   </mvc:interceptors>
这样所有的/organmgt/开头的请求都会被拦截,在这个拦截器进行检查是否登录就可以,这里我采用的是用户客户端ip和用户id两个key存储了用户信息保证用户的唯一信。


事实上到了这里,一个简单的Spring + ehCache Framework基本完成了。

分享到:
评论

相关推荐

    Ehcache_spring的demo

    简单的ehcache和spring的整合demo.....

    spring整合EhCache 的简单例子

    spring整合EhCache 的简单例子

    Spring AOP+ehCache简单缓存系统解决方案

    需要使用Spring来实现一个Cache简单的解决方案,具体需求如下:使用任意一个现有开源Cache Framework,要求可以Cache系统中Service或则DAO层的get/find等方法返回结果,如果数据更新(使用Create/update/delete方法...

    spring+shiro+ehcache例子

    项目简介:此项目只是简单的集成spring+springmvc+shiro+ehcahce 二: 步骤说明: 1:项目集成spring 在web.xml中配置spring容器的监听器。 2:项目集成springmvc 在web.xml中配置前端控制器 3:项目集成...

    Maven项目Spring4+Hibernate4+shiro+Ehcache项目集成

    使用Intellj IDEA 集成开发工具 搭建的maven项目,使用Spring+Hibernate+Shiro+Ehcache集成,完成一个简单的用户角色菜单项目

    简单配置 shiro + spring +springMVC+hibernate简单框架

    如果有多个realm,使用‘realms’属性代替 --&gt; &lt;property name="realm" ref="authorizingRealm" /&gt; &lt;property name="cacheManager" ref="shiroCacheManager" /&gt; &lt;/bean&gt; 服务器 web.xml中配置 &lt;filter&gt; ...

    springmvc+ehcache简单例子

    springmvc+ehcache简单例子,一看就懂

    基于SpringMVC+Spring+MyBatis (SSM) 架构的高效率便捷开发框架源码+项目说明.zip

    项目封装了一系列常用方法、部署运行简单,便于个人或企业进行高效开发。 ## 一、项目开发环境&工具(Environment&Tools) * MacOS Sierra / Windows 7 * MySql 5.7 * JDK 1.8 * CentOS 7 * IntelliJ IDEA 2017.2...

    ehcache-spring

    spring集成ehcache简单示例

    Spring AOP+ehCache简单缓存系统解决方案.doc

    缘起需求:需要使用Spring来实现一个Cache简单的解决方案,具体需求如下:使用任意一个现有开源Cache Framework,要求可以Cache系统中Service或者DAO层的get/find等方法返回结果,如果数据更新(使用Create/update/...

    spring整合EhCache 简单例子

    spring整合EhCache 简单例子

    (2.0版本)自己写的struts2+hibernate+spring实例

    2.3.8.jar struts2-spring-plugin-2.0.11.1 antlr-2.7.5H3.jar asm.jar asm-attrs.jar cglib-2.1.3.jar commons-collections-2.1.1.jar dom4j-1.6.1.jar ehcache-1.1.jar ...

    Spring整合Ecache

    本实例的环境 eclipse + maven + spring + ehcache + junit EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。Ehcache是一种广泛使用的开 源Java分布式缓存。主要...

    Ehcache分布式缓存与其在SpringBoot应用

    Ehcache 是一种广泛使用的开源 Java 分布式缓存。主要面向通用缓存,Java EE 和轻量级容器。它具有内存和磁盘存储,缓存加载器,缓存扩展,缓存异常处理程序,一个 gzip 缓存 servlet 过滤器,支持 REST 和 SOAP api...

    EhCache缓存技术

    【EhCache】Java缓存框架使用EhCache结合Spring AOP EhCache是一个纯Java的进程内缓存框架,具有如下特点: 1. 快速简单,非常容易和应用集成。 2.支持多种缓存策略 。 3. 缓存数据有两级:内存和磁盘,因此无需...

    shiro集成mybatis和spring以及redis

    架构采用的是SpringMVC4.2.4+mybatis3.4.4+ehcache+redis+shiro1.2.2 虽然redis集成了,但是我自己写的SessionDao有些问题目前就还是用的shiro的EnterpriseCacheSessionDAO,因此就没有用redis来缓存Session,但是集成...

    spring+springMVC+mybatis整合简单的增删查改

    本次上传的资源是spring+springMVC+mybatis整合的简单增删查改,有助于初学者在idea软件上操作,其中用到的数据库是mysql,资源里面还整合了spring的ehcache二级缓存。

    java版商城源码下载-web_frame:springmvc+spring+mybaitsSSM

    +spring+ mybaits SSM A 集成代码生成器 +快速构建表单; freemaker模版技术 ,0个代码不用写,生成完整的一个模块,带页面、建表sql脚本,处理类,service等完整模块 B 集成阿里巴巴数据库连接池druid; 数据库连接池...

    jeecg-framework-v2.0 (最新源码)

    • 架构技术: Struts2+Spring3+Hibernate4+EasyUI1.3+Spring JDBC+Highcharts报表+Jquery+Ehcache+Freemarker • 代码生成器:自动生成美观大方的前台页面及后台代码 • 查询条件生成器: 动态拼SQL,追加查询条件 •...

Global site tag (gtag.js) - Google Analytics