From ee735c0ec49011d05570aa9d495578369bdc1a92 Mon Sep 17 00:00:00 2001 From: wuwenbin Date: Mon, 11 May 2020 23:02:34 +0800 Subject: [PATCH] =?UTF-8?q?fix=20redis=20=E7=BC=93=E5=AD=98=E5=AE=A2?= =?UTF-8?q?=E6=88=B7=E7=AB=AF=EF=BC=8C=E5=8C=85=E6=8B=ACjedis=EF=BC=8Credi?= =?UTF-8?q?sson=EF=BC=8Cspring-data-redis?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- common/mall-spring-boot-starter-cache/pom.xml | 36 ++++ .../mall/cache/config/JedisClient.java | 79 +++++++++ .../mall/cache/config/RedissonClient.java | 51 ++++++ .../cache/config/SpringDataRedisConfig.java | 165 ++++++++++++++++++ .../src/main/resources/redis.properties | 17 ++ common/pom.xml | 10 ++ pom.xml | 1 + 7 files changed, 359 insertions(+) create mode 100644 common/mall-spring-boot-starter-cache/pom.xml create mode 100644 common/mall-spring-boot-starter-cache/src/main/java/cn/iocoder/mall/cache/config/JedisClient.java create mode 100644 common/mall-spring-boot-starter-cache/src/main/java/cn/iocoder/mall/cache/config/RedissonClient.java create mode 100644 common/mall-spring-boot-starter-cache/src/main/java/cn/iocoder/mall/cache/config/SpringDataRedisConfig.java create mode 100644 common/mall-spring-boot-starter-cache/src/main/resources/redis.properties diff --git a/common/mall-spring-boot-starter-cache/pom.xml b/common/mall-spring-boot-starter-cache/pom.xml new file mode 100644 index 000000000..f41982b20 --- /dev/null +++ b/common/mall-spring-boot-starter-cache/pom.xml @@ -0,0 +1,36 @@ + + + + onemall + cn.iocoder.mall + 1.0-SNAPSHOT + + 4.0.0 + + mall-spring-boot-starter-cache + + + + org.springframework.boot + spring-boot-starter-data-redis + + + + org.redisson + redisson + 3.10.6 + + + + redis.clients + jedis + 3.1.0 + + + + + + + \ No newline at end of file diff --git a/common/mall-spring-boot-starter-cache/src/main/java/cn/iocoder/mall/cache/config/JedisClient.java b/common/mall-spring-boot-starter-cache/src/main/java/cn/iocoder/mall/cache/config/JedisClient.java new file mode 100644 index 000000000..6a5ef8dd5 --- /dev/null +++ b/common/mall-spring-boot-starter-cache/src/main/java/cn/iocoder/mall/cache/config/JedisClient.java @@ -0,0 +1,79 @@ +package cn.iocoder.mall.cache.config; + + +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisSentinelPool; + +import javax.annotation.PostConstruct; +import javax.annotation.Resource; + + +@Component +public class JedisClient { + + @Resource + private static JedisSentinelPool jedisSentinelPool; + + public static String get(String key) { + Jedis jedis = null; + try { + jedis = jedisSentinelPool.getResource(); + return jedis.get(key); + } catch (Exception e) { + } finally { + if (jedis != null) { + jedis.close(); + } + } + return ""; + } + + public static boolean set(String key, String value) { + Jedis jedis = null; + try { + jedis = jedisSentinelPool.getResource(); + String ret = jedis.set(key, value); + return "ok".equalsIgnoreCase(ret); + } catch (Exception e) { + } finally { + if (jedis != null) { + jedis.close(); + } + } + return false; + } + + public static boolean set(String key, String value, int seconds) { + Jedis jedis = null; + try { + jedis = jedisSentinelPool.getResource(); + String ret = jedis.set(key, value); + jedis.expire(key, seconds); + return "ok".equalsIgnoreCase(ret); + } catch (Exception e) { + } finally { + if (jedis != null) { + jedis.close(); + } + } + return false; + } + + public static boolean del(String key) { + Long removedSize = 0L; + Jedis jedis = null; + try { + jedis = jedisSentinelPool.getResource(); + removedSize = jedis.del(key); + } catch (Exception e) { + } finally { + if (jedis != null) { + jedis.close(); + } + } + return removedSize > 0; + } + +} diff --git a/common/mall-spring-boot-starter-cache/src/main/java/cn/iocoder/mall/cache/config/RedissonClient.java b/common/mall-spring-boot-starter-cache/src/main/java/cn/iocoder/mall/cache/config/RedissonClient.java new file mode 100644 index 000000000..baf19fda4 --- /dev/null +++ b/common/mall-spring-boot-starter-cache/src/main/java/cn/iocoder/mall/cache/config/RedissonClient.java @@ -0,0 +1,51 @@ +package cn.iocoder.mall.cache.config; + + +import org.redisson.Redisson; +import org.redisson.config.Config; +import org.redisson.config.ReadMode; +import org.redisson.config.SentinelServersConfig; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.stereotype.Component; + + +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + + +@Component +public class RedissonClient { + + @Value("${spring.redis.database}") + private int database; + + @Value("${spring.redis.sentinel.master}") + private String master; + + @Value("${spring.redis.sentinel.nodes}") + private String nodes; + + /** + * 哨兵模式 redisson 客户端 + * @return + */ + @Bean + public org.redisson.api.RedissonClient redissonClient() { + Config config = new Config(); + List nodes = Arrays.asList(this.nodes.split(",")); + List newNodes = new ArrayList(nodes.size()); + nodes .forEach((index) -> newNodes.add( + index.startsWith("redis://") ? index : "redis://" + index)); + + SentinelServersConfig serverConfig = config.useSentinelServers() + .addSentinelAddress(newNodes.toArray(new String[3])) + .setMasterName(this.master) + .setReadMode(ReadMode.SLAVE) ; + + serverConfig.setDatabase(this.database); + return Redisson.create(config); + } +} diff --git a/common/mall-spring-boot-starter-cache/src/main/java/cn/iocoder/mall/cache/config/SpringDataRedisConfig.java b/common/mall-spring-boot-starter-cache/src/main/java/cn/iocoder/mall/cache/config/SpringDataRedisConfig.java new file mode 100644 index 000000000..690dc13d6 --- /dev/null +++ b/common/mall-spring-boot-starter-cache/src/main/java/cn/iocoder/mall/cache/config/SpringDataRedisConfig.java @@ -0,0 +1,165 @@ +package cn.iocoder.mall.cache.config; + +import com.fasterxml.jackson.annotation.JsonAutoDetect; +import com.fasterxml.jackson.annotation.PropertyAccessor; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.redisson.Redisson; +import org.redisson.api.RedissonClient; +import org.redisson.config.Config; +import org.redisson.config.ReadMode; +import org.redisson.config.SentinelServersConfig; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cache.CacheManager; +import org.springframework.cache.annotation.CachingConfigurerSupport; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.cache.interceptor.KeyGenerator; +import org.springframework.cache.interceptor.SimpleKeyGenerator; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.cache.RedisCacheConfiguration; +import org.springframework.data.redis.cache.RedisCacheManager; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; +import org.springframework.data.redis.serializer.RedisSerializationContext; +import org.springframework.data.redis.serializer.RedisSerializer; +import org.springframework.data.redis.serializer.StringRedisSerializer; +import redis.clients.jedis.Jedis; + +import java.lang.reflect.Method; +import java.time.Duration; +import java.util.*; + +import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES; + +@Configuration +@EnableCaching +public class SpringDataRedisConfig extends CachingConfigurerSupport { + + @Value("${spring.redis.database}") + private int database; + + @Value("${spring.redis.sentinel.master}") + private String master; + + @Value("${spring.redis.sentinel.nodes}") + private String nodes; + + private static RedisTemplate redisTemplate; + + static { + + } + + public static String get(String key) { + redisTemplate.opsForValue().get(key); + return ""; + } + + public static boolean set(String key, String value) { + redisTemplate.opsForValue().set(key,value); + return false; + } + + public static boolean set(String key, String value, int seconds) { + redisTemplate.opsForValue().set(key,value,seconds); + return false; + } + + + /** + * json序列化 + * @return + */ + @Bean + public RedisSerializer jackson2JsonRedisSerializer() { + //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值 + Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class); + + ObjectMapper mapper = new ObjectMapper(); + mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); + mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); + mapper.configure(FAIL_ON_UNKNOWN_PROPERTIES, false); + serializer.setObjectMapper(mapper); + return serializer; + } + + @Bean + public RedisTemplate redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) { + //StringRedisTemplate的构造方法中默认设置了stringSerializer + RedisTemplate template = new RedisTemplate<>(); + //set key serializer + StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); + template.setKeySerializer(stringRedisSerializer); + template.setHashKeySerializer(stringRedisSerializer); + + + //set value serializer + template.setDefaultSerializer(jackson2JsonRedisSerializer()); + + template.setConnectionFactory(lettuceConnectionFactory); + template.afterPropertiesSet(); + return template; + } + + @Bean + public StringRedisTemplate stringRedisTemplate(LettuceConnectionFactory lettuceConnectionFactory) { + StringRedisTemplate template = new StringRedisTemplate(); + template.setConnectionFactory(lettuceConnectionFactory); + return template; + } + + @Override + @Bean + public KeyGenerator keyGenerator() { + return new SimpleKeyGenerator() { + + @Override + public Object generate(Object target, Method method, Object... params) { + StringBuilder sb = new StringBuilder(); + sb.append(target.getClass().getName()); + sb.append(".").append(method.getName()); + + StringBuilder paramsSb = new StringBuilder(); + for (Object param : params) { + // 如果不指定,默认生成包含到键值中 + if (param != null) { + paramsSb.append(param.toString()); + } + } + + if (paramsSb.length() > 0) { + sb.append("_").append(paramsSb); + } + return sb.toString(); + } + + }; + + } + + private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer time, int timeType) { + + Duration duration = Duration.ofMillis(time); + if (timeType == 1){//时 + duration = Duration.ofHours(time); + }else if (timeType == 2){//分 + duration = Duration.ofMinutes(time); + }else if (timeType == 3){//秒 + duration = Duration.ofSeconds(time); + } + RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig(); + redisCacheConfiguration = redisCacheConfiguration + .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())) + .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer()) + + ) + //超时时间 + .entryTtl(duration); + + return redisCacheConfiguration; + } + +} diff --git a/common/mall-spring-boot-starter-cache/src/main/resources/redis.properties b/common/mall-spring-boot-starter-cache/src/main/resources/redis.properties new file mode 100644 index 000000000..43529de5d --- /dev/null +++ b/common/mall-spring-boot-starter-cache/src/main/resources/redis.properties @@ -0,0 +1,17 @@ +redis.pool.maxIdle=200 +redis.pool.minIdle=10 +#redis.pool.maxActive=600 +redis.pool.maxTotal=1024 +redis.pool.maxWaitMillis=3000 +redis.pool.minEvictableIdleTimeMillis=300000 +redis.pool.numTestsPerEvictionRun=1024 +redis.pool.timeBetweenEvictionRunsMillis=30000 +redis.pool.testOnBorrow=true +redis.pool.testWhileIdle=true +redis.pool.testOnReturn=true + +#Redis 配置 +spring.redis.sentinel.master= +spring.redis.sentinel.nodes= +spring.redis.database= + diff --git a/common/pom.xml b/common/pom.xml index c9938d864..5bdc0c06f 100644 --- a/common/pom.xml +++ b/common/pom.xml @@ -19,6 +19,16 @@ mall-spring-boot-starter-security mall-spring-boot-starter-mybatis + + + org.springframework + spring-context + + + redis.clients + jedis + + diff --git a/pom.xml b/pom.xml index 95aded6bf..364e64fae 100644 --- a/pom.xml +++ b/pom.xml @@ -31,6 +31,7 @@ order/order-rpc order/order-rpc-api order-rest + mall-spring-boot-starter-cache pom