一起來學SpringBoot | 第二十三篇:輕鬆搞定重複提交(分佈式鎖)

SpringBoot 是爲了簡化 Spring 應用的創建、運行、調試、部署等一系列問題而誕生的產物,自動裝配的特性讓我們可以更好的關注業務本身而不是外部的XML配置,我們只需遵循規範,引入相關的依賴就可以輕易的搭建出一個 WEB 工程

一起來學SpringBoot | 第二十二篇:輕鬆搞定重複提交(一) 一文中介紹了單機版的重複提交解決方案,在如今這個分佈式與集羣橫行的世道中,那怎麼夠用呢,所以本章重點來了....

重複提交(分佈式)

單機版中我們用的是Guava Cache,但是這玩意存在集羣的時候就涼了,所以我們還是要藉助類似RedisZooKeeper 之類的中間件實現分佈式鎖。

本章目標

利用 自定義註解Spring AopRedis Cache 實現分佈式鎖,你想鎖表單鎖表單,想鎖接口鎖接口….

具體代碼

也很簡單…

導入依賴

pom.xml 中添加上 starter-webstarter-aopstarter-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 相關的配置項

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

CacheLock 註解

創建一個 CacheLock 註解,本章內容都是實戰使用過的,所以屬性配置會相對完善了,話不多說註釋都給各位寫齊全了….

  • prefix: 緩存中 key 的前綴
  • expire: 過期時間,此處默認爲 5 秒
  • timeUnit: 超時單位,此處默認爲秒
  • delimiter: key 的分隔符,將不同參數值分割開來
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 "";

    /**
     * 過期秒數,默認爲5秒
     *
     * @return 輪詢鎖的時間
     */
    int expire() default 5;

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

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

CacheParam 註解

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

package com.battcn.annotation;

import java.lang.annotation.*;

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

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

Key 生成策略(接口)

創建一個 CacheKeyGenerator 具體實現由使用者自己去注入

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

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

Key 生成策略(實現)

解析過程雖然看上去優點繞,但認真閱讀或者調試就會發現,主要是解析帶 CacheLock 註解的屬性,獲取對應的屬性值,生成一個全新的緩存 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;

/**
 * 上一章說過通過接口注入的方式去寫不同的生成規則;
 * @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 默認解析方法裏面帶 CacheParam 註解的屬性,如果沒有嘗試着解析實體對象中的
        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 的朋友都知道它是線程安全的,我們利用它的特性可以很輕鬆的實現一個分佈式鎖,如 opsForValue().setIfAbsent(key,value) 它的作用就是如果緩存中沒有當前 Key 則進行緩存同時返回 true 反之亦然;當緩存後給 key 在設置個過期時間,防止因爲系統崩潰而導致鎖遲遲不釋放形成死鎖; 那麼我們是不是可以這樣認爲當返回 true 我們認爲它獲取到鎖了,在鎖未釋放的時候我們進行異常的拋出….

package com.battcn.interceptor;

import com.battcn.annotation.CacheLock;
import com.battcn.utils.RedisLockHelper;
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.util.StringUtils;

import java.lang.reflect.Method;
import java.util.UUID;

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

    @Autowired
    public LockMethodInterceptor(RedisLockHelper redisLockHelper, CacheKeyGenerator cacheKeyGenerator) {
        this.redisLockHelper = redisLockHelper;
        this.cacheKeyGenerator = cacheKeyGenerator;
    }

    private final RedisLockHelper redisLockHelper;
    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);
        String value = UUID.randomUUID().toString();
        try {
            // 假設上鎖成功,但是設置過期時間失效,以後拿到的都是 false
            final boolean success = redisLockHelper.lock(lockKey, value, lock.expire(), lock.timeUnit());
            if (!success) {
                throw new RuntimeException("重複提交");
            }
            try {
                return pjp.proceed();
            } catch (Throwable throwable) {
                throw new RuntimeException("系統異常");
            }
        } finally {
            // TODO 如果演示的話需要註釋該代碼;實際應該放開
            redisLockHelper.unlock(lockKey, value);
        }
    }
}

RedisLockHelper

通過封裝成 API 方式調用,靈活度更加高

package com.battcn.utils;

import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
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.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

/**
 * 需要定義成 Bean
 *
 * @author Levin
 * @since 2018/6/15 0015
 */
