溫馨提示×

溫馨提示×

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

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

Spring Boot整合分布式鎖

發(fā)布時間:2020-06-10 21:48:13 來源:網(wǎng)絡(luò) 閱讀:579 作者:Java_老男孩 欄目:編程語言

SpringBoot?是為了簡化?Spring?應(yīng)用的創(chuàng)建、運(yùn)行、調(diào)試、部署等一系列問題而誕生的產(chǎn)物,自動裝配的特性讓我們可以更好的關(guān)注業(yè)務(wù)本身而不是外部的XML配置,我們只需遵循規(guī)范,引入相關(guān)的依賴就可以輕易的搭建出一個 WEB 工程

重復(fù)提交(分布式)

單機(jī)版中我們用的是Guava Cache,但是這玩意存在集群的時候就涼了,所以我們還是要借助類似Redis、ZooKeeper 之類的中間件實(shí)現(xiàn)分布式鎖。

本章目標(biāo)

利用?自定義注解Spring Aop、Redis Cache?實(shí)現(xiàn)分布式鎖,你想鎖表單鎖表單,想鎖接口鎖接口….

具體代碼

也很簡單…

導(dǎo)入依賴

在?pom.xml?中添加上?starter-web、starter-aop、starter-data-redis?的依賴即可

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
</dependencies>

屬性配置

在?application.properites?資源文件中添加?redis?相關(guān)的配置項(xiàng)

spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=battcn

CacheLock 注解

創(chuàng)建一個?CacheLock?注解,本章內(nèi)容都是實(shí)戰(zhàn)使用過的,所以屬性配置會相對完善了,話不多說注釋都給各位寫齊全了….

  • prefix:?緩存中 key 的前綴
  • expire:?過期時間,此處默認(rèn)為 5 秒
  • timeUnit:?超時單位,此處默認(rèn)為秒
  • delimiter:?key 的分隔符,將不同參數(shù)值分割開來
package com.battcn.annotation;

import java.lang.annotation.*;
import java.util.concurrent.TimeUnit;

/**
 * @author Levin
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface CacheLock {

    /**
     * redis 鎖key的前綴
     *
     * @return redis 鎖key的前綴
     */
    String prefix() default "";

    /**
     * 過期秒數(shù),默認(rèn)為5秒
     *
     * @return 輪詢鎖的時間
     */
    int expire() default 5;

    /**
     * 超時時間單位
     *
     * @return 秒
     */
    TimeUnit timeUnit() default TimeUnit.SECONDS;

    /**
     * <p>Key的分隔符(默認(rèn) :)</p>
     * <p>生成的Key:N:SO1008:500</p>
     *
     * @return String
     */
    String delimiter() default ":";
}

CacheParam 注解

上一篇中給說過 key 的生成規(guī)則是自己定義的,如果通過表達(dá)式語法自己得去寫解析規(guī)則還是比較麻煩的,所以依舊是用注解的方式…

package com.battcn.annotation;

import java.lang.annotation.*;

/**
 * 鎖的參數(shù)
 *
 * @author Levin
 */
@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface CacheParam {

    /**
     * 字段名稱
     *
     * @return String
     */
    String name() default "";
}

Key 生成策略(接口)

創(chuàng)建一個?CacheKeyGenerator?具體實(shí)現(xiàn)由使用者自己去注入

/**
 * key生成器
 *
 * @author Levin
 * @date 2018/03/22
 */
public interface CacheKeyGenerator {

    /**
     * 獲取AOP參數(shù),生成指定緩存Key
     *
     * @param pjp PJP
     * @return 緩存KEY
     */
    String getLockKey(ProceedingJoinPoint pjp);
}

Key 生成策略(實(shí)現(xiàn))

解析過程雖然看上去優(yōu)點(diǎn)繞,但認(rèn)真閱讀或者調(diào)試就會發(fā)現(xiàn),主要是解析帶?CacheLock?注解的屬性,獲取對應(yīng)的屬性值,生成一個全新的緩存 Key

package com.battcn.interceptor;

import com.battcn.annotation.CacheLock;
import com.battcn.annotation.CacheParam;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

/**
 * 上一章說過通過接口注入的方式去寫不同的生成規(guī)則;
 * @author Levin
 * @since 2018/6/13 0026
 */
public class LockKeyGenerator implements CacheKeyGenerator {

    @Override
    public String getLockKey(ProceedingJoinPoint pjp) {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        CacheLock lockAnnotation = method.getAnnotation(CacheLock.class);
        final Object[] args = pjp.getArgs();
        final Parameter[] parameters = method.getParameters();
        StringBuilder builder = new StringBuilder();
        // TODO 默認(rèn)解析方法里面帶 CacheParam 注解的屬性,如果沒有嘗試著解析實(shí)體對象中的
        for (int i = 0; i < parameters.length; i++) {
            final CacheParam annotation = parameters[i].getAnnotation(CacheParam.class);
            if (annotation == null) {
                continue;
            }
            builder.append(lockAnnotation.delimiter()).append(args[i]);
        }
        if (StringUtils.isEmpty(builder.toString())) {
            final Annotation[][] parameterAnnotations = method.getParameterAnnotations();
            for (int i = 0; i < parameterAnnotations.length; i++) {
                final Object object = args[i];
                final Field[] fields = object.getClass().getDeclaredFields();
                for (Field field : fields) {
                    final CacheParam annotation = field.getAnnotation(CacheParam.class);
                    if (annotation == null) {
                        continue;
                    }
                    field.setAccessible(true);
                    builder.append(lockAnnotation.delimiter()).append(ReflectionUtils.getField(field, object));
                }
            }
        }
        return lockAnnotation.prefix() + builder.toString();
    }
}

