Redisson 分布式锁超简封装

Redisson是一个在Redis的基础上实现的Java驻内存数据网格。它几乎提供了Redis所有工具,不仅封装Redis底层数据结构,而且还提供了很多Java类型映射。Redisson支持redis单实例、redis哨兵、redis cluster、redis master-slave等各种部署架构。Redisson出了普通分布式锁还支持 联锁(MultiLock),读写锁(ReadWriteLock),公平锁(Fair Lock),红锁(RedLock),信号量(Semaphore),可过期性信号量(PermitExpirableSemaphore)和闭锁(CountDownLatch)等。

Redisson 虽然功能强大但是它依然不能解决分布式锁有可能锁不住的情况,这不是Redisson或者Redis的问题(目前遇到这种问题只能人工干预)。本篇主要是平时工作中使用对Redisson分布式锁的封装

Maven主要包配置

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.6</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <version>2.1.9.RELEASE</version>
</dependency>
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
</dependency>
<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson</artifactId>
    <version>3.11.2</version>
</dependency>

yml 配置

redis:
 server:
  database: 0
  host: redis的ip地址
  maxIdle: 500
  maxTotal: 50
  maxWaitMillis: 10000
  minEvictableIdleTimeMillis: 60000
  minIdle: 10
  numTestsPerEvictionRun: 10
  password: yiwei-redis-666
  port: redis的端口号
  testOnBorrow: true
  testOnReturn: true
  testWhileIdle: true
  timeBetweenEvictionRunsMillis: 30000
  timeOut: 2000

JedisProperties属性配置

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Data
@Component
public class JedisProperties {
    @Value("${redis.server.host}")
    private String host;
    @Value("${redis.server.port}")
    private int port;
    @Value("${redis.server.password}")
    private String password;
    @Value("${redis.server.maxTotal}")
    private int maxTotal;
    @Value("${redis.server.maxIdle}")
    private int maxIdle;
    @Value("${redis.server.minIdle}")
    private int minIdle;
    @Value("${redis.server.maxWaitMillis}")
    private int maxWaitMillis;
    @Value("${redis.server.timeOut}")
    private int timeOut;
    @Value("${redis.server.testOnBorrow}")
    private boolean testOnBorrow;
    @Value("${redis.server.testOnReturn}")
    private boolean testOnReturn;
    @Value("${redis.server.testWhileIdle}")
    private boolean testWhileIdle;
    @Value("${redis.server.timeBetweenEvictionRunsMillis}")
    private int timeBetweenEvictionRunsMillis;
    @Value("${redis.server.numTestsPerEvictionRun}")
    private int numTestsPerEvictionRun;
    @Value("${redis.server.minEvictableIdleTimeMillis}")
    private int minEvictableIdleTimeMillis;
    @Value("${redis.server.database}")
    private int database;
}

JedisConfig 相关Bean配置

import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.EnableCaching;
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.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import redis.clients.jedis.JedisPoolConfig;
import javax.annotation.Resource;

@Slf4j
@Configuration
@EnableCaching
public class JedisConfig {
    @Resource
    private JedisProperties prop;
    @Bean(name = "jedisPoolConfig")
    public JedisPoolConfig jedisPoolConfig() {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(prop.getMaxTotal());
        config.setMaxIdle(prop.getMaxIdle());
        config.setMinIdle(prop.getMinIdle());
        config.setMaxWaitMillis(prop.getMaxWaitMillis());
        config.setTestOnBorrow(prop.isTestOnBorrow());
        config.setTestOnReturn(prop.isTestOnReturn());
        config.setTestWhileIdle(prop.isTestWhileIdle());
        config.setNumTestsPerEvictionRun(prop.getNumTestsPerEvictionRun());
        config.setMinEvictableIdleTimeMillis(prop.getMinEvictableIdleTimeMillis());
        config.setTimeBetweenEvictionRunsMillis(prop.getTimeBetweenEvictionRunsMillis());
        return config;
    }
    @Bean(name ="jedisConnectionFactory")
    public JedisConnectionFactory jedisConnectionFactory(){
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
        redisStandaloneConfiguration.setPort(prop.getPort());
        redisStandaloneConfiguration.setHostName(prop.getHost());
        redisStandaloneConfiguration.setPassword(RedisPassword.of(prop.getPassword()));
        redisStandaloneConfiguration.setDatabase(prop.getDatabase());
        return new JedisConnectionFactory(redisStandaloneConfiguration);
    }
    @Bean(name ="redisTemplate")
    public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory jedisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(jedisConnectionFactory);
        return template;
    }

}

RedissonConfig 配置类

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;

@Configuration
public class RedissonConfig {
    @Resource
    private JedisProperties prop;
    @Bean
    public RedissonClient redissonClient(){
        Config config = new Config();
        config.useSingleServer().setAddress("redis://" + prop.getHost() + ":" + prop.getPort())
                .setPassword(prop.getPassword()).setDatabase(prop.getDatabase());
        return Redisson.create(config);
    }
}

