中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

SpringBoot中怎么利用Redisson實現分布式鎖

發布時間:2021-06-23 16:32:18 來源:億速云 閱讀:277 作者:Leah 欄目:編程語言

這篇文章將為大家詳細講解有關SpringBoot中怎么利用Redisson實現分布式鎖,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。

導入依賴

<dependency><groupId>org.redisson</groupId><artifactId>redisson</artifactId><version>3.8.0</version></dependency>

屬性配置

application.properites 資源文件中添加單機&哨兵相關配置

server.port=3000# redisson lock 單機模式redisson.address=redis://127.0.0.1:6379redisson.password=#哨兵模式#redisson.master-name= master#redisson.password=#redisson.sentinel-addresses=10.47.91.83:26379,10.47.91.83:26380,10.47.91.83:26381

注意:

這里如果不加 redis:// 前綴會報 URI 構建錯誤

Caused by: java.net.URISyntaxException: Illegal character in scheme name at index 0

更多的配置信息可以去官網查看

定義Lock的接口定義類

package com.tuhu.thirdsample.service;import org.redisson.api.RLock;import java.util.concurrent.TimeUnit;/** * @author chendesheng * @create 2019/10/12 10:48 */public interface DistributedLocker { RLock lock(String lockKey); RLock lock(String lockKey, int timeout); RLock lock(String lockKey, TimeUnit unit, int timeout); boolean tryLock(String lockKey, TimeUnit unit, int waitTime, int leaseTime); void unlock(String lockKey); void unlock(RLock lock);}

Lock接口實現類

package com.tuhu.thirdsample.service;import org.redisson.api.RLock;import org.redisson.api.RedissonClient;import java.util.concurrent.TimeUnit;/** * @author chendesheng * @create 2019/10/12 10:49 */public class RedissonDistributedLocker implements DistributedLocker{ private RedissonClient redissonClient; @Override public RLock lock(String lockKey) {  RLock lock = redissonClient.getLock(lockKey);  lock.lock();  return lock; } @Override public RLock lock(String lockKey, int leaseTime) {  RLock lock = redissonClient.getLock(lockKey);  lock.lock(leaseTime, TimeUnit.SECONDS);  return lock; } @Override public RLock lock(String lockKey, TimeUnit unit ,int timeout) {  RLock lock = redissonClient.getLock(lockKey);  lock.lock(timeout, unit);  return lock; } @Override public boolean tryLock(String lockKey, TimeUnit unit, int waitTime, int leaseTime) {  RLock lock = redissonClient.getLock(lockKey);  try {   return lock.tryLock(waitTime, leaseTime, unit);  } catch (InterruptedException e) {   return false;  } } @Override public void unlock(String lockKey) {  RLock lock = redissonClient.getLock(lockKey);  lock.unlock(); } @Override public void unlock(RLock lock) {  lock.unlock(); } public void setRedissonClient(RedissonClient redissonClient) {  this.redissonClient = redissonClient; }}

redisson屬性裝配類

package com.tuhu.thirdsample.common;import lombok.Data;import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.context.annotation.Configuration;/** * @author chendesheng * @create 2019/10/11 20:04 */@Configuration@ConfigurationProperties(prefix = "redisson")@ConditionalOnProperty("redisson.password")@Datapublic class RedissonProperties { private int timeout = 3000; private String address; private String password; private int database = 0; private int connectionPoolSize = 64; private int connectionMinimumIdleSize=10; private int slaveConnectionPoolSize = 250; private int masterConnectionPoolSize = 250; private String[] sentinelAddresses; private String masterName;}

SpringBoot自動裝配類

package com.tuhu.thirdsample.configuration;import com.tuhu.thirdsample.common.RedissonProperties;import com.tuhu.thirdsample.service.DistributedLocker;import com.tuhu.thirdsample.service.RedissonDistributedLocker;import com.tuhu.thirdsample.util.RedissonLockUtil;import org.apache.commons.lang3.StringUtils;import org.redisson.Redisson;import org.redisson.api.RedissonClient;import org.redisson.config.Config;import org.redisson.config.SentinelServersConfig;import org.redisson.config.SingleServerConfig;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;import org.springframework.boot.context.properties.EnableConfigurationProperties;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;/** * @author chendesheng * @create 2019/10/12 10:50 */@Configuration@ConditionalOnClass(Config.class)@EnableConfigurationProperties(RedissonProperties.class)public class RedissonAutoConfiguration { @Autowired private RedissonProperties redissonProperties; /**  * 哨兵模式自動裝配  * @return  */ @Bean @ConditionalOnProperty(name="redisson.master-name") RedissonClient redissonSentinel() {  Config config = new Config();  SentinelServersConfig serverConfig = config.useSentinelServers().addSentinelAddress(redissonProperties.getSentinelAddresses())    .setMasterName(redissonProperties.getMasterName())    .setTimeout(redissonProperties.getTimeout())    .setMasterConnectionPoolSize(redissonProperties.getMasterConnectionPoolSize())    .setSlaveConnectionPoolSize(redissonProperties.getSlaveConnectionPoolSize());  if(StringUtils.isNotBlank(redissonProperties.getPassword())) {   serverConfig.setPassword(redissonProperties.getPassword());  }  return Redisson.create(config); } /**  * 單機模式自動裝配  * @return  */ @Bean @ConditionalOnProperty(name="redisson.address") RedissonClient redissonSingle() {  Config config = new Config();  SingleServerConfig serverConfig = config.useSingleServer()    .setAddress(redissonProperties.getAddress())    .setTimeout(redissonProperties.getTimeout())    .setConnectionPoolSize(redissonProperties.getConnectionPoolSize())    .setConnectionMinimumIdleSize(redissonProperties.getConnectionMinimumIdleSize());  if(StringUtils.isNotBlank(redissonProperties.getPassword())) {   serverConfig.setPassword(redissonProperties.getPassword());  }  return Redisson.create(config); } /**  * 裝配locker類,并將實例注入到RedissLockUtil中  * @return  */ @Bean DistributedLocker distributedLocker(RedissonClient redissonClient) {  DistributedLocker locker = new RedissonDistributedLocker();  ((RedissonDistributedLocker) locker).setRedissonClient(redissonClient);  RedissonLockUtil.setLocker(locker);  return locker; }}

