使用redisson实现分布式锁

一: 添加依赖

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson</artifactId>
            <version>3.12.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

二: redisson加入spring容器

@Configuration
public class WebConfig {
    @Bean
    public Redisson redisson() {
        // 1. Create config object
        Config config = new Config();
        config.useSingleServer()
                .setAddress("redis://127.0.0.1:6379")
                .setDatabase(0);
        // 2. Create Redisson instance
        return (Redisson) Redisson.create(config);
    }
}

三: 代码实现

@RestController
@SpringBootApplication
@RequiredArgsConstructor
public class RedisDistributeLockApplication {

    final StringRedisTemplate redisTemplate;
    final Redisson redisson;

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


    private static final String KEY_STOCK = "stock";
    private static final String KEY_LOCK = "lock";


    @GetMapping("/decrStock")
    public void decrStock() {

        RLock rLock = redisson.getLock(KEY_LOCK);
        rLock.lock(60, TimeUnit.SECONDS);
        try {
            String s = redisTemplate.opsForValue().get(KEY_STOCK);
            assert s != null;
            int stock = Integer.parseInt(s);
            if (stock > 0) {
                redisTemplate.opsForValue().set(KEY_STOCK, String.valueOf(stock - 1));
                System.out.println("扣减成功,库存stock:" + (stock - 1));
            } else {
                System.out.println("扣减失败,库存不足!");
            }
        } finally {
            rLock.unlock();
        }

    }
}

四: 使用jemeter压测

200线程同时执行,循环5次

 

测试结果: 符合预期

 

posted @ 2020-05-15 15:04  alenblue\own  阅读(243)  评论(0编辑  收藏  举报