Springboot統合redisson分散ロック(redisクラスタモード)

5152 ワード

1.maven導入redisson
        
            org.redisson
            redisson
            3.5.0
        

2.redisson構成クラス、redissonオブジェクトを取得し、その後の分散ロックはredissonオブジェクトによって操作される
2.1 springbootのプロファイルアプリケーション.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 java.io.IOException;
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 java.util.concurrent.TimeUnit;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

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);

}

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 org.springframework.stereotype.Service;
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();
    }
}

5.分散ロックの使用
@RestController
@RequestMapping("/redisson")
public class AdvMaterialController {
	@Autowired
	private DistributedLocker distributedLocker;
	
	@RequestMapping("/test")
	public void redissonTest() {
		String key = "redisson_key";
		for (int i = 0; i < 100; i++) {
		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					System.err.println("=============    ============"+Thread.currentThread().getName());
					/*distributedLocker.lock(key,10L); //    ,             
					 Thread.sleep(100); //              
					 System.err.println("======           ======"+Thread.currentThread().getName());
					 distributedLocker.unlock(key);  //  
					 System.err.println("============================="+Thread.currentThread().getName());*/
					boolean isGetLock =  distributedLocker.tryLock(key,TimeUnit.SECONDS,5L,10L); //     ,  5 ,            10      
					if(isGetLock){
						 Thread.sleep(100); //              
						 System.err.println("======           ======"+Thread.currentThread().getName());
						 //distributedLocker.unlock(key);
						 System.err.println("============================="+Thread.currentThread().getName());
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		t.start();
	}
	}
}