前段时间写了一篇SSM三大框架的整合教程,
今天就顺便在这个基础上继续整合下redis吧。
第一步,加入相关依赖包,pom.xml:
<!--redis--> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.6.1.RELEASE</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.7.3</version> </dependency>
第二步,Redis的 相关配置参数redis.properties:
redis.host=127.0.0.1 redis.port=6379 redis.password=12345 redis.maxIdle=100 redis.maxWait=1000 redis.testOnBorrow=true redis.timeout=100000 defaultCacheExpireTime=3600
第三步,applicationContext-Redis.xml:
这里说明下,如果你不分开单独一个redis的配置文件也可以。我目前单独分开了,所以我是web.xml里面加载读取的是spring-root-context.xml文件,而spring-root-context.xml文件内再去加载读取其他的配置文件,
好,继续看我们的applicationContext-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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--引入Redis配置文件--> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath*:redis.properties</value> </list> </property> <property name="ignoreUnresolvablePlaceholders" value="true" /> </bean> <!-- jedis 连接池配置 --> <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxIdle" value="${redis.maxIdle}"/> <property name="maxWaitMillis" value="${redis.maxWait}"/> <property name="testOnBorrow" value="${redis.testOnBorrow}"/> </bean> <!-- redis连接工厂 --> <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <property name="poolConfig" ref="poolConfig"/> <property name="port" value="${redis.port}"/> <property name="hostName" value="${redis.host}"/> <property name="password" value="${redis.password}"/> <property name="timeout" value="${redis.timeout}"></property> </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"></property> </bean> <!-- 缓存拦截器配置 --> <bean id="methodCacheInterceptor" class="com.springmvc.interceptor.MethodCacheInterceptor"> <property name="redisUtil" ref="redisUtil"/> <property name="defaultCacheExpireTime" value="${defaultCacheExpireTime}"/> <!-- 禁用缓存的类名列表 --> <property name="targetNamesList"> <list> <value></value> </list> </property> <!-- 禁用缓存的方法名列表 --> <property name="methodNamesList"> <list> <value></value> </list> </property> </bean> <bean id="redisUtil" class="com.springmvc.util.RedisUtil"> <property name="redisTemplate" ref="redisTemplate"/> </bean> <!--配置切面拦截方法 --> <aop:config proxy-target-class="true"> <aop:pointcut id="controllerMethodPointcut" expression="execution(* com.springmvc.service.impl.*.select*(..))"/> <aop:advisor advice-ref="methodCacheInterceptor" pointcut-ref="controllerMethodPointcut"/> </aop:config> </beans>
OK,到了这里配置的XML基本完毕,这时候你可以看到配置文件里面有些地方显示红色了,不慌,是因为缺少了
RedisUtil.java (对应redis的数据相关存储读取操作工具类 )
MethodCacheInterceptor.java(缓存过滤器,可以看到配置文件里面,我们采取了AOP方式配置切面进行拦截)
那么接下来加入RedisUtil.java:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import java.util.*; import java.util.concurrent.TimeUnit; @Component public final class RedisUtil { @Autowired private RedisTemplate redisTemplate; // ============================Common============================= /** * 功能描述:根据key 设置过期时间 * @param key * @param time * @return */ public boolean expire(String key, long time) { try { if (time > 0) { redisTemplate.expire(key, time, TimeUnit.SECONDS); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 功能描述:根据key 获取过期时间 * * @param key 键,不能为null * @return 时间(s) 返回0 代表永久有效 * @author Jesson * @date 2018/8/27 10:10 */ public long getExpire(String key) { return redisTemplate.getExpire(key, TimeUnit.SECONDS); } /** * 功能描述:判断key是否存在 * * @param key * @return true 存在 false不存在 * @author Jesson * @date 2018/8/27 10:12 */ public boolean hasKey(String key) { try { return redisTemplate.hasKey(key); } catch (Exception e) { e.printStackTrace(); return false; } } /** * 功能描述:删除缓存 * * @param key 可为多个 * @return * @author Jesson * @date 2018/8/27 10:13 */ @SuppressWarnings("unchecked") public void del(String... key) { if (key != null && key.length > 0) { if (key.length == 1) { redisTemplate.delete(key[0]); } else { redisTemplate.delete(CollectionUtils.arrayToList(key)); } } } // ============================String============================= /** * 普通缓存获取 * * @param key 键 * @return 值 */ public Object get(String key) { return key == null ? null : redisTemplate.opsForValue().get(key); } /** * 普通缓存放入 * * @param key 键 * @param value 值 * @return true成功 false失败 */ public boolean set(String key, Object value) { try { redisTemplate.opsForValue().set(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 普通缓存放入并设置时间 * * @param key 键 * @param value 值 * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期 * @return true成功 false 失败 */ public boolean set(String key, Object value, long time) { try { if (time > 0) { redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); } else { set(key, value); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 递增 * * @param key 键 * @param delta 要增加几(大于0) * @return */ public long incr(String key, long delta) { if (delta < 0) { throw new RuntimeException("递增因子必须大于0"); } return redisTemplate.opsForValue().increment(key, delta); } /** * 递减 * * @param key 键 * @param delta 要减少几(小于0) * @return */ public long decr(String key, long delta) { if (delta < 0) { throw new RuntimeException("递减因子必须大于0"); } return redisTemplate.opsForValue().increment(key, -delta); } // ================================Map================================= /** * HashGet * * @param key 键 不能为null * @param item 项 不能为null * @return 值 */ public Object hget(String key, String item) { return redisTemplate.opsForHash().get(key, item); } /** * 获取hashKey对应的所有键值 * * @param key 键 * @return 对应的多个键值 */ public Map<Object, Object> hmget(String key) { return redisTemplate.opsForHash().entries(key); } /** * HashSet * * @param key 键 * @param map 对应多个键值 * @return true 成功 false 失败 */ public boolean hmset(String key, Map<String, Object> map) { try { redisTemplate.opsForHash().putAll(key, map); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * HashSet 并设置时间 * * @param key 键 * @param map 对应多个键值 * @param time 时间(秒) * @return true成功 false失败 */ public boolean hmset(String key, Map<String, Object> map, long time) { try { redisTemplate.opsForHash().putAll(key, map); if (time > 0) { expire(key, time); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 向一张hash表中放入数据,如果不存在将创建 * * @param key 键 * @param item 项 * @param value 值 * @return true 成功 false失败 */ public boolean hset(String key, String item, Object value) { try { redisTemplate.opsForHash().put(key, item, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 向一张hash表中放入数据,如果不存在将创建 * * @param key 键 * @param item 项 * @param value 值 * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间 * @return true 成功 false失败 */ public boolean hset(String key, String item, Object value, long time) { try { redisTemplate.opsForHash().put(key, item, value); if (time > 0) { expire(key, time); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 删除hash表中的值 * * @param key 键 不能为null * @param item 项 可以使多个 不能为null */ public void hdel(String key, Object... item) { redisTemplate.opsForHash().delete(key, item); } /** * 判断hash表中是否有该项的值 * * @param key 键 不能为null * @param item 项 不能为null * @return true 存在 false不存在 */ public boolean hHasKey(String key, String item) { return redisTemplate.opsForHash().hasKey(key, item); } /** * hash递增 如果不存在,就会创建一个 并把新增后的值返回 * * @param key 键 * @param item 项 * @param by 要增加几(大于0) * @return */ public double hincr(String key, String item, double by) { return redisTemplate.opsForHash().increment(key, item, by); } /** * hash递减 * * @param key 键 * @param item 项 * @param by 要减少记(小于0) * @return */ public double hdecr(String key, String item, double by) { return redisTemplate.opsForHash().increment(key, item, -by); } // ============================set============================= /** * 根据key获取Set中的所有值 * * @param key 键 * @return */ public Set<Object> sGet(String key) { try { return redisTemplate.opsForSet().members(key); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 根据value从一个set中查询,是否存在 * * @param key 键 * @param value 值 * @return true 存在 false不存在 */ public boolean sHasKey(String key, Object value) { try { return redisTemplate.opsForSet().isMember(key, value); } catch (Exception e) { e.printStackTrace(); return false; } } /** * 将数据放入set缓存 * * @param key 键 * @param values 值 可以是多个 * @return 成功个数 */ public long sSet(String key, Object... values) { try { return redisTemplate.opsForSet().add(key, values); } catch (Exception e) { e.printStackTrace(); return 0; } } /** * 将set数据放入缓存 * * @param key 键 * @param time 时间(秒) * @param values 值 可以是多个 * @return 成功个数 */ public long sSetAndTime(String key, long time, Object... values) { try { Long count = redisTemplate.opsForSet().add(key, values); if (time > 0) { expire(key, time); } return count; } catch (Exception e) { e.printStackTrace(); return 0; } } /** * 获取set缓存的长度 * * @param key 键 * @return */ public long sGetSetSize(String key) { try { return redisTemplate.opsForSet().size(key); } catch (Exception e) { e.printStackTrace(); return 0; } } /** * 移除值为value的 * * @param key 键 * @param values 值 可以是多个 * @return 移除的个数 */ public long setRemove(String key, Object... values) { try { Long count = redisTemplate.opsForSet().remove(key, values); return count; } catch (Exception e) { e.printStackTrace(); return 0; } } // ===============================list================================= /** * 获取list缓存的内容 * * @param key 键 * @param start 开始 * @param end 结束 0 到 -1代表所有值 * @return */ public List<Object> lGet(String key, long start, long end) { try { return redisTemplate.opsForList().range(key, start, end); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 获取list缓存的长度 * * @param key 键 * @return */ public long lGetListSize(String key) { try { return redisTemplate.opsForList().size(key); } catch (Exception e) { e.printStackTrace(); return 0; } } /** * 通过索引 获取list中的值 * * @param key 键 * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推 * @return */ public Object lGetIndex(String key, long index) { try { return redisTemplate.opsForList().index(key, index); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 将list放入缓存 * * @param key 键 * @param value 值 * @return */ public boolean lSet(String key, Object value) { try { redisTemplate.opsForList().rightPush(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 将list放入缓存 * * @param key 键 * @param value 值 * @param time 时间(秒) * @return */ public boolean lSet(String key, Object value, long time) { try { redisTemplate.opsForList().rightPush(key, value); if (time > 0) { expire(key, time); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 将list放入缓存 * * @param key 键 * @param value 值 * @return */ public boolean lSet(String key, List<Object> value) { try { redisTemplate.opsForList().rightPushAll(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 将list放入缓存 * * @param key 键 * @param value 值 * @param time 时间(秒) * @return */ public boolean lSet(String key, List<Object> value, long time) { try { redisTemplate.opsForList().rightPushAll(key, value); if (time > 0) { expire(key, time); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 根据索引修改list中的某条数据 * * @param key 键 * @param index 索引 * @param value 值 * @return */ public boolean lUpdateIndex(String key, long index, Object value) { try { redisTemplate.opsForList().set(key, index, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 移除N个值为value * * @param key 键 * @param count 移除多少个 * @param value 值 * @return 移除的个数 */ public long lRemove(String key, long count, Object value) { try { Long remove = redisTemplate.opsForList().remove(key, count, value); return remove; } catch (Exception e) { e.printStackTrace(); return 0; } } /** * 功能描述:获取所有键值 * */ public Set<String> getKeys(String pattern) { return redisTemplate.keys(pattern); } public void setRedisTemplate(RedisTemplate redisTemplate) { this.redisTemplate = redisTemplate; } public RedisTemplate getRedisTemplate() { return redisTemplate; } }
然后是, MethodCacheInterceptor.java:
import com.springmvc.util.RedisUtil; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import java.util.List; /** * @Author : JCccc * @CreateTime : 2019/8/1 * @Description : **/ /** * Redis缓存过滤器 */ public class MethodCacheInterceptor implements MethodInterceptor { private RedisUtil redisUtil; private List<String> targetNamesList; // 禁用缓存的类名列表 private List<String> methodNamesList; // 禁用缓存的方法列表 private String defaultCacheExpireTime; // 缓存默认的过期时间 @Override public Object invoke(MethodInvocation invocation) throws Throwable { Object value = null; String targetName = invocation.getThis().getClass().getName(); String methodName = invocation.getMethod().getName(); if (!isAddCache(targetName, methodName)) { // 跳过缓存返回结果 return invocation.proceed(); } Object[] arguments = invocation.getArguments(); String key = getCacheKey(targetName, methodName, arguments); try { // 判断是否有缓存 if (redisUtil.hasKey(key)) { return redisUtil.get(key); } // 写入缓存 value = invocation.proceed(); if (value != null) { final String tkey = key; final Object tvalue = value; new Thread(new Runnable() { @Override public void run() { redisUtil.set(tkey, tvalue, Long.parseLong(defaultCacheExpireTime)); } }).start(); } } catch (Exception e) { e.printStackTrace(); if (value == null) { return invocation.proceed(); } } return value; } /** * 是否加入缓存 * * @return */ private boolean isAddCache(String targetName, String methodName) { boolean flag = true; if (targetNamesList.contains(targetName) || methodNamesList.contains(methodName) || targetName.contains("$$EnhancerBySpringCGLIB$$")) { flag = false; } return flag; } /** * 创建缓存key * * @param targetName * @param methodName * @param arguments */ private String getCacheKey(String targetName, String methodName, Object[] arguments) { StringBuffer sbu = new StringBuffer(); sbu.append(targetName).append("_").append(methodName); if ((arguments != null) && (arguments.length != 0)) { for (int i = 0; i < arguments.length; i++) { sbu.append("_").append(arguments[i]); } } return sbu.toString(); } public void setRedisUtil(RedisUtil redisUtil) { this.redisUtil = redisUtil; } public void setTargetNamesList(List<String> targetNamesList) { this.targetNamesList = targetNamesList; } public void setMethodNamesList(List<String> methodNamesList) { this.methodNamesList = methodNamesList; } public void setDefaultCacheExpireTime(String defaultCacheExpireTime) { this.defaultCacheExpireTime = defaultCacheExpireTime; } }
OK,整合全部完成,接下来可以进行测试下,看看是什么效果。
在进行测试之前,先惯例说下流程:
我们是想将某些方法从mysql数据库查询数据,然后又想理由redis缓存技术。那么就是,在查数据之前,先要去redis数据库里面看下,是否对应的缓存数据存在,如果存在就没必要去mysql数据库查询了,直接取出数据返回即可;如果不存在,则需要去mysql数据查询出相关数据,然后顺便也存入redis缓存中(这样下次就能直接从缓存读取)。
正因为我们想实现上述的流程逻辑,所以我们利用AOP进行了缓存过滤器,也就是在过滤器配置的相关方法,我们都会进行AOP切面拦截,目前我在代码里面配置的是我的service层里面的实现类impl里面带有‘select’的方法,
好了,一下子没忍住又啰嗦了很多,我们来开始测试,
随便在一个controller里面写个测试接口,调用一个查询的方法:
@Autowired RedisUtil redisUtil; @RequestMapping(value = "/getMessageBoardData", produces = "application/json; charset=utf-8") public String getMessageBoardData() { Messageboard messageboard = messageboardServiceImpl.selectByPrimaryKey(5); return messageboard.toString(); }
OK,我们项目跑起来,然后先看看我们的Redis数据库(没有任何值):
然后我们调用接口, 可以看到已经查出相关数据了,而且看看控制台,是执行了MYSQL语句查询的,因为我们原先的redis里面啥数据都没缓存:
然后紧接着,我们去看看本地的redis数据库,发现多了一个存入的值:
没错,这个正是我们的缓存过滤器存进去的(TTL是指缓存数据的存在时长,单位秒,使我们自己设置的时长,可以回过头看看代码)。
所以我们继续调用刚刚的接口,再查一次,发现数据一样是查询出来了,但是控制台没有新的执行SQL语句日志打印:
没错,这就是因为每次调用查询方法的时候,缓存过滤器都在启作用,第一次已经把数据存进redis了,所以第二次查询的时候,就直接从redis取出缓存数据了,就是缓存过滤器的这段代码:
OK,测试完毕。
PS:以下补充一些调用Redis.java对数据的存入,查询,删除等接口测试,毕竟可能有些小伙伴整合redis就是单纯想存一些数据和查询一下。
@RequestMapping(value = "/operationRedisData", produces = "application/json; charset=utf-8") public void operationRedisData() { //简单举例调用下 redisUtil 里面的一些方法,其余都可以自己调用 redisUtil.set("test1","JCccc"); redisUtil.set("test2",123456); Map map =new HashMap(); map.put("A","a"); map.put("B","b"); redisUtil.hmset("TEST-MAP",map); System.out.println(redisUtil.get("test2")+" \n "+redisUtil.hget("TEST-MAP","A")); }
调用接口,看看redis数据库,存入了相关的值,控制台也打印出了相关的查询值:
好了,该篇整合教程到此。