#Redisson配置singleServerConfig: address: "redis://49.235.125.47:6379" password: 123456 clientName: null database: 0 #选择使用哪个数据库0~15 idleConnectionTimeout: 10000# pingTimeout: 1000# connectTimeout: 10000# timeout: 3000# retryAttempts: 3# retryInterval: 1500# reconnectionTimeout: 3000# failedAttempts: 3# subscriptionsPerConnection: 5# subscriptionConnectionMinimumIdleSize: 1# subscriptionConnectionPoolSize: 50# connectionMinimumIdleSize: 32# connectionPoolSize: 64# dnsMonitoringInterval: 5000 #dnsMonitoring: falsethreads: 0nettyThreads: 0codec: class: "org.redisson.codec.JsonJacksonCodec"transportMode: "NIO"
写配置类,加入been:package com.example.business9090.config;import org.redisson.Redisson;import org.redisson.config.Config;import org.redisson.jcache.configuration.RedissonConfiguration;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import java.io.IOException;@Configurationpublic class Business9090Config { @Bean public Redisson redisson(){ Config config = null; // 本例子使用的是yaml格式的配置文件,读取使用Config.fromYAML,如果是Json文件,则使用Config.fromJSON try { config = Config.fromYAML(Business9090Config.class.getClassLoader().getResource("redisson-config.yml")); } catch (IOException e) { e.printStackTrace(); } return (Redisson) Redisson.create(config); }}
编写分布锁业务:package com.example.business9090.controller;import lombok.extern.slf4j.Slf4j;import org.redisson.Redisson;import org.redisson.api.RLock;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import java.util.UUID;import java.util.concurrent.TimeUnit;@RestController@RequestMapping("/cloud")@Slf4jpublic class CloudController { @Autowired private Redisson redisson; @Autowired private RedisTemplate redisTemplate; @PostMapping("/test") public String cloudTest(){ String lockKey = "product_001"; String clientId = UUID.randomUUID().toString();// ridisson分布式锁 获取锁对象 RLock rLock = redisson.getLock(lockKey); try{ // 不具备原则性,宕机时会出现bug// Boolean resulet = redisTemplate.opsForValue().setIfAbsent(lockKey,"chunfeng");// redisTemplate.expire(lockKey,10, TimeUnit.SECONDS);// Boolean resulet = redisTemplate.opsForValue().setIfAbsent(lockKey,clientId,30,TimeUnit.SECONDS);// if(!resulet){// return "error code";// }// 加分布式锁 rLock.lock(); System.out.println("9090 -------访问"); }catch (Exception e){ log.error(e.getMessage()); }finally {// 释放锁 rLock.unlock();// if(clientId.equals(redisTemplate.opsForValue().get(lockKey))){// redisTemplate.delete(lockKey);// } } return "1"; }}
redis主从架构有一定的bug,就一个主节点挂掉,从节点这时可能还没有同步线程锁的值,导致锁失效一部份
zookeeper能保证主从节点都会同步了值才会允许访问
但redis的高并发性能更好,承受高并发能力强!!!所以一般还是选redis,出问题了就人工去修复