搜尋
首頁資料庫RedisSpringboot怎麼利用Redis實現介面冪等性攔截

正文

Springboot怎麼利用Redis實現介面冪等性攔截

自訂註解怎麼玩的:      

①標記哪個介面需要進行冪等性攔截       

②每個介面可以要求冪等性範圍時間不一樣,舉例:可以2秒內,可以3秒內,時間自己傳       

③ 一旦觸發了,提示語可以不同,舉例:VIP的接口,普通使用者的接口,提示語不一樣(開玩笑)

效果:

Springboot怎麼利用Redis實現介面冪等性攔截

Springboot怎麼利用Redis實現介面冪等性攔截

實戰開始

核心三件組

註解、攔截器、攔截器設定

① RepeatDaMie.java

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
 
/**
 * @Author: JCccc
 * @Date: 2022-6-13 9:04
 * @Description:  自定义注解,防止重复提交
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface RepeatDaMie {
 
    /**
     * 时间ms限制
     */
    public int second() default 1;
 
    /**
     * 提示消息
     */
    public String describe() default "重复提交了,兄弟";
    
}

②ApiRepeatInterceptor.java

import com.example.repeatdemo.annotation.RepeatDaMie;
import com.example.repeatdemo.util.ContextUtil;
import com.example.repeatdemo.util.Md5Encrypt;
import com.example.repeatdemo.util.RedisUtils;
import com.example.repeatdemo.wrapper.CustomHttpServletRequestWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
 
/**
 * @Author: JCccc
 * @Date: 2022-6-15 9:11
 * @Description: 接口幂等性校验拦截器
 */
@Component
public class ApiRepeatInterceptor implements HandlerInterceptor {
 
    private final Logger log = LoggerFactory.getLogger(this.getClass());
 
    private static final String POST="POST";
    private static final String GET="GET";
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            if (handler instanceof HandlerMethod) {
                HandlerMethod handlerMethod = (HandlerMethod) handler;
                // 获取RepeatDaMie注解
                RepeatDaMie repeatDaMie = handlerMethod.getMethodAnnotation(RepeatDaMie.class);
                if (null==repeatDaMie) {
                    return true;
                }
                //限制的时间范围
                int seconds = repeatDaMie.second();
                //这个用户唯一标识,可以自己细微调整,是userId还是token还是sessionId还是不需要
                String userUniqueKey = request.getHeader("userUniqueKey");
                String method = request.getMethod();
                String apiParams = "";
                if (GET.equals(method)){
                    log.info("GET请求来了");
                    apiParams = new ObjectMapper().writeValueAsString(request.getParameterMap());
                }else if (POST.equals(method)){
                    log.info("POST请求来了");
                    CustomHttpServletRequestWrapper wrapper = (CustomHttpServletRequestWrapper) request;
                    apiParams = wrapper.getBody();
                }
               log.info("当前参数是:{}",apiParams);
                // 存储key
                String keyRepeatDaMie = Md5Encrypt.md5(userUniqueKey+request.getServletPath()+apiParams) ;
                RedisUtils redisUtils = ContextUtil.getBean(RedisUtils.class);
                if (Objects.nonNull(redisUtils.get(keyRepeatDaMie))){
                   log.info("重复请求了,重复请求了,拦截了");
                   returnData(response,repeatDaMie.describe());
                   return false;
               }else {
                    redisUtils.setWithTime(keyRepeatDaMie, true,seconds);
               }
 
            }
            return true;
        } catch (Exception e) {
            log.warn("请求过于频繁请稍后再试");
            e.printStackTrace();
        }
        return true;
    }
 
    public void returnData(HttpServletResponse response,String msg) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        ObjectMapper objectMapper = new ObjectMapper();
        //这里传提示语可以改成自己项目的返回数据封装的类
        response.getWriter().println(objectMapper.writeValueAsString(msg));
        return;
    }
 
}

③ WebConfig.java

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 
/**
 * @Author: JCccc
 * @Date: 2022-6-15 9:24
 * @Description:
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {
 
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new ApiRepeatInterceptor()).addPathPatterns("/**");
    }
}

工具類別三件套

①ContextUtil.java

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
 * @Author: JCccc
 * @Date: 2022-6-15 9:24
 * @Description:
 */
