Spring、Shiro和EHCache 缓存的使用案例

本文介绍 Shiro + EHCache Spring 的结合java

1、首先有两种方式来建立缓存实例,

只介绍spring bean配置方式spring

一、Spring EhCacheManagerFactoryBean方式建立。apache

图片

二、EhCacheManager方式建立。 缓存

图片

2、EHCache配置文件说明

1EHCache 配置文件代码。app

图片

二、 EHCache  配置文件说明jvm

<?xml version="1.0" encoding="UTF-8"?>ide

<ehcache >测试

    <diskStore path="java.io.tmpdir"/>spa

 <!--  name Cache的名称,必须是惟一的(ehcache会把这个cache放到HashMap里)线程

 maxElementsInMemory 内存中保持的对象数量

 maxElementsOnDisk DiskStore中保持的对象数量,默认值为0,表示不限制

 eternal 是不是永恒数据,若是是,则它的超时设置会被忽略

 overflowToDisk 若是内存中数据数量超过maxElementsInMemory限制,是否要缓存到磁盘上

 timeToIdleSeconds 对象空闲时间,指对象在多长时间没有被访问就会失效。只对eternal为false的有效。默认值0,表示一直能够访问

 timeToLiveSeconds 对象存活时间,指对象从建立到失效所须要的时间。只对eternal为false的有效。默认值0,表示一直能够访问

 diskPersistent 是否在磁盘上持久化。指重启jvm后,数据是否有效。默认为false

 diskExpiryThreadIntervalSeconds 对象检测线程运行时间间隔。标识对象状态的线程多长时间运行一次

 diskSpoolBufferSizeMB DiskStore使用的磁盘大小,默认值30MB。每一个cache使用各自的DiskStore

 memoryStoreEvictionPolicy 若是内存中数据超过内存限制,向磁盘缓存时的策略。默认值LRU,可选FIFO、LFU-->

    <cache name="authorizationCache" 

           maxElementsInMemory="10000"

            eternal="false" 

            timeToIdleSeconds="120"

            timeToLiveSeconds="120"

            overflowToDisk="false"

            diskPersistent="false"

            diskExpiryThreadIntervalSeconds="120">

    </cache>

</ehcache>

3、 ShiroCacheManager管理类。

ShiroCacheManager实现org.apache.shiro.cache.Cache接口,重写里面方法。

图片


4、实例测试

看代码。

package com.ehcache.test;

import org.apache.shiro.cache.Cache;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

public static void main(String[] args) {

//一、建立 Spring 的 IOC 容器

ClassPathXmlApplicationContext ctx =new ClassPathXmlApplicationContext("applicationContext.xml");

//二、获取IOC容器中ShiroCacheManager实例

ShiroCacheManager<String, String> shiroCacheManager =(ShiroCacheManager<String, String>)ctx.getBean("shiroCacheManager");

Cache<String, String>  cache =shiroCacheManager.getCache();

//三、保存

cache.put("key""12");

System.out.println(cache.get("key"));

System.out.println("***************************");

//四、 删除

cache.remove("key");

System.out.println(cache.get("key"));

}

}

相关文章
相关标签/搜索