分布式锁 · 2021年3月25日 0

基于redisson的分布式锁使用

  • 依赖
<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson-spring-boot-starter</artifactId>
    <version>2.15.1</version>
</dependency>
  • 配置默认使用spring的
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=root
package com.sunyw.xyz.config;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.redisson.config.TransportMode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

/**
 * @description:
 * @author: sunyw
 * @version:1.0.0
 * @time: 2020-12-11 14:46
 */
@Configuration
public class RedissonConfig {

    @Value("${spring.redis.host}")
    String host;
    @Value("${spring.redis.port}")
    String port;
    @Value("${spring.redis.password}")
    String passwd;

    @Bean
    public RedissonClient initRedisson() {
        Config config = new Config ();
        SingleServerConfig singleServerConfig = config.useSingleServer ().setAddress ("redis://" + host + ":" + port);
        if (!StringUtils.isEmpty (passwd)) {
            singleServerConfig.setPassword (passwd);
        }
        //配置看门狗有效时间20s
        config.setLockWatchdogTimeout (2000);
        //配置保持发布订阅模式
        config.setKeepPubSubOrder (true);
        //传输模式为NIO
        config.setTransportMode (TransportMode.NIO);
        return Redisson.create (config);
    }
}
  • 公平锁
    
    package com.sunyw.xyz.controller;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**

  • @description:
  • @author: sunyw
  • @version:1.0.0
  • @time: 2020-12-11 14:45
    */
    @RestController
    @Slf4j
    public class RedissonController {

    @Autowired
    private RedissonClient redissonClient;

    private static final String LOCK_NAME = "lock";

    @GetMapping("/add/{id}")
    public String add(@PathVariable String id) {
    String name = Thread.currentThread ().getName ();
    RLock lock = redissonClient.getFairLock (LOCK_NAME);
    log.info ("线程[{}]进入add方法,开始进行取锁操作", name);
    try {
    lock.lock ();
    log.info ("线程[{}]获取到锁", name);
    Thread.sleep (3000);
    } catch (Exception e) {
    log.error ("错误信息", e);
    } finally {
    log.info ("线程[{}]释放锁", name);
    lock.unlock ();
    }
    return id;
    }
    }

- 非公平锁

`package com.sunyw.xyz.controller;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**

  • @description:
  • @author: sunyw
  • @version:1.0.0
  • @time: 2020-12-11 14:45
    */
    @RestController
    @Slf4j
    public class RedissonController {

    @Autowired
    private RedissonClient redissonClient;

    private static final String LOCK_NAME = "lock";

    @GetMapping("/add/{id}")
    public String add(@PathVariable String id) {
    String name = Thread.currentThread ().getName ();
    RLock lock = redissonClient.getLock (LOCK_NAME);
    log.info ("线程[{}]进入add方法,开始进行取锁操作", name);
    try {
    lock.lock ();
    log.info ("线程[{}]获取到锁", name);
    Thread.sleep (3000);
    } catch (Exception e) {
    log.error ("错误信息", e);
    } finally {
    log.info ("线程[{}]释放锁", name);
    lock.unlock ();
    }
    return id;
    }
    }

  • 尝试加锁,最多等待时间为100s,锁有效时间为10s
package com.sunyw.xyz.controller;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: sunyw
 * @version:1.0.0
 * @time: 2020-12-11 14:45
 */
@RestController
@Slf4j
public class RedissonController {

    @Autowired
    private RedissonClient redissonClient;

    private static final String LOCK_NAME = "lock";

    @GetMapping("/add/{id}")
    public String add(@PathVariable String id) {
        String name = Thread.currentThread ().getName ();
        RLock lock = redissonClient.getLock (LOCK_NAME);
        log.info ("线程[{}]进入add方法,开始进行取锁操作", name);
        try {
            boolean b = lock.tryLock (100, 10, TimeUnit.SECONDS);
            if (b){
                log.info ("线程[{}]获取到锁", name);
                Thread.sleep (3000);
            }
        } catch (Exception e) {
            log.error ("错误信息", e);
        } finally {
            log.info ("线程[{}]释放锁", name);
            lock.unlock ();
        }
        return id;
    }
}