@Component
public final class ContextUtil implements ApplicationContextAware {
    protected static ApplicationContext applicationContext ;
    @Override
    public void setApplicationContext(ApplicationContext arg0) throws BeansException {
        if (applicationContext == null) {
            applicationContext = arg0;
        }
    }
    public static Object getBean(String name) {
        //name表示其他要注入的注解name名
        return applicationContext.getBean(name);
    }
    /**
     * 拿到ApplicationContext对象实例后就可以手动获取Bean的注入实例对象
     */
    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }
}

②Md5Encrypt.java

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
 
/**
 * @Author: JCccc
 * @CreateTime: 2018-10-30
 * @Description:
 */
public class Md5Encrypt {
 
    private static final char[] DIGITS = {&#39;0&#39;, &#39;1&#39;, &#39;2&#39;, &#39;3&#39;, &#39;4&#39;, &#39;5&#39;, &#39;6&#39;, &#39;7&#39;, &#39;8&#39;, &#39;9&#39;, &#39;a&#39;,
            &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;};
 
    /**
     * 对字符串进行MD5加密
     *
     * @param text 明文
     * @return 密文
     */
    public static String md5(String text) {
        MessageDigest msgDigest = null;
 
        try {
            msgDigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("System doesn&#39;t support MD5 algorithm.");
        }
 
        try {
            // 注意该接口是按照指定编码形式签名
            msgDigest.update(text.getBytes("UTF-8"));
 
        } catch (UnsupportedEncodingException e) {
 
            throw new IllegalStateException("System doesn&#39;t support your  EncodingException.");
 
        }
 
        byte[] bytes = msgDigest.digest();
 
        String md5Str = new String(encodeHex(bytes));
 
        return md5Str;
    }
 
    private static char[] encodeHex(byte[] data) {
 
        int l = data.length;
 
        char[] out = new char[l << 1];
        // two characters form the hex value.
        for (int i = 0, j = 0; i < l; i++) {
            out[j++] = DIGITS[(0xF0 & data[i]) >>> 4];
            out[j++] = DIGITS[0x0F & data[i]];
        }
 
        return out;
    }
}

③RedisUtils.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
 
 
@Component
public class RedisUtils {
 
    @Autowired
    private RedisTemplate redisTemplate;
 
    /**
     * 写入String型 [ 键,值]
     *
     * @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) {
            e.printStackTrace();
        }
        return result;
 
    }
 
 
 
    /**
     * 写入String型,顺便带有过期时间 [ 键,值]
     *
     * @param key
     * @param value
     * @return
     */
 
    public boolean setWithTime(final String key, Object value,int seconds) {
        boolean result = false;
        try {
 
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value,seconds, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
 
    }
 
 
 
    /**
     * 批量删除对应的value
     *
     * @param keys
     */
 
    public void remove(final String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }
 
    /**
     * 批量删除key
     *
     * @param pattern
     */
 
    public void removePattern(final String pattern) {
        Set<Serializable> keys = redisTemplate.keys(pattern);
        if (keys.size() > 0)
            redisTemplate.delete(keys);
    }
 
    /**
     * 删除对应的value
     *
     * @param key
     */
 
    public void remove(final String key) {
        if (exists(key)) {
            redisTemplate.delete(key);
        }
    }
 
 
    /**
     * 判断缓存中是否有对应的value
     *
     * @param key
     * @return
     */
 
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }
 
 
    /**
     * 读取缓存
     *
     * @param key
     * @return
     */
 
    public Object get(final String key) {
        Object result = null;
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        result = operations.get(key);
        return result;
    }
 
 
    /**
     * 哈希 添加
     * hash 一个键值(key->value)对集合
     *
     * @param key
     * @param hashKey
     * @param value
     */
 
    public void hmSet(String key, Object hashKey, Object value) {
 
        HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
 
        hash.put(key, hashKey, value);
 
    }
 
 
    /**
     * Hash获取数据
     *
     * @param key
     * @param hashKey
     * @return
     */
 
    public Object hmGet(String key, Object hashKey) {
        HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
        return hash.get(key, hashKey);
 
    }
 
 
    /**
     * 列表添加
     * list:lpush key value1
     *
     * @param k
     * @param v
     */
 
    public void lPush(String k, Object v) {
        ListOperations<String, Object> list = redisTemplate.opsForList();
        list.rightPush(k, v);
    }
 
 
    /**
     * 列表List获取
     * lrange: key 0 10 (读取的个数 从0开始 读取到下标为10 的数据)
     *
     * @param k
     * @param l
     * @param l1
     * @return
     */
 