函数式接口两个
分布式锁主要采用,模板模式,应为它天生就有业务骨架属性。当我们使用1.8以上的JDK时,针对模板模式,使用方简化了很多操作。只是需要注意定义模板方法时要定义成函数接口

public interface VoidHandle {

    /**
     * 业务处理
     */
    void execute();

}
public interface ReturnHandle<T> {

    /**
     * 业务处理
     * @return
     */
    T execute();

}

分布式锁模板封装

@Slf4j
@Service
public class RedisLock {

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 分布式锁实现
     * @param lockName 锁名称
     * @param businessId 业务ID
     * @param handle 业务处理
     */
    @Transactional(rollbackFor = Exception.class)
    public void lock(String lockName, Object businessId, VoidHandle handle) {
        RLock rLock = getLock(lockName, businessId);
        try {
            rLock.lock();
            log.info("业务ID{},获取锁成功", businessId);
            handle.execute();
        } finally {
            rLock.unlock();
        }
    }

    /**
     * 带返回值分布式锁实现
     * @param lockName 锁名称
     * @param businessId 业务ID
     * @param handle 业务处理
     * @param <T> 返回值
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public <T> T lock(String lockName, Object businessId, ReturnHandle<T> handle) {
        RLock rLock = getLock(lockName, businessId);
        try {
            rLock.lock();
            log.info("业务ID{},获取锁成功", businessId);
            return handle.execute();
        } finally {
            rLock.unlock();
        }
    }

    /**
     * 分布式锁实现
     * @param lockName 锁名称
     * @param businessId 业务ID
     * @param handle 业务处理
     */
    @Transactional(rollbackFor = Exception.class)
    public void tryLock(String lockName, Object businessId, VoidHandle handle) {
        RLock rLock = getLock(lockName, businessId);
        if (!rLock.tryLock()) {
            log.info("业务ID{},获取锁失败,返回", businessId);
            return;
        }

        try {
            log.info("业务ID{},获取锁成功", businessId);
            handle.execute();
        } finally {
            rLock.unlock();
        }
    }

    /**
     * 带返回值分布式锁实现
     * @param lockName 锁名称
     * @param businessId 业务ID
     * @param handle 业务处理
     * @param <T> 返回值
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public <T> T tryLock(String lockName, Object businessId, ReturnHandle<T> handle) {
        RLock rLock = getLock(lockName, businessId);
        if (!rLock.tryLock()) {
            log.info("业务ID{},获取锁失败,返回null", businessId);
            return null;
        }

        try {
            log.info("业务ID{},获取锁成功", businessId);
            return handle.execute();
        } finally {
            rLock.unlock();
        }
    }

    /**
     * 分布式锁实现
     * @param lockName 锁名称
     * @param businessId 业务ID
     * @param handle 业务处理
     */
    @Transactional(rollbackFor = Exception.class)
    public void tryLockException(String lockName, Object businessId, VoidHandle handle) {
        RLock rLock = getLock(lockName, businessId);
        if (!rLock.tryLock()) {
            log.info("业务ID{},获取锁失败,抛异常处理", businessId);
            throw new RuntimeException("处理中");
        }

        try {
            log.info("业务ID{},获取锁成功", businessId);
            handle.execute();
        } finally {
            rLock.unlock();
        }
    }

    /**
     * 带返回值分布式锁实现
     * @param lockName 锁名称
     * @param businessId 业务ID
     * @param handle 业务处理
     * @param <T> 返回值
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public <T> T tryLockException(String lockName, Object businessId, ReturnHandle<T> handle) {
        RLock rLock = getLock(lockName, businessId);
        if (!rLock.tryLock()) {
            log.info("业务ID{},获取锁失败,抛异常处理", businessId);
            throw new RuntimeException("处理中");
        }

        try {
            log.info("业务ID{},获取锁成功", businessId);
            return handle.execute();
        } finally {
            rLock.unlock();
        }
    }

    /**
     * 获取锁
     * @param lockName
     * @param businessId
     * @return
     */
    private RLock getLock(String lockName, Object businessId) {
        log.info("获取分布式锁lockName:{},businessId:{}", lockName, businessId);
        if (StringUtils.isEmpty(lockName)) {
            throw new RuntimeException("分布式锁KEY为空");
        }
        if (StringUtils.isEmpty(businessId)) {
            throw new RuntimeException("业务ID为空");
        }

        String lockKey = lockName + businessId.toString();
        return redissonClient.getLock(lockKey);
    }

}

使用例子

@Autowired
private RedisLock redisLock;

@Test
public void test() {
    redisLock.tryLock("order:pay:", 1, () -> {
        // 业务逻辑
    });

    Boolean payResult = redisLock.tryLock("order:pay:", 2, () -> {
        // 业务逻辑
        return true;
    });

    Integer payResult2 = redisLock.tryLock("order:pay:", 2, () -> {
        // 业务逻辑
        return 0;
    });

    String payResult3 = redisLock.tryLock("order:pay:", 2, () -> {
        // 业务逻辑
        return "";
    });
}

