本文共 2335 字,大约阅读时间需要 7 分钟。
Redis在项目中使用频率是很高的,使用的时候经常都是以Redis集群的形式。现整理一下Spring-Boot整合redis cluster最基础配置,方便以后查阅。
下面2个依赖是spring-boot集成Redis的必备依赖。
org.springframework.boot spring-boot-starter ${spring-boot.version} org.springframework.boot spring-boot-starter-redis 1.4.4.RELEASE
如果启用spring-boot单元测试,还需要加入下面的依赖。
org.springframework.boot spring-boot-starter-test ${spring-boot.version} test
application.yml配置Redis集群节点信息
spring: redis: cluster: nodes: - redis1.itclj.com:7000 - redis1.itclj.com:7001 - redis2.itclj.com:7002 - redis2.itclj.com:7003 - redis3.itclj.com:7004 - redis3.itclj.com:7005
spring-boot默认都采用注解方式初始化bean。
首先建一个redis集群配置bean,从配置文件中读取配置到配置bean里面。 其次建一个redis Cluster初始化配置bean,用于初始化Redis Cluster。由于复杂配置项,如数组不能通过@Value
注解直接读取配置项,所有只能采用新建配置Bean通过@ConfigurationProperties
注解读取。
@Configuration@ConfigurationProperties(prefix = "spring.redis.cluster")public class RedisClusterProperties { //集群节点 private Listnodes=new ArrayList<>(); public List getNodes() { return nodes; } public void setNodes(List nodes) { this.nodes = nodes; }}
@Configuration@ConditionalOnClass(RedisClusterConfig.class)@EnableConfigurationProperties(RedisClusterProperties.class)public class RedisClusterConfig { @Resource private RedisClusterProperties redisClusterProperties; @Bean public JedisCluster redisCluster(){ Setnodes = new HashSet<>(); for (String node:redisClusterProperties.getNodes()){ String[] parts= StringUtils.split(node,":"); Assert.state(parts.length==2, "redis node shoule be defined as 'host:port', not '" + Arrays.toString(parts) + "'"); nodes.add(new HostAndPort(parts[0], Integer.valueOf(parts[1]))); } return new JedisCluster(nodes); }}
@RunWith(SpringRunner.class)@SpringBootTestpublic class RedisTest { @Autowired private JedisCluster jedisCluster; @Test public void get(){ System.out.println("=============="+jedisCluster.get("youqian-spread-sync-to-mysql-date")); }}
原文地址:
项目地址:转载地址:http://iuvmb.baihongyu.com/