当前位置:   article > 正文

SpringBoot 配置redis集群_springboot redis集群配置

springboot redis集群配置

导入依赖

  1. <!--Springboot集成 Redis ,Springboot2.x默认是用Lettuce连接redis,Lettuce可伸缩,线程安全-->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-data-redis</artifactId>
  5. </dependency>

配置applcation.yml

  1. # redis 配置
  2. redis:
  3. server:
  4. pattern: cluster
  5. nodes: 127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002,127.0.0.1:3003,127.0.0.1:3004,127.0.0.1:3005
  6. password:
  7. maxIdle: 8
  8. minIdle: 4
  9. maxTotal: 8
  10. maxWaitMillis: 6000
  11. timeOut: 6000

方式一:redis(存储各种对象)

  (1).配置

  1. @Configuration
  2. public class RedisConfig {
  3. @Value("${redis.server.nodes}")
  4. private String redisServerNodes;
  5. @Value("${redis.server.password}")
  6. private String redisServerPassword;
  7. @Bean
  8. public RedisClusterConfiguration getRedisClusterConfiguration() {
  9. RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration();
  10. String[] serverArray = redisServerNodes.split(",");
  11. Set<RedisNode> nodes = new HashSet<RedisNode>();
  12. for (String ipPort : serverArray) {
  13. String[] ipAndPort = ipPort.split(":");
  14. nodes.add(new RedisNode(ipAndPort[0].trim(), Integer.parseInt(ipAndPort[1])));
  15. }
  16. redisClusterConfiguration.setClusterNodes(nodes);
  17. RedisPassword pwd = RedisPassword.of(redisServerPassword);
  18. redisClusterConfiguration.setPassword(pwd);
  19. return redisClusterConfiguration;
  20. }
  21. //指定redisTemplate类型,如下为<String, Object>
  22. @Bean
  23. public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
  24. RedisTemplate<String, Object> template = new RedisTemplate();
  25. template.setConnectionFactory(redisConnectionFactory);
  26. // 使用JSON格式序列化对象,对缓存数据keyvalue进行转换
  27. Jackson2JsonRedisSerializer<Object> jacksonSeial = new Jackson2JsonRedisSerializer<>(Object.class);
  28. // 解决查询缓存转换异常的问题
  29. ObjectMapper objectMapper = new ObjectMapper();
  30. objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  31. objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
  32. jacksonSeial.setObjectMapper(objectMapper);
  33. // 设置RedisTemplate模板API的序列化方式为JSON
  34. template.setDefaultSerializer(jacksonSeial);
  35. return template;
  36. }
  37. }

 (2).使用

  1. //1.指定存储类型
  2. @Autowired
  3. private RedisTemplate<String,Object> redisTemplate;
  4. //2.未指定存储类型
  5. @Autowired
  6. private RedisTemplate redisTemplate;
  7. //存储
  8. redisTemplate.opsForValue().set(keyName, valueObject, Duration.ofXXX(n));
  9. //Duration.ofNanos() 纳秒
  10. //Duration.ofMillis() 毫秒
  11. //Duration.ofSeconds() 秒
  12. //Duration.ofMinutes() 分钟
  13. //Duration.ofHours() 小时
  14. //Duration.ofDays() 天
  15. //查询
  16. redisTemplate.opsForValue().get(keyName);

方式二:redission (常用于储存分布式锁)

(1).配置

  1. @Configuration
  2. public class RedissonConfig {
  3. @Value("${redis.server.pattern:single}")
  4. private String pattern;
  5. @Value("${redis.server.host:127.0.0.1}")
  6. private String host;
  7. @Value("${redis.server.nodes:1}")
  8. private List<String> nodes;
  9. @Value("${redis.server.port:6379}")
  10. private String port;
  11. @Value("${redis.server.password}")
  12. private String password;
  13. @Value("${redis.server.database:1}")
  14. private Integer database;
  15. @Bean
  16. @ConditionalOnProperty(prefix = "redis.server", name = "pattern", havingValue = "cluster")
  17. public RedissonClient clusterRedisClient() {
  18. Config config = new Config();
  19. ClusterServersConfig clusterServersConfig = config.useClusterServers();
  20. if (!StringUtils.isBlank(password)) {
  21. clusterServersConfig.setPassword(password);
  22. }
  23. // 集群状态扫描间隔时间,单位是毫秒
  24. clusterServersConfig.setScanInterval(2000);
  25. for (String node : nodes) {
  26. String url = "redis://" + node;
  27. clusterServersConfig.addNodeAddress(url);
  28. }
  29. RedissonClient redissonClient = Redisson.create(config);
  30. return redissonClient;
  31. }
  32. @Bean
  33. @ConditionalOnProperty(prefix = "redis.server", name = "pattern", havingValue = "single")
  34. public RedissonClient singleRedisClient() {
  35. Config config = new Config();
  36. SingleServerConfig singleServerConfig = config.useSingleServer();
  37. if (!StringUtils.isBlank(password)) {
  38. singleServerConfig.setPassword(password);
  39. }
  40. String url = "redis://" + host + ":" + port;
  41. singleServerConfig.setAddress(url);
  42. singleServerConfig.setDatabase(database);
  43. RedissonClient redissonClient = Redisson.create(config);
  44. return redissonClient;
  45. }
  46. }

redis.server.name=cluster 集群模式

redis.server.name=single 单击模式

(2).使用

  1. //锁工具封装
  2. public class RedissionLockTools{
  3. @Autowired
  4. private static RedissonClient redissonClient;
  5. //加锁
  6. public static boolean lock(String lockName){
  7. //声明key对象
  8. String key = "LOCK_TITLE" + lockName;
  9. //获取锁对象
  10. RLock mylock = redissonClient.getLock(key);
  11. //加锁,并且设置锁过期时间3秒,防止死锁的产生 uuid+threadId
  12. mylock.lock(3, TimeUnit.SECONDS);
  13. //加锁成功
  14. return true;
  15. }
  16. //锁的释放
  17. public static void unlock(String lockName) {
  18. //必须是和加锁时的同一个key
  19. String key = "LOCK_TITLE" + lockName;
  20. //获取所对象
  21. RLock mylock = redissonClient.getLock(key);
  22. //释放锁(解锁)
  23. mylock.unlock();
  24. }
  25. }
  1. public Object getUserById(User user) throws IOException{
  2. String lockName = "lockName01";
  3. //加锁
  4. RedissionLockTools.lock(lockName);
  5. //执行具体业务逻辑
  6. //~~~~~~~
  7. //执行具体业务逻辑
  8. //释放锁
  9. RedissionLockTools.unlock(lockName);
  10. //返回结果
  11. return result;
  12. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/57805
推荐阅读
相关标签
  

闽ICP备14008679号