亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Redis+aop實(shí)現(xiàn)接口防刷(冪等)的解決方案

 更新時(shí)間:2024年03月28日 09:43:19   作者:不負(fù)朝陽(yáng)  
在高并發(fā)場(chǎng)景下,可能會(huì)因?yàn)榫W(wǎng)絡(luò)或者服務(wù)器原因,造成延遲,同時(shí)就是有可能會(huì)有人用腳本大量訪(fǎng)問(wèn)你的接口,造成資源崩潰,所以本文給大家介紹了Redis+aop實(shí)現(xiàn)接口防刷(冪等)的解決方案,需要的朋友可以參考下

冪等和接口防刷概念

這兩者其實(shí)是屬于不同的場(chǎng)景但是在一些情況下,實(shí)現(xiàn)方式上有異曲同工之妙。

防刷

顧名思義,想讓某個(gè)接口某個(gè)人在某段時(shí)間內(nèi)只能請(qǐng)求N次。一般是對(duì)一些不發(fā)人員用腳本對(duì)接口進(jìn)行大量請(qǐng)求,或者說(shuō)利用腳本進(jìn)行秒殺。

冪等

冪等的數(shù)學(xué)概念

冪等是源于一種數(shù)學(xué)概念。其主要有兩個(gè)定義

如果在一元運(yùn)算中,x 為某集合中的任意數(shù),如果滿(mǎn)足 f(x) = f(f(x)) ,那么該 f 運(yùn)算具有冪等性,比如絕對(duì)值運(yùn)算 abs(a) = abs(abs(a)) 就是冪等性函數(shù)。

如果在二元運(yùn)算中,x 為某集合中的任意數(shù),如果滿(mǎn)足 f(x,x) = x,前提是 f 運(yùn)算的兩個(gè)參數(shù)均為 x,那么我們稱(chēng) f 運(yùn)算也有冪等性,比如求大值函數(shù) max(x,x) = x 就是冪等性函數(shù)。

冪等性在開(kāi)發(fā)中的概念

在數(shù)學(xué)中冪等的概念或許比較抽象,但是在開(kāi)發(fā)中冪等性是極為重要的。簡(jiǎn)單來(lái)說(shuō),對(duì)于同一個(gè)系統(tǒng),在同樣條件下,一次請(qǐng)求和重復(fù)多次請(qǐng)求對(duì)資源的影響是一致的,就稱(chēng)該操作為冪等的。比如說(shuō)如果有一個(gè)接口是冪等的,當(dāng)傳入相同條件時(shí),其效果必須是相同的。

特別是對(duì)于現(xiàn)在分布式系統(tǒng)下的 RPC 或者 Restful 接口互相調(diào)用的情況下,很容易出現(xiàn)由于網(wǎng)絡(luò)錯(cuò)誤等等各種原因?qū)е抡{(diào)用的時(shí)候出現(xiàn)異常而需要重試,這時(shí)候就必須保證接口的冪等性,否則重試的結(jié)果將與第一次調(diào)用的結(jié)果不同,如果有個(gè)接口的調(diào)用鏈 A->B->C->D->E,在 D->E 這一步發(fā)生異常重試后返回了錯(cuò)誤的結(jié)果,A,B,C也會(huì)受到影響,這將會(huì)是災(zāi)難性的。

為什么要進(jìn)行接口防刷(冪等)

在高并發(fā)場(chǎng)景下,可能會(huì)因?yàn)榫W(wǎng)絡(luò)或者服務(wù)器原因,造成延遲,具體來(lái)說(shuō)就是,一個(gè)人點(diǎn)了一下,沒(méi)反應(yīng),又點(diǎn)了一下,但其實(shí)這兩次都發(fā)送請(qǐng)求成功了,這樣就可能造成數(shù)據(jù)不一致問(wèn)題,同時(shí)還對(duì)資源進(jìn)行浪費(fèi)。同時(shí)就是有可能會(huì)有人用腳本大量訪(fǎng)問(wèn)你的接口,造成資源崩潰。

