redis分布式锁
redis有一版客户端对分布式锁有很好的支持,所以我使用的是该客户端
首先添加客户端依赖
<dependency> <groupId>org.redisson</groupId> <artifactId>redisson-spring-boot-starter</artifactId> <version>3.10.2</version> </dependency>
然后添加redis客户端的信息配置
spring.redis.host=localhost spring.redis.port=6379 spring.redis.password=123456 spring.redis.timeout=3600 spring.redis.database=1 spring.redis.jedis.pool.max-active=8 spring.redis.jedis.pool.max-wait=1 spring.redis.jedis.pool.max-idle=500 spring.redis.jedis.pool.min-idle=0
最后添加工具类即可
package com.voole.platform.util; import java.util.concurrent.TimeUnit; import org.redisson.api.RLock; import org.redisson.api.RedissonClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * * <P>Description: * 使用RFuture 异步获取锁 </P> * @ClassName: DistributedLockByRedis * @author 冯浩 2019年3月20日 上午9:53:41 * @see TODO */ @Component public class DistributedLockByRedis { @Autowired private RedissonClient client; public boolean lock(String key) { RLock lock = client.getLock(key); boolean trylock = false; try { trylock = lock.tryLock(60, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); } return trylock; } public void release(String key) { RLock lock = client.getLock(key); if(lock.isLocked()) { lock.unlock(); } } }