1.引入redis相关jar包
1 <dependency> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-data-redis</artifactId> 4 </dependency> 5 6 <dependency> 7 <groupId>org.redisson</groupId> 8 <artifactId>redisson</artifactId> 9 <version>1.0.2</version> 10 </dependency>
2.配置Redis相关信息
1 #redis 配置 2 # Redis数据库索引(默认为0) 3 spring.redis.database=${dev.spring.redis.database} 4 # Redis服务器地址 5 spring.redis.host=${dev.spring.redis.host} 6 # Redis服务器连接端口 7 spring.redis.port=${dev.spring.redis.port} 8 # Redis服务器连接密码(默认为空) 9 spring.redis.password=${dev.spring.redis.password} 10 # 连接池最大连接数(使用负值表示没有限制) 11 spring.redis.pool.max-active=${dev.spring.redis.pool.max-active} 12 # 连接池最大阻塞等待时间(使用负值表示没有限制) 13 spring.redis.pool.max-wait=${dev.spring.redis.pool.max-wait} 14 # 连接池中的最大空闲连接 15 spring.redis.pool.max-idle=${dev.spring.redis.pool.max-idle} 16 # 连接池中的最小空闲连接 17 spring.redis.pool.min-idle=${dev.spring.redis.pool.min-idle} 18 # 连接超时时间(毫秒) 19 spring.redis.timeout=${dev.spring.redis.timeout}
3.读取Redis链接信息 RedisConn
1 @Component 2 @ConfigurationProperties(prefix = "spring.redis") 3 public class RedisConn { 4 private String host; 5 //prefix+参数名 对应于配置文件config.properties中的spring.redis.*信息 6 private int port; 7 8 private int timeout;
4.RedisConfig
1 package com.sinosoft.product.service.redis; 2 3 import com.fasterxml.jackson.annotation.JsonAutoDetect; 4 import com.fasterxml.jackson.annotation.PropertyAccessor; 5 import com.fasterxml.jackson.databind.ObjectMapper; 6 import org.springframework.beans.factory.annotation.Autowired; 7 import org.springframework.cache.CacheManager; 8 import org.springframework.cache.annotation.CachingConfigurerSupport; 9 import org.springframework.cache.annotation.EnableCaching; 10 import org.springframework.cache.interceptor.KeyGenerator; 11 import org.springframework.context.annotation.Bean; 12 import org.springframework.context.annotation.Configuration; 13 import org.springframework.data.redis.cache.RedisCacheManager; 14 import org.springframework.data.redis.connection.RedisConnectionFactory; 15 import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; 16 import org.springframework.data.redis.core.RedisTemplate; 17 import org.springframework.data.redis.core.StringRedisTemplate; 18 import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; 19 20 import java.lang.reflect.Method; 21 import java.util.HashMap; 22 import java.util.Map; 23 24 25 @Configuration 26 @EnableCaching 27 public class RedisConfig extends CachingConfigurerSupport { 28 @Autowired 29 private RedisConn redisConn; 30 31 /** 32 * 生产key的策略 33 * 34 * @return 35 */ 36 37 @Bean 38 @Override 39 public KeyGenerator keyGenerator() { 40 return new KeyGenerator() { 41 42 @Override 43 public Object generate(Object target, Method method, Object... params) { 44 StringBuilder sb = new StringBuilder(); 45 sb.append(target.getClass().getName()); 46 sb.append(method.getName()); 47 for (Object obj : params) { 48 sb.append(obj.toString()); 49 } 50 return sb.toString(); 51 } 52 }; 53 54 } 55 56 /** 57 * 管理缓存 58 * 59 * @param redisTemplate 60 * @return 61 */ 62 63 @SuppressWarnings("rawtypes") 64 @Bean 65 public CacheManager CacheManager(RedisTemplate redisTemplate) { 66 RedisCacheManager rcm = new RedisCacheManager(redisTemplate); 67 // 设置cache过期时间,时间单位是秒 68 rcm.setDefaultExpiration(60); 69 Map<String, Long> map = new HashMap<String, Long>(); 70 map.put("test", 60L); 71 rcm.setExpires(map); 72 return rcm; 73 } 74 75 /** 76 * redis 数据库连接池 77 * @return 78 */ 79 80 @Bean 81 public JedisConnectionFactory redisConnectionFactory() { 82 JedisConnectionFactory factory = new JedisConnectionFactory(); 83 factory.setHostName(redisConn.getHost()); 84 factory.setPort(redisConn.getPort()); 85 factory.setTimeout(redisConn.getTimeout()); // 设置连接超时时间 86 return factory; 87 } 88 89 /** 90 * redisTemplate配置 91 * 92 * @param factory 93 * @return 94 */ 95 @SuppressWarnings({ "rawtypes", "unchecked" }) 96 @Bean 97 public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) { 98 StringRedisTemplate template = new StringRedisTemplate(factory); 99 Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); 100 ObjectMapper om = new ObjectMapper(); 101 om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); 102 om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); 103 jackson2JsonRedisSerializer.setObjectMapper(om); 104 template.setValueSerializer(jackson2JsonRedisSerializer); 105 template.afterPropertiesSet(); 106 return template; 107 } 108 109 }
5.RedisUtils Redis工具类
1 package com.sinosoft.product.service.redis; 2 3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.data.redis.core.RedisTemplate; 5 import org.springframework.data.redis.core.ValueOperations; 6 import org.springframework.stereotype.Component; 7 8 import java.io.Serializable; 9 import java.util.Set; 10 import java.util.concurrent.TimeUnit; 11 12 @Component 13 public class RedisUtil{ 14 @SuppressWarnings("rawtypes") 15 @Autowired 16 private RedisTemplate redisTemplate; 17 18 /** 19 * 批量删除对应的value 20 * 21 * @param keys 22 */ 23 public void remove(final String... keys) { 24 for (String key : keys) { 25 remove(key); 26 } 27 } 28 29 /** 30 * 批量删除key 31 * 32 * @param pattern 33 */ 34 @SuppressWarnings("unchecked") 35 public void removePattern(final String pattern) { 36 Set<Serializable> keys = redisTemplate.keys(pattern); 37 if (keys.size() > 0) 38 redisTemplate.delete(keys); 39 } 40 41 /** 42 * 删除对应的value 43 * 44 * @param key 45 */ 46 @SuppressWarnings("unchecked") 47 public void remove(final String key) { 48 if (exists(key)) { 49 redisTemplate.delete(key); 50 } 51 } 52 53 /** 54 * 判断缓存中是否有对应的value 55 * 56 * @param key 57 * @return 58 */ 59 @SuppressWarnings("unchecked") 60 public boolean exists(final String key) { 61 return redisTemplate.hasKey(key); 62 } 63 64 /** 65 * 读取缓存 66 * 67 * @param key 68 * @return 69 */ 70 @SuppressWarnings("unchecked") 71 public Object get(final String key) { 72 Object result = null; 73 ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); 74 result = operations.get(key); 75 return result; 76 } 77 78 /** 79 * 写入缓存 80 * 81 * @param key 82 * @param value 83 * @return 84 */ 85 @SuppressWarnings("unchecked") 86 public boolean set(final String key, Object value) { 87 boolean result = false; 88 try { 89 ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); 90 operations.set(key, value); 91 result = true; 92 } catch (Exception e) { 93 e.printStackTrace(); 94 } 95 return result; 96 } 97 98 /** 99 * 写入缓存 100 * 101 * @param key 102 * @param value 103 * @return 104 */ 105 @SuppressWarnings("unchecked") 106 public boolean set(final String key, Object value, Long expireTime) { 107 boolean result = false; 108 try { 109 ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); 110 operations.set(key, value); 111 redisTemplate.expire(key, expireTime, TimeUnit.SECONDS); 112 result = true; 113 } catch (Exception e) { 114 e.printStackTrace(); 115 } 116 return result; 117 } 118 119 }
6.Redis的使用
1 //注入Redis的工具类 2 3 @Autowired 4 private RedisUtils redisUtil; 5 6 //判断Redis中是否存在对应key的信息,若存在则在reids中获取,若不存在从数据库查询,同时存入redis缓存中 7 8 if (redisUtil.exists(calcode+calFlag)) { 9 Log.info("从Redis缓存中获取产品计算编码:{" + calcode+calFlag + "}信息"); 10 tLMCalCulate = (LMCalCulate) redisUtil.get(calcode+calFlag); 11 } else { 12 LMCalCulateExample tLMCalCulateExample=new LMCalCulateExample(); 13 tLMCalCulateExample.createCriteria().andCalcodeEqualTo(calcode).andCalflgEqualTo(calFlag); 14 List<LMCalCulate> tListLMCalCulate = lMCalCulateMapper.selectByExample(tLMCalCulateExample); 15 if(null!=tListLMCalCulate && tListLMCalCulate.size()>0){ 16 tLMCalCulate=tListLMCalCulate.get(0); 17 redisUtil.set(calcode+calFlag, tLMCalCulate); 18 } 19 }