spring-boot using the tools-redis achieve Distributed Lock

1. Import tools-redis in file pom

  <dependency>
            <groupId>cn.gjing</groupId>
            <artifactId>tools-redis</artifactId>
            <version>1.0.0</version>
        </dependency>

2. Add redis connected application.properties file

#redis数据库链接配置
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
spring.redis.database=0

3. Add in the DemoApplication.java

@EnableRedisLock

4. Write an example to give
4.1 Creating DemoController

@RestController
public class DemoController {
    @Autowired
    private DemoService demoService;

    @GetMapping("demo")
    public boolean demo(){
        return demoService.demo();
    }
}

4.2 Creating DemoService

@Service
public class DemoService {

    private static Integer thread=20;

    @Lock(key = "demo")
    public boolean demo(){
        System.out.println("当前线程:" + Thread.currentThread().getName()+"未消费:"+thread);
        if(thread==0) {System.out.println("消费完成");
         return true;}
        --thread;
        return false;
    }
}

5. Test

http://127.0.0.1:1111/demo

Guess you like

Origin yq.aliyun.com/articles/706696