java1234 shiro 第0 .1课 缓存

pom.xml

    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-ehcache</artifactId>
        <version>1.2.4</version>
    </dependency>

spring-config.xml

       <!-- 缓存管理器 使用 Ehcache 实现 -->
    <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
        <property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/>
    </bean>
    <!-- 安全管理器 -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  
        <property name="realm" ref="myRealm"/>  
                
        <!-- 缓存管理器 -->    
        <property name="cacheManager" ref="cacheManager" />
    </bean>  

 ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache name="shirocache">

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

    <!-- 登录记录缓存 锁定10分钟 -->
    <cache name="passwordRetryCache"
           maxEntriesLocalHeap="2000"
           eternal="false"
           timeToIdleSeconds="3600"
           timeToLiveSeconds="0"
           overflowToDisk="false"
           statistics="true">
    </cache>

    <cache name="authorizationCache"
           maxEntriesLocalHeap="2000"
           eternal="false"
           timeToIdleSeconds="10"
           timeToLiveSeconds="0"
           overflowToDisk="false"
           statistics="true">
    </cache>

    <cache name="authenticationCache"
           maxEntriesLocalHeap="2000"
           eternal="false"
           timeToIdleSeconds="20"
           timeToLiveSeconds="0"
           overflowToDisk="false"
           statistics="true">
    </cache>

    <cache name="shiro-activeSessionCache"
           maxEntriesLocalHeap="2000"
           eternal="false"
           timeToIdleSeconds="3600"
           timeToLiveSeconds="0"
           overflowToDisk="false"
           statistics="true">
    </cache>

</ehcache>

ehcache.xml  说明: http://my.oschina.net/004/blog/214851

1.ehcache.xml配置文件详解

 

<ehcache>

 

<!--磁盘存储配置:用来指定缓存在磁盘上的存储位置。

可以使用JavaVM环境变量(user.home, user.dir, java.io.tmpdir)-->

<diskStore path = "c:/cache/" />

 

<!--指定CacheManagerEventListenerFactory,这个对象在缓存添加的时候会得到相应的通知。

CacheManagerEventListenerFactory的属性:

*class :CacheManagerEventListenerFactory的一个实现类。

*properties :CacheManagerEventListenerFactory的属性值,以逗号(,)分割多个属性。

如果没有实现类被指定,则系统不创建CacheManager的监听器,没有默认值-->

<cacheManagerEventListenerFactory class="" properties="" />

 

<!--在进行分布式缓存的应用时需要指定CacheManagerPeerProviderFactory,用来生成CacheManagerPeerProvider的实例,以便和集群中的其他CacheManager通信。

CacheManagerPeerProvider的属性:

*class :CacheManagerPeerProviderFactory的一个实现类。

*properties :CacheManagerPeerProviderFactory的属性值,以逗号(,)分割多个属性。

 

Ehcache内建了2种基于RMI分布系统的通信策略:

*automatic :使用多播组。在一个节点加入或者推出集群的时候自动感应。

*manual :硬编码方式

-->

<cacheManagerPeerListenerFactory class="" properties="" />

 

<!--默认缓存配置,以下属性是必须的:

name :cache的标识符,在一个CacheManager中必须唯一。

maxElementsInMemory : 在内存中缓存的element的最大数目。

maxElementsOnDisk : 在磁盘上缓存的element的最大数目。

eternal : 设定缓存的elements是否有有效期。如果为true,timeouts属性被忽略。

overflowToDisk : 设定当内存缓存溢出的时候是否将过期的element缓存到磁盘上。

 

以下属性是可选的:

timeToIdleSeconds : 缓存element在过期前的空闲时间。

timeToLiveSeconds : 缓存element的有效生命期。

diskPersistent : 在VM重启的时候是否持久化磁盘缓存,默认是false。

diskExpiryThreadIntervalSeconds : 磁盘缓存的清理线程运行间隔,默认是120秒.

memoryStoreEvictionPolicy : 当内存缓存达到最大,有新的element加入的时候,

移除缓存中element的策略。默认是LRU,可选的有LFU和FIFO

 

缓存子元素:
cacheEventListenerFactory:注册相应的的缓存监听类,用于处理缓存事件,如put,remove,update,和expire
bootstrapCacheLoaderFactory:指定相应的BootstrapCacheLoader,用于在初始化缓存,以及自动设置。

-->

<defaultCache

maxElementsInMemory="10000"

eternal="false"

timeToIdleSeconds="120"