解決方案

防刷

防刷的解決一般是不會(huì)用后端寫(xiě)邏輯解決,一般可以在請(qǐng)求到nginx的時(shí)候就可以進(jìn)行判斷,然后加入黑名單,不需要請(qǐng)求到后端就能攔截,阿里的sentinel也可以解決這個(gè)問(wèn)題

冪等

因?yàn)閮绲雀嗍窃诟卟l(fā)和分布式場(chǎng)景下,所以?xún)绲雀嗍怯胷edis做,畢竟redis一般就是用來(lái)解決分布式問(wèn)題的

實(shí)戰(zhàn)

話(huà)不多說(shuō)直接上代碼

首先架構(gòu)是用的xfg的ddd腳手架,架構(gòu)方面就不展開(kāi)講了,我個(gè)人是寫(xiě)在觸發(fā)器層的,因?yàn)檫壿嬓枰獙?duì)controller進(jìn)行操作,如果寫(xiě)在別的層感覺(jué)很怪,如果寫(xiě)在domain層應(yīng)該也是合理的,畢竟所有層都對(duì)domain有依賴(lài),而且domain層本身是用來(lái)實(shí)現(xiàn)業(yè)務(wù)規(guī)則的。(這不是重點(diǎn),想聽(tīng)ddd,我理解深一點(diǎn)以后單獨(dú)講)

 
 
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
 
/**
 * @author: Larry
 * @Date: 2024 /03 /25 / 10:27
 * @Description:
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RequestLimit {
    long time() default 10;
    int count() default 1;
}

這個(gè)是對(duì)注解的定義,規(guī)定了時(shí)間范圍和次數(shù),默認(rèn)10秒內(nèi)只能進(jìn)行1次訪(fǎng)問(wèn)

package cn.bugstack.aop;
 
import cn.bugstack.config.RequestLimit;
import cn.bugstack.infrastructure.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
 
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;
 
/**
 * @author: Larry
 * @Date: 2024 /03 /25 / 10:30
 * @Description:
 */
@Aspect
@Component
@Slf4j
public class LimitAOP {
    @Resource
    RedisUtil redisUtil;
    @Pointcut("execution(public * cn.bugstack.*..*.*(..))")
    public void LimitPointCut(){}
    //規(guī)定必須在上面路徑下同時(shí)方法上帶@requestLimit注解
    @Around("LimitPointCut()&&@annotation(requestLimit)")
    public Object Before(ProceedingJoinPoint proceedingJoinPoint, RequestLimit requestLimit) throws Throwable {
        log.info("進(jìn)入aop中");
        //根據(jù)注解獲取注解上的值
       int limitCount = requestLimit.count();
        System.out.println(limitCount+"limit");
       long time = requestLimit.time();
       //根據(jù)ServletRequestAttributes獲取當(dāng)前請(qǐng)求信息
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
 
        if (requestAttributes != null) {
            HttpServletRequest request;
            request = requestAttributes.getRequest();
            String ip = request.getRemoteAddr();
            String url = request.getRequestURI();
            //將ip和url拼接成唯一key
            String key = "request"+ip+url;
            log.info(key);
            if(redisUtil.get(key)!=null){
                Integer count = (Integer) redisUtil.get(key);
                System.out.println(count+"==="+limitCount);
                if(count >= limitCount){
                      throw new LimitException("請(qǐng)不要頻繁操作");
                }
                   redisUtil.incr(key,1L);
            }
            else{
                redisUtil.set(key,1,time);
            }
 
        }
        return proceedingJoinPoint.proceed();
    }
}

