一、 測試
@autowired
private redislockhelper redislockhelper;
private static final string lock ="lock:equipment";
// 14: 48執行
//@scheduled(cron = "0 48 14 ? * *")
public void ordersync() else
}
二、操作redis的工具類
package com.kmnfsw.util;
import lombok.extern.slf4j.slf4j;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.data.redis.core.redistemplate;
import org.springframework.stereotype.component;
/** *
* @author wyg
*/@component
@slf4j
public class redislockhelper
// 判斷鎖超時 - 防止原來的操作異常,沒有執行解鎖操作 防止死鎖
long currentlock = (long) redistemplate.opsforvalue().get(target);
// 如果鎖過期 currentlock不為空且小於當前時間
if(currentlock < system.currenttimemillis())
}return false;
}/**
* 解鎖
* @param target
* @param timestamp
*/public void unlock(string target,long timestamp)
} catch (exception e) ",e);}}
}
還有一種寫法:
public boolean lock(string target)
try catch (exception e)finally
}//注:這裡有個缺點,當執行**的時間超過鎖的過期時間,會導致鎖被釋放掉,或者導致永久失效,這是需要加執行緒延長鎖的時間或者用redission框架
}
還有一種redission加鎖
@autowired
private redissonclient redissonclient
/** 這裡只演示可重入鎖,其他鎖詳情請檢視官方文件
*/// 獲取redisson鎖物件
rlock lock = redissonclient.getlock("anylock");
//(1) 最常見的使用方法
lock.lock();
//(2) 加鎖以後10秒鐘自動解鎖
// 無需呼叫unlock方法手動解鎖
lock.lock(10, timeunit.seconds);
// 嘗試加鎖,最多等待100秒,上鎖以後10秒自動解鎖
boolean res = lock.trylock(100, 10, timeunit.seconds);
if (res) finally
}// (3)redisson同時還為分布式鎖提供了非同步執行的相關方法
lock.lockasync();
lock.lockasync(10, timeunit.seconds);
futureres = lock.trylockasync(100, 10, timeunit.seconds);
org.redisson
redisson
3.13.3
Spring Boot系列筆記 整合Redis
autowired stringredistemplate stringredistemplate autowired redistemplate redistemplate redistemplate類中提供了redis常見的五種資料型別 stringredistemplate.opsforval...
springboot2 x基礎 整合redis
在springboot中一般使用redistemplate提供的方法來操作redis。那麼使用springboot整合redis 需要那些步驟呢。環境安裝 任選 centos7 搭建redis 5單機服務 centos7 搭建 redis 5 cluster 集群服務 在專案中新增 spring b...
Redis benchmark測試Redis效能
redis benchmark是官方自帶的redis效能測試工具,可以有效的測試redis服務的效能。使用說明如下 usage redis benchmark h p c n k h server hostname default 127.0.0.1 p server port default 63...