快速入门Redisson实现分布式锁及原理浅析

1、分布式锁产生的背景

    在系统单体架构下不会存在分布式锁的问题,通过JVM提供的synchronized   JUC中提供的ReentrantLock 就可以满足当前业务加锁需求,当随着业务发展,采用系统采用集群部署后,多个节点下相互独立,此刻用JVM提供的锁就无法在并发场景下锁住资源,在分布式系统中,常常需要协调他们的动作。如果不同的系统或是同一个系统的不同主机之间共享了一个或一组资源,那么访问这些资源的时候,往往需要互斥来防止彼此干扰来保证一致性,这个时候便需要使用到分布式锁。场景如下图所示:

项目实践中分布式锁的常见解决方案:

1. 基于数据库实现分布式锁

2. 基于缓存(Redis等)实现分布式锁

3. 基于Zookeeper实现分布式锁

特别注意:本篇文章中使用的Redisson 也是基于"Redis" 实现RedissonClient 进行加锁操作的。

2、引入Redisson依赖的Jar包

<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson</artifactId>
    <version>2.10.0</version>
</dependency>

3、项目工程中添加Redisson配置类

spring:
  redis:
    timeout: 6000ms
    password: 
    cluster:
      max-redirects: 1
      nodes:
        - 10.98.66.65:6379
        - 10.98.66.66:6379
        - 10.98.66.67:6379
package com.demo.configuration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;

/**
 * @author youyun.xu
 * @ClassName: RedisConfigProperties
 * @Description: 读取Reids配置字段值
 * @date 2020/10/22 15:26
 */
@Component
@ConfigurationProperties(prefix = "spring.redis")
public class RedisConfigProperties {

    private String password;
    private cluster cluster;

    public static class cluster {
        private List<String> nodes;

        public List<String> getNodes() {
            return nodes;
        }

        public void setNodes(List<String> nodes) {
            this.nodes = nodes;
        }
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public RedisConfigProperties.cluster getCluster() {
        return cluster;
    }

    public void setCluster(RedisConfigProperties.cluster cluster) {
        this.cluster = cluster;
    }
}
package com.demo.configuration;

import org.redisson.Redisson;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

/**
 * @author youyun.xu
 * @ClassName: RedissonConfigure
 * @Description: Redisson 客户端(实现分布式锁)
 * @date 2020/10/22 15:26
 */
@Configuration
public class RedissonConfigure {

    @Autowired
    private RedisConfigProperties redisConfigProperties;

    @Bean
    public Redisson redisson() {
        List<String> clusterNodes = new ArrayList<>();
        for (int i = 0; i < redisConfigProperties.getCluster().getNodes().size(); i++) {
            clusterNodes.add("redis://" + redisConfigProperties.getCluster().getNodes().get(i));
        }
        Config config = new Config();
        /**
         * 单机
         */
        //config.useSingleServer().setAddress("redis://127.0.0.1:6379").setPassword("xxx");

        /**
         * 哨兵
         */
        //config.useSentinelServers().addSentinelAddress("");

        /**
         * 集群
         */
        config.useClusterServers().addNodeAddress(clusterNodes.toArray(new String[clusterNodes.size()]));
        return (Redisson) Redisson.create(config);
    }
}

4、项目工程中使用Redisson锁住资源

package com.demo.configuration;

import com.tcl.uf.common.base.dto.ResponseData;
import com.tcl.uf.marketing.utils.RedisUtils;
import io.swagger.annotations.Api;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author youyun.xu
 * @ClassName: DemoController
 * @Description: Redis 和 Redisson 工具测试
 * @date 2020/10/22 15:59
 */
@RestController
@RequestMapping("/demo")
@Api(tags = "Redisson 测试工具类")
public class DemoController {

    private static final Logger _logger = LoggerFactory.getLogger(DemoController.class);

    @Autowired
    private Redisson redisson;

    //总库存为100张票
    private static int ticket = 100;

    /**
     * 功能:分布式锁应用(使用jmeter并发请求)
     * 描述:
     *
     * @return ResponseData
     * @throws Exception
     */
    @RequestMapping(value = "/use/distributedLock")
    public ResponseData distributedLock() throws Exception {
        long threadId = Thread.currentThread().getId();
        /*
         * 1.加锁设置(获取锁等待时间、占用锁等待时间)
         * 2.释放锁(不管业务执行成功或失败都需要释放锁)
         * 3.锁的粒度可以根据自己业务定制
         * */
        RLock lock = redisson.getLock("DISTRIBUTED_LOCK_KEY_DEMO");
        if (lock.tryLock(10, 10, TimeUnit.SECONDS)) {
            try {
                if (ticket > 0) {
                    ticket--;
                    _logger.info("获得锁(出票成功) tryLock thread--{}, lock {} ticket count {}", threadId, lock, ticket);
                } else {
                    _logger.info("获得锁(已售罄) tryLock thread--{}, lock {} ticket count {}", threadId, lock, ticket);
                }
            } catch (Exception e) {
                _logger.error("执行业务出错 business error thread---{}, lock {} exception {}", threadId, lock);
            } finally {
                _logger.info("释放锁 unlock thread--{} lock {}", threadId, lock);
                lock.unlock();
            }
        } else {
            _logger.info("获取锁失败(请稍后重试) fail thread--{} lock {}", threadId, lock);
        }
        return new ResponseData();
    }
}

5、项目工程中使用Redisson注意事项

1、分布式锁加锁时间

  •       获取锁等待时间(waitTime)  :"获取这把锁愿意等多久"
  •       占用锁时间(leaseTime)       :"获取锁后占用使用多久"

2、分布式锁看门狗机制

设置占用锁时间(leaseTime),但实际业务执行过程中超过设定的leaseTime,看门狗会定时检查,会自动续命,不用担心业务时间长,锁自动过期被删掉(默认延长30秒),也可以通过修改Config.lockWatchdogTimeout来另行指定。

6、Redisson实现分布式锁原理简析

7、留一道思考题

集群模式下:Redis集群中选择一台master实例去实现锁机制,如果master和salve同步的过程中,master宕机了,偏偏在这之前某个服务实例刚刚写入了一把锁,salve还没有同步到这把锁,就被切换成了master,另一个服务实例在新的master上获取到一把新锁,这时候就会出现俩台服务实例都持有锁,执行业务逻辑的场景,这个是有问题的,该如何解决呢?

 

  • 9
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

热情的码农

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值