1、引入jar包
<!-- 引入 redis 依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.redisson</groupId> <artifactId>redisson</artifactId> <version>3.14.1</version> </dependency>
2、添加配置
package com.wisedu.portal.config; import org.redisson.Redisson; 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; @Configuration public class RedissonConfig { @Value("${spring.redis.host}") private String host; @Value("${spring.redis.port}") private String port; @Value("${spring.redis.password}") private String password; @Value("${spring.redis.database}") private Integer database; @Bean public RedissonClient redissonClient(){ Config config = new Config(); config.useSingleServer().setAddress("redis://" + host + ":" + port).setPassword(password).setDatabase(database); return Redisson.create(config); } }
3、编写代码
@Autowired @Qualifier("redissonClient") private RedissonClient redissonClient; RLock lock = redissonClient.getLock("contract_no"); try { lock.lock(); // 执行业务代码 }finally { lock.unlock(); }
4、备注
redis的版本号要在4.0以上,否则redisson调用失败
标签:redisson,spring,redis,private,优雅,Redisson,import,org,分布式 From: https://www.cnblogs.com/liu-dong/p/16720512.html