---
title: "Shiro User Manual-Caching"
author: "Technoboy"
date: "2013-04-18T10:52:56Z"
tags: []
categories: ["企业架构"]
slug: "shiro-user-manual-caching"
draft: false
lastmod: "2013-04-11T22:19:30Z"
id: 1846045
url: "https://technoboy.iteye.com/blog/1846045"
---

1. Caching
 Shiro团队了解性能的重要性，因此，缓存被作为一个重要的特性纳入到安全操作中。

2. Caching API
 Shiro有3个重要的缓存接口：
 a. CacheManager 缓存的管理组件，它返回Cache实例。
 b. Cache  维护键值对形式的缓存
 c. CacheManagerAware  一个接口，由想获得和使用CacheManager的组件实现。
 CacheManager返回Cache实例，不同的Shiro组件使用这些Cache缓存数据。实现了CacheManagerAware接口的组件将获得CacheManager，并进一步通过CacheManager获取Cache。
 SecurityManager，AuthenticatingRealm，以及AuthorizingRealm，他们默认都实现了CacheManagerAware接口。如果把CacheManager设置到SecurityManager属性里，所有实现了CacheManagerAware的Realm都将获取到CacheManager实例。

```java

securityManager.realms = $myRealm1, $myRealm2, ..., $myRealmN
...
cacheManager = my.implementation.of.CacheManager
...
securityManager.cacheManager = $cacheManager
# at this point, the securityManager and all CacheManagerAware
# realms have been set with the cacheManager instance

```


3. CacheManager Implementations
 Shiro提供了一系列的CacheManager实现以满足你的需求。

3.1 MemoryConstrainedCacheManager
 MemoryConstrainedCacheManager是一个基于单JVM的CacheManager实现，它不支持分布式或集群，如果你的应用部署在多JVM上(比如，web应用部署在多台服务器上)，且想在JVM间进行缓存的访问，你需要使用分布式缓存实现。
 MemoryConstrainedCacheManager管理多个MapCache实例，一个命名的缓存即为一个MapCache实例。每一个MapCache都提供了SoftHashMap，它基于应用程序运行时内存约束和需求，可以自动调整大小的(通过利用JDK的SoftReference)。
 由于MemoryConstrainedCacheManager可以基于应用配置文件自动调整自身大小，因此其可以在单JVM的生产环境和测试中使用。但是，它不支持那些高级的特性，比如设置存活时间，过期时间等设置。在INI文件中配置：

```java

...
cacheManager = org.apache.shiro.cache.MemoryConstrainedCacheManager
...
securityManager.cacheManager = $cacheManager

```


3.2 HazelcastCacheManager
 当前版本不支持HazelcastCacheManager， 将在1.3版本中出现。