分散式鎖-基於redis的分散式鎖實現
阿新 • • 發佈:2021-10-07
在微服務中快取重建的時候一般會考慮使用分散式鎖來避免快取重建工作在不同的服務中重複執行
以下是使用Spring Cloud工程,基於Redis實現的分散式鎖, 使用時需要引入 spring-boot-data-redis 依賴
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import java.util.concurrent.TimeUnit; @Component public class RedisLockSample { @Autowired private RedisTemplate redisTemplate; public synchronized String reconstructionCache() { boolean findValue = false; try{ for (int i = 0; i < 3; i++) { // 使用nx特性獲取鎖 boolean lock = redisTemplate.boundValueOps("lock").setIfAbsent("test"); if (lock) { // 多重檢查避免無效更新 if (redisTemplate.hasKey("data:cache")) { findValue = true; break; } redisTemplate.opsForValue().set("data:cache", "業務資料部分"); findValue = true; break; } // 無法獲取到鎖 進入等待 try { TimeUnit.MILLISECONDS.sleep(200L); } catch (InterruptedException e) { e.printStackTrace(); } // 檢查值是否被其他服務設定,如果被設定了則提前退出鎖獲取流程 if (redisTemplate.hasKey("data:cache")) { findValue = true; break; } } return findValue ? (String) redisTemplate.opsForValue().get("data:cache") : null; }finally { // 釋放鎖 redisTemplate.delete("lock"); } } }