一,Redis实现

1,利用redis 客户端手动实现

主要使用setnx 以及lua来实现。(不推荐)

2,利用redisson实现

引入一下pom

<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson-spring-boot-starter</artifactId>
    <version>3.13.6</version>
</dependency>

具体使用

@Autowired
private RedissonClient redissonClient;

RLock lock = redissonClient.getLock("lock-key");
if (lock.tryLock()) {
    try {
        System.out.println("lock");
    } finally {
        lock.unlock();
    }
}
//公平锁
redissonClient.getFairLock("key");
redissonClient.getMultiLock(lock1, lock2, ...);

3,spring integration redis

引入一下pom

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-integration</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.integration</groupId>
    <artifactId>spring-integration-redis</artifactId>
</dependency>

注入bean

@Bean
public RedisLockRegistry redisLockRegistry(RedisConnectionFactory redisConnectionFactory){
    return new RedisLockRegistry(redisConnectionFactory,"activity-lock");
}
@Resource
private RedisLockRegistry lockRegistry;

Lock lock = lockRegistry.obtain("key")
Lock lock = ...;
if (lock.tryLock()) {
    try {
        // manipulate protected state
    } finally {
        lock.unlock();
    }
} else {
    // perform alternative actions
}

4 ,封装成注解

4.1,简介

lock4j是一个分布式锁组件,其提供了多种不同的支持以满足不同性能和环境的需求。

立志打造一个简单但富有内涵的分布式锁组件。

开源地址:https://gitee.com/baomidou/lock4j

4.2,特性

  1. 简单易用,功能强大,扩展性强。
  2. 支持redission,redisTemplate,zookeeper。可混用,支持扩展。

4.3,如何使用

  1. 引入相关依赖(支持同时存在,不同方法不同锁实现)。
<dependencies>
    <!--若使用redisTemplate作为分布式锁底层,则需要引入-->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>lock4j-redis-template-spring-boot-starter</artifactId>
        <version>${latest.version}</version>
    </dependency>
    <!--若使用redisson作为分布式锁底层,则需要引入-->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>lock4j-redisson-spring-boot-starter</artifactId>
        <version>${latest.version}</version>
    </dependency>
    <!--若使用zookeeper作为分布式锁底层,则需要引入-->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>lock4j-zookeeper-spring-boot-starter</artifactId>
        <version>${latest.version}</version>
    </dependency>
</dependencies>
@Service
public class DemoService {

    //默认获取锁超时3秒,30秒锁过期
    @Lock4j
    public void simple() {
        //do something
    }

    //完全配置,支持spel
    @Lock4j(keys = {"#user.id", "#user.name"}, expire = 60000, acquireTimeout = 1000)
    public User customMethod(User user) {
        return user;
    }

}

二,其他

1,ZooKeeper 实现

引入 Curator

InterProcessMutex interProcessMutex = new InterProcessMutex(client,"/anyLock");
interProcessMutex.acquire();
interProcessMutex.release();

参考资料:
https://mp.weixin.qq.com/s/v8QuYCdr-ggEZ8MtdsG73Q

https://juejin.cn/post/6844903719318847495

文章目录