一、 redis分布式锁原理
并发 到Redis里变成了串行排队,单线程
二、基于Redis的Setnx实现分布式锁
1、pom
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
2、application.properties 配置redis
spring.redis.host=192.168.73.130
3、Controller层测试
package com.example.distributelock.controller; import com.example.distributelock.lock.RedisLock; import com.example.distributelock.lock.ZkLock; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @Slf4j public class RedisLockController { @Autowired private RedisTemplate redisTemplate; @RequestMapping("redisLock") public String redisLock(){ log.info("我进入了方法!"); try (RedisLock redisLock = new RedisLock(redisTemplate,"redisKey",30)){ if (redisLock.getLock()) { log.info("我进入了锁!!"); Thread.sleep(15000); } } catch (InterruptedException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } log.info("方法执行完成"); return "方法执行完成"; } @RequestMapping("zkLock") public String zkLock(){ log.info("我进入了方法!"); try (ZkLock zkLock = new ZkLock("localhost:2181","order")){ if (zkLock.getLock()) { log.info("我进入了锁!!"); Thread.sleep(15000); } } catch (InterruptedException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } log.info("方法执行完成"); return "方法执行完成"; } }
View Code
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:基于Redis的Setnx实现分布式锁 - Python技术站