ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

分布式锁(五)——基于redisson的分布式锁实例

2020-01-30 11:07:32  阅读:270  来源: 互联网

标签:redisson return 实例 productLockDto Redisson public 分布式


Redisson简介

Redisson是一个在Redis的基础上实现的Java驻内存数据网格(In-Memory Data Grid)。它不仅提供了一系列的分布式的Java常用对象,还提供了许多分布式服务。redisson参考文档。一定程度上他丰富了redis的数据类型 ,同时底层采用NIO的网络交互方式,进一步提升了分布式协调的相关能力。

更多关于Redisson的内容可以参见上述贴出的文档地址。Redisson实现分布式锁相比redis就方便了许多。

springboot中引入Redisson

1、引入redisson的配置

spring.redisson.address=redis://127.0.0.1:6379

配置需要以redis开头,毕竟在redisson的create源码中有这一段

public static URI create(String uri) {
    URI u = URI.create(uri);
    // Let's assuming most of the time it is OK.
    if (u.getHost() != null) {
        return u;
    }
    String s = uri.substring(0, uri.lastIndexOf(":")).replaceFirst("redis://", "").replaceFirst("rediss://", "");
    // Assuming this is an IPv6 format, other situations will be handled by
    // Netty at a later stage.
    return URI.create(uri.replace(s, "[" + s + "]"));
}

很明显的看到这里的字符串处理的时候,会切割掉redis开头或者rediss开头,如果没有则会抛出异常。

2、将redisson交给容器管理

/**
 * redisson的分布式客户端
 * @return
 */
@Bean
public RedissonClient redissonClient(){
    Config config = new Config();
    config.useSingleServer().setAddress(env.getProperty("spring.redisson.address"));
    RedissonClient client = Redisson.create(config);
    return client;
}

将这个bean交给有configuration注解的类进行托管。并返回RedissonClient(其实可以直接返回Redisson)

引入redisson,封装各种操作

package com.learn.lockservce.component;

import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * autor:liman
 * createtime:2020/1/30
 * comment: Redisson的分布式锁组件。
 */
@Component
@Slf4j
public class RedissonLockComponent implements InitializingBean {

    @Autowired
    private RedissonClient redissonClient;

    private static Redisson redisson;

    //注入后的属性设置方法,这里其实有点稍微多此一举,可以直接在容器托管的时候就返回Redisson就行。
    public void afterPropertiesSet() throws Exception {
        redisson = (Redisson) redissonClient;
    }

    /**
     * 获取锁
     * @param lockName
     * @return
     */
    public RLock acquireLock(String lockName){
        RLock lock = redisson.getLock(lockName);
        lock.lock();
        return lock;
    }

    /**
     * 释放锁
     * @param lock
     */
    public void releaseLock(RLock lock){
        lock.unlock();
    }
}

这里封装了获取锁和释放锁的操作,同时通过实现InitializingBean接口中的afterProperties的方法,完成了类型的强行转换。这里再顺带提一下,源码中可以看到Redisson是RedissonClient的一种实现。

在这里插入图片描述

同样的业务处理

/**
 * 基于Redisson分布式锁
 * @param productLockDto
 * @return
 */
@Transactional(rollbackFor = Exception.class)
public int updateStockRedisson(ProductLockDto productLockDto){
    int res = 0;
    boolean flag = true;
    while(flag){
		//获取分布式锁。
        RLock rLock = redissonLockComponent.acquireLock(String.valueOf(productLockDto.getId()));
        try{
            if(rLock!=null){
				//真正的业务处理
                flag=false;
                ProductLock productLockEntity = lockMapper.selectByPrimaryKey(productLockDto.getId());
                int leftStock = productLockEntity.getStock();
                if(productLockEntity!=null && productLockEntity.getStock().compareTo(productLockDto.getStock())>=0){
                    productLockEntity.setStock(productLockDto.getStock());
                    res = lockMapper.updateStockForNegative(productLockEntity);
                    if(res>0){
                        log.info("基于redisson获取分布式锁成功,剩余stock:{}",leftStock-1);
                    }
                }
            }
        }catch (Exception e){
			//异常处理之后,继续获取锁
            log.error("获取锁异常,{}",e.fillInStackTrace());
            flag=true;
        }finally {
			//正确释放锁
            if(rLock!=null){
                redissonLockComponent.releaseLock(rLock);
                flag=false;
            }
        }
    }
    return res;
}

和之前几篇博客,一样的业务逻辑,一样的代码主体,一样的思想,这里就不总结了,似乎可以看出大体上都是这样的轮子

/**
 * 基于Redisson分布式锁
 * @param productLockDto
 * @return
 */
@Transactional(rollbackFor = Exception.class)
public int updateStockRedisson(ProductLockDto productLockDto){
    int res = 0;
    boolean flag = true;
    while(flag){
		//获取分布式锁。
        RLock rLock = redissonLockComponent.acquireLock(String.valueOf(productLockDto.getId()));
        try{
            if(rLock!=null){
				//真正的业务处理
                
            }
        }catch (Exception e){
			//异常处理之后,继续获取锁
            log.error("获取锁异常,{}",e.fillInStackTrace());
            flag=true;
        }finally {
			//正确释放锁
            
        }
    }
    return res;
}

总结

至此,关于几种分布式锁的简单实例,总结完成,具体参见如下:

分布式锁(一)——实例基本环境搭建

分布式锁(二)——基于数据库的分布式锁实例

分布式锁(三)——基于redis的分布式锁实例

分布式锁(四)——基于zookeeper的分布式锁实例

谜一样的Coder 发布了125 篇原创文章 · 获赞 35 · 访问量 8万+ 私信 关注

标签:redisson,return,实例,productLockDto,Redisson,public,分布式
来源: https://blog.csdn.net/liman65727/article/details/104113038

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有