上两篇介绍了两种 redis 分布式锁,均是redis 自己类库实现的,而今天这种redis 分布式锁,是spring 封装的redis 模板类,开箱即用简单方便。
1、工具类如下:
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.util.concurrent.TimeUnit; /** * Redis工具类 */ @Component public class RedisUtil { private static final String key = "nandao"; private static final String value = "123456"; private static final long EXPIRE = 60000; @Resource private StringRedisTemplate redisTemplate;//这就是redis 模板类,依赖注入到这里。 //加锁核心方法 public boolean tryLock(String key,String value){ try{ //先加锁,然后设置超时时间, if (redisTemplate.opsForValue().setIfAbsent(key, value)) { redisTemplate.expire(key,EXPIRE,TimeUnit.MILLISECONDS); return true; } }catch (Exception ex){ ex.printStackTrace(); } return false; } public void releaseLock(){ try { redisTemplate.opsForValue().getOperations().delete(key);//这里释放锁 } catch (Exception ex) { ex.printStackTrace(); } } }
2、这种分布式锁,底层原理和前两篇类似,可以根据不同的业务场景选择不同的方式去实现,没有最好的方案,只有最合适的;同时,如果有需要,小伙伴在使用过程中,可以继续修改优化,万变不离其宗!!!!以后有时间我会和大家,解析这是锁实现的源码和原理,让大家有个更深入的理解,敬请期待!