Java分布式锁(一行代码搞定)

本文介绍了一种使用Redis实现的一行代码搞定的Java分布式锁方案。该方案通过自定义的LockTemplate简化了分布式锁的使用,使得开发者能够更专注于业务逻辑而非锁的实现细节。文章还提供了具体的Spring Boot项目示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java分布式锁(一行代码搞定)

前面几篇文章都是介绍的java juc lock包单机锁,但是目前很多应用都是分布式的(不同jvm进程),单机锁已经不能满足应用的需求了。
网上有关分布式锁的文章很多有基于memcached,redis,zookeeper,但感觉直接拿到线上使用,供公司内部使用还是差点火候,于是就一行代码搞定分布式锁文章就诞生了。

现在几乎每个应用都会用redis,我们就以redis为例使用分布式锁:
先看在springboot项目中使用方式:

lockTemplate.doBiz(LockedCallback<R> lockedCallback,String scene,String uniqueId,String key,Long expireSecond)

这样一来你只需要在回调类lockedCallback写你的业务逻辑,极大地简化了使用分布式锁的使用,能让你更加专注你的业务逻辑,集中管理所有的锁,而不是项目中每个人一套(而且并不是所有人都能用对)。

下面是我做的测试:

@RestController
@RequestMapping(path="/monitor")
public class MonitorController {

    @Autowired
    private LockTemplate<String> lockTemplate;
    private ExecutorService pool = Executors.newFixedThreadPool(10);
    /**
     * @description
     * @param
     * @return
     * @date: 2018/6/12 下午5:18
     * @author:yzMa
     */
    @GetMapping("/lock/go")
    public ApiResult<Object> lockTest(){
        for (int i = 0; i < 6; i++) {
            pool.submit(new Callable<String>() {
                @Override
                public String call() throws Exception {
                    return doSomething();
                }
            });
        }
        return ApiResult.buildSuccess(null);
    }

    /**
     * @description 竞态条件
     * @param 
     * @return 
     * @date: 2018/6/12 下午6:15
     * @author:yzMa
     */
    private String doSomething(){
        return lockTemplate.doBiz(new LockedCallback<String>() {
            @Override
            public String callback() {

                try {
        System.out.println(Thread.currentThread().getName()+" 成功获取到了锁开始执行逻辑");
                    Thread.sleep(4000);
                    System.out.println(Thread.currentThread().getName()+" 成功获取到了锁开始执行逻辑结束");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return "aa";
            }
        },"testLock-scene","aaaa-uniqueId","aaaa",5L);
    }
}

受到网上前辈的影响,使用redis.set(key,val,expire,nx)命令加锁,使用lua脚本执行解锁,至于为什么自行百度下(多笔操作这个失败了,那个超时了,加锁了释放锁失败了如何处理等等),我也是踩过很多坑,分析过很多次才有了这个线上版本。

分布式锁模板类

@Slf4j
@Component
public class LockTemplate<R> {

    @Resource(name = "luaRedisDistributeLock")
    private DistributeLock distributeLock;
    public <R> R doBiz(LockedCallback<R> lockedCallback,String scene,String uniqueId,String key,Long expireSecond){
        if(StringUtils.isBlank(uniqueId)){
            log.info("|doBiz no uniqueId use serialize lock (变为分布式串行锁)");
            uniqueId = key+System.currentTimeMillis();
        }
        boolean acquiredSuccess = false;
        try{
            acquiredSuccess = distributeLock.tryLock(key, uniqueId, expireSecond);
            if(!acquiredSuccess){
                log.info("|doBiz acquire lock fail scene={}, key={},uniqueId={},expireSecond={}",scene,key,uniqueId,expireSecond);
                throw new BusinessException(ApiResult.ACQUIRE_LOCK_FAIL,ApiResult.ACQUIRE_LOCK_FAIL_MSG);
            }
            log.info("|doBiz acquire lock success scene={}, key={},uniqueId={},expireSecond={}",scene,key,uniqueId,expireSecond);
            return (R)lockedCallback.callback();

        }catch (Exception e){
            if(! (e instanceof BusinessException)){
                log.error("|doBiz|lockedCallback not BusinessException, scene={},key={},uniqueId={},expireSecond={} exception e:",scene,key,uniqueId,expireSecond,e);
            }
            throw e;
        }finally {
            if(acquiredSuccess){
                distributeLock.unlock(key,uniqueId);
                log.info("|doBiz release lock success scene={}, key={},uniqueId={},expireSecond={}",scene,key,uniqueId,expireSecond);
            }
        }
    }

