redis分佈式鎖在項目中的使用

 

1 pom

        <dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson-spring-boot-starter</artifactId>
            <version>3.11.5</version>
        </dependency>

 

2 使用

import org.redisson.api.RedissonClient;

    @Resource
    private RedissonClient redissonClient;

加鎖

RLock lock = redissonClient.getLock("key");
// 獲得鎖5s後自動解鎖
lock.lockInterruptibly(5L, TimeUnit.SECONDS);
try{
    // 業務代碼
}finally {
            try{
                lock.unlock();
            }catch (Exception e){
                log.error("解鎖失敗", e);
            }
        }

 

 

3 記錄一個問題:redis分佈式鎖與spring-session-data-redis衝突問題分析

security使用redis做session存儲

加入redisson後導致redisson的hash slot計算出錯:CROSSSLOT Keys in request don't hash to the same slot……

解決:

	
		@EnableRedisHttpSession(redisNamespace = "{spring:session}")

 

    原理:
        1 當mget/mset批量操作時,集羣環境下需要Hash Tag:{}包裹主體key值計算,例如:{a:b:c:}111,{a:b:c:}222
        2 當SpringSecurity集成redis做session時,會處理批量操作,所以會出現此錯誤(猜測)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章