springboot连接redis集群

刺骨的言语ヽ痛彻心扉 2022-04-15 06:16 520阅读 0赞

1.创建maven工程,导入依赖,pom文件内容如下

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3. <modelVersion>4.0.0</modelVersion>
  4. <groupId>com.szcatic</groupId>
  5. <artifactId>springboot</artifactId>
  6. <version>0.0.1-SNAPSHOT</version>
  7. <packaging>war</packaging>
  8. <name>springboot</name>
  9. <url>http://maven.apache.org</url>
  10. <parent>
  11. <groupId>org.springframework.boot</groupId>
  12. <artifactId>spring-boot-starter-parent</artifactId>
  13. <version>2.1.0.RELEASE</version>
  14. </parent>
  15. <dependencies>
  16. <dependency>
  17. <groupId>org.springframework.boot</groupId>
  18. <artifactId>spring-boot-starter-web</artifactId>
  19. </dependency>
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-starter-test</artifactId>
  23. <scope>test</scope>
  24. </dependency>
  25. <!-- junit5运行所需jar包 -->
  26. <dependency>
  27. <groupId>org.junit.jupiter</groupId>
  28. <artifactId>junit-jupiter-engine</artifactId>
  29. <scope>test</scope>
  30. </dependency>
  31. <dependency>
  32. <groupId>org.junit.platform</groupId>
  33. <artifactId>junit-platform-runner</artifactId>
  34. <scope>test</scope>
  35. </dependency>
  36. <!-- spring-boot-starter-jdbc -->
  37. <dependency>
  38. <groupId>org.springframework.boot</groupId>
  39. <artifactId>spring-boot-starter-jdbc</artifactId>
  40. </dependency>
  41. <!-- mysql-connector-java -->
  42. <dependency>
  43. <groupId>mysql</groupId>
  44. <artifactId>mysql-connector-java</artifactId>
  45. </dependency>
  46. <!-- spring-boot-starter-data-redis -->
  47. <dependency>
  48. <groupId>org.springframework.boot</groupId>
  49. <artifactId>spring-boot-starter-data-redis</artifactId>
  50. </dependency>
  51. <!-- jedis -->
  52. <dependency>
  53. <groupId>redis.clients</groupId>
  54. <artifactId>jedis</artifactId>
  55. </dependency>
  56. </dependencies>
  57. <properties>
  58. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  59. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  60. <java.version>1.8</java.version>
  61. <!-- 指定springboot入口类 -->
  62. <start-class>com.szcatic.Application</start-class>
  63. </properties>
  64. <build>
  65. <plugins>
  66. <plugin>
  67. <groupId>org.springframework.boot</groupId>
  68. <artifactId>spring-boot-maven-plugin</artifactId>
  69. <configuration>
  70. <source>1.8</source>
  71. <target>1.8</target>
  72. </configuration>
  73. </plugin>
  74. </plugins>
  75. </build>
  76. </project>

2.在配置文件application.properties中添加redis集群配置

  1. # redis集群配置
  2. spring.redis.cluster.nodes=127.0.0.1:7000,127.0.0.1:7001,127.0.0.1:7002,127.0.0.1:7003,127.0.0.1:7004,127.0.0.1:7005
  3. # Redis服务器连接密码(默认为空)
  4. spring.redis.password=
  5. # 连接池最大连接数(使用负值表示没有限制)
  6. spring.redis.pool.max-active=20
  7. # 连接池最大阻塞等待时间(使用负值表示没有限制)
  8. spring.redis.pool.max-wait=-1
  9. # 连接池中的最大空闲连接
  10. spring.redis.pool.max-idle=20
  11. # 连接池中的最小空闲连接
  12. spring.redis.pool.min-idle=0
  13. # 连接超时时间(毫秒)
  14. spring.redis.timeout=60000

3.自定义配置类RedisClusterConfig.java

  1. package com.szcatic.configuration;
  2. import java.util.HashSet;
  3. import java.util.Set;
  4. import org.springframework.beans.factory.annotation.Value;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. import redis.clients.jedis.HostAndPort;
  8. import redis.clients.jedis.JedisCluster;
  9. import redis.clients.jedis.JedisPoolConfig;
  10. @Configuration
  11. public class RedisClusterConfig {
  12. @Value("${spring.redis.cluster.nodes}")
  13. private String clusterNodes;
  14. @Value("${spring.redis.database}")
  15. private int database;
  16. @Value("${spring.redis.timeout}")
  17. private int timeout;
  18. @Value("${spring.redis.pool.max-idle}")
  19. private int maxIdle;
  20. @Value("${spring.redis.pool.min-idle}")
  21. private int minIdle;
  22. @Value("${spring.redis.pool.max-active}")
  23. private int maxActive;
  24. @Value("${spring.redis.pool.max-wait}")
  25. private long maxWait;
  26. @Bean
  27. public JedisCluster getJedisCluster() {
  28. return new JedisCluster(getNodes(), timeout, poolConfig());
  29. }
  30. private JedisPoolConfig poolConfig() {
  31. JedisPoolConfig config = new JedisPoolConfig();
  32. config.setMaxIdle(maxIdle);
  33. config.setMinIdle(minIdle);
  34. config.setMaxTotal(maxActive);
  35. config.setMaxWaitMillis(maxWait);
  36. return config;
  37. }
  38. private Set<HostAndPort> getNodes() {
  39. String[] cNodes = clusterNodes.split(",");
  40. Set<HostAndPort> nodes = new HashSet<HostAndPort>();
  41. // 分割出集群节点
  42. String[] hp;
  43. for (String node : cNodes) {
  44. hp = node.split(":");
  45. nodes.add(new HostAndPort(hp[0], Integer.parseInt(hp[1])));
  46. }
  47. return nodes;
  48. }
  49. }

