欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 产业 > Redisson实现分布式锁

Redisson实现分布式锁

2025/2/24 4:25:58 来源:https://blog.csdn.net/weixin_45411101/article/details/143518576  浏览:    关键词:Redisson实现分布式锁

Redisson 是一个基于 Redis 的 Java 客户端,它提供了许多高级功能,包括分布式锁。使用 Redisson 实现分布式锁非常简单。

1.添加依赖:首先,你需要在你的项目中添加 Redisson 的依赖。如果你使用的是 Maven,可以在 pom.xml 文件中添加以下依赖:

<dependency><groupId>org.redisson</groupId><artifactId>redisson</artifactId><version>3.16.4</version> <!-- 请根据需要选择最新版本 -->
</dependency>

2.创建 Redisson 配置文件:创建一个名为 redisson.yml 的文件,并在其中配置 Redisson 的参数。

redisson:config: |singleServerConfig:address: "redis://127.0.0.1:6379"connectionMinimumIdleSize: 11password: "yourpassword"database: 0

3.加载配置信息并创建 Redisson 客户端:在 Java 代码中,加载 redisson.yml 文件中的配置信息,并使用这些信息来创建 Redisson 客户端。

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;import java.io.IOException;@Configuration
public class RedissonConfig {@Value("classpath:redisson.yml")private Resource configFile;@Bean(destroyMethod = "shutdown")public RedissonClient redisson() throws IOException {Config config = Config.fromYAML(configFile.getInputStream());return Redisson.create(config);}
}

4.使用分布式锁:现在你可以使用 Redisson 提供的分布式锁了。

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.concurrent.TimeUnit;@Service
public class DistributedLockService {@Autowiredprivate RedissonClient redissonClient;public void performTaskWithLock() {RLock lock = redissonClient.getLock("myLock");try {// 尝试获取锁,等待时间为10秒,锁定时间为100秒if (lock.tryLock(10, 100, TimeUnit.SECONDS)) {try {// 执行需要加锁的业务逻辑System.out.println("Lock acquired, performing task...");Thread.sleep(5000); // 模拟任务执行时间} finally {lock.unlock(); // 确保在业务逻辑执行完毕后释放锁System.out.println("Lock released");}} else {System.out.println("Failed to acquire lock");}} catch (InterruptedException e) {e.printStackTrace();}}
}

5.测试分布式锁:最后,你可以在你的应用程序中调用 DistributedLockService 来测试分布式锁的功能

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class LockController {@Autowiredprivate DistributedLockService distributedLockService;@GetMapping("/lock-task")public String lockTask() {distributedLockService.performTaskWithLock();return "Task executed with lock";}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词