Java 分布式服务中分布试锁应用

一、分布式锁 pom依赖

<dependencies>        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson</artifactId>
            <version>3.8.2</version>
        </dependency>
        
</dependencies>
二、配置文件
spring:
  redis:
    mode: single
    database: 0
    host: ${db.redis.xxx.host}
    password: ${db.redis.xx.password}
    port: ${db.redis.xxx.port}
    timeout: 5000
    lettuce:
      pool:
        max-active: 8
        max-wait: 5000
        max-idle: 8
        min-idle: 8

三、启动配置件 初始化

package com.xxx.zhubai.api.config;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * Redisson配置类
 *
 * @author qiaoheng
 * @date 2019/12/03
 */
@Configuration
@ConditionalOnClass(Config.class)
public class RedissonAutoConfiguration {

    @Resource
    private RedisProperties properties;

    @Bean
    @ConditionalOnProperty(name = "spring.redis.mode", havingValue = "single")
    public RedissonClient redissonClient() {
        Config config = new Config();
        String address = "redis://" + properties.getHost() + ":" + properties.getPort();
        config.useSingleServer()
                .setAddress(address)
                .setTimeout((int) properties.getTimeout().toMillis())
                .setPassword(properties.getPassword())
                .setConnectionPoolSize(8)
                .setConnectionMinimumIdleSize(4);

        return Redisson.create(config);
    }
}

四、分布式工具类

package com.xxxx.xxx.service.core.utils;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.Pair;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

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

/**
 *
 * 分布式锁 -redisson
 *
 */
@Component
@Slf4j
public class LockUtil {

    @Resource
    RedissonClient redissonClient;

    /**
     * 尝试获取锁最多等待2秒
     * 上锁后60秒自动释放锁防止死锁
     */
    public Pair<Boolean, RLock> tryLock(String lockValue) {
        RLock lock = redissonClient.getLock(lockValue);
        try {
            return Pair.of(lock.tryLock(2, 60, TimeUnit.SECONDS), lock);
        } catch (InterruptedException e) {
            log.error("推送任务加锁异常, lockValue:{}, e:", lockValue, e);
            return Pair.of(false, lock);
        }
    }

}

 

五、应用

try{
 Pair<Boolean, RLock> pairLock=lockUtil2.tryLock(this.lockKey);
            if(!pairLock.getLeft()) {
                log.info("分布式锁lock-锁了");
                return;
            }
            log.info("分布式锁lock-通过");
            rLock=pairLock.getRight();
   // to do    执行业务逻辑

}catch(Exception ex){

}
finally {
            rLock.unlock();
  }

 

 

 

 

posted @ 2025-11-12 10:22  xiaoBai1001  阅读(2)  评论(0)    收藏  举报