Get the App
SLTechnology News&Howtos  ›  Servers  › 

Distributed global lock

Shulou Source: shulou.com Published: 2022-06-02 04:55:59 11月15日 Update

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());}

Tags: Services distributed business global consistent doctor manual server task prefix principle sentry actual document standard identity process class name structure cache Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi Shulou Information Apple Docker Microsoft