Lock幫助類

package com.tuhu.thirdsample.util;import com.tuhu.thirdsample.service.DistributedLocker;import org.redisson.api.RLock;import java.util.concurrent.TimeUnit;/** * @author chendesheng * @create 2019/10/12 10:54 */public class RedissonLockUtil { private static DistributedLocker redissLock; public static void setLocker(DistributedLocker locker) {  redissLock = locker; } /**  * 加鎖  * @param lockKey  * @return  */ public static RLock lock(String lockKey) {  return redissLock.lock(lockKey); } /**  * 釋放鎖  * @param lockKey  */ public static void unlock(String lockKey) {  redissLock.unlock(lockKey); } /**  * 釋放鎖  * @param lock  */ public static void unlock(RLock lock) {  redissLock.unlock(lock); } /**  * 帶超時的鎖  * @param lockKey  * @param timeout 超時時間 單位:秒  */ public static RLock lock(String lockKey, int timeout) {  return redissLock.lock(lockKey, timeout); } /**  * 帶超時的鎖  * @param lockKey  * @param unit 時間單位  * @param timeout 超時時間  */ public static RLock lock(String lockKey, TimeUnit unit , int timeout) {  return redissLock.lock(lockKey, unit, timeout); } /**  * 嘗試獲取鎖  * @param lockKey  * @param waitTime 最多等待時間  * @param leaseTime 上鎖后自動釋放鎖時間  * @return  */ public static boolean tryLock(String lockKey, int waitTime, int leaseTime) {  return redissLock.tryLock(lockKey, TimeUnit.SECONDS, waitTime, leaseTime); } /**  * 嘗試獲取鎖  * @param lockKey  * @param unit 時間單位  * @param waitTime 最多等待時間  * @param leaseTime 上鎖后自動釋放鎖時間  * @return  */ public static boolean tryLock(String lockKey, TimeUnit unit, int waitTime, int leaseTime) {  return redissLock.tryLock(lockKey, unit, waitTime, leaseTime); }}

控制層

package com.tuhu.thirdsample.task;import com.tuhu.thirdsample.common.KeyConst;import lombok.extern.slf4j.Slf4j;import org.redisson.api.RLock;import org.redisson.api.RedissonClient;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import java.util.concurrent.TimeUnit;/** * @author chendesheng * @create 2019/10/12 11:03 */@RestController@RequestMapping("/lock")@Slf4jpublic class LockController { @Autowired RedissonClient redissonClient;  @GetMapping("/task") public void task(){  log.info("task start");  RLock lock = redissonClient.getLock(KeyConst.REDIS_LOCK_KEY);  boolean getLock = false;  try {   if (getLock = lock.tryLock(0,5,TimeUnit.SECONDS)){    //執行業務邏輯    System.out.println("拿到鎖干活");   }else {    log.info("Redisson分布式鎖沒有獲得鎖:{},ThreadName:{}",KeyConst.REDIS_LOCK_KEY,Thread.currentThread().getName());   }  } catch (InterruptedException e) {   log.error("Redisson 獲取分布式鎖異常,異常信息:{}",e);  }finally {   if (!getLock){    return;   }   //如果演示的話需要注釋該代碼;實際應該放開   //lock.unlock();   //log.info("Redisson分布式鎖釋放鎖:{},ThreadName :{}", KeyConst.REDIS_LOCK_KEY, Thread.currentThread().getName());  } }}

RLock 繼承自 java.util.concurrent.locks.Lock ,可以將其理解為一個重入鎖,需要手動加鎖和釋放鎖 。

來看它其中的一個方法:tryLock(long waitTime, long leaseTime, TimeUnit unit)

getLock = lock.tryLock(0,5,TimeUnit.SECONDS)

通過 tryLock() 的參數可以看出,在獲取該鎖時如果被其他線程先拿到鎖就會進入等待,等待 waitTime 時間,如果還沒用機會獲取到鎖就放棄,返回 false;若獲得了鎖,除非是調用 unlock 釋放,那么會一直持有鎖,直到超過 leaseTime 指定的時間。

關于SpringBoot中怎么利用Redisson實現分布式鎖就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

西和县| 清远市| 格尔木市| 青田县| 古丈县| 若羌县| 深州市| 阳曲县| 二手房| 合水县| 荔波县| 上蔡县| 潍坊市| 平泉县| 石景山区| 舟曲县| 南昌县| 北辰区| 襄城县| 抚远县| 赫章县| 南康市| 荥经县| 龙里县| 东明县| 竹山县| 友谊县| 藁城市| 贵德县| 曲水县| 都昌县| 安龙县| 鸡东县| 新津县| 西丰县| 四川省| 曲沃县| 彭山县| 临夏市| 盐城市| 武汉市|