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";}
}