在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
一、Redis介绍 <!--Redis start --> <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 end --> 2、配置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.JdkSerializationRedisSerializer" /> </property> </bean > <!-- cache配置 --> <bean id="methodCacheInterceptor" class="com.mucfc.msm.common.MethodCacheInterceptor" > <property name="redisUtil" ref="redisUtil" /> </bean > <bean id="redisUtil" class="com.mucfc.msm.common.RedisUtil" > <property name="redisTemplate" ref="redisTemplate" /> </bean > 其中配置文件redis一些配置数据redis.properties如下: #redis中心 redis.host=10.75.202.11 redis.port=6379 redis.password=123456 redis.maxIdle=100 redis.maxActive=300 redis.maxWait=1000 redis.testOnBorrow=true redis.timeout=100000 # 不需要加入缓存的类 targetNames=xxxRecordManager,xxxSetRecordManager,xxxStatisticsIdentificationManager # 不需要缓存的方法 methodNames= #设置缓存失效时间 com.service.impl.xxxRecordManager= 60 com.service.impl.xxxSetRecordManager= 60 defaultCacheExpireTime=3600 fep.local.cache.capacity =10000 要扫这些properties文件,在application.xml加入如下配置 <!-- 引入properties配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:properties/*.properties</value> <!--要是有多个配置文件,只需在这里继续添加即可 --> </list> </property> </bean> 3、一些工具类 package com.mucfc.msm.common; import java.io.Serializable; import java.util.Set; import java.util.concurrent.TimeUnit; import org.apache.log4j.Logger; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; /** * redis cache 工具类 * */ public final class RedisUtil { private Logger logger = Logger.getLogger(RedisUtil.class); private RedisTemplate<Serializable, Object> redisTemplate; /** * 批量删除对应的value * * @param keys */ public void remove(final String... keys) { for (String key : keys) { remove(key); } } /** * 批量删除key * * @param pattern */ public void removePattern(final String pattern) { Set<Serializable> keys = redisTemplate.keys(pattern); if (keys.size() > 0) redisTemplate.delete(keys); } /** * 删除对应的value * * @param key */ public void remove(final String key) { if (exists(key)) { redisTemplate.delete(key); } } /** * 判断缓存中是否有对应的value * * @param key * @return */ public boolean exists(final String key) { return redisTemplate.hasKey(key); } /** * 读取缓存 * * @param key * @return */ public Object get(final String key) { Object result = null; ValueOperations<Serializable, Object> operations = redisTemplate .opsForValue(); result = operations.get(key); return result; } /** * 写入缓存 * * @param key * @param value * @return */ public boolean set(final String key, Object value) { boolean result = false; try { ValueOperations<Serializable, Object> operations = redisTemplate .opsForValue(); operations.set(key, value); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /** * 写入缓存 * * @param key * @param value * @return */ public boolean set(final String key, Object value, Long expireTime) { boolean result = false; try { ValueOperations<Serializable, Object> operations = redisTemplate .opsForValue(); operations.set(key, value); redisTemplate.expire(key, expireTime, TimeUnit.SECONDS); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } public void setRedisTemplate( RedisTemplate<Serializable, Object> redisTemplate) { this.redisTemplate = redisTemplate; } } (2)MethodCacheInterceptor package com.mucfc.msm.common; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Properties; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.apache.log4j.Logger; public class MethodCacheInterceptor implements MethodInterceptor { private Logger logger = Logger.getLogger(MethodCacheInterceptor.class); private RedisUtil redisUtil; private List<String> targetNamesList; // 不加入缓存的service名称 private List<String> methodNamesList; // 不加入缓存的方法名称 private Long defaultCacheExpireTime; // 缓存默认的过期时间 private Long xxxRecordManagerTime; // private Long xxxSetRecordManagerTime; // /** * 初始化读取不需要加入缓存的类名和方法名称 */ public MethodCacheInterceptor() { try { File f = new File("D:\\lunaJee-workspace\\msm\\msm_core\\src\\main\\java\\com\\mucfc\\msm\\common\\cacheConf.properties"); //配置文件位置直接被写死,有需要自己修改下 InputStream in = new FileInputStream(f); // InputStream in = getClass().getClassLoader().getResourceAsStream( // "D:\\lunaJee-workspace\\msm\\msm_core\\src\\main\\java\\com\\mucfc\\msm\\common\\cacheConf.properties"); Properties p = new Properties(); p.load(in); // 分割字符串 String[] targetNames = p.getProperty("targetNames").split(","); String[] methodNames = p.getProperty("methodNames").split(","); // 加载过期时间设置 defaultCacheExpireTime = Long.valueOf(p.getProperty("defaultCacheExpireTime")); xxxRecordManagerTime = Long.valueOf(p.getProperty("com.service.impl.xxxRecordManager")); xxxSetRecordManagerTime = Long.valueOf(p.getProperty("com.service.impl.xxxSetRecordManager")); // 创建list targetNamesList = new ArrayList<String>(targetNames.length); methodNamesList = new ArrayList<String>(methodNames.length); Integer maxLen = targetNames.length > methodNames.length ? targetNames.length : methodNames.length; // 将不需要缓存的类名和方法名添加到list中 for (int i = 0; i < maxLen; i++) { if (i < targetNames.length) { targetNamesList.add(targetNames[i]); } if (i < methodNames.length) { methodNamesList.add(methodNames[i]); } } } catch (Exception e) { e.printStackTrace(); } } @Override public Object invoke(MethodInvocation invocation) throws Throwable { Object value = null; String targetName = invocation.getThis().getClass().getName(); String methodName = invocation.getMethod().getName(); // 不需要缓存的内容 //if (!isAddCache(StringUtil.subStrForLastDot(targetName), methodName)) { if (!isAddCache(targetName, methodName)) { // 执行方法返回结果 return invocation.proceed(); } Object[] arguments = invocation.getArguments(); String key = getCacheKey(targetName, methodName, arguments); System.out.println(key); try { // 判断是否有缓存 if (redisUtil.exists(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() { if (tkey.startsWith("com.service.impl.xxxRecordManager")) { redisUtil.set(tkey, tvalue, xxxRecordManagerTime); } else if (tkey.startsWith("com.service.impl.xxxSetRecordManager")) { redisUtil.set(tkey, tvalue, xxxSetRecordManagerTime); } else { redisUtil.set(tkey, tvalue, 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)) { 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; } } 4、配置需要缓存的类或方法 <!-- 需要加入缓存的类或方法 --> <bean id="methodCachePointCut" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor" > <property name="advice" > <ref local="methodCacheInterceptor" /> </property> <property name="patterns" > <list> <!-- 确定正则表达式列表 --> <value>com\.mucfc\.msm\.service\.impl\...*ServiceImpl.*</value > </list> </property> </bean > 5、执行结果: @Test public void getSettUnitBySettUnitIdTest() { String systemId = "CES"; String merchantId = "133"; SettUnit configSettUnit = settUnitService.getSettUnitBySettUnitId(systemId, merchantId, "ESP"); SettUnit configSettUnit1 = settUnitService.getSettUnitBySettUnitId(systemId, merchantId, "ESP"); boolean flag= (configSettUnit == configSettUnit1); System.out.println(configSettUnit); logger.info("查找结果" + configSettUnit.getBusinessType()); // localSecondFIFOCache.put("configSettUnit", configSettUnit.getBusinessType()); // String string = localSecondFIFOCache.get("configSettUnit"); logger.info("查找结果" + string); } 这是第一次执行单元测试的过程:
依次运行,发现没有缓存,所以会直接去查数据库 打印了出来的SQL语句: 第二次执行: 3、取两次的结果进行地址的对比: 以上就是本文的全部内容,希望对大家的学习有所帮助。 |
请发表评论