Springboot操作redis叢集的工具類
阿新 • • 發佈:2018-12-25
最近一直在做SpringCloud的專案,由於用到了redis叢集,所以就想著寫一個操作redis叢集的工具類來。廢話不多說,直接上乾貨。
第一,redis的地址配置:
#redis cluster
spring.redis.cache.clusterNodes=192.168.10.4:7000,192.168.10.4:7001,192.168.10.4:7002,192.168.10.4:7000,192.168.10.4:7003,192.168.10.4:7004,192.168.10.4:7005
spring.redis.cache.commandTimeout=5000
第二步:載入配置
@Component @ConfigurationProperties(prefix = "spring.redis.cache") class RedisProperties { private String clusterNodes; private Integer commandTimeout; public String getClusterNodes() { return clusterNodes; } public void setClusterNodes(String clusterNodes) { this.clusterNodes = clusterNodes; } public Integer getCommandTimeout() { return commandTimeout; } public void setCommandTimeout(Integer commandTimeout) { this.commandTimeout = commandTimeout; } }
第三步: 得到JedisCluster工具
@Configuration @ConditionalOnClass({ JedisCluster.class}) @EnableConfigurationProperties(RedisProperties.class) public class JedisClusterConfig { @Autowired private RedisProperties redisProperties; @Bean public JedisCluster getJedisCluster() { String[] serverArray = redisProperties.getClusterNodes().split(","); Set<HostAndPort> nodes = new HashSet<HostAndPort>(); for (String ipPort: serverArray) { String[] ipPortPair = ipPort.split(":"); nodes.add(new HostAndPort(ipPortPair[0].trim(),Integer.valueOf(ipPortPair[1].trim()))); } return new JedisCluster(nodes, redisProperties.getCommandTimeout()); } }
第四步:測試
@Autowired
private JedisCluster jedisCluster;
jedisCluster.set("key","value");
jedisCluster.hset("id","key","value");還有很多功能根據自己的需要去用即可!