1. 程式人生 > 其它 >springboot+redis+Interceptor+自定義annotation實現介面自動冪等

springboot+redis+Interceptor+自定義annotation實現介面自動冪等

冪等

1.概念: 任意多次執行所產生的影響均與一次執行的影響相同。
按照這個含義,最終的含義就是 對資料庫的影響只能是一次性的,不能重複處理。如何保證其冪等性,通常有以下手段:

1: 資料庫建立唯一性索引,可以保證最終插入資料庫的只有一條資料

2: token 機制,每次介面請求前先獲取一個 token,然後再下次請求的時候在請求的 header 體中加上這個 token,後臺進行驗證,如果驗證通過刪除 token,下次請求再次判斷 token

3: 悲觀鎖或者樂觀鎖,悲觀鎖可以保證每次 for update 的時候其他 sql 無法 update 資料 (在資料庫引擎是 innodb 的時候, select 的條件必須是唯一索引, 防止鎖全表)

4: 先查詢後判斷,首先通過查詢資料庫是否存在資料,如果存在證明已經請求過了,直接拒絕該請求,如果沒有存在,就證明是第一次進來,直接放行。

redis 實現自動冪等的原理圖:

一. 搭建redis的服務Api

1: 首先是搭建 redis 伺服器。詳情可參考:https://www.cnblogs.com/wyq178/p/10340234.html

2: 引入 springboot 中到的 redis 的 stater,或者 Spring 封裝的 jedis 也可以,後面主要用到的 api 就是它的 set 方法和 exists 方法, 這裡我們使用 springboot 的封裝好的 redisTemplate
程式碼如下:

/*
redis工具類
*/
@Component
public class RedisService {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 寫入快取
     * @param key
     * @param value
     * @return
     */
    public  boolean set(final String key,Object value){
        boolean result = false;
        try {
            ValueOperations<Serializable,Object> operations = redisTemplate.opsForValue();
            operations.set(key,value);
            result = true;
        }catch (Exception e){
            result = false;
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 寫入快取有效期
     * @return
     */
    public boolean setEx(final String key ,Object value,Long expireTime){
        boolean result = false;
        try {
            ValueOperations<Serializable,Object> operations = redisTemplate.opsForValue();
            operations.set(key,value);
            redisTemplate.expire(key,expireTime, TimeUnit.SECONDS);//有效期
            result = true;
        }catch (Exception e){
            result = false;
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 判斷快取中是否有對應的value
     * @param key
     * @return
     */
    public boolean exists(final String key){
       return redisTemplate.hasKey(key);
    }

    /**
     * 讀取快取
     * @param key
     * @return
     */
    public Object get(final String key){
        Object obj = null;
        ValueOperations<Serializable,Object> operations= redisTemplate.opsForValue();
        obj =  operations.get(key);
        return obj;
    }

    /**
     * 刪除對應的value
     * @param key
     * @return
     */
    public boolean remvoe(final String key){
        if(exists(key)){
            Boolean delete = redisTemplate.delete(key);
            return delete;
        }
        return false;
    }


}

二.自定義 AutoIdempotent

自定義一個註解,定義此註解的主要目的是把它新增在需要實現冪等的方法上,凡是某個方法註解了它,都會實現自動冪等。後臺利用反射如果掃描到這個註解,就會處理這個方法實現自動冪等,使用元註解 ElementType.METHOD 表示它只能放在方法上,etentionPolicy.RUNTIME 表示它在執行時

package com.yxkj.springboot_redis_interceptor.annotion;

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 AutoIdempotent {
}

三. token 建立和檢驗

1.token服務介面

我們新建一個介面,建立 token 服務,裡面主要是兩個方法,一個用來建立 token,一個用來驗證 token。建立 token 主要產生的是一個字串,檢驗 token 的話主要是傳達 request 物件,為什麼要傳 request 物件呢?主要作用就是獲取 header 裡面的 token, 然後檢驗,通過丟擲的 Exception 來獲取具體的報錯資訊返回給前端

public interface TokenService {

    /**
     * 建立token
     * @return
     */
    String createToken();

    /**
     * 檢驗token的合法性
     * @param request
     * @return
     * @throws Exception
     */
    boolean checkToken(HttpServletRequest request) throws Exception;
}

2.token 的服務實現類

token 引用了 redis 服務,建立 token 採用隨機演算法工具類生成隨機 uuid 字串, 然後放入到 redis 中 (為了防止資料的冗餘保留, 這裡設定過期時間為 10000 秒, 具體可視業務而定),如果放入成功,最後返回這個 token 值。checkToken 方法就是從 header 中獲取 token 到值 (如果 header 中拿不到,就從 paramter 中獲取),如若不存在, 直接丟擲異常。這個異常資訊可以被攔截器捕捉到,然後返回給前端。