1 .引入相关组件
org.springframework.boot spring-boot-starter-integration org.springframework.integration spring-integration-redis org.springframework.boot spring-boot-starter-data-redis
2 . 在application.yml中添加redis的配置
在application.yml中添加redis的配置 spring: redis: host: 127.0.0.1 port: 6379
3 . 建立配置类,注入RedisLockRegistry
@Configuration
public class RedisLockConfiguration {
@Bean
public RedisLockRegistry redisLockRegistry(RedisConnectionFactory redisConnectionFactory){
return new RedisLockRegistry(redisConnectionFactory, "redis-lock");
}
}
- 编写测试代码
@RestController
@RequestMapping("lock")
@Log4j2
public class DistributedLockController {
@Autowired
private RedisLockRegistry redisLockRegistry;
@GetMapping("/redis")
public void test1() {
Lock lock = redisLockRegistry.obtain("redis-product");
try{
//尝试在指定时间内加锁,如果已经有其他锁锁住,获取当前线程不能加锁,则返回false,加锁失败;加锁成功则返回true
if(lock.tryLock(3, TimeUnit.SECONDS)){
log.info("lock is ready");
dowork();//业务代码
}
} catch (InterruptedException e) {
log.error("obtain lock error",e);
} finally {
lock.unlock();
}
}
}
如果出现下面事列
说明第二个实例没有拿到锁,证明了分布式锁的存在。
二 基于Zookeeper实现1 .引入组件
org.springframework.boot spring-boot-starter-integration org.springframework.integration spring-integration-zookeeper
2 . 在application.yml中添加zookeeper的配置
zookeeper:
host: 127.0.0.1:2181
3 . 建立配置类,注入ZookeeperLockRegistry
@Configuration
public class ZookeeperLockConfiguration {
@Value("${zookeeper.host}")
private String zkUrl;
@Bean
public CuratorframeworkFactoryBean curatorframeworkFactoryBean(){
return new CuratorframeworkFactoryBean(zkUrl);
}
@Bean
public ZookeeperLockRegistry zookeeperLockRegistry(Curatorframework curatorframework){
return new ZookeeperLockRegistry(curatorframework,"/zookeeper-lock");
}
}
4 . 编写测试代码
@RestController
@RequestMapping("lock")
@Log4j2
public class DistributedLockController {
@Autowired
private ZookeeperLockRegistry zookeeperLockRegistry;
@GetMapping("/zookeeper")
public void test2() {
Lock lock = zookeeperLockRegistry.obtain("zookeeper");
try{
//尝试在指定时间内加锁,如果已经有其他锁锁住,获取当前线程不能加锁,则返回false,加锁失败;加锁成功则返回true
if(lock.tryLock(3, TimeUnit.SECONDS)){
log.info("lock is ready");
dowork();//业务代码
}
} catch (InterruptedException e) {
log.error("obtain lock error",e);
} finally {
lock.unlock();
}
}
}
验证的结果与reids相同