具體邏輯就是當(dāng)用戶(hù)發(fā)過(guò)來(lái)請(qǐng)求,(前提是controller上有對(duì)應(yīng)注解)進(jìn)入這個(gè)接口,然后根據(jù)ip和請(qǐng)求路徑作為key進(jìn)行判斷,如果此時(shí)redis有key,但是key的value不超過(guò)默認(rèn)次數(shù),就放行,如果沒(méi)有key,就根據(jù)其創(chuàng)建一個(gè)key設(shè)置過(guò)期時(shí)間為注解上的時(shí)間,然后放行,如果value過(guò)默認(rèn)次數(shù),就會(huì)被攔截,然后拋出一個(gè)自定義異常,可以在controller里捕獲并提示前端。為什么用ip+url,因?yàn)橛行┚W(wǎng)站是允許賬號(hào)多端同時(shí)使用的,這就會(huì)對(duì)一些用戶(hù)產(chǎn)生不友好的體驗(yàn),當(dāng)然一般情況下用userId也可以

package cn.bugstack.infrastructure.util;
 
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
 
import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
 
 
@Component
public class RedisUtil {
 
 
    private RedisTemplate<String, Object> redisTemplate;
 
    public RedisTemplate<String, Object> getRedisTemplate() {
        return redisTemplate;
    }
    @Resource
    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
    //    public RedisUtil(RedisTemplate<String, Object> redisTemplate) {
//        this.redisTemplate = redisTemplate;
//    }
    /**
     * 向zset里存入數(shù)據(jù)
     *
     * @param key  鍵
     * @param member 值
     * @param score 分?jǐn)?shù)
     * @return
     */
    public boolean addToZSet(String key, String member, double score) {
       return Boolean.TRUE.equals(redisTemplate.opsForZSet().add(key, member, score));
    }
    /**
     * 指定緩存失效時(shí)間
     *
     * @param key  鍵
     * @param time 時(shí)間(秒)
     * @return
     */
    public boolean expire(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
    /**
     * 根據(jù)key 獲取過(guò)期時(shí)間
     *
     * @param key 鍵 不能為null
     * @return 時(shí)間(秒) 返回0代表為永久有效
     */
    public long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }
 
