Redis集群——SpringBoot连接Redis集群(带密码)

r囧r小猫 2022-03-15 05:10 543阅读 0赞

第一步,新建项目maven项目,添加依赖

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>springboot-redis-cluster</groupId>
  7. <artifactId>redis-cluster</artifactId>
  8. <version>1.0-SNAPSHOT</version>
  9. <description>springboot连接redis-cluster集群</description>
  10. <parent>
  11. <groupId>org.springframework.boot</groupId>
  12. <artifactId>spring-boot-starter-parent</artifactId>
  13. <version>2.0.2.RELEASE</version>
  14. <relativePath/>
  15. </parent>
  16. <dependencies>
  17. <dependency>
  18. <groupId>org.mybatis.spring.boot</groupId>
  19. <artifactId>mybatis-spring-boot-starter</artifactId>
  20. </dependency>
  21. <dependency>
  22. <groupId>org.springframework.boot</groupId>
  23. <artifactId>spring-boot-starter-web</artifactId>
  24. </dependency>
  25. <dependency>
  26. <groupId>org.springframework.boot</groupId>
  27. <artifactId>spring-boot-starter-data-redis</artifactId>
  28. </dependency>
  29. <dependency>
  30. <groupId>org.projectlombok</groupId>
  31. <artifactId>lombok</artifactId>
  32. </dependency>
  33. <dependency>
  34. <groupId>redis.clients</groupId>
  35. <artifactId>jedis</artifactId>
  36. <version>2.9.0</version>
  37. </dependency>
  38. </dependencies>
  39. <build>
  40. <plugins>
  41. <plugin>
  42. <groupId>org.springframework.boot</groupId>
  43. <artifactId>spring-boot-maven-plugin</artifactId>
  44. </plugin>
  45. </plugins>
  46. </build>
  47. </project>

第二步,编写配置文件

  1. spring:
  2. application:
  3. name: redis-cluster
  4. redis:
  5. cluster:
  6. nodes: 192.168.1.10:7001,192.168.1.10:7004,192.168.1.11:7002,192.168.1.11:7005,192.168.1.12:7003,192.168.1.12:7006
  7. max-redirects: 6
  8. redis:
  9. timeout: 10000 #客户端超时时间单位是毫秒 默认是2000
  10. maxIdle: 300 #最大空闲数
  11. maxTotal: 1000 #控制一个pool可分配多少个jedis实例,用来替换上面的redis.maxActive,如果是jedis 2.4以后用该属性
  12. maxWaitMillis: 1000 #最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。
  13. minEvictableIdleTimeMillis: 300000 #连接的最小空闲时间 默认1800000毫秒(30分钟)
  14. numTestsPerEvictionRun: 1024 #每次释放连接的最大数目,默认3
  15. timeBetweenEvictionRunsMillis: 30000 #逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1
  16. testOnBorrow: true #是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个
  17. testWhileIdle: true #在空闲时检查有效性, 默认false
  18. password: 123456 #密码
  19. server:
  20. port: 8080