    // 分布式锁模板,大锁 没有并发
    public <R> R doBiz(LockedCallback<R> lockedCallback,String scene,String key,Long expireSecond){

            return doBiz(lockedCallback,scene,"",key,expireSecond);
    }
}

lua分布式锁实现类

@Component("luaRedisDistributeLock")
public class LuaRedisDistributeLock implements DistributeLock{

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

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private JdkSerializationRedisSerializer jdkSerializer = new JdkSerializationRedisSerializer();

    class ExpirationSub extends Expiration{
        long expirationTime;
        TimeUnit timeUnit;
        public ExpirationSub(long expirationTime,TimeUnit timeUnit){
            super(expirationTime,timeUnit);
        }
    }

    @Override
    public void lock(String key, String uniqueId, Long expireTime) {
        throw new RuntimeException("lua redis not support for now");
    }

    @Override
    public boolean tryLock(String key,String uniqueId, Long expireSeconds) {
        Assert.notNull(key,"redis key 不能为空");
        Assert.notNull(uniqueId,"uniqueId 不能为空");
        Assert.notNull(expireSeconds,"expireTime 不能为空");
        Assert.isTrue(expireSeconds > 0 && expireSeconds <= 10 ,"锁的过期时间范围介于(0,10]秒");
        Boolean lockedSuccess = stringRedisTemplate.execute(new RedisCallback<Boolean>() {
            @Override
            public Boolean doInRedis(RedisConnection redisConnection) throws DataAccessException {
            return redisConnection.set(key.getBytes(), val, expirationSub, RedisStringCommands.SetOption.SET_IF_ABSENT);//老版本
            }
        });

        if(lockedSuccess){
            return true;
        }
        return false;
    }

    public void unlock(String key, String uniqueId) {

        //使用Lua脚本删除Redis中匹配value的key,可以避免由于方法执行时间过长而redis锁自动过期失效的时候误删其他线程的锁
        //spring自带的执行脚本方法中,集群模式直接抛出不支持执行脚本的异常,所以只能拿到原redis的connection来执行脚本
        stringRedisTemplate.execute(new RedisCallback<Boolean>() {
            @Override
            public Boolean doInRedis(RedisConnection redisConnection) throws DataAccessException {
                Object nativeConnection = redisConnection.getNativeConnection();

                //集群模式和单机模式虽然执行脚本的方法一样,但是没有共同的接口,所以只能分开执行
                Long luaResult = 0L;
                if (nativeConnection instanceof JedisCluster) {
                    luaResult =  (Long)((JedisCluster) nativeConnection).eval(unlockLua, Collections.singletonList(key), Collections.singletonList(uniqueId));
                }
                if(nativeConnection instanceof Jedis){
                    luaResult =  (Long)((Jedis)nativeConnection).eval(unlockLua, Collections.singletonList(key), Collections.singletonList(uniqueId));
                }
                return luaResult != 0;
            }
        });
    }
}

分布式锁接口类

public interface DistributeLock {
    void lock(String key,String uniqueId,Long expireTime);
    boolean tryLock(String key,String uniqueId,Long expireTime);
    void unlock(String key,String uniqueId);
}

业务回调类

public interface LockedCallback<R> {
    R callback();
}

redisTemplate配置类

@Bean("cardRedisTemplate")
    public <String,V> RedisTemplate<String,V> cardRedisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String,V> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);

        //定义key序列化方式
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();//Long类型会出现异常信息;需要我们上面的自定义key生成策略,一般没必要
        template.setKeySerializer(stringRedisSerializer);

        //定义value的序列化方式
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);

        template.afterPropertiesSet();
        return template;
    }