timeToLiveSeconds="120"

overflowToDisk="true"

maxElementsOnDisk="1000000"

diskPersistent="false"

diskExpiryThreadIntervalSeconds="120"

memoryStoreEvictionPolicy="LRU"

/>

<!--cache配置同defaultCache -->

<cache name="test"
maxElementsInMemory="100"
eternal="false"
timeToIdleSeconds="100"
timeToLiveSeconds="100"
overflowToDisk="false"

/>

</ehcache>

 

2.ehcache 包可用方法介绍:

创建CacheManager 的方法:

方法一:
CacheManager manager = new CacheManager();

方法二:
CacheManager manager = new CacheManager("src/config/ehcache.xml");

方法三:
URL url = getClass().getResource("/anotherconfigurationname.xml");
CacheManager manager = new CacheManager(url);

方法四:
InputStream fis = new FileInputStream(new File("src/config/ehcache.xml").getAbsolutePath());
try {
CacheManager manager = new CacheManager(fis);
} finally {
fis.close();
}


获取cacheNames 列表:


方法一:
CacheManager.create();
String[] cacheNames = CacheManager.getInstance().getCacheNames();

方法二:
CacheManager manager = new CacheManager();
String[] cacheNames = manager.getCacheNames();

方法三:
CacheManager manager1 = new CacheManager("src/config/ehcache1.xml");
CacheManager manager2 = new CacheManager("src/config/ehcache2.xml");
String[] cacheNamesForManager1 = manager1.getCacheNames();
String[] cacheNamesForManager2 = manager2.getCacheNames();

添加和删除缓存元素:

设置一个名为testCache 的新cache,属性为默认:
CacheManager singletonManager = CacheManager.create();
singletonManager.addCache("testCache");
Cache test = singletonManager.getCache("testCache");

设置一个名为testCache 的新cache,并定义其属性: 
CacheManager singletonManager = CacheManager.create();
Cache memoryOnlyCache = new Cache("testCache", 5000, false, false, 5, 2);
singletonManager.addCache(memoryOnlyCache);
Cache test = singletonManager.getCache("testCache");

Cache 属性说明:

构造函数:
public Cache(String name,

int maxElementsInMemory,

boolean overflowToDisk,
boolean eternal,

long timeToLiveSeconds,

long timeToIdleSeconds)

参数说明:
name :元素名字。
maxElementsInMemory :设定内存中创建对象的最大值。
overflowToDisk : 设置当内存中缓存达到 maxInMemory 限制时元素是否可写到磁盘上。
eternal : 设置元素是否永久驻留。
timeToIdleSeconds : 设置某个元素消亡前的停顿时间。也就是在一个元素消亡之前,两次访问时间的最大时间间隔值。只能在元素不是永久驻留时有效。
timeToLiveSeconds : 设置某个元素消亡前的生存时间。也就是一个元素从构建到消亡的最大时间间隔值。只能在元素不是永久驻留时有效。

删除缓存元素:


CacheManager singletonManager = CacheManager.create();
singletonManager.removeCache("testCache");


关闭缓存管理器 CacheManager

CacheManager.getInstance().shutdown();


对于缓存对象的操作:


放入一个简单的对象到缓存元素;
Cache cache = manager.getCache("testCache");
Element element = new Element("key1", "value1");
cache.put(element);

得到一个序列化后的对象属性值;
Cache cache = manager.getCache("testCache");
Element element = cache.get("key1");
Serializable value = element.getValue();

得到一个没有序列化后的对象属性值;
Cache cache = manager.getCache("testCache");
Element element = cache.get("key1");
Object value = element.getObjectValue();

删除一个对象从元素;
Cache cache = manager.getCache("testCache");
Element element = new Element("key1", "value1");
cache.remove("key1");

对于永固性磁盘存储,立即存储到磁盘:

Cache cache = manager.getCache("testCache");
cache.flush();


获得缓存大小:


得到缓存的对象数量;
Cache cache = manager.getCache("testCache");
int elementsInMemory = cache.getSize();

得到缓存对象占用内存的数量
Cache cache = manager.getCache("testCache");
long elementsInMemory = cache.getMemoryStoreSize();

得到缓存对对象占用磁盘的数量
Cache cache = manager.getCache("testCache");
long elementsInMemory = cache.getDiskStoreSize();

关于缓存的读取和丢失的记录:


得到缓存读取的命中次数;
Cache cache = manager.getCache("testCache");
int hits = cache.getHitCount();