测试方法没有粘类,不过已经可以看出用起来还是超方便的。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
购买提醒:全程代码实战,本系列课程建议有Java开发经验2年以上的学员观看和购买。录制本套教程的初衷,通过从业10年接触过很多的技术开发人员,尤其在面试一些技术人员的时候,发现他们的技术知识更新较慢,很多人渴望接触到高并发系统和一些高级技术架构,为了帮助更多人能够提升自己和接触到这类技术架构,并满足企业的人才需求,利用业余时间我开始录制这套教程。通过录制教程有很多学员给我反馈信息,给了我很大的鼓舞,当然也有吐槽,我想说的是技术是没有边界的,脱离一线业务场景去谈技术,都是耍流氓的。如对我录制的教程内容有建议请及时交流。本套课程历经1年时间研发,案例来源于真实业务场景抽离,由从业10年企业一线架构师实录,没有基础不建议购买。购买后提供企业级多方位指导,通过本套案例可以让你学习目前主流的微服务技术架构和多种企业级高并发和海量数据、高可用、分布式、支付、多语言、前后端分离等技术的综合应用解决方案。在开始本课程前给大家科普几个概念: 高并发是指在比较短的时间内有大量的访问者访问目标系统,系统负载饱和或者过载宕机。 高并发的应用,我们应该都有用过或者见过,比如天猫、京东、拼多多、亚马逊的秒杀抢购还有12306的抢票。我们在体验应用的时候,可能并不会像到这种高并发系统背后的技术实现难度。高并发系统都存在这几种问题,高并发读、高并发写、访问高峰突发性、反馈结果的即时性。在抢购的时候,尤其是抢购火车票的时候,我们经常会疯狂的刷库存,几亿用户产生非常大的高并发读; 通过以上的科普相信大家对课程有一个基本的认知了,本套教程以应用最为广泛的电商系统为标本,给大家构建一个亿级微服务秒杀系统,让大家跟着我的步骤能学习行为背后的原理。本课程采用全新的微服务架构,运用了很多工业界企业解决方案和高级技术,带大家手把手实现一个高性能,高并发,高可用等的亿级微服务秒杀系统,本课程会包含很多高级的内容,比如微服务架构、分布式部署方案、多线程、支付、多语言、全链路性能压力测试等,让大家在实战中学习知识,在实战中不断进步。该课程是一个完整的微服务架构秒杀系统项目代码,案例具有很高的商业价值,大家可以根据自己的业务进行修改,便可以使用。本套课程可以满足世面上绝大多数企业级的业务场景,本课程全部代码可以直接部署企业,普通集群,支撑**并发;集群规模大,支撑亿级并发。本课程包含的技术: IDEA集成开发工具 SpringBoot2.0.2.RELEASE SpringCloudFinchley.RELEASE Thymeleaf(模板引擎技术) 微信支付 支付宝支付 银联支付 分布式数据库Mycat MySQL Druid RabbitMQ 分布式事务 分布式锁 事件驱动 多线程 MyBatis QuartzEhcache Redis Hystrix 单点登陆CAS Nginx Lua Restful AOP技术 性能压力测试Jemter VUE+jQuery+Ajax+NodeJS Python Go语言课程亮点: 1.与企业无缝对接、真实工业界产品 2.主流支付全覆盖(微信、支付宝、银联) 3.前后端分离(主流技术架构) 4.实现高并发请求和实现高可用架构解决方案 5.多语言(Java、Go、Python) 6.亿级微服务秒杀系统(支撑海量数据) 7.大型系统分布式部署方案 8.全链路性能压力测试  9.分布式事务解决方案 10.事件驱动设计解决方案 11.多线程技术的实战应用 12.高并发下的服务降级、限流实战 13.分布式架构师下实现分布式定时调度 14.集成MyBatis实现多数据源路由实战 15.集成Redis缓存实战 16.Eureka注册中心 17.OpenFeign声明式服务调用 18.Hystrix服务熔断降级方式 19.基于Hystrix实现接口降级实战 20.集成SpringCloud实现统一整合方案 21.全程代码实操,提供全部代码和资料 22.提供答疑和提供企业技术方案咨询购买提醒: 我本人在企业从业10年,因为热爱,所以坚持,下一个10年依然会在企业一线服务,因此对于课程中的技术点可以提供全方面的业务场景解决方案。我本人并非培训机构脱离一线业务场景的讲师,从业多年接触过大量的真实业务场景案例,后面会逐步通过教程案例分享我多年的实战经验,送给同行一句话:技术是服务于业务的,脱离一线业务场景就是耍流氓。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

源码猎人

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

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

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

打赏作者

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

抵扣说明:

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

余额充值