    public List<Object> lRange(String k, long l, long l1) {
        ListOperations<String, Object> list = redisTemplate.opsForList();
        return list.range(k, l, l1);
    }
 
 
    /**
     * Set集合添加
     *
     * @param key
     * @param value
     */
 
    public void add(String key, Object value) {
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        set.add(key, value);
    }
 
 
    /**
     * Set 集合获取
     *
     * @param key
     * @return
     */
 
    public Set<Object> setMembers(String key) {
 
        SetOperations<String, Object> set = redisTemplate.opsForSet();
 
        return set.members(key);
 
    }
 
 
    /**
     * Sorted set :有序集合添加
     *
     * @param key
     * @param value
     * @param scoure
     */
 
    public void zAdd(String key, Object value, double scoure) {
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        zset.add(key, value, scoure);
    }
 
 
    /**
     * Sorted set:有序集合获取
     *
     * @param key
     * @param scoure
     * @param scoure1
     * @return
     */
 
    public Set<Object> rangeByScore(String key, double scoure, double scoure1) {
 
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
 
        return zset.rangeByScore(key, scoure, scoure1);
 
    }
 
 
    /**
     * 根据key获取Set中的所有值
     *
     * @param key 键
     * @return
     */
 
    public Set<Integer> sGet(String key) {
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
 
 
    /**
     * 根据value从一个set中查询,是否存在
     *
     * @param key   键
     * @param value 值
     * @return true 存在 false不存在
     */
 
    public boolean sHasKey(String key, Object value) {
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
}

REDIS配置類別

RedisConfig.java

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import static org.springframework.data.redis.cache.RedisCacheConfiguration.defaultCacheConfig;
 
/**
 * @Author: JCccc
 * @CreateTime: 2018-09-11
 * @Description:
 */
@Configuration
@EnableCaching
public class RedisConfig {
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        RedisCacheConfiguration cacheConfiguration =
                defaultCacheConfig()
                        .disableCachingNullValues()
                        .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new Jackson2JsonRedisSerializer(Object.class)));
        return RedisCacheManager.builder(connectionFactory).cacheDefaults(cacheConfiguration).build();
    }
 
 
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        //序列化设置 ,这样为了存储操作对象时正常显示的数据,也能正常存储和获取
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        return redisTemplate;
    }
    @Bean
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(factory);
        return stringRedisTemplate;
    }
 
}

最後寫測試接口,看看效果(一個POST,一個GET):

故意把時間放大,1000秒內重複調用,符合我們攔截規則的都會被攔截。

TestController.java

import com.example.repeatdemo.dto.PayOrderApply;
import com.example.repeatdemo.annotation.RepeatDaMie;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
 
/**
 * @Author: JCccc
 * @Date: 2022-6-05 9:44
 * @Description:
 */
@RestController
public class TestController {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
 
    @RepeatDaMie(second = 1000,describe = "尊敬的客户,您慢点")
    @PostMapping(value = "/doPost")
    @ResponseBody
    public void test(@RequestBody PayOrderApply payOrderApply) {
        log.info("Controller POST请求:"+payOrderApply.toString());
    }
 
    @RepeatDaMie(second = 1000,describe = "大哥,你冷静点")
    @GetMapping(value = "/doGet")
    @ResponseBody
    public void doGet( PayOrderApply payOrderApply) {
        log.info("Controller GET请求:"+payOrderApply.toString());
    }
 
}

PayOrderApply.java

/**
 * @Author: JCccc
 * @Date: 2022-6-12 9:46
 * @Description:
 */
public class PayOrderApply {
 
    private String sn;
    private Long amount;
    private String proCode;
 
    public String getSn() {
        return sn;
    }
 
    public void setSn(String sn) {
        this.sn = sn;
    }
 
    public Long getAmount() {
        return amount;
    }
 
    public void setAmount(Long amount) {
        this.amount = amount;
    }
 
    public String getProCode() {
        return proCode;
    }
 
    public void setProCode(String proCode) {
        this.proCode = proCode;
    }
 
    @Override
    public String toString() {
        return "PayOrderApply{" +
                "sn=&#39;" + sn + &#39;\&#39;&#39; +
                ", amount=" + amount +
                ", proCode=&#39;" + proCode + &#39;\&#39;&#39; +
                &#39;}&#39;;
    }
}

Springboot怎麼利用Redis實現介面冪等性攔截

redis產生了值:

