|
<
文章目次
①. 怎样基于民网停止开拓
- ①. 进进redis中文民网,面击文档
- ②.挑选散布式锁,翻开页里
- ③. 面击Wiki
- ④. 后绝闭于散布式锁,需求甚么内乱容,停止文档的查阅
- ⑤. 天上飞的理念(RedLock)一定有降天的完成(Redisson)
- ⑥. redission打点了两个成绩
- 锁的主动绝期,假如营业超少,运转时期主动给锁绝上新的30s,不消担忧营业工夫少
- 假如营业宕机了,那个默许的过时工夫是30s,制止了逝世锁
- 减锁的营业只需运转完成,便没有会给当前锁绝期,即便没有脚动解锁,锁默许正在30s当前主动删除
②. 基于Redisson的进门案例
- <!--引进redisson散布式锁-->
- <dependency>
- <groupId>org.redisson</groupId>
- <artifactId>redisson</artifactId>
- <version>3.13.4</version>
- </dependency>
复造代码
- //2.成立设置类
- @Configuration
- public class MyRedisConfig {
- /**
- * 一切对Redisson的利用
- * @return
- * @throws IOException
- */
- //https://github.com/redisson/redisson/wiki/14.-%E7%AC%AC%E4%B8%89%E6%96%B9%E6%A1%86%E6%9E%B6%E6%95%B4%E5%90%88
- @Bean(destroyMethod="shutdown")
- public RedissonClient redisson() throws IOException {
- Config config = new Config();
- // 创立单例形式的设置
- //config.useSingleServer().setAddress("redis://" + ipAddr + ":6379");
- config.useSingleServer().setAddress("redis://192.168.56.10:6379");
- return Redisson.create(config);
- }
- }
复造代码
- @Autowired
- //RedissonClient redissonClient;
- RedissonClient redisson;
- @Test
- public void redission(){
- System.out.println(redissonClient);
- RLock lock = redisson.getLock("lock");
- }
复造代码 ③. setnx的散布式锁有哪些不敷
- 线程1起首获得锁胜利,将键值对写进 redis 的 master 节面
- 正在redis将该键值对同步到slave节面之前,master 发作了毛病
- redis 触收毛病转移,此中一个 slave 晋级为新的 master
- 此时新的master其实不包含线程1写进的键值对,因而线程2尝试获得锁也能够胜利拿到锁
- 此时相称于有两个线程获得到了锁,大要会招致各类预期以外的状况发作,比方最多见的净数据。
我们减的是排它独有锁,统一工夫只能有一个建redis锁胜利并持有锁,宽禁呈现2个以上的恳求线程拿到锁。
- ②. redis之女提出了Redlock算法打点那个成绩
(Redis也供给了Redlock算法,用去完成基于多个真例的散布式锁。锁变量由多个真例保护,即便有真例发作了毛病,锁变量仍旧是存正在的,客户端仍是能够完成锁操纵。Redlock算法是完成下牢靠散布式锁的一种有用打点计划,能够正在理想开拓中利用)
- ③. Redis散群的AP(redis同步复制作成的锁丧失,好比:主节面出去的及把方才set出去那条数据给从节面,便挂了)
- ④. redis散布式锁,多主散群形式,需求计较容错率(N=2X+1)
好比,收集中逝世了1台机械,我请求仍是OK的,能够用,请示,最多主散群安排几台?
N=2*1+1=3
- ⑤. 为何是偶数? N = 2X + 1 (N是终极安排机械数,X是容错机械数)
起码的机械,最多的产出结果
参加正在散群状况中,redis失利1台,可担任。2N+2= 2 * 1+2 =4,安排4台
参加正在散群状况中,redis失利2台,可担任。2N+2 = 2 * 2+2 =6,安排6台
- ⑥. 那末甚么是容错呢?
- 失利了几个机械真例后我仍是能够容忍的,所谓的容忍便是数据分歧性仍是能够Ok的,CP数据分歧性仍是能够合意
- 参加正在散群状况中,redis失利1台,可担任。2X+1 = 2 * 1+1 =3,安排3台,逝世了1个剩下2个能够一般事情,那便安排3台
- 参加正在散群状况中,redis失利2台,可担任。2X+1 = 2 * 2+1 =5,安排5台,逝世了2个剩下3个能够一般事情,那便安排5台
④. 三台主机案例拆建
- docker run -p 6381:6379 --name redis-master-1 -d redis:6.08
- docker run -p 6382:6379 --name redis-master-2 -d redis:6.0.8
- docker run -p 6383:6379 --name redis-master-3 -d redis:6.0.8
复造代码
- ②. 建Module(redis_redlock)、改pom.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>2.3.10.RELEASE</version>
- <relativePath/> <!-- lookup parent from repository -->
- </parent>
- <groupId>com.xiaozhi.redis.redlock</groupId>
- <artifactId>redis_redlock</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <properties>
- <java.version>1.8</java.version>
- </properties>
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.redisson</groupId>
- <artifactId>redisson</artifactId>
- <!--<version>3.12.0</version>-->
- <version>3.13.4</version>
- </dependency>
- <dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- <version>1.18.8</version>
- </dependency>
- <!--swagger-->
- <dependency>
- <groupId>io.springfox</groupId>
- <artifactId>springfox-swagger2</artifactId>
- <version>2.9.2</version>
- </dependency>
- <!--swagger-ui-->
- <dependency>
- <groupId>io.springfox</groupId>
- <artifactId>springfox-swagger-ui</artifactId>
- <version>2.9.2</version>
- </dependency>
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-lang3</artifactId>
- <version>3.4</version>
- <scope>compile</scope>
- </dependency>
- </dependencies>
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- </plugin>
- </plugins>
- </build>
- </project>
复造代码
- spring.application.name=spring-boot-redis
- server.port=9090
- spring.swagger2.enabled=true
- spring.redis.database=0
- spring.redis.password=
- spring.redis.timeout=3000
- #sentinel/cluster/single
- spring.redis.mode=single
- spring.redis.pool.conn-timeout=3000
- spring.redis.pool.so-timeout=3000
- spring.redis.pool.size=10
- spring.redis.single.address1=192.168.111.147:6381
- spring.redis.single.address2=192.168.111.147:6382
- spring.redis.single.address3=192.168.111.147:6383
复造代码- //CacheConfiguration
- @Configuration
- @EnableConfigurationProperties(RedisProperties.class)
- public class CacheConfiguration {
- @Autowired
- RedisProperties redisProperties;
- @Bean
- RedissonClient redissonClient1() {
- Config config = new Config();
- String node = redisProperties.getSingle().getAddress1();
- node = node.startsWith("redis://") ? node : "redis://" + node;
- SingleServerConfig serverConfig = config.useSingleServer()
- .setAddress(node)
- .setTimeout(redisProperties.getPool().getConnTimeout())
- .setConnectionPoolSize(redisProperties.getPool().getSize())
- .setConnectionMinimumIdleSize(redisProperties.getPool().getMinIdle());
- if (StringUtils.isNotBlank(redisProperties.getPassword())) {
- serverConfig.setPassword(redisProperties.getPassword());
- }
- return Redisson.create(config);
- }
- @Bean
- RedissonClient redissonClient2() {
- Config config = new Config();
- String node = redisProperties.getSingle().getAddress2();
- node = node.startsWith("redis://") ? node : "redis://" + node;
- SingleServerConfig serverConfig = config.useSingleServer()
- .setAddress(node)
- .setTimeout(redisProperties.getPool().getConnTimeout())
- .setConnectionPoolSize(redisProperties.getPool().getSize())
- .setConnectionMinimumIdleSize(redisProperties.getPool().getMinIdle());
- if (StringUtils.isNotBlank(redisProperties.getPassword())) {
- serverConfig.setPassword(redisProperties.getPassword());
- }
- return Redisson.create(config);
- }
- @Bean
- RedissonClient redissonClient3() {
- Config config = new Config();
- String node = redisProperties.getSingle().getAddress3();
- node = node.startsWith("redis://") ? node : "redis://" + node;
- SingleServerConfig serverConfig = config.useSingleServer()
- .setAddress(node)
- .setTimeout(redisProperties.getPool().getConnTimeout())
- .setConnectionPoolSize(redisProperties.getPool().getSize())
- .setConnectionMinimumIdleSize(redisProperties.getPool().getMinIdle());
- if (StringUtils.isNotBlank(redisProperties.getPassword())) {
- serverConfig.setPassword(redisProperties.getPassword());
- }
- return Redisson.create(config);
- }
- /**
- * 单机
- * @return
- */
- /*@Bean
- public Redisson redisson()
- {
- Config config = new Config();
- config.useSingleServer().setAddress("redis://192.168.111.147:6379").setDatabase(0);
- return (Redisson) Redisson.create(config);
- }*/
- }
复造代码- //RedisPoolProperties
- @Data
- public class RedisPoolProperties {
- private int maxIdle;
- private int minIdle;
- private int maxActive;
- private int maxWait;
- private int connTimeout;
- private int soTimeout;
- /**
- * 池巨细
- */
- private int size;
- }
复造代码- //RedisProperties
- @ConfigurationProperties(prefix = "spring.redis", ignoreUnknownFields = false)
- @Data
- public class RedisProperties {
- private int database;
- /**
- * 等候节面复兴号令的工夫。该工夫从号令收收胜利时开端计时
- */
- private int timeout;
- private String password
- private String mode;
- /**
- * 池设置
- */
- private RedisPoolProperties pool;
- /**
- * 单机疑息设置
- */
- private RedisSingleProperties single;
- }
复造代码- //RedisSingleProperties
- @Data
- public class RedisSingleProperties {
- private String address1;
- private String address2;
- private String address3;
- }
复造代码
- @RestController
- @Slf4j
- public class RedLockController {
- public static final String CACHE_KEY_REDLOCK = "TANGZHI_REDLOCK";
- @Autowired
- RedissonClient redissonClient1;
- @Autowired
- RedissonClient redissonClient2;
- @Autowired
- RedissonClient redissonClient3;
- @GetMapping(value = "/redlock")
- public void getlock() {
- //CACHE_KEY_REDLOCK为redis 散布式锁的key
- RLock lock1 = redissonClient1.getLock(CACHE_KEY_REDLOCK);
- RLock lock2 = redissonClient2.getLock(CACHE_KEY_REDLOCK);
- RLock lock3 = redissonClient3.getLock(CACHE_KEY_REDLOCK);
- RedissonRedLock redLock = new RedissonRedLock(lock1, lock2, lock3);
- boolean isLockBoolean;
- try {
- //waitTime 抢锁的等候工夫,一般状况劣等3秒
- //leaseTime便是redis key的过时工夫,一般状况劣等5分钟300秒。
- isLockBoolean = redLock.tryLock(3, 300, TimeUnit.SECONDS);
- log.info("线程{},能否拿到锁:{} ",Thread.currentThread().getName(),isLockBoolean);
- if (isLockBoolean) {
- System.out.println(Thread.currentThread().getName()+"\t"+"---come in biz");
- //营业逻辑,闲10分钟
- try { TimeUnit.MINUTES.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); }
- }
- } catch (Exception e) {
- log.error("redlock exception ",e);
- } finally {
- // 不管怎样, 最初皆要解锁
- redLock.unlock();
- }
- }
- }
复造代码
- ⑤. 测试:http://localhost:9090/redlock
- [root@TANG2021 ~]# docker exec -it redis-master-1 redis-cli
- 127.0.0.1:6379> keys *
- 1) "TANGZHI_REDLOCK"
- 127.0.0.1:6379> type TANGZHI_REDLOCK
- hash
- 127.0.0.1:6379> hgetall TANGZHI_REDLOCK
- 1) "ca512c4b-f05f-4578-9b8f-45e2e35aa0d7:50"
- 2) "1"
复造代码 ⑤. Redisson源码分析
- public class WatchDogDemo {
- public static final String LOCKKEY = "DEBUG_YUANMA";
- private static Config config;
- private static Redisson redisson;
- static {
- config = new Config();
- config.useSingleServer().setAddress("redis://"+"192.168.68.143"+":6379").setDatabase(0);
- redisson = (Redisson)Redisson.create(config);
- }
- public static void main(String[] args) {
- RLock redissonLock = redisson.getLock(LOCKKEY);
- redissonLock.lock();
- try {
- System.out.println("1111-------biz");
- //停息几秒钟线程
- try { TimeUnit.SECONDS.sleep(25); } catch (InterruptedException e) { e.printStackTrace(); }
- }catch (Exception e){
- e.printStackTrace();
- }finally {
- if(redissonLock.isLocked() && redissonLock.isHeldByCurrentThread()) {
- redissonLock.unlock();
- }
- }
- System.out.println(Thread.currentThread().getName() + " main ------ ends.");
- //停息几秒钟线程
- try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); }
- redisson.shutdown();
- }
- }
复造代码
- ②. Redis散布式锁过时了,可是营业逻辑借出处置完怎样办?引进缓存绝命
- 分外起一个线程,按期查抄线程能否借持有锁,假如有则耽误过时工夫。
- Redisson里面便完成了那个计划,利用“看门狗”按期查抄(每1/3的锁工夫查抄1次),假如线程借持有锁,则革新过时工夫
- 正在获得锁胜利后,给锁减一个watchdog,watchdog 会起一个按时使命,正在锁出有被开释且将近过时的时分会绝期
- ③. 详解缓存绝命源码分析一:经由过程redisson新建出去的锁key,默许是30秒
- ④. 详解缓存绝命源码分析两
- ⑤. 详解缓存绝命源码分析三
- 那里面初初化了一个按时器,dely 的工夫是 internalLockLeaseTime/3
- 正在Redisson中,internalLockLeaseTime是30s,也便是每隔10s绝期一次,每次30s
- ⑥. watch dog主动延期机造
(客户端A减锁胜利,便会启动一个watch dog看门狗,他是一个背景线程,会每隔10秒查抄一下,假如客户端A借持有锁key,那末便会不竭的耽误锁key的保存工夫,默许每次绝命又从30秒新开端)
- ⑦. 详解缓存绝命源码分析四:减锁逻辑(针关于默许工夫30s过时的) lock.lock()
- 出有锁,减锁(独一的id),启动按时使命,设置30s的过时工夫
- 有锁:将独一id+1(可重进锁)
- 非减锁线程,返回当前减锁线程的过时工夫
- 假如开释的锁的线程战已存正在锁的线程没有是统一个线程,返回null
- 经由过程hincrby递加1,先开释一次锁。若盈余次数借年夜于0,则证实当前锁是可重进锁,革新过时工夫
- 若盈余次数小于0,删除key并开释锁,解锁胜利
- ⑨. 详解缓存绝命源码分析六:减锁逻辑
(lock.lock(10,TimeUnit.SECONDS):10s主动解锁,没有会主动绝期)
底层道理:假如我们传递了锁的超不时间,便收收给redis施行lua剧本,停止占锁,默许超时便是我们指定的工夫
- <T> RFuture<T> tryLockInnerAsync(long waitTime, long leaseTime, TimeUnit unit, long threadId, RedisStrictCommand<T> command) {
- this.internalLockLeaseTime = unit.toMillis(leaseTime);
- return this.evalWriteAsync(this.getName(), LongCodec.INSTANCE,
- command, "if (redis.call('exists', KEYS[1]) == 0) then redis.call('hincrby', KEYS[1], ARGV[2], 1); redis.call('pexpire', KEYS[1], ARGV[1]); return nil; end; if (redis.call('hexists', KEYS[1], ARGV[2]) == 1) then redis.call('hincrby', KEYS[1], ARGV[2], 1); redis.call('pexpire', KEYS[1], ARGV[1]); return nil; end; return redis.call('pttl', KEYS[1]);", Collections.singletonList(this.getName()), this.internalLockLeaseTime, this.getLockName(threadId));
- }
复造代码
免责声明:假如进犯了您的权益,请联络站少,我们会实时删除侵权内乱容,感谢协作! |
1、本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,按照目前互联网开放的原则,我们将在不通知作者的情况下,转载文章;如果原文明确注明“禁止转载”,我们一定不会转载。如果我们转载的文章不符合作者的版权声明或者作者不想让我们转载您的文章的话,请您发送邮箱:Cdnjson@163.com提供相关证明,我们将积极配合您!
2、本网站转载文章仅为传播更多信息之目的,凡在本网站出现的信息,均仅供参考。本网站将尽力确保所提供信息的准确性及可靠性,但不保证信息的正确性和完整性,且不对因信息的不正确或遗漏导致的任何损失或损害承担责任。
3、任何透过本网站网页而链接及得到的资讯、产品及服务,本网站概不负责,亦不负任何法律责任。
4、本网站所刊发、转载的文章,其版权均归原作者所有,如其他媒体、网站或个人从本网下载使用,请在转载有关文章时务必尊重该文章的著作权,保留本网注明的“稿件来源”,并自负版权等法律责任。
|