Lock 攔截器(AOP)

熟悉?Redis?的朋友都知道它是線程安全的,我們利用它的特性可以很輕松的實(shí)現(xiàn)一個分布式鎖,如?opsForValue().setIfAbsent(key,value)它的作用就是如果緩存中沒有當(dāng)前 Key 則進(jìn)行緩存同時返回?true?反之亦然;當(dāng)緩存后給 key 在設(shè)置個過期時間,防止因?yàn)橄到y(tǒng)崩潰而導(dǎo)致鎖遲遲不釋放形成死鎖;?那么我們是不是可以這樣認(rèn)為當(dāng)返回?true?我們認(rèn)為它獲取到鎖了,在鎖未釋放的時候我們進(jìn)行異常的拋出….

package com.battcn.interceptor;

import com.battcn.annotation.CacheLock;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.types.Expiration;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;

/**
 * redis 方案
 *
 * @author Levin
 * @since 2018/6/12 0012
 */
@Aspect
@Configuration
public class LockMethodInterceptor {

    @Autowired
    public LockMethodInterceptor(StringRedisTemplate lockRedisTemplate, CacheKeyGenerator cacheKeyGenerator) {
        this.lockRedisTemplate = lockRedisTemplate;
        this.cacheKeyGenerator = cacheKeyGenerator;
    }

    private final StringRedisTemplate lockRedisTemplate;
    private final CacheKeyGenerator cacheKeyGenerator;

    @Around("execution(public * *(..)) && @annotation(com.battcn.annotation.CacheLock)")
    public Object interceptor(ProceedingJoinPoint pjp) {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        CacheLock lock = method.getAnnotation(CacheLock.class);
        if (StringUtils.isEmpty(lock.prefix())) {
            throw new RuntimeException("lock key don't null...");
        }
        final String lockKey = cacheKeyGenerator.getLockKey(pjp);
        try {
            // 采用原生 API 來實(shí)現(xiàn)分布式鎖
            final Boolean success = lockRedisTemplate.execute((RedisCallback<Boolean>) connection -> connection.set(lockKey.getBytes(), new byte[0], Expiration.from(lock.expire(), lock.timeUnit()), RedisStringCommands.SetOption.SET_IF_ABSENT));
            if (!success) {
                // TODO 按理來說 我們應(yīng)該拋出一個自定義的 CacheLockException 異常;這里偷下懶
                throw new RuntimeException("請勿重復(fù)請求");
            }
            try {
                return pjp.proceed();
            } catch (Throwable throwable) {
                throw new RuntimeException("系統(tǒng)異常");
            }
        } finally {
            // TODO 如果演示的話需要注釋該代碼;實(shí)際應(yīng)該放開
            // lockRedisTemplate.delete(lockKey);
        }
    }
}

控制層

在接口上添加?@CacheLock(prefix = "books"),然后動態(tài)的值可以加上@CacheParam;生成后的新 key 將被緩存起來;(如:該接口 token = 1,那么最終的 key 值為 books:1,如果多個條件則依次類推

package com.battcn.controller;

import com.battcn.annotation.CacheLock;
import com.battcn.annotation.CacheParam;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * BookController
 *
 * @author Levin
 * @since 2018/6/06 0031
 */
@RestController
@RequestMapping("/books")
public class BookController {

    @CacheLock(prefix = "books")
    @GetMapping
    public String query(@CacheParam(name = "token") @RequestParam String token) {
        return "success - " + token;
    }

}

主函數(shù)

這里需要注入前面定義好的?CacheKeyGenerator?接口具體實(shí)現(xiàn)…

package com.battcn;

import com.battcn.interceptor.CacheKeyGenerator;
import com.battcn.interceptor.LockKeyGenerator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

/**
 * @author Levin
 */
@SpringBootApplication
public class Chapter22Application {

    public static void main(String[] args) {

        SpringApplication.run(Chapter22Application.class, args);

    }

    @Bean
    public CacheKeyGenerator cacheKeyGenerator() {
        return new LockKeyGenerator();
    }

}

測試

完成準(zhǔn)備事項(xiàng)后,啟動?Chapter22Application?自行測試即可,測試手段相信大伙都不陌生了,如?瀏覽器、postmanjunit、swagger,此處基于?postman,如果你覺得自帶的異常信息不夠友好,那么配上巧用SpringBoot輕松搞定全局異常?可以輕松搞定…

第一次請求

Spring Boot整合分布式鎖

正確響應(yīng)

第二次請求

Spring Boot整合分布式鎖

Spring Boot整合分布式鎖錯誤響應(yīng)

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI