`
zk_chs
  • 浏览: 212836 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

通过spring配置redis cluster

阅读更多

上周spring data redis更新了1.7.1版本,正式支持redis cluster集群模式,这里就介绍一下关于redis cluster集群的相关配置,例如redis连接池等内容。不过想要使用redis cluster集群的话,还是需要你先启动redis cluster才行,具体操作可以参考我之前的redis cluster集群搭建

 

1、与之前的文章相同,不采用xml,而是使用代码的方式进行配置,首先我们先定义一个redis的配置类:

@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "spring.redis.cluster")
public class RedisClusterConfigProperties {
  private List<String> nodes;
  getter/setter...
}

在这里,需要你自己先定义一个用来保存redis配置的properties或yml文件,如下:

spring.redis.cluster.nodes[0]=192.168.0.1:6379
spring.redis.cluster.nodes[1]=192.168.0.2:6379
或
spring:
   redis:
      cluster:
         nodes:
            - 192.168.0.1:6379
            - 192.168.0.2:6379

spring会自动读取并将内容set进我们的nodes中,其中,nodes配置多个是为了防止单个节点挂掉,理论上只需要配置一个节点即可。

 

2、配置redis cluster的bean:

@Configuration
public class RedisClusterConfig {

  @Autowired
  private RedisClusterConfigProperties clusterProperties;

  @Bean
  private RedisConnectionFactory connectionFactory() {
    private JedisConnectionFactory factory = new JedisConnectionFactory(new RedisClusterConfiguration(clusterProperties.getNodes()))
    /** 如果需要定制连接池,可以使用下面的方式进行配置 */
//    private JedisPoolConfig pool = new JedisPoolConfig();
//    pool.setMaxIdle(8)
//    pool.setMaxTotal(8)
//    pool.set...
//    factory.setPoolConfig(pool)
    return factory;
  }

  /**
    * 对redis的存取,据需要先行转换成byte[]
    **/
  @Bean
  @Autowired
  private RedisClusterConnection redisClusterConnection(RedisConnectionFactory connectionFactory) {
    return connectionFactory.getClusterConnection();
  }

  /**
    * 该bean可以直接操作String,无需转成byte[]
    **/
  @Bean
  @Autowired
  private StringRedisTemplate stringRedisTemplate(RedisConnectionFactory connectionFactory) {
    return new StringRedisTemplate(connectionFactory);
  }

}

上述总共配置了3个bean,其中,第一个bean为redis cluster的connection factory,后两个为redis客户端操作模板。

 

在factory中,可以自定义连接池pool,maxIdle与maxTotal分别表示最大空闲连接和总连接,spring默认为我们配置的连接池内,这两项均为8。

 

后 面的两个bean可以直接用,总的来说能用StringRedisTemplate就用,毕竟减少了很多麻烦的操作,只不过一些api与redis命令行 不一样,需要再稍微看一下,而RedisClusterConnection的api就和redis命令行一样了,但是需要先将你的内容转换成 byte[]才行。

 

 

2
7
分享到:
评论
1 楼 ygaolei123 2017-04-18  
帮了我大忙,谢谢

相关推荐

Global site tag (gtag.js) - Google Analytics