一、配置
1、yml配置
spring:
redis:
cluster:
nodes:
- ip:port #替换为正确的redis集群的IP和端口号
- ip:port
- ip:port
- ip:port
- ip:port
- ip:port
connectionTimeout: 6000
soTimeout: 6000
maxAttempts: 5
password: password #写正确的密码
2、接收配置
import lombok.Data;
@Component
@ConfigurationProperties(prefix = "spring.redis.cluster")
@Data //使用了lombok的标签 如果未引用lombok需写getter 和 setter方法
public class RedisClusterConfigProperties {
private List nodes;
private Integer maxAttempts;
private Integer connectionTimeout;
private Integer soTimeout;
private String password;
}
3、集群配置
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
@Resource
private RedisClusterConfigProperties clusterProperties;
@Bean
public RedisClusterConfiguration getClusterConfig() {
RedisClusterConfiguration rcc = new RedisClusterConfiguration(clusterProperties.getNodes());
rcc.setMaxRedirects(clusterProperties.getMaxAttempts());
rcc.setPassword(RedisPassword.of(clusterProperties.getPassword()));
return rcc;
}
@Bean
public JedisCluster getJedisCluster() {
JedisPoolConfig poolConfig = new JedisPoolConfig();
// 截取集群节点
String[] cluster = clusterProperties.getNodes().toArray(new String[0]);
// 创建set集合
Set nodes = new HashSet();
// 循环数组把集群节点添加到set集合中
for (String node : cluster) {
String[] host = node.split(":");
//添加集群节点
nodes.add(new HostAndPort(host[0], Integer.parseInt(host[1])));
}
return new JedisCluster(nodes, clusterProperties.getConnectionTimeout(), clusterProperties.getSoTimeout(), clusterProperties.getMaxAttempts(), clusterProperties.getPassword(), poolConfig);
}
@Bean
public JedisConnectionFactory redisConnectionFactory(RedisClusterConfiguration cluster) {
return new JedisConnectionFactory(cluster);
}
/**
* RedisTemplate配置
* key 和 value 都为String类型
* 都使用Jackson2JsonRedisSerializer进行序列化
*/
@Bean(name = "redisTemplate1")
public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
/**
* RedisTemplate配置
* key 为String类型
* value 为 Object 类型
* 都使用Jackson2JsonRedisSerializer进行序列化
*/
@Bean(name = "redisTemplate2")
public RedisTemplate redisTemplate2(RedisConnectionFactory factory) {
RedisTemplate template = new RedisTemplate<>();
RedisSerializer stringSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper om = new ObjectMapper();
template.setConnectionFactory(factory);
template.afterPropertiesSet();
template.setKeySerializer(stringSerializer);
template.setHashKeySerializer(stringSerializer);
template.setHashValueSerializer(stringSerializer);
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
RedisTemplate配置说明:
1⃣️、序列化看源代码默认是 JdkSerializationRedisSerializer
,这样的话使用redis-client看的话,无法看懂对应的值,为了方便看懂使用jackson2JsonRedisSerializer
;
2⃣️、redisTemplate1
和redisTemplate2
的区别是为了针对不同的业务情况,方便写入不同的value,当然可以配置自己需要的redisTemplate3
等等。
二、使用
1、使用redisTemplate1
只是示例几个例子
import lombok.extern.slf4j.Slf4j;
@Component
@Slf4j //使用了lombok的标签 方便写日志
public class RedisStringUtils {
@Resource(name = "redisTemplate1")
private RedisTemplate redisTemplate;
public Object getObject(String key) {
return redisTemplate.opsForValue().get(key);
}
public void saveWithExpireTime(String key, String object, long timeout) {
redisTemplate.opsForValue().set(key, object, timeout, TimeUnit.SECONDS);
}
/**
* List 数据结构
*/
public List range(String key) {
try {
return redisTemplate.opsForList().range(key, 0, -1);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return null;
}
/**
* hash 数据结构
* 如果 field 存在就不在修改
*/
public void hsetIfAbsent(String key, String field, String value) {
try {
redisTemplate.opsForHash().putIfAbsent(key, field, value);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
public boolean hasKey(String key) {
return redisTemplate.hasKey(key);
}
/**
* 将一个元素及其 score 值加入到有序集 key 当中
* O(M*log(N)), N 是有序集的基数, M 为成功添加的新成员的数量
*
* @param key key
* @param value member
* @param source score
* @return 是否成功
*/
public Boolean zAdd(String key, String value, double source) {
try {
return redisTemplate.opsForZSet().add(key, value, source);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return null;
}
}
2、使用redisTemplate2
区别就是注入了不同
import lombok.extern.slf4j.Slf4j;
@SuppressWarnings({"WeakerAccess", "unused"})
@Component
@Slf4j //使用了lombok的标签 方便写日志
public class RedisUtils {
@Resource(name = "redisTemplate2")
private RedisTemplate redisTemplate;
}