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
上一篇:JPA EntityManager批量保存/删除


下一篇:减少该死的 if else 嵌套