Redis 3:分布式锁

1.redis分布式锁基础知识

  1. 缓存有效期
    redis中的数据,不一定都是持久化的;给定key设置的生存时间,当key过期时,它会被自动删除。
  2. SETNX 命令
    SETNX key value,将 key 的值设为 value ,当且仅当 key 不存在。若给定的 key 已经存在,则 SETNX 不做任何动作。SETNX 是『SET if Not eXists』(如果不存在,则 SET)的简写。
  3. lua脚本
    轻量小巧的脚本语言,用于支持redis操作序列的原子性。

2.加锁

通过setnx向特定的key写入一个随机值,并同时设置失效时间,写值成功既加锁成功;
注意点:

  1. 必须给锁设置一个失效时间------避免死锁
  2. 加锁时,每个节点产生一个随机字符串------避免锁误删
  3. 写入随机值与设置失效时间必须是同时的------保证加锁是原子的

3.解锁

匹配随机值,删除redis上的特点key数据,要保证获取数据、判断一致以及删除数据三个操作是原子的;
执行如下lua脚本:

if redis.call("get",KEYS[1]) == ARGV[1] then
    return redis.call("del",KEYS[1])
else
    return 0
end

4.创建一个springboot工程

  • springboot使用2.2.2版本

在这里插入图片描述

  • spring-data-redis和jedis的jar不需要指定版本,springboot会自动加载对应的版本;这里spring-data-redis的版本是2.2.3.RELEASE,jedis版本是3.1.0。如果你指定的版本过低,启动会报错。

在这里插入图片描述

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>redis-lock</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>redis-lock</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </repository>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </pluginRepository>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>

</project>

5.创建lua脚本

if redis.call("get",KEYS[1]) == ARGV[1] then 
    return redis.call("del",KEYS[1]) 
else 
    return 0 
end

6.创建读取lua脚本的工具类FileUtils

package com.example.redislock.util;

import java.io.*;

public class FileUtils {

    public static String getScripts(String fileName){
        String path = FileUtils.class.getClassLoader().getResource(fileName).getPath();
        File file = new File(path);
        return new String(getFileToByte(file));
    }

    /**
     * 把文件转化为二进制数组
     * @param file 文件
     * @return 二进制数组
     */
    public static byte[] getFileToByte(File file) {
        byte[] by = new byte[(int)file.length()];
        InputStream is = null;
        try {
            is = new FileInputStream(file);
            ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
            byte[] bb = new byte[2048];
            // 从此输入流中读入bb.length个字节放进bb数组
            int ch = is.read(bb);
            while(ch != -1) {
                // 将bb数组中的内容写入到输出流
                bytestream.write(bb, 0, ch);
                ch = is.read(bb);
            }
            // 将输出流中的内容复制到by数组
            by = bytestream.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return by;
    }

    public static void main(String[] args) {
        String str = getScripts("unlock.lua");
        System.out.println(str);
    }
}

7.创建jedis配置类RedisConfig

package com.example.redislock.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class RedisConfig {
    //连接池配置信息
    @Bean
    public JedisPoolConfig jedisPoolConfig() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        //最大空闲连接数
        jedisPoolConfig.setMaxIdle(10);
        //最大连接数
        jedisPoolConfig.setMaxTotal(10000);
        //当池内没有可用连接时,最大等待时间
        jedisPoolConfig.setMaxWaitMillis(10000);
        return jedisPoolConfig;
    }

  //jedis连接工厂
    @Bean
    public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig jedisPoolConfig) {
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
        redisStandaloneConfiguration.setHostName("58.220.56.46");
        redisStandaloneConfiguration.setPort(6379);
        redisStandaloneConfiguration.setPassword(RedisPassword.of("12345678"));
        //如果使用了ssl加密,则使用JedisClientConfiguration.builder().useSsl()
        JedisClientConfiguration.JedisPoolingClientConfigurationBuilder jpcf = (JedisClientConfiguration.JedisPoolingClientConfigurationBuilder) JedisClientConfiguration.builder();
        jpcf.poolConfig(jedisPoolConfig);
        JedisClientConfiguration jedisClientConfiguration = jpcf.build();
        return new JedisConnectionFactory(redisStandaloneConfiguration, jedisClientConfiguration);
    }

}

8.创建加锁解锁工具类RedisLock

package com.example.redislock.lock;

import com.example.redislock.util.FileUtils;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.params.SetParams;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

@Service
public class RedisLock implements Lock {
    private static final String KEY = "LOCK_KEY";

    @Resource
    private JedisConnectionFactory factory;

    private ThreadLocal<String> local = new ThreadLocal<>();

    //阻塞式加锁
    @Override
    public void lock() {
        //1.尝试加锁
        if (tryLock()) {
            return;
        }
        //2.加锁失败,当前任务休眠一段时间
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //3.递归调用,再次去抢锁
        lock();
    }

    //使用setNx命令,返回OK的加锁成功,并生产随机数
    @Override
    public boolean tryLock() {
        String uuid = UUID.randomUUID().toString();
        Jedis jedis = (Jedis) factory.getConnection().getNativeConnection();
        //nx()-仅当key不存在时,set才返回OK,px()-设置key有效期
        SetParams setParams = new SetParams().nx().px(1000);
        String result = jedis.set(KEY, uuid,setParams);
        //设置成功,获得锁
        if ("OK".equals(result)) {
            //抢锁成功则把锁唯一标识记录到本线程--ThreadLocal
            local.set(uuid);
            return true;
        }
        //key里面已经有值了,uuid设入失败,抢锁失败
        return false;
    }

    //解锁
    @Override
    public void unlock() {
        //获取lua脚本
        String script = FileUtils.getScript("unlock.lua");
        //获取jedis原始连接
        Jedis jedis = (Jedis) factory.getConnection().getNativeConnection();
        //执行lua脚本
        jedis.eval(script, Arrays.asList(KEY), Arrays.asList(local.get()));

    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public Condition newCondition() {
        return null;
    }
}

9.创建controller

package com.example.redislock.controller;

import com.example.redislock.lock.RedisLock;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.CountDownLatch;

@RestController
public class LockController {

    //总共20张票
    private static long count = 20;
    //5个线程同时跑
    private CountDownLatch countDownLatch = new CountDownLatch(5);

    @Resource
    private RedisLock lock;

    //线程模拟窗口买车票
    public class LockThread extends Thread {
        //抢到的票的数量
        private int amount = 0;

        public void run() {
            System.out.println(Thread.currentThread().getName() + "开始售票");
            countDownLatch.countDown();
            if (countDownLatch.getCount() == 0) {
                System.out.println("--------------售票结果--------------------");
            }
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            while (count > 0) {
                lock.lock();
                try {
                    if (count > 0) {
                        //模拟卖票
                        amount++;
                        count--;
                    }
                } finally {
                    lock.unlock();
                }
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName() + "售出" + amount + "张票");
        }
    }

    @RequestMapping(value = "/sale")
    public Long sale() {
        count=20;
        countDownLatch = new CountDownLatch(5);
        System.out.println("共20张票,分5个窗口售票");
        for (int i = 0; i < 5; i++) {
            new LockThread().start();
        }
        return count;
    }

}

10.发送请求,查看打印结果

在这里插入图片描述
在这里插入图片描述

代码下载地址https://gitee.com/fisher3652/redis-lock_8-16
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值