一、配置
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<String> 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();
// 截取集群節(jié)點
String[] cluster = clusterProperties.getNodes().toArray(new String[0]);
// 創(chuàng)建set集合
Set<HostAndPort> nodes = new HashSet<HostAndPort>();
// 循環(huán)數(shù)組把集群節(jié)點添加到set集合中
for (String node : cluster) {
String[] host = node.split(":");
//添加集群節(jié)點
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<String, String> 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<String, Object> redisTemplate2(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
RedisSerializer<String> 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的區(qū)別是為了針對不同的業(yè)務情況,方便寫入不同的value,當然可以配置自己需要的redisTemplate3等等。
二、使用
1、使用redisTemplate1 只是示例幾個例子
import lombok.extern.slf4j.Slf4j;
@Component
@Slf4j //使用了lombok的標簽 方便寫日志
public class RedisStringUtils {
@Resource(name = "redisTemplate1")
private RedisTemplate<String, String> 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 數(shù)據結構
*/
public List<String> range(String key) {
try {
return redisTemplate.opsForList().range(key, 0, -1);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return null;
}
/**
* hash 數(shù)據結構
* 如果 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 是有序集的基數(shù), M 為成功添加的新成員的數(shù)量
*
* @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 區(qū)別就是注入了不同
import lombok.extern.slf4j.Slf4j;
@SuppressWarnings({"WeakerAccess", "unused"})
@Component
@Slf4j //使用了lombok的標簽 方便寫日志
public class RedisUtils {
@Resource(name = "redisTemplate2")
private RedisTemplate<String, Object> redisTemplate;
}