Springboot怎麼利用Redis實現介面冪等性攔截

Springboot怎麼利用Redis實現介面冪等性攔截

#

以上是Springboot怎麼利用Redis實現介面冪等性攔截的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:亿速云。如有侵權,請聯絡admin@php.cn刪除
REDIS:它如何充當數據存儲和服務REDIS:它如何充當數據存儲和服務Apr 24, 2025 am 12:08 AM

REDISACTSASBOTHADATASTOREANDASERVICE.1)ASADATASTORE,ITUSESIN-MEMORYSTOOGATOFORFOFFASTESITION,支持VariousDatharptructuresLikeKey-valuepairsandsortedsetsetsetsetsetsetsets.2)asaservice,ItprovidespunctionslikeItionitionslikepunikeLikePublikePublikePlikePlikePlikeAndluikeAndluAascriptingiationsmpleplepleclexplectiations

REDIS與其他數據庫:比較分析REDIS與其他數據庫:比較分析Apr 23, 2025 am 12:16 AM

Redis與其他數據庫相比,具有以下獨特優勢:1)速度極快,讀寫操作通常在微秒級別;2)支持豐富的數據結構和操作;3)靈活的使用場景,如緩存、計數器和發布訂閱。選擇Redis還是其他數據庫需根據具體需求和場景,Redis在高性能、低延遲應用中表現出色。

REDIS的角色:探索數據存儲和管理功能REDIS的角色:探索數據存儲和管理功能Apr 22, 2025 am 12:10 AM

Redis在數據存儲和管理中扮演著關鍵角色,通過其多種數據結構和持久化機製成為現代應用的核心。 1)Redis支持字符串、列表、集合、有序集合和哈希表等數據結構,適用於緩存和復雜業務邏輯。 2)通過RDB和AOF兩種持久化方式,Redis確保數據的可靠存儲和快速恢復。

REDIS:了解NOSQL概念REDIS:了解NOSQL概念Apr 21, 2025 am 12:04 AM

Redis是一種NoSQL數據庫,適用於大規模數據的高效存儲和訪問。 1.Redis是開源的內存數據結構存儲系統,支持多種數據結構。 2.它提供極快的讀寫速度,適合緩存、會話管理等。 3.Redis支持持久化,通過RDB和AOF方式確保數據安全。 4.使用示例包括基本的鍵值對操作和高級的集合去重功能。 5.常見錯誤包括連接問題、數據類型不匹配和內存溢出,需注意調試。 6.性能優化建議包括選擇合適的數據結構和設置內存淘汰策略。

REDIS:現實世界的用例和示例REDIS:現實世界的用例和示例Apr 20, 2025 am 12:06 AM

Redis在現實世界中的應用包括:1.作為緩存系統加速數據庫查詢,2.存儲Web應用的會話數據,3.實現實時排行榜,4.作為消息隊列簡化消息傳遞。 Redis的多功能性和高性能使其在這些場景中大放異彩。

REDIS:探索其功能和功能REDIS:探索其功能和功能Apr 19, 2025 am 12:04 AM

Redis脫穎而出是因為其高速、多功能性和豐富的數據結構。 1)Redis支持字符串、列表、集合、散列和有序集合等數據結構。 2)它通過內存存儲數據,支持RDB和AOF持久化。 3)從Redis6.0開始引入多線程處理I/O操作,提升了高並發場景下的性能。

Redis是SQL還是NOSQL數據庫?答案解釋了Redis是SQL還是NOSQL數據庫?答案解釋了Apr 18, 2025 am 12:11 AM

RedisisclassifiedasaNoSQLdatabasebecauseitusesakey-valuedatamodelinsteadofthetraditionalrelationaldatabasemodel.Itoffersspeedandflexibility,makingitidealforreal-timeapplicationsandcaching,butitmaynotbesuitableforscenariosrequiringstrictdataintegrityo

REDIS:提高應用程序性能和可擴展性REDIS:提高應用程序性能和可擴展性Apr 17, 2025 am 12:16 AM

Redis通過緩存數據、實現分佈式鎖和數據持久化來提升應用性能和可擴展性。 1)緩存數據:使用Redis緩存頻繁訪問的數據,提高數據訪問速度。 2)分佈式鎖:利用Redis實現分佈式鎖,確保在分佈式環境中操作的安全性。 3)數據持久化:通過RDB和AOF機制保證數據安全性,防止數據丟失。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境