    /**
     * 判斷key是否存在
     *
     * @param key 鍵
     * @return true 存在 false不存在
     */
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
    /**
     * 刪除緩存
     *
     * @param key 可以傳一個(gè)值 或多個(gè)
     */
    @SuppressWarnings("unchecked")
    public void del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key));
            }
        }
    }
 
    //============================String=============================
 
    /**
     * 普通緩存獲取
     *
     * @param key 鍵
     * @return 值
     */
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }
 
    /**
     * 普通緩存放入
     *
     * @param key   鍵
     * @param value 值
     * @return true成功 false失敗
     */
    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
    /**
     * 普通緩存放入并設(shè)置時(shí)間
     *
     * @param key   鍵
     * @param value 值
     * @param time  時(shí)間(秒) time要大于0 如果time小于等于0 將設(shè)置無(wú)限期
     * @return true成功 false 失敗
     */
    public boolean set(String key, Object value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
    /**
     * 分布式鎖
     * @param key               鎖住的key
     * @param lockExpireMils    鎖住的時(shí)長(zhǎng)。如果超時(shí)未解鎖,視為加鎖線(xiàn)程死亡,其他線(xiàn)程可奪取鎖
     * @return
     */
    public boolean setNx(String key, Long lockExpireMils) {
        return (boolean) redisTemplate.execute((RedisCallback) connection -> {
            //獲取鎖
            return connection.setNX(key.getBytes(), String.valueOf(System.currentTimeMillis() + lockExpireMils + 1).getBytes());
        });
    }
 
    /**
     * 遞增
     *
     * @param key   鍵
     * @param delta 要增加幾(大于0)
     * @return
     */
    public long incr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("遞增因子必須大于0");
        }
        return redisTemplate.opsForValue().increment(key, delta);
    }
 
    /**
     * 遞減
     *
     * @param key   鍵
     * @param delta 要減少幾(小于0)
     * @return
     */
    public long decr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("遞減因子必須大于0");
        }
        return redisTemplate.opsForValue().increment(key, -delta);
    }
 
    //================================Map=================================
 
    /**
     * HashGet
     *
     * @param key  鍵 不能為null
     * @param item 項(xiàng) 不能為null
     * @return 值
     */
    public Object hget(String key, String item) {
        return redisTemplate.opsForHash().get(key, item);
    }
 
    /**
     * 獲取hashKey對(duì)應(yīng)的所有鍵值
     *
     * @param key 鍵
     * @return 對(duì)應(yīng)的多個(gè)鍵值
     */
    public Map<Object, Object> hmget(String key) {
        return redisTemplate.opsForHash().entries(key);
    }
 
    /**
     * HashSet
     *
     * @param key 鍵
     * @param map 對(duì)應(yīng)多個(gè)鍵值
     * @return true 成功 false 失敗
     */
    public boolean hmset(String key, Map<String, Object> map) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
    /**
     * HashSet 并設(shè)置時(shí)間
     *
     * @param key  鍵
     * @param map  對(duì)應(yīng)多個(gè)鍵值
     * @param time 時(shí)間(秒)
     * @return true成功 false失敗
     */
    public boolean hmset(String key, Map<String, Object> map, long time) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
    /**
     * 向一張hash表中放入數(shù)據(jù),如果不存在將創(chuàng)建
     *
     * @param key   鍵
     * @param item  項(xiàng)
     * @param value 值
     * @return true 成功 false失敗
     */
    public boolean hset(String key, String item, Object value) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
    /**
     * 向一張hash表中放入數(shù)據(jù),如果不存在將創(chuàng)建
     *
     * @param key   鍵
     * @param item  項(xiàng)
     * @param value 值
     * @param time  時(shí)間(秒)  注意:如果已存在的hash表有時(shí)間,這里將會(huì)替換原有的時(shí)間
     * @return true 成功 false失敗
     */
    public boolean hset(String key, String item, Object value, long time) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
    /**
     * 刪除hash表中的值
     *
     * @param key  鍵 不能為null
     * @param item 項(xiàng) 可以使多個(gè) 不能為null
     */
    public void hdel(String key, Object... item) {
        redisTemplate.opsForHash().delete(key, item);
    }
 
    /**
     * 判斷hash表中是否有該項(xiàng)的值
     *
     * @param key  鍵 不能為null
     * @param item 項(xiàng) 不能為null
     * @return true 存在 false不存在
     */
    public boolean hHasKey(String key, String item) {
        return redisTemplate.opsForHash().hasKey(key, item);
    }
 
    /**
     * hash遞增 如果不存在,就會(huì)創(chuàng)建一個(gè) 并把新增后的值返回
     *
     * @param key  鍵
     * @param item 項(xiàng)
     * @param by   要增加幾(大于0)
     * @return
     */
    public double hincr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, by);
    }
 
    /**
     * hash遞減
     *
     * @param key  鍵
     * @param item 項(xiàng)
     * @param by   要減少記(小于0)
     * @return
     */
    public double hdecr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, -by);
    }
 
    //============================set=============================
 
    /**
     * 根據(jù)key獲取Set中的所有值
     *
     * @param key 鍵
     * @return
     */
    public Set<Object> sGet(String key) {
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
 
    /**
     * 根據(jù)value從一個(gè)set中查詢(xún),是否存在
     *
     * @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;
        }
    }
 
    /**
     * 將數(shù)據(jù)放入set緩存
     *
     * @param key    鍵
     * @param values 值 可以是多個(gè)
     * @return 成功個(gè)數(shù)
     */
    public long sSet(String key, Object... values) {
        try {
            return redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
 
    /**
     * 將set數(shù)據(jù)放入緩存
     *
     * @param key    鍵
     * @param time   時(shí)間(秒)
     * @param values 值 可以是多個(gè)
     * @return 成功個(gè)數(shù)
     */
    public long sSetAndTime(String key, long time, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().add(key, values);
            if (time > 0) {
                expire(key, time);
            }
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
 
    /**
     * 獲取set緩存的長(zhǎng)度
     *
     * @param key 鍵
     * @return
     */
    public long sGetSetSize(String key) {
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
 
    /**
     * 移除值為value的
     *
     * @param key    鍵
     * @param values 值 可以是多個(gè)
     * @return 移除的個(gè)數(shù)
     */
    public long setRemove(String key, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().remove(key, values);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    //===============================list=================================
 
    /**
     * 獲取list緩存的內(nèi)容
     *
     * @param key   鍵
     * @param start 開(kāi)始
     * @param end   結(jié)束  0 到 -1代表所有值
     * @return
     */
    public List<Object> lGet(String key, long start, long end) {
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
 
    /**
     * 獲取list緩存的長(zhǎng)度
     *
     * @param key 鍵
     * @return
     */
    public long lGetListSize(String key) {
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
 
    /**
     * 通過(guò)索引 獲取list中的值
     *
     * @param key   鍵
     * @param index 索引  index>=0時(shí), 0 表頭,1 第二個(gè)元素,依次類(lèi)推;index<0時(shí),-1,表尾,-2倒數(shù)第二個(gè)元素,依次類(lèi)推
     * @return
     */
    public Object lGetIndex(String key, long index) {
        try {
            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
 
    /**
     * 將list放入緩存
     *
     * @param key   鍵
     * @param value 值
     * @return
     */
    public boolean lSet(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
    /**
     * 將list放入緩存
     *
     * @param key   鍵
     * @param value 值
     * @param time  時(shí)間(秒)
     * @return
     */
    public boolean lSet(String key, Object value, long time) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
    /**
     * 將list放入緩存
     *
     * @param key   鍵
     * @param value 值
     * @return
     */
    public boolean lSet(String key, List<Object> value) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
    /**
     * 將list放入緩存
     *
     * @param key   鍵
     * @param value 值
     * @param time  時(shí)間(秒)
     * @return
     */
    public boolean lSet(String key, List<Object> value, long time) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
    /**
     * 根據(jù)索引修改list中的某條數(shù)據(jù)
     *
     * @param key   鍵
     * @param index 索引
     * @param value 值
     * @return
     */
    public boolean lUpdateIndex(String key, long index, Object value) {
        try {
            redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
    /**
     * 移除N個(gè)值為value
     *
     * @param key   鍵
     * @param count 移除多少個(gè)
     * @param value 值
     * @return 移除的個(gè)數(shù)
     */
    public long lRemove(String key, long count, Object value) {
        try {
            Long remove = redisTemplate.opsForList().remove(key, count, value);
            return remove;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
 
    /**
     * 模糊查詢(xún)獲取key值
     *
     * @param pattern
     * @return
     */
    public Set keys(String pattern) {
        return redisTemplate.keys(pattern);
    }
 
    /**
     * 使用Redis的消息隊(duì)列
     *
     * @param channel
     * @param message 消息內(nèi)容
     */
    public void convertAndSend(String channel, Object message) {
        redisTemplate.convertAndSend(channel, message);
    }
 
 
    //=========BoundListOperations 用法 start============
 
    /**
     * 將數(shù)據(jù)添加到Redis的list中(從右邊添加)
     *
     * @param listKey
     * @param timeout 有效時(shí)間
     * @param unit    時(shí)間類(lèi)型
     * @param values  待添加的數(shù)據(jù)
     */
    public void addToListRight(String listKey, long timeout, TimeUnit unit, Object... values) {
        //綁定操作
        BoundListOperations<String, Object> boundValueOperations = redisTemplate.boundListOps(listKey);
        //插入數(shù)據(jù)
        boundValueOperations.rightPushAll(values);
        //設(shè)置過(guò)期時(shí)間
        boundValueOperations.expire(timeout, unit);
    }
 
    /**
     * 根據(jù)起始結(jié)束序號(hào)遍歷Redis中的list
     *
     * @param listKey
     * @param start   起始序號(hào)
     * @param end     結(jié)束序號(hào)
     * @return
     */
    public List<Object> rangeList(String listKey, long start, long end) {
        //綁定操作
        BoundListOperations<String, Object> boundValueOperations = redisTemplate.boundListOps(listKey);
        //查詢(xún)數(shù)據(jù)
        return boundValueOperations.range(start, end);
    }
 
    /**
     * 彈出右邊的值 --- 并且移除這個(gè)值
     *
     * @param listKey
     */
    public Object rightPop(String listKey) {
        //綁定操作
        BoundListOperations<String, Object> boundValueOperations = redisTemplate.boundListOps(listKey);
        return boundValueOperations.rightPop();
    }
 
    //=========BoundListOperations 用法 End============
 
}

然后這是對(duì)應(yīng)的redis工具類(lèi),記得自己配置序列化反序列化,或者直接用默認(rèn)的。

另一種思路

涉及數(shù),redis,統(tǒng)計(jì),大家能想到什么?沒(méi)錯(cuò)--zset

可以采用一種滑動(dòng)窗口的思想,(key同上文)每次請(qǐng)求往滑動(dòng)窗口里存一條記錄,zset的score為這個(gè)接口請(qǐng)求時(shí)的時(shí)間戳,然后用當(dāng)前時(shí)間戳減去規(guī)定的限制時(shí)間的時(shí)間戳獲得一個(gè)窗口邊界,用zSetOperations.zCount(key, minScore, maxScore),請(qǐng)求在邊界窗口到現(xiàn)在的請(qǐng)求的數(shù)量,有多少條就是在限制的時(shí)間下發(fā)了多少次請(qǐng)求(比如過(guò)期時(shí)間是10分鐘,就是看過(guò)期時(shí)間到現(xiàn)在的請(qǐng)求的數(shù)量);這種方法個(gè)人感覺(jué)性能上不一定有提升,沒(méi)有進(jìn)行測(cè)試,不過(guò)這個(gè)方法對(duì)思維上的幫助和對(duì)rediszset用法的理解上都是挺有好處的,大家可以自己實(shí)踐一下。

結(jié)語(yǔ)

總之,冪等和接口防刷都是業(yè)務(wù)中常見(jiàn)的場(chǎng)景,redis,aop也是非常常用的技術(shù)棧,希望大家通過(guò)這個(gè)文章加深對(duì)業(yè)務(wù)、redis、springAOP的使用,后面考慮更ddd重構(gòu)老項(xiàng)目,mq等,不過(guò)時(shí)間不一定,敬請(qǐng)期待。

以上就是Redis+aop實(shí)現(xiàn)接口防刷(冪等)的解決方案的詳細(xì)內(nèi)容,更多關(guān)于Redis aop接口防刷的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Redis持久化解讀

    Redis持久化解讀

    Redis是一種內(nèi)存級(jí)數(shù)據(jù)庫(kù),提供高速讀寫(xiě)性能,但數(shù)據(jù)易失,它支持三種持久化方式:RDB(快照持久化)、AOF(追加文件持久化)和混合持久化,RDB通過(guò)快照將數(shù)據(jù)保存到磁盤(pán),AOF記錄所有寫(xiě)操作命令,混合持久化結(jié)合兩者優(yōu)點(diǎn)
    2025-01-01
  • Redis數(shù)據(jù)庫(kù)的應(yīng)用場(chǎng)景介紹

    Redis數(shù)據(jù)庫(kù)的應(yīng)用場(chǎng)景介紹

    這篇文章主要介紹了Redis數(shù)據(jù)庫(kù)的應(yīng)用場(chǎng)景介紹,本文講解了MySql+Memcached架構(gòu)的問(wèn)題、Redis常用數(shù)據(jù)類(lèi)型、Redis數(shù)據(jù)類(lèi)型應(yīng)用和實(shí)現(xiàn)方式、Redis實(shí)際應(yīng)用場(chǎng)景等內(nèi)容,需要的朋友可以參考下
    2015-06-06
  • Redis連接錯(cuò)誤的情況總結(jié)分析

    Redis連接錯(cuò)誤的情況總結(jié)分析

    這篇文章主要給大家總結(jié)介紹了關(guān)于Redis連接錯(cuò)誤的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-02-02
  • Redis教程(六):Sorted-Sets數(shù)據(jù)類(lèi)型

    Redis教程(六):Sorted-Sets數(shù)據(jù)類(lèi)型

    這篇文章主要介紹了Redis教程(六):Sorted-Sets數(shù)據(jù)類(lèi)型,本文講解了Sorted-Sets數(shù)據(jù)類(lèi)型概述、相關(guān)命令列表、命令使用示例、應(yīng)用范圍等內(nèi)容,需要的朋友可以參考下
    2015-04-04
  • redis實(shí)現(xiàn)排行榜的簡(jiǎn)單方法

    redis實(shí)現(xiàn)排行榜的簡(jiǎn)單方法

    這篇文章主要給大家介紹了關(guān)于redis實(shí)現(xiàn)排行榜的簡(jiǎn)單方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用redis具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-08-08
  • redis事務(wù)如何解決超賣(mài)問(wèn)題

    redis事務(wù)如何解決超賣(mài)問(wèn)題

    使用Redis事務(wù)可以有效避免超賣(mài)問(wèn)題,首先,通過(guò)MULTI命令開(kāi)啟事務(wù),將需要執(zhí)行的多個(gè)命令加入到事務(wù)中,然后通過(guò)EXEC命令提交事務(wù),確保這些命令可以一次性、順序地執(zhí)行,在事務(wù)執(zhí)行期間,Redis服務(wù)器不會(huì)執(zhí)行其他客戶(hù)端的命令
    2024-11-11
  • Reactor?WebFlux集成Redis處理緩存操作

    Reactor?WebFlux集成Redis處理緩存操作

    這篇文章主要為大家介紹了Reactor?WebFlux集成Redis處理緩存操作示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-09-09
  • 異步redis隊(duì)列實(shí)現(xiàn) 數(shù)據(jù)入庫(kù)的方法

    異步redis隊(duì)列實(shí)現(xiàn) 數(shù)據(jù)入庫(kù)的方法

    今天小編就為大家分享一篇異步redis隊(duì)列實(shí)現(xiàn) 數(shù)據(jù)入庫(kù)的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2019-10-10
  • Mac中Redis服務(wù)啟動(dòng)時(shí)錯(cuò)誤信息:NOAUTH Authentication required

    Mac中Redis服務(wù)啟動(dòng)時(shí)錯(cuò)誤信息:NOAUTH Authentication required

    這篇文章主要介紹了Mac中使用Redis服務(wù)啟動(dòng)時(shí)錯(cuò)誤信息:"NOAUTH Authentication required"問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-08-08
  • 淺談Redis緩存擊穿、緩存穿透、緩存雪崩的解決方案

    淺談Redis緩存擊穿、緩存穿透、緩存雪崩的解決方案

    這篇文章主要介紹了淺談Redis緩存擊穿、緩存穿透、緩存雪崩的解決方案,緩存是分布式系統(tǒng)中的重要組件,主要解決在高并發(fā)、大數(shù)據(jù)場(chǎng)景下,熱點(diǎn)數(shù)據(jù)訪(fǎng)問(wèn)的性能問(wèn)題,需要的朋友可以參考下
    2023-03-03

最新評(píng)論