這里想將自己學(xué)習(xí)到的分布式鎖和樂(lè)觀鎖的一些知識(shí)記錄下让歼,希望能夠?qū)@兩樣?xùn)|西有更加深刻的理解和更為嫻熟的使用压彭。
分布式鎖
分布式鎖可以基于很多組件來(lái)完成留凭。
zookeeper辙浑,基于臨時(shí)節(jié)點(diǎn)
redis狸捅,基于setnx命令;
memcache衷蜓,基于add函數(shù);
分布式鎖我們可以理解為排他鎖。一個(gè)分布式鎖需要具備哪些條件呢尘喝?
1. 鎖能主動(dòng)釋放
2. 鎖超時(shí)后能夠釋放磁浇,防止死鎖
以redis為例,來(lái)說(shuō)明分布式鎖的在實(shí)際中的使用(以下代碼是示例代碼, 運(yùn)行不了瞧省,缺少必要的pom文件和配置文件以及必要的jar包)扯夭。
首先給出自定義的RedisLockAnnotation注解,然后在需要加鎖的方法上添加對(duì)應(yīng)注解: @RedisLockAnnotation(key = "DistributedLock:Records")
鞍匾。
package com.meituan.redisLockAspect;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface RedisLockAnnotation {
//redis緩存key
String key();
//redis緩存key對(duì)應(yīng)的value
String value() default "";
//過(guò)期時(shí)間
long expire() default 100;
}
package com.meituan.redisLockAspect;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
interface Records {
void doSomething();
}
@Component("dealRecords")
public class DealRecords implements Records {
@RedisLockAnnotation(key = "DistributedLock:Records")
public void doSomething() {
System.out.println("doSomething");
}
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
Records dealRecords = (Records) ctx.getBean("dealRecords");
dealRecords.doSomething();
}
}
完成這些后交洗,需要利用spring的AOP編程編寫(xiě)(前置-before,后置-after橡淑,環(huán)繞-around)切換函數(shù):
package com.meituan.redisLockAspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.lang.reflect.Method;
@Aspect
@Component
public class RedisLockAspect {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(RedisLockAspect.class);
@Resource
private RedisLockUtil redisLockUtil;
@Around(value = "execution(* *(..)) &&@annotation(RedisLockAnnotation)", argNames = "pjp,RedisLockAnnotation")
public Object redisDistributedLock(final ProceedingJoinPoint pjp, RedisLockAnnotation redisLockAnnotation) throws Throwable {
System.out.println("Around.... ");
Object result = null;
Signature signature = pjp.getSignature();
if (!(signature instanceof MethodSignature)) {
return result;
}
MethodSignature methodSignature = (MethodSignature) signature;
Method targetMethod = methodSignature.getMethod();
//獲取注解信息
String key = redisLockAnnotation.key();
try {
boolean isHit = redisLockUtil.acquireLock(key);
if (isHit) {
result = pjp.proceed();
}
} catch (Exception e) {
logger.error("RedisLockAspect內(nèi)錯(cuò)誤构拳,錯(cuò)誤信息為: {}", e.getMessage());
} finally {
redisLockUtil.releaseLock(key);
}
return result;
}
}
最后編寫(xiě)獲取redis key的流程,利用setnx命名的特性:
package com.meituan.redisLockAspect;
import com.dianping.squirrel.client.impl.redis.RedisStoreClient;
import org.apache.commons.lang.StringUtils;
import org.slf4j.LoggerFactory;
import com.dianping.squirrel.client.StoreKey;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
@Component
public class RedisLockUtil {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(RedisLockUtil.class);
public static final int PRODUCTLOCK_VALID_TIME = 4;
public static final int MAX_RETRY_GET_LOCK_NUMBER = 2;
public static final int NEXT_RETRY_TIME = 50;
private String REDIS_LOCK_NAME_PREFIX = "redis_lock_name_prefix";
@Resource(name = "redisClient")
private RedisStoreClient redisStoreClient;
public boolean acquireLock(String key) {
return acquireLock(REDIS_LOCK_NAME_PREFIX, key, PRODUCTLOCK_VALID_TIME);
}
public boolean releaseLock(String key) {
return releaseLock(REDIS_LOCK_NAME_PREFIX, key);
}
private boolean acquireLock(String prefixName, String key, int expireSecond) {
int retryNumber = 1;
boolean isGetLock = false;
while (retryNumber <= MAX_RETRY_GET_LOCK_NUMBER) {
StoreKey storeKey = getStoreKey(prefixName, key);
boolean result = redisStoreClient.setnx(storeKey, 1, expireSecond);
if (result) {
isGetLock = true;
break;
} else {
try {
Thread.sleep(NEXT_RETRY_TIME);
} catch (InterruptedException e) {
logger.error("獲取分布式鎖失敗", e);
}
retryNumber++;
}
}
if (!isGetLock) {
logger.error("獲取分布式鎖失敗,key=" + prefixName + key);
}
return isGetLock;
}
public boolean releaseLock(String prefixName, String key) {
boolean result = redisStoreClient.delete(getStoreKey(prefixName, key)) == null ? false : true;
if (result) {
return result;
} else {
logger.error(new StringBuilder().append("刪除分布式鎖失敗,key=").append(prefixName).append(key).toString());
}
return result;
}
private StoreKey getStoreKey(String prefixName, String key) {
if (!StringUtils.isBlank(key)) {
return new StoreKey(prefixName, key);
}
return null;
}
}
樂(lè)觀鎖
我理解的樂(lè)觀鎖就是CAS(CompareAndSwap)梁棠,樂(lè)觀鎖一般認(rèn)為數(shù)據(jù)的沖突不會(huì)非常頻繁出現(xiàn)置森,所以數(shù)據(jù)在正式提交的時(shí)候才去檢測(cè)是否沖突,如果出現(xiàn)沖突就返回錯(cuò)誤給用戶符糊,讓用戶自己決定如何處理凫海。一般的樂(lè)觀鎖實(shí)現(xiàn)是給這條數(shù)據(jù)增加一個(gè)標(biāo)記字段:version
或者timestamp
。在讀取數(shù)據(jù)的時(shí)候?qū)?biāo)記字段信息一并讀取出來(lái)男娄,更新記錄的時(shí)候行贪,帶上這個(gè)標(biāo)記漾稀,如果更新時(shí)候發(fā)現(xiàn)這條記錄的標(biāo)記不等于之前讀取的,那么就說(shuō)明這條記錄已經(jīng)被其他線程修改了建瘫,直接返回崭捍,我們采用Mybatis來(lái)寫(xiě)demo說(shuō)明。最終落到sql上的表現(xiàn)是:
update table_name
set status=2,
version=version+1
where id = #{id}
and version=#{version}
使用Mybatis實(shí)踐啰脚,如下: