ZooKeeper(四) 使用Redis RedissonLock 实现分布式锁

本章将介绍使用RedissonLock 在SpringBoot 工程中实现分布式锁。

项目工程文档目录:

│  pom.xml  //maven 依赖文件
├─src
│  ├─main
│  │  ├─java
│  │  │  └─com
│  │  │      └─xiaohui
│  │  │          │  MainApplication.java  //springBoot 启动类
│  │  │          ├─bean
│  │  │          │      Stock.java        //库存模拟类
│  │  │          ├─cfg
│  │  │          │      RedissonConfig.java  //Redisson配置类
│  │  │          └─web
│  │  │                 WebController.java   //web测试类
│  │  └─resources
│  │          application.properties        //项目配置文件
│  └─test

1,pom文件如下:加入了web工程starter和redisson的依赖



    4.0.0

    com.xiaohui
    zklockdemo
    1.0-SNAPSHOT

    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.7.RELEASE
        
    

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

        
            org.springframework.boot
            spring-boot-starter-web
        
        
        
            org.redisson
            redisson
            3.6.5
        
    

2,application.properties 主要设置了web工程的访问端口

server.port=8888

3,库存模拟类Stock.java。当库存为0时在进行下单操作则返回false.

package com.xiaohui.bean;

public class Stock {
    //库存当前数量
    public static int count = 1;

    /**
     * 下订单,减少库存操作
     * @return true 下单成功,false 下单失败
     */
    public static boolean reduceStock(){
        if(count <= 0){
            return false;
        }
        try {
            Thread.sleep(400);
        }catch (Exception e){e.printStackTrace();}
        count-- ;
        return  true;
    }
}

4.Redisson配置类 RedissonConfig.java

package com.xiaohui.cfg;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RedissonConfig {

    @Bean
    public RLock redissonLock(){
        Config config = new Config();
        config.useSingleServer().setAddress("redis://127.0.0.1:6379").setDatabase(0);
        RedissonClient client = Redisson.create(config);
        return  client.getLock("redissonLock_name");
    }
}

5. web测试类 

package com.xiaohui.web;

import com.xiaohui.bean.ReadisLock;
import com.xiaohui.bean.Stock;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.TimeUnit;


@RestController
public class WebController {

    @Autowired
    RLock redissonLock;

    @GetMapping("/startReduce")
    public String startReduce(){

        new Thread(new Runnable() {
            @Override
            public void run() {
                redissonLock.lock(15, TimeUnit.SECONDS);
                boolean b = Stock.reduceStock();
                System.out.println(Thread.currentThread().getName()+"下单:"+( b ? "成功":"失败"));
                redissonLock.unlock();
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                redissonLock.lock(15, TimeUnit.SECONDS);
                boolean b = Stock.reduceStock();
                System.out.println(Thread.currentThread().getName()+"下单:"+( b ? "成功":"失败"));
                redissonLock.unlock();
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                redissonLock.lock(15, TimeUnit.SECONDS);
                boolean b = Stock.reduceStock();
                System.out.println(Thread.currentThread().getName()+"下单:"+( b ? "成功":"失败"));
                redissonLock.unlock();
            }
        }).start();

        try {
            Thread.sleep(3000);
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println("Stock.count = " +Stock.count);
        return  "set ok!";
    }

}

6. SpringBoot 启动类

package com.xiaohui;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MainApplication {

    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class,args);
    }
}

 测试:启动后 访问测试地址 http://127.0.0.1:8888/startReduce 控制台打印如下,可以看到只有一个线程下单成功,其他两个下单失败,符合预期效果。

ZooKeeper(四) 使用Redis RedissonLock 实现分布式锁_第1张图片

你可能感兴趣的:(ZK+Dubbo,分布式,spring,boot)