fix redis 缓存客户端,包括jedis,redisson,spring-data-redis

pull/2/MERGE
wuwenbin 2020-05-11 23:02:34 +08:00
parent cce62c43f4
commit ee735c0ec4
7 changed files with 359 additions and 0 deletions

View File

@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>onemall</artifactId>
<groupId>cn.iocoder.mall</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>mall-spring-boot-starter-cache</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.10.6</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.1.0</version>
</dependency>
</dependencies>
</project>

View File

@ -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;
}
}

View File

@ -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<String> nodes = Arrays.asList(this.nodes.split(","));
List<String> 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);
}
}

View File

@ -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<Object> 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<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
//StringRedisTemplate的构造方法中默认设置了stringSerializer
RedisTemplate<String, Object> 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;
}
}

View File

@ -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=

View File

@ -19,6 +19,16 @@
<module>mall-spring-boot-starter-security</module>
<module>mall-spring-boot-starter-mybatis</module>
</modules>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>

View File

@ -31,6 +31,7 @@
<module>order/order-rpc</module>
<module>order/order-rpc-api</module>
<module>order-rest</module>
<module>mall-spring-boot-starter-cache</module>
</modules>
<packaging>pom</packaging>