目录
1. 添加spring-redis.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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
<!-- redis的相关配置已经在applicationContext.xml导入了,因为spring只允许有一个context:property-placeholder -->
<!-- 所以下面的配置会注释掉了 -->
<!-- 1. 引入properties配置文件 -->
<!-- <context:property-placeholder ignore-unresolvable="true" location="classpath:sa.properties" />-->
<!-- 2. redis连接池配置-->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<!--最大空闲数-->
<property name="maxIdle" value="${redis.maxIdle}"/>
<!--连接池的最大数据库连接数 -->
<property name="maxTotal" value="${redis.maxTotal}"/>
<!--最大建立连接等待时间-->
<property name="maxWaitMillis" value="${redis.maxWaitMillis}"/>
<!--逐出连接的最小空闲时间 默认1800000毫秒(30分钟)-->
<property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}"/>
<!--每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3-->
<property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}"/>
<!--逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1-->
<property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}"/>
<!--是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个-->
<property name="testOnBorrow" value="${redis.testOnBorrow}"/>
<!--在空闲时检查有效性, 默认false -->
<property name="testWhileIdle" value="${redis.testWhileIdle}"/>
</bean>
<!-- 3. redis连接工厂 -->
<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
destroy-method="destroy">
<property name="poolConfig" ref="poolConfig"/>
<!--IP地址 -->
<property name="hostName" value="${redis.hostName}"/>
<!--端口号 -->
<property name="port" value="${redis.port}"/>
<!--如果Redis设置有密码 -->
<!-- <property name="password" value="${redis.password}"/>-->
<!--客户端超时时间单位是毫秒 -->
<property name="timeout" value="${redis.timeout}"/>
</bean>
<!-- 4. redis操作模板,使用该对象可以操作redis -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="connectionFactory"/>
<!--如果不配置Serializer,那么存储的时候缺省使用String,如果用User类型存储,那么会提示错误User can't cast to String!! -->
<property name="keySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
<property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
</property>
<property name="hashKeySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
<property name="hashValueSerializer">
<bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
</property>
<!--开启事务 -->
<property name="enableTransactionSupport" value="false"/>
</bean>
<!--5.配置缓冲管理-->
<bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
<constructor-arg name="redisOperations" ref="redisTemplate" />
<!--redis缓存数据过期时间单位秒-->
<property name="defaultExpiration" value="${redis.expiration}" />
<!--是否使用储存前缀-->
<property name="usePrefix" value="true"/>
<property name="cachePrefix">
<bean class="org.springframework.data.redis.cache.DefaultRedisCachePrefix">
<constructor-arg index="0" value="-cache-"/>
</bean>
</property>
</bean>
<!--6.配置自定义Key生成器CacheKeyGenerator-->
<bean id="cacheKeyGenerator" class="com.jmh.shiro.redis.CacheKeyGenerator" />
<!--7.开启注解式储存-->
<cache:annotation-driven cache-manager="redisCacheManager" key-generator="cacheKeyGenerator"/>
</beans>
2. 添加redis.properties文件
- 注意修改你的ip地址 and 密码
#ip地址
redis.hostName=192.168.111.132
#端口号
redis.port=6379
#如果有密码
#redis.password=123456
#客户端超时时间单位是毫秒 默认是2000
redis.timeout=10000
#redis缓存数据过期时间单位秒
redis.expiration=3600
##################### redis连接池配置 ###########################################
#最大空闲数
redis.maxIdle=300
#连接池的最大数据库连接数。设为0表示无限制,如果是jedis 2.4以后用redis.maxTotal
#redis.maxActive=600
#控制一个pool可分配多少个jedis实例,用来替换上面的redis.maxActive,如果是jedis 2.4以后用该属性
redis.maxTotal=1000
#最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。
redis.maxWaitMillis=1000
#连接的最小空闲时间 默认1800000毫秒(30分钟)
redis.minEvictableIdleTimeMillis=300000
#每次释放连接的最大数目,默认3
redis.numTestsPerEvictionRun=1024
#逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1
redis.timeBetweenEvictionRunsMillis=30000
#是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个
redis.testOnBorrow=true
#在空闲时检查有效性, 默认false
redis.testWhileIdle=true
#redis集群配置
#redis.sentinel.host1=172.20.1.230
#redis.sentinel.port1=26379
#redis.sentinel.host2=172.20.1.231
#redis.sentinel.port2=26379
#redis.sentinel.host3=172.20.1.232
#redis.sentinel.port3=26379
3. 修改spring.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--1. 引入外部properties文件 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="ignoreResourceNotFound" value="true" />
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
<value>classpath:redis.properties</value>
</list>
</property>
</bean>
<import resource="spring-mybatis.xml"/>
<import resource="spring-ehcache.xml"/>
<import resource="spring-shiro.xml"/>
<import resource="spring-redis.xml"/>
</beans>
4. 添加pom.xml依赖
<properties>
<jedis.version>2.9.0</jedis.version>
<spring-data-redis.version>1.7.1.RELEASE</spring-data-redis.version>
</properties>
<!-- ********************** redis相关依赖 ********************** -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>${jedis.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-pool2</artifactId>
<groupId>org.apache.commons</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- spring-data-redis 依赖-->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>${spring-data-redis.version}</version>
</dependency>
5. 缓存注解
5.1 @Cacheable
配置在方法或类上,作用:本方法执行后,先去缓存看有没有数据,如果没有,从数据库中查找出来,给缓存中存一份,返回结果,下次本方法执行,在缓存未过期情况下,先在缓存中查找,有的话直接返回,没有的话从数据库查找
value:缓存位置的一段名称,不能为空
key:缓存的key,默认为空,表示使用方法的参数类型及参数值作为key,支持SpEL
keyGenerator:指定key的生成策略
condition:触发条件,满足条件就加入缓存,默认为空,表示全部都加入缓存,支持SpEL
实例
package com.jmh.shiro.service.impl;
import com.jmh.shiro.mapper.UserMapper;
import com.jmh.shiro.model.User;
import com.jmh.shiro.service.IUserService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Set;
@Service
public class UserServiceImpl implements IUserService {
//注入
@Resource
private UserMapper userMapper;
@Cacheable(value = "selectByUserName",key = "'user-'+#username",condition = "#username.equals('admin')")
@Override
public User selectByUserName(String username) {
return userMapper.selectByUserName(username);
}
}
- 注1:condition是在方法执行前评估, unless是在方法执行后评估.
5.2 @CachePut
类似于更新操作,即每次不管缓存中有没有结果,都从数据库查找结果,并将结果更新到缓存,并返回结果
value 缓存的名称,在 spring 配置文件中定义,必须指定至少一个
key 缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合
condition 缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才进行缓存
实例
package com.jmh.shiro.service.impl;
import com.jmh.shiro.mapper.UserMapper;
import com.jmh.shiro.model.User;
import com.jmh.shiro.service.IUserService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Set;
@Service
public class UserServiceImpl implements IUserService {
//注入
@Resource
private UserMapper userMapper;
@CachePut(value = "selectByUserName",key = "'user-'+#username",condition = "#username.equals('zhangsan')")
@Override
public User selectByUserName(String username) {
return userMapper.selectByUserName(username);
}
}
5.3 @CacheEvict
用来清除用在本方法或者类上的缓存数据(用在哪里清除哪里)
value:缓存位置的一段名称,不能为空
key:缓存的key,默认为空,表示使用方法的参数类型及参数值作为key,支持SpEL
condition:触发条件,满足条件就加入缓存,默认为空,表示全部都加入缓存,支持SpEL
allEntries:true表示清除value中的全部缓存,默认为false
实例
package com.jmh.shiro.service.impl;
import com.jmh.shiro.mapper.UserMapper;
import com.jmh.shiro.model.User;
import com.jmh.shiro.service.IUserService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Set;
@Service
public class UserServiceImpl implements IUserService {
//注入
@Resource
private UserMapper userMapper;
//条件1
@CacheEvict(value = "selectByUserName",key = "'user-'+#username")
//条件2
@CacheEvict(value = "selectByUserName",allEntries = true)
@Override
public User selectByUserName(String username) {
return userMapper.selectByUserName(username);
}
}