@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisLockHelper {


    private static final String DELIMITER = "|";

    /**
     * 如果要求比較高可以通過注入的方式分配
     */
    private static final ScheduledExecutorService EXECUTOR_SERVICE = Executors.newScheduledThreadPool(10);

    private final StringRedisTemplate stringRedisTemplate;

    public RedisLockHelper(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 獲取鎖(存在死鎖風險)
     *
     * @param lockKey lockKey
     * @param value   value
     * @param time    超時時間
     * @param unit    過期單位
     * @return true or false
     */
    public boolean tryLock(final String lockKey, final String value, final long time, final TimeUnit unit) {
        return stringRedisTemplate.execute((RedisCallback<Boolean>) connection -> connection.set(lockKey.getBytes(), value.getBytes(), Expiration.from(time, unit), RedisStringCommands.SetOption.SET_IF_ABSENT));
    }

    /**
     * 獲取鎖
     *
     * @param lockKey lockKey
     * @param uuid    UUID
     * @param timeout 超時時間
     * @param unit    過期單位
     * @return true or false
     */
    public boolean lock(String lockKey, final String uuid, long timeout, final TimeUnit unit) {
        final long milliseconds = Expiration.from(timeout, unit).getExpirationTimeInMilliseconds();
        boolean success = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, (System.currentTimeMillis() + milliseconds) + DELIMITER + uuid);
        if (success) {
            stringRedisTemplate.expire(lockKey, timeout, TimeUnit.SECONDS);
        } else {
            String oldVal = stringRedisTemplate.opsForValue().getAndSet(lockKey, (System.currentTimeMillis() + milliseconds) + DELIMITER + uuid);
            final String[] oldValues = oldVal.split(Pattern.quote(DELIMITER));
            if (Long.parseLong(oldValues[0]) + 1 <= System.currentTimeMillis()) {
                return true;
            }
        }
        return success;
    }


    /**
     * @see <a href="http://redis.io/commands/set">Redis Documentation: SET</a>
     */
    public void unlock(String lockKey, String value) {
        unlock(lockKey, value, 0, TimeUnit.MILLISECONDS);
    }

    /**
     * 延遲unlock
     *
     * @param lockKey   key
     * @param uuid      client(最好是唯一鍵的)
     * @param delayTime 延遲時間
     * @param unit      時間單位
     */
    public void unlock(final String lockKey, final String uuid, long delayTime, TimeUnit unit) {
        if (StringUtils.isEmpty(lockKey)) {
            return;
        }
        if (delayTime <= 0) {
            doUnlock(lockKey, uuid);
        } else {
            EXECUTOR_SERVICE.schedule(() -> doUnlock(lockKey, uuid), delayTime, unit);
        }
    }

    /**
     * @param lockKey key
     * @param uuid    client(最好是唯一鍵的)
     */
    private void doUnlock(final String lockKey, final String uuid) {
        String val = stringRedisTemplate.opsForValue().get(lockKey);
        final String[] values = val.split(Pattern.quote(DELIMITER));
        if (values.length <= 0) {
            return;
        }
        if (uuid.equals(values[1])) {
            stringRedisTemplate.delete(lockKey);
        }
    }

}

控制層

在接口上添加 @CacheLock(prefix = "books"),然後動態的值可以加上@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;
    }

}

主函數

這裏需要注入前面定義好的 CacheKeyGenerator 接口具體實現…

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();
    }

}

測試

完成準備事項後,啓動 Chapter22Application 自行測試即可,測試手段相信大夥都不陌生了,如 瀏覽器postmanjunitswagger,此處基於 postman,如果你覺得自帶的異常信息不夠友好,那麼配上一起來學SpringBoot | 第十八篇:輕鬆搞定全局異常 可以輕鬆搞定…

第一次請求

正確響應

第二次請求

錯誤響應

總結

目前很多大佬都寫過關於 SpringBoot 的教程了,如有雷同,請多多包涵,本教程基於最新的 spring-boot-starter-parent:2.0.2.RELEASE編寫,包括新版本的特性都會一起介紹…

說點什麼

  • 個人QQ:1837307557
  • battcn開源羣(適合新手):391619659
  • 微信公衆號(歡迎調戲):battcn

公衆號

個人博客:http://blog.battcn.com/

全文代碼:https://github.com/battcn/spring-boot2-learning/tree/master/chapter22

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