springboot整合redisson分布式锁(集群模式)

1.maven引入redisson

        
            org.redisson
            redisson
            3.5.0
        

2.redisson配置类,得到redisson对象,之后的分布式锁由redisson对象操作

2.1 在springboot的配置文件application.yml中添加redis集群的ip和端口还有密码

spring:
	redis:
		password: 123456
		clusters: 10.10.1.1:7000,10.10.1.1:7001,10.10.1.1:7002,10.10.1.1:7003,10.10.1.1:7004,10.10.1.1:7005

2.2 创建 redisson配置类RedissonManager


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

/**
 * redisson配置
 */
@Configuration
public class RedissonManager {
	@Value("${spring.redis.clusters}")
	private  String cluster;
	@Value("${spring.redis.password}")
	private String password;

	@Bean
	public RedissonClient getRedisson(){
		String[] nodes = cluster.split(",");
		//redisson版本是3.5,集群的ip前面要加上“redis://”,不然会报错,3.2版本可不加
		for(int i=0;i

3.创建分布式锁的接口DistributedLocker


import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

public interface DistributedLocker {
	RLock lock(String lockKey);

    RLock lock(String lockKey, long timeout);

    RLock lock(String lockKey, TimeUnit unit, long timeout);

    boolean tryLock(String lockKey, TimeUnit unit, long waitTime, long leaseTime);

    void unlock(String lockKey);

    void unlock(RLock lock);

	void setRedissonClient(RedissonClient redissonClient);
}

4.创建接口DistributedLocker的实现类


import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;

@Component
public class RedissonDistributedLocker implements DistributedLocker {
    @Autowired
    private RedissonClient redissonClient;  //RedissonClient已经由配置类生成,这里自动装配即可

    //lock(), 拿不到lock就不罢休,不然线程就一直block
    @Override
    public RLock lock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock();
        return lock;
    }

    //leaseTime为加锁时间,单位为秒
    @Override
    public RLock lock(String lockKey, long leaseTime) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock(leaseTime, TimeUnit.SECONDS);
        return lock;
    }

    //timeout为加锁时间,时间单位由unit确定
    @Override
    public RLock lock(String lockKey, TimeUnit unit ,long timeout) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock(timeout, unit);
        return lock;
    }
    //tryLock(),马上返回,拿到lock就返回true,不然返回false。
    //带时间限制的tryLock(),拿不到lock,就等一段时间,超时返回false.
    @Override
    public boolean tryLock(String lockKey, TimeUnit unit, long waitTime, long leaseTime) {
        RLock lock = redissonClient.getLock(lockKey);
        try {
            return lock.tryLock(waitTime, leaseTime, unit);
        } catch (InterruptedException e) {
            return false;
        }
    }

    @Override
    public void unlock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.unlock();
    }

    @Override
    public void unlock(RLock lock) {
        lock.unlock();
    }

    @Override
    public void setRedissonClient(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }
}

5.使用分布式锁


import cn.rojao.redisson.DistributedLocker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/redission")
public class testController {
	@Autowired
	private DistributedLocker distributedLocker;

	@RequestMapping("/test")
	public void check() {
		try {
			new Thread(() -> {
				try {
					System.out.println("准备获取锁1");
					long timestart = System.currentTimeMillis();
					boolean isGetLock = distributedLocker.tryLock("889941", TimeUnit.SECONDS, 2L, 5L);
					long timeend = System.currentTimeMillis();
					System.out.println("获取锁1需要的时间:"+String.valueOf(timestart-timeend));
					System.out.println(isGetLock);
					//Thread.sleep(5000);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			).start();

			new Thread(() -> {
						try {
							System.out.println("准备获取锁2");
							long timestart = System.currentTimeMillis();
							boolean isGetLock = distributedLocker.tryLock("889941",TimeUnit.SECONDS, 6L, 15L);
							long timeend = System.currentTimeMillis();
							System.out.println("获取锁2需要的时间:"+String.valueOf(timestart-timeend));
							System.out.println(isGetLock);

						} catch (Exception e) {
							e.printStackTrace();
						}
					}
			).start();

		} catch (Exception e) {
			e.printStackTrace();
		}
    }

}

 

你可能感兴趣的:(redis)