得到内存中缓存读取的命中次数;
Cache cache = manager.getCache("testCache");
int hits = cache.getMemoryStoreHitCount();

得到磁盘中缓存读取的命中次数;
Cache cache = manager.getCache("testCache");
int hits = cache.getDiskStoreCount();

得到缓存读取的丢失次数;
Cache cache = manager.getCache("testCache");
int hits = cache.getMissCountNotFound();

得到缓存读取的已经被销毁的对象丢失次数;
Cache cache = manager.getCache("testCache");
int hits = cache.getMissCountExpired();

© 著作权归作者所有

 

转载于:https://my.oschina.net/u/1760858/blog/729449

SLF4J: No SLF4J providers were found. SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See https://www.slf4j.org/codes.html#noProviders for further details. Exception in thread "main" org.apache.shiro.config.ConfigurationException: Unable to instantiate class [org.apache.shiro.web.mgt.DefaultWebSecurityManager] for object named 'securityManager'. Please ensure you've specified the fully qualified class name correctly. at org.apache.shiro.config.ReflectionBuilder.createNewInstance(ReflectionBuilder.java:309) at org.apache.shiro.config.ReflectionBuilder$InstantiationStatement.doExecute(ReflectionBuilder.java:927) at org.apache.shiro.config.ReflectionBuilder$Statement.execute(ReflectionBuilder.java:887) at org.apache.shiro.config.ReflectionBuilder$BeanConfigurationProcessor.execute(ReflectionBuilder.java:765) at org.apache.shiro.config.ReflectionBuilder.buildObjects(ReflectionBuilder.java:260) at org.apache.shiro.config.IniSecurityManagerFactory.buildInstances(IniSecurityManagerFactory.java:167) at org.apache.shiro.config.IniSecurityManagerFactory.createSecurityManager(IniSecurityManagerFactory.java:130) at org.apache.shiro.config.IniSecurityManagerFactory.createSecurityManager(IniSecurityManagerFactory.java:108) at org.apache.shiro.config.IniSecurityManagerFactory.createInstance(IniSecurityManagerFactory.java:94) at org.apache.shiro.config.IniSecurityManagerFactory.createInstance(IniSecurityManagerFactory.java:46) at org.apache.shiro.config.IniFactorySupport.createInstance(IniFactorySupport.java:123) at org.apache.shiro.util.AbstractFactory.getInstance(AbstractFactory.java:47) at com.xiu.Quickstart.main(Quickstart.java:26) Caused by: org.apache.shiro.util.UnknownClassException: Unable to load class named [org.apache.shiro.web.mgt.DefaultWebSecurityManager] from the thread context, current, or system/application ClassLoaders. All heuristics have been exhausted. Class could not be found. at org.apache.shiro.util.ClassUtils.forName(ClassUtils.java:152) at org.apache.shiro.util.ClassUtils.newInstance(ClassUtils.java:168) at org.apache.shiro.config.ReflectionBuilder.createNewInstance(ReflectionBuilder.java:302) ... 12 more
06-10
这个异常是因为 Shiro 框架没有找到 SLF4J(Simple Logging Facade for Java)的实现类,导致默认使用了 NOP(No-Operation)日志记录器实现。 可以通过以下几个步骤解决这个异常: 1. 确保在应用程序的 classpath 下存在 SLF4J 的实现类,比如 Logback、Log4j 等。 2. 确认应用程序中已经正确引入了 SLF4J 的依赖,比如以下 Maven 依赖: ``` <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.30</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.3</version> </dependency> ``` 3. 确认 SLF4J 的配置文件是否正确,比如 logback.xml 或者 log4j.properties 等。 如果以上步骤都没有解决问题,可以尝试修改 Shiro 的日志记录器实现类,比如使用 Logback 作为日志记录器实现: ``` # 修改 Shiro 的日志记录器实现类为 Logback log4j.logger.org.apache.shiro=INFO, stdout log4j.logger.org.apache.shiro.util.ThreadContext=INFO, stdout log4j.logger.org.apache.shiro.realm=INFO, stdout log4j.logger.org.apache.shiro.web=INFO, stdout log4j.logger.org.apache.shiro.cache=INFO, stdout log4j.logger.org.apache.shiro.session=INFO, stdout # Logback 配置文件,可以将日志输出到控制台 <configuration> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%d [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <logger name="org.apache.shiro" level="INFO"/> <root level="DEBUG"> <appender-ref ref="STDOUT" /> </root> </configuration> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值