上兩篇介紹了兩種 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、這種分佈式鎖,底層原理和前兩篇類似,可以根據不同的業務場景選擇不同的方式去實現,沒有最好的方案,只有最合適的;同時,如果有需要,小夥伴在使用過程中,可以繼續修改優化,萬變不離其宗!!!!以後有時間我會和大家,解析這是鎖實現的源碼和原理,讓大家有個更深入的理解,敬請期待!