package com.common.core.utils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; import java.util.concurrent.TimeUnit; @Component public class DistributedLock { @Autowired private RedisTemplate redisTemplate; public boolean getLock(String lockId, long millisecond) { Boolean success = redisTemplate.opsForValue().setIfAbsent(lockId, "lock", millisecond, TimeUnit.MILLISECONDS); return success != null && success; } public boolean waitLock(String lockId, long millisecond) { do { if(this.getLock(lockId,millisecond)){ return true; }else{ try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }while(true); } public void releaseLock(String lockId) { redisTemplate.delete(lockId); } }