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





你可能感兴趣的:(架构设计,Nosql)