4.编写测试类RedisClusterConfigTest.java

  1. package com.szcatic.test;
  2. import org.junit.jupiter.api.Test;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import redis.clients.jedis.JedisCluster;
  5. public class RedisClusterConfigTest {
  6. @Autowired
  7. private JedisCluster jedisCluster;
  8. @Test
  9. void test() {
  10. jedisCluster.set("userName", "zhangsan");
  11. String userName = jedisCluster.get("userName");
  12. System.out.println("userName======" + userName);
  13. }
  14. }

5.启动redis集群,运行测试方法test(),控制台输出内容如下

  1. 15:57:05.335 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
  2. 15:57:05.385 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
  3. 15:57:05.412 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.szcatic.test.RedisClusterConfigTest] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
  4. 15:57:05.480 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.szcatic.test.RedisClusterConfigTest], using SpringBootContextLoader
  5. 15:57:05.496 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.szcatic.test.RedisClusterConfigTest]: class path resource [com/szcatic/test/RedisClusterConfigTest-context.xml] does not exist
  6. 15:57:05.497 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.szcatic.test.RedisClusterConfigTest]: class path resource [com/szcatic/test/RedisClusterConfigTestContext.groovy] does not exist
  7. 15:57:05.497 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.szcatic.test.RedisClusterConfigTest]: no resource found for suffixes {-context.xml, Context.groovy}.
  8. 15:57:05.604 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [com.szcatic.test.RedisClusterConfigTest]
  9. 15:57:05.912 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - @TestExecutionListeners is not present for class [com.szcatic.test.RedisClusterConfigTest]: using defaults.
  10. 15:57:05.913 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
  11. 15:57:06.001 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@1d8bd0de, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@45ca843, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@11c9af63, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@757acd7b, org.springframework.test.context.support.DirtiesContextTestExecutionListener@36b4fe2a, org.springframework.test.context.transaction.TransactionalTestExecutionListener@574b560f, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@ba54932, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@28975c28, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@3943a2be, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@343570b7, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@157853da, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@71c3b41]
  12. 15:57:06.022 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext@41c2284a testClass = RedisClusterConfigTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@53aad5d5 testClass = RedisClusterConfigTest, locations = '{}', classes = '{class com.szcatic.Application, class com.szcatic.Application}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@2805c96b, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@5bfa9431, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@147ed70f, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@2bbf180e], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true]], class annotated with @DirtiesContext [false] with mode [null].
  13. 15:57:06.082 [main] DEBUG org.springframework.test.context.support.TestPropertySourceUtils - Adding inlined properties to environment: {spring.jmx.enabled=false, org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true, server.port=-1}
  14. . ____ _ __ _ _
  15. /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
  16. ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
  17. \\/ ___)| |_)| | | | | || (_| | ) ) ) )
  18. ' |____| .__|_| |_|_| |_\__, | / / / /
  19. =========|_|==============|___/=/_/_/_/
  20. :: Spring Boot :: (v2.1.0.RELEASE)
  21. 2018-11-22 15:57:07.237 INFO 10472 --- [ main] com.szcatic.test.RedisClusterConfigTest : Starting RedisClusterConfigTest on zsx with PID 10472 (started by admin in F:\workspace4.7\springboot)
  22. 2018-11-22 15:57:07.242 INFO 10472 --- [ main] com.szcatic.test.RedisClusterConfigTest : No active profile set, falling back to default profiles: default
  23. 2018-11-22 15:57:10.224 INFO 10472 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
  24. 2018-11-22 15:57:10.240 INFO 10472 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
  25. 2018-11-22 15:57:10.385 INFO 10472 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 97ms. Found 0 repository interfaces.
  26. 2018-11-22 15:57:11.408 INFO 10472 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$b2ec53b2] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
  27. 2018-11-22 15:57:13.942 INFO 10472 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
  28. 2018-11-22 15:57:15.235 INFO 10472 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService
  29. 2018-11-22 15:57:16.501 INFO 10472 --- [ main] com.szcatic.test.RedisClusterConfigTest : Started RedisClusterConfigTest in 10.366 seconds (JVM running for 12.41)
  30. userName======zhangsan
  31. 2018-11-22 15:57:17.164 INFO 10472 --- [ Thread-3] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService
  32. 2018-11-22 15:57:17.168 INFO 10472 --- [ Thread-3] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3pzeDE4MjczMTE3MDAz_size_16_color_FFFFFF_t_70

从以上结果可以看出操作redis集群成功

6.项目结构如下

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3pzeDE4MjczMTE3MDAz_size_16_color_FFFFFF_t_70 1

发表评论

表情:
评论列表 (有 0 条评论,520人围观)

还没有评论,来说两句吧...

相关阅读