Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Distributed global lock

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/02 Report--

Distlock

Reference: redis.io/topics/distlock

Distributed global locking is used in: distributed timed tasks (lock before execution), ask doctor (lock before doctor answers question)

Design principle: use redis SET resource_name my_random_value NX PX30000, set value only when key does not exist, key is lock identification, value is lock deletion Captcha, used to delete lock

Specific process: 1. Take the lock before operation and set the deletion code. 2. Perform business operations. 3. If the lock value is consistent with the previously set deletion code, delete the lock. If it is inconsistent, consider whether the lock expires and other people have already obtained the lock to do related business.

Actual use:

1.pom add redis dependency:

org.springframework.boot spring-boot-starter-redis

2.application.properties Configure redis server

spring.application.name =provider-service#Use sentinel, do not manually specify redis server spring.redis.host=10.3.5.21spring.redis.port=6379#spring.redis.sentinel.master=master1#spring.redis.sentinel.nodes=10.3.5.36:26379,10.3.5.38:26379#microservice-specific database All keys need to be prefixed with standard prefixes (manually specify microservice name: or cache automatically specify complete path of class name) All keys that are not of this structure are deleted spring.redis.database=2spring.redis.timeout=10000

3. Using Distributed Global Locks

@Value("${spring.application.name}")private String appName;@Inject@Resource(name = "redisTemplate")private ValueOperations valueOperations;@Scheduled(cron = "0 58 * * * ? ")public void foo(){ if(! RedisDistributedLock.lock(valueOperations, appName+":lock_BarService.foo()", "", 60)){ System.out.println("EnableScheduling return. "); return; } System.out.println("EnableScheduling "+System.currentTimeMillis());}

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report