目录
- <!--定义redis版本-->
- <redis.version>2.9.0</redis.version>
- <redis.spring.version>1.7.1.RELEASE</redis.spring.version>
-
- <!--redis整合-->
- <dependency>
- <groupId>redis.clients</groupId>
- <artifactId>jedis</artifactId>
- <version>${redis.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework.data</groupId>
- <artifactId>spring-data-redis</artifactId>
- <version>${redis.spring.version}</version>
- </dependency>
redis.properties
- redis.hostName=IP地址
- redis.port=6379
- redis.password=123456
- redis.timeout=10000
- redis.maxIdle=300
- redis.maxTotal=1000
- redis.maxWaitMillis=1000
- redis.minEvictableIdleTimeMillis=300000
- redis.numTestsPerEvictionRun=1024
- redis.timeBetweenEvictionRunsMillis=30000
- redis.testOnBorrow=true
- redis.testWhileIdle=true
- redis.expiration=3600
spring-redis.xml
- "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"
- 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/context
- http://www.springframework.org/schema/context/spring-context.xsd
- http://www.springframework.org/schema/cache
- http://www.springframework.org/schema/cache/spring-cache.xsd">
-
-
- <context:property-placeholder location="classpath:redis.properties" />
-
-
- <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}"/>
-
- <property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}"/>
-
- <property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}"/>
-
- <property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}"/>
-
- <property name="testOnBorrow" value="${redis.testOnBorrow}"/>
-
- <property name="testWhileIdle" value="${redis.testWhileIdle}"/>
- bean>
-
-
- <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
- destroy-method="destroy">
- <property name="poolConfig" ref="poolConfig"/>
-
- <property name="hostName" value="${redis.hostName}"/>
-
- <property name="port" value="${redis.port}"/>
-
- <property name="password" value="${redis.password}"/>
-
- <property name="timeout" value="${redis.timeout}"/>
- bean>
-
-
- <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
- <property name="connectionFactory" ref="connectionFactory"/>
-
- <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="true"/>
- bean>
-
-
- <bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
- <constructor-arg name="redisOperations" ref="redisTemplate"/>
-
- <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>
-
-
- <bean id="cacheKeyGenerator" class="com.ouyang.ssm.redis.CacheKeyGenerator">bean>
-
-
- <cache:annotation-driven cache-manager="redisCacheManager" key-generator="cacheKeyGenerator"/>
- beans>
缓存key的工具类 CacheKeyGenerator
- package com.ouyang.ssm.redis;
-
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.cache.annotation.Cacheable;
- import org.springframework.cache.interceptor.KeyGenerator;
- import org.springframework.util.ClassUtils;
-
- import java.lang.reflect.Array;
- import java.lang.reflect.Method;
-
- /**
- * 指定redis中的key value存储中的key字符串的生成规则
- * uname:oy uname是手动赋值的
- *
- * @enableCache
- */
- @Slf4j
- public class CacheKeyGenerator implements KeyGenerator {
- // custom cache key
- public static final int NO_PARAM_KEY = 0;
- public static final int NULL_PARAM_KEY = 53;
-
- @Cacheable
- @Override
- public Object generate(Object target, Method method, Object... params) {
- StringBuilder key = new StringBuilder();
- key.append(target.getClass().getSimpleName()).append(".").append(method.getName()).append(":");
- if (params.length == 0) {
- key.append(NO_PARAM_KEY);
- } else {
- int count = 0;
- for (Object param : params) {
- if (0 != count) {//参数之间用,进行分隔
- key.append(',');
- }
- if (param == null) {
- key.append(NULL_PARAM_KEY);
- } else if (ClassUtils.isPrimitiveArray(param.getClass())) {
- int length = Array.getLength(param);
- for (int i = 0; i < length; i++) {
- key.append(Array.get(param, i));
- key.append(',');
- }
- } else if (ClassUtils.isPrimitiveOrWrapper(param.getClass()) || param instanceof String) {
- key.append(param);
- } else {//Java一定要重写hashCode和eqauls
- key.append(param.hashCode());
- }
- count++;
- }
- }
-
- String finalKey = key.toString();
- // IEDA要安装lombok插件
- log.debug("using cache key={}", finalKey);
- return finalKey;
- }
- }
如果没有安装lombok插件,此时这里是会报错的
安装好后重启IDEA就好了
注意:redis.properties与jdbc.properties在与Spring做整合时会发生冲突;所以引入配置文件的地方要放到SpringContext.xml中
将上图两个圈起来的注释掉
-
- <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.propertiesvalue>
- <value>classpath:redis.propertiesvalue>
- list>
- property>
- bean>
- "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" xmlns:tx="http://www.springframework.org/schema/tx"
- xmlns:aop="http://www.springframework.org/schema/aop"
- 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 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
-
-
- <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.propertiesvalue>
- <value>classpath:redis.propertiesvalue>
- list>
- property>
- bean>
-
- <import resource="applocationContext-mybatis.xml">import>
- <import resource="spring-redis.xml">import>
- beans>
pom中可以编译的文件以及目录
测试能运行起来就行
配置在方法或类上,作用:本方法执行后,先去缓存看有没有数据,如果没有,从数据库中查找出来,给缓存中存一份,返回结果,
下次本方法执行,在缓存未过期情况下,先在缓存中查找,有的话直接返回,没有的话从数据库查找
- value:缓存位置的一段名称,不能为空
- key:缓存的key,默认为空,表示使用方法的参数类型及参数值作为key,支持SpEL
- condition:触发条件,满足条件就加入缓存,默认为空,表示全部都加入缓存,支持SpEL
- @RunWith(SpringJUnit4ClassRunner.class)
- @ContextConfiguration(locations={"classpath:applicationContext.xml"})
- @Cacheable(value = "user-clz",key = "'clz:'+#cid",condition = "#cid < 5")
- Clazz selectByPrimaryKey(Integer cid);
测试结果:redis中有数据,则访问redis;如果没有数据,则访问MySQL;
类似于更新操作,即每次不管缓存中有没有结果,都从数据库查找结果,并将结果更新到缓存,并返回结果
- value缓存的名称,在 spring 配置文件中定义,必须指定至少一个
- key缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合
- condition缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才进行缓存
- @CachePut(value = "user-clz-put")
- Clazz selectByPrimaryKey(Integer cid);
测试结果:只存不取
用来清除用在本方法或者类上的缓存数据(用在哪里清除哪里)
- value:缓存位置的一段名称,不能为空
- key:缓存的key,默认为空,表示使用方法的参数类型及参数值作为key,支持SpEL
- condition:触发条件,满足条件就加入缓存,默认为空,表示全部都加入缓存,支持SpEL
- allEntries:true表示清除value中的全部缓存,默认为false
- // @CacheEvict(value = "user-clz-put",key = "'clz:'+#cid") 删除指定的缓存数据
- @CacheEvict(value = "user-clz-put",allEntries = true) // 删除以 user-clz-put开头的 缓存
- int deleteByPrimaryKey(Integer cid);
测试结果:可以配置删除指定缓存数据,也可以删除符合规则的所有缓存数据;