好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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

前提:搭建好 redis 集群环境,搭建方式请看: http://www.tuohang.net/article/29914.html

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

?

1

2

3

4

<dependency>

   <groupid>org.springframework.boot</groupid>

   <artifactid>spring-boot-starter-data-redis</artifactid>

</dependency>

2.配置application.properties

?

1

2

3

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

spring.redis.cluster.timeout= 1000

spring.redis.cluster.max-redirects= 3

3.      新建下面的两个类

?

1

2

3

4

5

6

7

8

9

10

11

12

13

@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;

   }

}

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

@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. 执行测试

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

@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,有如下显示,证明成功。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

原文链接:http://www.cnblogs.com/xymBlog/p/9303032.html

查看更多关于Springboot2.X集成redis集群(Lettuce)连接的方法的详细内容...

  阅读:63次