天天看點

spring-boot使用tools-redis實作分布式鎖

1.在pom檔案中導入tools-redis

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

2.在application.properties檔案中添加redis連接配接

#redis資料庫連結配置
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
spring.redis.database=0           

3.在DemoApplication.java中添加

@EnableRedisLock           

4.編寫一個例子給到

4.1建立DemoController

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

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

4.2建立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.測試

http://127.0.0.1:1111/demo           

繼續閱讀