Springboot2.X集成redis集群(Lettuce)连接

2018-07-13 02:39:56来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

前提:搭建好redis集群环境,搭建方式请看:https://www.cnblogs.com/xymBlog/p/9300574.html

1. 新建工程,pom.xml文件中添加redis支持

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

 2.      配置application.properties

 

1 spring.redis.cluster.nodes=127.0.0.1:6380,127.0.0.1:6381,127.0.0.1:6382,127.0.0.1:6383,127.0.0.1:6384,127.0.0.1:6385
2 
3 spring.redis.cluster.timeout=1000
4 
5 spring.redis.cluster.max-redirects=3

 

 

3.      新建下面的两个类

 

@Configuration

public class RedisConfiguration {



    @Resource

    private LettuceConnectionFactory myLettuceConnectionFactory;



    @Bean

    public RedisTemplate<String, Serializable> redisTemplate() {

        RedisTemplate<String, Serializable> template = new RedisTemplate<>();

        template.setKeySerializer(new StringRedisSerializer());

        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());

        template.setConnectionFactory(myLettuceConnectionFactory);

        return template;

    }



}

  

 

 

@Configuration

public class RedisFactoryConfig {



    @Autowired

    private Environment environment;



    @Bean

    public RedisConnectionFactory myLettuceConnectionFactory() {



        Map<String, Object> source = new HashMap<String, Object>();



        source.put("spring.redis.cluster.nodes", environment.getProperty("spring.redis.cluster.nodes"));



        source.put("spring.redis.cluster.timeout", environment.getProperty("spring.redis.cluster.timeout"));



        source.put("spring.redis.cluster.max-redirects", environment.getProperty("spring.redis.cluster.max-redirects"));



        RedisClusterConfiguration redisClusterConfiguration;

        redisClusterConfiguration = new RedisClusterConfiguration(new MapPropertySource("RedisClusterConfiguration", source));



        return new LettuceConnectionFactory(redisClusterConfiguration);

    }

}

  

 

 

4.      执行测试

 

@SpringBootTest
@RunWith(SpringRunner.class)
public class RedisConfigurationTest {

    @Autowired
private RedisTemplate redisTemplate;

@Test
public void redisTemplate() throws Exception {

        redisTemplate.opsForValue().set("author", "Damein_xym");
}

}

 

5.      验证,使用Redis Desktop Manager 连接redis节点,查看里面的数据是否存在author,有如下显示,证明成功。

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:eclispe创建gradle多模块项目

下一篇:Java面向对象