在你写分布式锁的时候最好先看下这篇文章redis分布式锁的正确姿势
考虑好这些问题之后再开始动手写。

处理百万级别的CSV文件并将其转换为TXT格式、再将数据存入数据库,并与其他系统同步是一个复杂的过程,涉及到高效的数据读取、转化、存储以及网络传输等多个方面。下面我会逐步为你解释如何实现。 ### 一、Java读取大容量CSV文件 对于超大型的CSV文件,在Java中有几种有效的方式可以考虑: 1. **BufferedReader逐行读取**:这是最基础也是效率较高的做法之一。通过`java.io.BufferedReader`按照行来读取内容而不是一次性加载整个文档到内存中。 2. **Apache Commons CSV库**:这个第三方库简化了CSV解析过程,支持流式操作避免占用过多内存资源。 3. **OpenCSV或其他专用工具**:如果需要更强大的功能比如自定义分隔符等,则可以选择像OpenCSV这样的成熟开源项目来进行优化后的解析工作。 #### 示例代码片段 - 使用BufferedReader ```java public static void readCsvUsingBufferReader(String filePath) throws IOException { try (BufferedReader br = new BufferedReader(new FileReader(filePath))) { String line; while ((line = br.readLine()) != null) { // 遍历每一行记录 System.out.println(line); } } catch (IOException e){ throw new RuntimeException(e.getMessage(),e); } } ``` ### 二、转化为TXT文本文件 由于是从CSV直接保存为目标相同的纯文本文档(TXT),所以实际上只需要改变输出路径及编码方式即可完成此步骤。可以在上述循环内添加简单的写入逻辑至目标位置处。 例如: ```java try(BufferedWriter writer = Files.newBufferedWriter(Paths.get("output.txt"), StandardCharsets.UTF_8)){ writer.write(currentLine); // 基于之前读出的内容继续书写进新的txt里去 } catch (IOException x){ // handle exception... } ``` 这里需要注意的是字符集的选择,确保源文件与目的文件之间的一致性以免出现乱码等问题。 ### 三、批量插入MySQL数据库 当面对大量数据时,单条SQL语句频繁提交会造成性能瓶颈。因此建议采用批量预编译(PreparedStatement)的方式来提升速度: - 准备好Insert模板; - 设置批大小BatchSize; - 每满一批次就execute()一次,清空缓存区; - 最后记得关闭连接防止泄漏。 ```sql INSERT INTO your_table(columnA,columnB,...) VALUES(valueA,valueB,...), (...),... ; -- 只需一行insert就能搞定成千上万的数据点 ``` 另外还可以利用JDBC提供的特性如setFetchSize(int rows)调整获取行数加快查询响应时间;使用Statement.RETURN_GENERATED_KEYS捕获主键值用于后续关联操作等等技巧进一步提高程序运行效能。 ### 四、跨平台间异步复制表结构+迁移已有资料 假设两个环境都基于关系型数据库管理系统的话,那么有三种通用方案可供选择: 1. **ETL工具**: Extract Transform Load流程能够自动化地把来自不同来源的数据集成起来做清洗过滤之后装载到指定仓库中; 2. **触发器机制**: 在原生DB内部设定事件监听规则每当某张表格发生变化就会自动触发展开对应的DML动作拷贝变动部分过去远端节点; 3. **消息队列服务MQTT/Kafka/RabbitMq** : 尤其适合分布式的应用场景下保证事务一致性的同时减轻服务器压力。 综上所述,以上就是关于“从CSV导出转储入库再到远程镜像”的完整解决方案框架啦!
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值