Redisは単純なバージョンの分散ロックを実現


原理:
実行時に指定した名前keyが存在するかどうかを取得し、存在してkeyが取得できない場合は、そのkeyに値を付与しない場合は、失効時間を設定します.
ロックを解除するロジックは、keyを削除します.
1.カスタムクラス
package com.xxx.cloud.assets.redis.lock;

import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

/**
 *      , new    lock  
 */

public class RedisLock {
    //    
    private String lockName; 

    //      
    private long time;

    private static final String KEY_PREFIX = "BusinessName:lock:";

    private long randomValue;

    private DefaultRedisScript redisScript;

    private RedisTemplate redisTemplate;

    private boolean locked;

    private RedisLock(String lockName, long time, RedisTemplate redisTemplate, DefaultRedisScript redisScript) {
        this.lockName = KEY_PREFIX + lockName;
        this.time = time;
        this.redisTemplate = redisTemplate;
        this.redisScript = redisScript;
        this.randomValue = UUID.randomUUID().getLeastSignificantBits();
    }

    public static RedisLock NewRedisLock(String lockName, long time, RedisTemplate redisTemplate,
            DefaultRedisScript redisScript) {
        return new RedisLock(lockName, time, redisTemplate, redisScript);
    }

    public boolean tryLock() {
        boolean success = redisTemplate.opsForValue().setIfAbsent(lockName, randomValue);
        // setIfAbsent  redis setNX  
        
        locked = success;
        if (success) {
            redisTemplate.expire(lockName, time, TimeUnit.SECONDS);
        }
        return success;
    }

    public void unLock() {
        if(locked){
            redisTemplate.execute(redisScript, Collections.singletonList(lockName), randomValue);
        }

    }

}

2.テストコード
package com.xxx.cloud.assets.service;

import com.xxx.cloud.assets.redis.lock.RedisLock;
import com.xxx.cloud.assets.test.TestBase;
import org.junit.Test;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import javax.annotation.Resource;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class TestRedisLock extends TestBase {

    @Resource(name = "redisTemplate")
    private RedisTemplate redisTemplate;

    @Resource(name = "dellockScript")
    private DefaultRedisScript dellockScript;

    @Test
    public void testRedisLock() throws InterruptedException {
        RedisLock lock = RedisLock.NewRedisLock("test",1000,redisTemplate,dellockScript);
        try {
            boolean success = lock.tryLock();
            System.out.println(success);
        }finally {
            lock.unLock();
        }
    }

    @Test
    public void testMulRedisLock() throws InterruptedException {
        final RedisLock lock1 = RedisLock.NewRedisLock("test",1000,redisTemplate,dellockScript);
        final RedisLock lock2 = RedisLock.NewRedisLock("test",1000,redisTemplate,dellockScript);
        Runnable task1 = new Runnable() {
            @Override public void run() {
                try {
                    boolean success = lock1.tryLock();
                    System.out.println("task1" + success);
                    TimeUnit.SECONDS.sleep(10);
                }catch (Exception e){
                    e.printStackTrace();
                }
                finally {
                    lock1.unLock();
                }
            }
        };

        Runnable task2 = new Runnable() {
            @Override public void run() {
                try {
                    boolean success = lock2.tryLock();
                    System.out.println("task2"+success);
                    TimeUnit.SECONDS.sleep(10);
                }catch (Exception e){
                    e.printStackTrace();
                }
                finally {
                    lock2.unLock();
                }
            }
        };

        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.submit(task1);
        executorService.submit(task2);
        TimeUnit.SECONDS.sleep(15);
    }
}

3.springの一部構成

		
		
			
		



		
		

4.dellock.luaスクリプト(コードロジックで置き換えることもできます)
if redis.call("get",KEYS[1]) == ARGV[1] then
	return redis.call("del",KEYS[1])
else
	return 0
end