我们知道Shiro 提供了一系列让我们自己实现的接口,包括org.apache.shiro.cache.CacheManager
、org.apache.shiro.cache.Cache
等接口。那么我们要对这些做实现,就实现了 Shiro 对 Session 和用户认证信息、用户缓存信息等的缓存,存储。我们可以用缓存,如 Redis 、 memcache 、 EHCache 等,甚至我们可以用数据库,如 Oracle 、 Mysql 等,都可以,只有效率的快慢问题,功能都可以达到, Redis 有一个更实用的功能,就是ttl功能,我们这时候又想到一个 Nosql --> Elasticsearch 也是带ttl功能的,那么也可以用它来实现。
那么我的教程是采用了 Redis ,而且是用了Jedis
。Jedis
可以实现pool
和hash
的集群Redis
。
在我的教程里命名为spring-cache.xml
,配置如下:
<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
default-lazy-init="false">
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxActive" value="500"/><!-- 最大连接数 -->
<property name="maxIdle" value="100"/><!-- 最大闲置 -->
<property name="minIdle" value="10"/><!-- 最小闲置 -->
<property name="maxWait" value="5000"/><!-- 最大等待 -->
<property name="testOnBorrow" value="true"/><!-- 可以获取 -->
</bean>
<bean id="jedisPool" class="redis.clients.jedis.JedisPool">
<constructor-arg index="0" ref="jedisPoolConfig"/>
<constructor-arg index="2" value="6379"/><!-- 端口 -->
<constructor-arg index="3" value="5000"/><!-- 超时 -->
<constructor-arg index="1" value="127.0.0.1"/><!--Redis IP地址 -->
</bean>
</beans>
如果 Redis 设置了密码,需要这样配置:
<bean id="jedisPool" class="redis.clients.jedis.JedisPool">
<constructor-arg index="0" ref="jedisPoolConfig"/>
<constructor-arg index="2" value="6379"/><!-- 端口 -->
<constructor-arg index="3" value="5000"/><!-- 超时 -->
<constructor-arg index="1" value="127.0.0.1"/><!--Redis IP地址 -->
<constructor-arg index="4" value="Redis-pswd"/><!--密码 -->
</bean>
对应的构造方法:
public JedisPool(final Config poolConfig, final String host, int port,
int timeout, final String password) {
this(poolConfig, host, port, timeout, password, Protocol.DEFAULT_DATABASE);
}
那么 Shiro 中的 Redis 配置已经配置好了,关于 Shiro + Redis 配置请看下一篇博客,会详细讲到,原因是我觉得和下一篇和 Spring 的配置文件一起讲会关联性更好一点。