第三步,编写配置类

  1. package com.config;
  2. import org.springframework.beans.factory.annotation.Value;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.data.redis.connection.RedisClusterConfiguration;
  6. import org.springframework.data.redis.connection.RedisNode;
  7. import org.springframework.data.redis.connection.RedisPassword;
  8. import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
  9. import org.springframework.data.redis.core.RedisTemplate;
  10. import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
  11. import org.springframework.data.redis.serializer.StringRedisSerializer;
  12. import redis.clients.jedis.JedisPoolConfig;
  13. import java.util.HashSet;
  14. import java.util.Set;
  15. /**
  16. * Created by Administrator on 2019/2/28.
  17. */
  18. @Configuration
  19. public class RedisClusterConfig {
  20. @Value("${spring.redis.cluster.nodes}")
  21. private String clusterNodes;
  22. @Value("${spring.redis.cluster.max-redirects}")
  23. private int maxRedirects;
  24. @Value("${redis.password}")
  25. private String password;
  26. @Value("${redis.timeout}")
  27. private int timeout;
  28. @Value("${redis.maxIdle}")
  29. private int maxIdle;
  30. @Value("${redis.maxTotal}")
  31. private int maxTotal;
  32. @Value("${redis.maxWaitMillis}")
  33. private int maxWaitMillis;
  34. @Value("${redis.minEvictableIdleTimeMillis}")
  35. private int minEvictableIdleTimeMillis;
  36. @Value("${redis.numTestsPerEvictionRun}")
  37. private int numTestsPerEvictionRun;
  38. @Value("${redis.timeBetweenEvictionRunsMillis}")
  39. private int timeBetweenEvictionRunsMillis;
  40. @Value("${redis.testOnBorrow}")
  41. private boolean testOnBorrow;
  42. @Value("${redis.testWhileIdle}")
  43. private boolean testWhileIdle;
  44. @Bean
  45. public JedisPoolConfig getJedisPoolConfig() {
  46. JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
  47. // 最大空闲数
  48. jedisPoolConfig.setMaxIdle(maxIdle);
  49. // 连接池的最大数据库连接数
  50. jedisPoolConfig.setMaxTotal(maxTotal);
  51. // 最大建立连接等待时间
  52. jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
  53. // 逐出连接的最小空闲时间 默认1800000毫秒(30分钟)
  54. jedisPoolConfig.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
  55. // 每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3
  56. jedisPoolConfig.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
  57. // 逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1
  58. jedisPoolConfig.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
  59. // 是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个
  60. jedisPoolConfig.setTestOnBorrow(testOnBorrow);
  61. // 在空闲时检查有效性, 默认false
  62. jedisPoolConfig.setTestWhileIdle(testWhileIdle);
  63. return jedisPoolConfig;
  64. }
  65. /**
  66. * Redis集群的配置
  67. * @return RedisClusterConfiguration
  68. * @throws
  69. */
  70. @Bean
  71. public RedisClusterConfiguration redisClusterConfiguration(){
  72. RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration();
  73. //Set<RedisNode> clusterNodes
  74. String[] serverArray = clusterNodes.split(",");
  75. Set<RedisNode> nodes = new HashSet<RedisNode>();
  76. for(String ipPort:serverArray){
  77. String[] ipAndPort = ipPort.split(":");
  78. nodes.add(new RedisNode(ipAndPort[0].trim(),Integer.valueOf(ipAndPort[1])));
  79. }
  80. redisClusterConfiguration.setClusterNodes(nodes);
  81. redisClusterConfiguration.setMaxRedirects(maxRedirects);
  82. redisClusterConfiguration.setPassword(RedisPassword.of(password));
  83. return redisClusterConfiguration;
  84. }
  85. /**
  86. * @param
  87. * @return
  88. * @Description:redis连接工厂类
  89. * @date 2018/10/25 19:45
  90. */
  91. @Bean
  92. public JedisConnectionFactory jedisConnectionFactory() {
  93. //集群模式
  94. JedisConnectionFactory factory = new JedisConnectionFactory(redisClusterConfiguration(),getJedisPoolConfig());
  95. factory.setDatabase(0);
  96. factory.setTimeout(timeout);
  97. factory.setUsePool(true);
  98. return factory;
  99. }
  100. /**
  101. * 实例化 RedisTemplate 对象
  102. *
  103. * @return
  104. */
  105. @Bean
  106. public RedisTemplate<String, Object> redisTemplate() {
  107. RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
  108. initDomainRedisTemplate(redisTemplate);
  109. return redisTemplate;
  110. }
  111. /**
  112. * 设置数据存入 redis 的序列化方式,并开启事务
  113. * 使用默认的序列化会导致key乱码
  114. *
  115. */
  116. private void initDomainRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
  117. //如果不配置Serializer,那么存储的时候缺省使用String,如果用User类型存储,那么会提示错误User can't cast to String!
  118. redisTemplate.setKeySerializer(new StringRedisSerializer());
  119. //这个地方有一个问题,这种序列化器会将value序列化成对象存储进redis中,如果
  120. //你想取出value,然后进行自增的话,这种序列化器是不可以的,因为对象不能自增;
  121. //需要改成StringRedisSerializer序列化器。
  122. redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
  123. redisTemplate.setEnableTransactionSupport(false);
  124. redisTemplate.setConnectionFactory(jedisConnectionFactory());
  125. }
  126. }

第四步,编写Controller

  1. @RestController
  2. public class TestController {
  3. @Autowired
  4. private RedisTemplate redisTemplate;
  5. @GetMapping("/test")
  6. public void test(){
  7. System.out.println(redisTemplate.hasKey("name"));
  8. redisTemplate.opsForValue().set("name","123214");
  9. String name = (String) redisTemplate.opsForValue().get("name");
  10. System.out.println(name);
  11. redisTemplate.opsForValue().set("name2","123214");
  12. String name2 = (String) redisTemplate.opsForValue().get("name");
  13. System.out.println(name2);
  14. redisTemplate.opsForValue().set("name3","123214");
  15. String name3 = (String) redisTemplate.opsForValue().get("name");
  16. System.out.println(name3);
  17. redisTemplate.opsForValue().set("name4","123214");
  18. String name4 = (String) redisTemplate.opsForValue().get("name");
  19. System.out.println(name4);
  20. HashOperations<String,String,String> hashOperations = redisTemplate.opsForHash();
  21. hashOperations.put("user","test","测试");
  22. System.out.println(hashOperations.get("user","test"));
  23. }
  24. }

第五步,启动项目测试,控制台打印

  1. true
  2. 123214
  3. 123214
  4. 123214
  5. 123214
  6. 测试

发表评论

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

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

相关阅读