当前位置: 代码网 > it编程>数据库>Redis > Redis+aop实现接口防刷(幂等)的解决方案

Redis+aop实现接口防刷(幂等)的解决方案

2024年05月15日 Redis 我要评论
幂等和接口防刷概念这两者其实是属于不同的场景但是在一些情况下,实现方式上有异曲同工之妙。防刷顾名思义,想让某个接口某个人在某段时间内只能请求n次。一般是对一些不发人员用脚本对接口进行大量请求,或者说利

幂等和接口防刷概念

这两者其实是属于不同的场景但是在一些情况下,实现方式上有异曲同工之妙。

防刷

顾名思义,想让某个接口某个人在某段时间内只能请求n次。一般是对一些不发人员用脚本对接口进行大量请求,或者说利用脚本进行秒杀。

幂等

幂等的数学概念

幂等是源于一种数学概念。其主要有两个定义

如果在一元运算中,x 为某集合中的任意数,如果满足 f(x) = f(f(x)) ,那么该 f 运算具有幂等性,比如绝对值运算 abs(a) = abs(abs(a)) 就是幂等性函数。

如果在二元运算中,x 为某集合中的任意数,如果满足 f(x,x) = x,前提是 f 运算的两个参数均为 x,那么我们称 f 运算也有幂等性,比如求大值函数 max(x,x) = x 就是幂等性函数。

幂等性在开发中的概念

在数学中幂等的概念或许比较抽象,但是在开发中幂等性是极为重要的。简单来说,对于同一个系统,在同样条件下,一次请求和重复多次请求对资源的影响是一致的,就称该操作为幂等的。比如说如果有一个接口是幂等的,当传入相同条件时,其效果必须是相同的。

特别是对于现在分布式系统下的 rpc 或者 restful 接口互相调用的情况下,很容易出现由于网络错误等等各种原因导致调用的时候出现异常而需要重试,这时候就必须保证接口的幂等性,否则重试的结果将与第一次调用的结果不同,如果有个接口的调用链 a->b->c->d->e,在 d->e 这一步发生异常重试后返回了错误的结果,a,b,c也会受到影响,这将会是灾难性的。

为什么要进行接口防刷(幂等)

在高并发场景下,可能会因为网络或者服务器原因,造成延迟,具体来说就是,一个人点了一下,没反应,又点了一下,但其实这两次都发送请求成功了,这样就可能造成数据不一致问题,同时还对资源进行浪费。同时就是有可能会有人用脚本大量访问你的接口,造成资源崩溃。

解决方案

防刷

防刷的解决一般是不会用后端写逻辑解决,一般可以在请求到nginx的时候就可以进行判断,然后加入黑名单,不需要请求到后端就能拦截,阿里的sentinel也可以解决这个问题

幂等

因为幂等更多是在高并发和分布式场景下,所以幂等更多是用redis做,毕竟redis一般就是用来解决分布式问题的

实战

话不多说直接上代码

首先架构是用的xfg的ddd脚手架,架构方面就不展开讲了,我个人是写在触发器层的,因为逻辑需要对controller进行操作,如果写在别的层感觉很怪,如果写在domain层应该也是合理的,毕竟所有层都对domain有依赖,而且domain层本身是用来实现业务规则的。(这不是重点,想听ddd,我理解深一点以后单独讲)

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

这个是对注解的定义,规定了时间范围和次数,默认10秒内只能进行1次访问

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(){}
    //规定必须在上面路径下同时方法上带@requestlimit注解
    @around("limitpointcut()&&@annotation(requestlimit)")
    public object before(proceedingjoinpoint proceedingjoinpoint, requestlimit requestlimit) throws throwable {
        log.info("进入aop中");
        //根据注解获取注解上的值
       int limitcount = requestlimit.count();
        system.out.println(limitcount+"limit");
       long time = requestlimit.time();
       //根据servletrequestattributes获取当前请求信息
        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("请不要频繁操作");
                }
                   redisutil.incr(key,1l);
            }
            else{
                redisutil.set(key,1,time);
            }
 
        }
        return proceedingjoinpoint.proceed();
    }
}

具体逻辑就是当用户发过来请求,(前提是controller上有对应注解)进入这个接口,然后根据ip和请求路径作为key进行判断,如果此时redis有key,但是key的value不超过默认次数,就放行,如果没有key,就根据其创建一个key设置过期时间为注解上的时间,然后放行,如果value过默认次数,就会被拦截,然后抛出一个自定义异常,可以在controller里捕获并提示前端。为什么用ip+url,因为有些网站是允许账号多端同时使用的,这就会对一些用户产生不友好的体验,当然一般情况下用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里存入数据
     *
     * @param key  键
     * @param member 值
     * @param score 分数
     * @return
     */
    public boolean addtozset(string key, string member, double score) {
       return boolean.true.equals(redistemplate.opsforzset().add(key, member, score));
    }
    /**
     * 指定缓存失效时间
     *
     * @param key  键
     * @param time 时间(秒)
     * @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;
        }
    }
 
    /**
     * 根据key 获取过期时间
     *
     * @param key 键 不能为null
     * @return 时间(秒) 返回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 可以传一个值 或多个
     */
    @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;
        }
    }
 
    /**
     * 普通缓存放入并设置时间
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期
     * @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    锁住的时长。如果超时未解锁,视为加锁线程死亡,其他线程可夺取锁
     * @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 项 不能为null
     * @return 值
     */
    public object hget(string key, string item) {
        return redistemplate.opsforhash().get(key, item);
    }
 
    /**
     * 获取hashkey对应的所有键值
     *
     * @param key 键
     * @return 对应的多个键值
     */
    public map<object, object> hmget(string key) {
        return redistemplate.opsforhash().entries(key);
    }
 
    /**
     * hashset
     *
     * @param key 键
     * @param map 对应多个键值
     * @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 并设置时间
     *
     * @param key  键
     * @param map  对应多个键值
     * @param time 时间(秒)
     * @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表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @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表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @param time  时间(秒)  注意:如果已存在的hash表有时间,这里将会替换原有的时间
     * @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 项 可以使多个 不能为null
     */
    public void hdel(string key, object... item) {
        redistemplate.opsforhash().delete(key, item);
    }
 
    /**
     * 判断hash表中是否有该项的值
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return true 存在 false不存在
     */
    public boolean hhaskey(string key, string item) {
        return redistemplate.opsforhash().haskey(key, item);
    }
 
    /**
     * hash递增 如果不存在,就会创建一个 并把新增后的值返回
     *
     * @param key  键
     * @param item 项
     * @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 项
     * @param by   要减少记(小于0)
     * @return
     */
    public double hdecr(string key, string item, double by) {
        return redistemplate.opsforhash().increment(key, item, -by);
    }
 
    //============================set=============================
 
    /**
     * 根据key获取set中的所有值
     *
     * @param key 键
     * @return
     */
    public set<object> 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;
        }
    }
 
    /**
     * 将数据放入set缓存
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sset(string key, object... values) {
        try {
            return redistemplate.opsforset().add(key, values);
        } catch (exception e) {
            e.printstacktrace();
            return 0;
        }
    }
 
    /**
     * 将set数据放入缓存
     *
     * @param key    键
     * @param time   时间(秒)
     * @param values 值 可以是多个
     * @return 成功个数
     */
    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缓存的长度
     *
     * @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 值 可以是多个
     * @return 移除的个数
     */
    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缓存的内容
     *
     * @param key   键
     * @param start 开始
     * @param end   结束  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缓存的长度
     *
     * @param key 键
     * @return
     */
    public long lgetlistsize(string key) {
        try {
            return redistemplate.opsforlist().size(key);
        } catch (exception e) {
            e.printstacktrace();
            return 0;
        }
    }
 
    /**
     * 通过索引 获取list中的值
     *
     * @param key   键
     * @param index 索引  index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
     * @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  时间(秒)
     * @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  时间(秒)
     * @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;
        }
    }
 
    /**
     * 根据索引修改list中的某条数据
     *
     * @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个值为value
     *
     * @param key   键
     * @param count 移除多少个
     * @param value 值
     * @return 移除的个数
     */
    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;
        }
    }
 
    /**
     * 模糊查询获取key值
     *
     * @param pattern
     * @return
     */
    public set keys(string pattern) {
        return redistemplate.keys(pattern);
    }
 
    /**
     * 使用redis的消息队列
     *
     * @param channel
     * @param message 消息内容
     */
    public void convertandsend(string channel, object message) {
        redistemplate.convertandsend(channel, message);
    }
 
 
    //=========boundlistoperations 用法 start============
 
    /**
     * 将数据添加到redis的list中(从右边添加)
     *
     * @param listkey
     * @param timeout 有效时间
     * @param unit    时间类型
     * @param values  待添加的数据
     */
    public void addtolistright(string listkey, long timeout, timeunit unit, object... values) {
        //绑定操作
        boundlistoperations<string, object> boundvalueoperations = redistemplate.boundlistops(listkey);
        //插入数据
        boundvalueoperations.rightpushall(values);
        //设置过期时间
        boundvalueoperations.expire(timeout, unit);
    }
 
    /**
     * 根据起始结束序号遍历redis中的list
     *
     * @param listkey
     * @param start   起始序号
     * @param end     结束序号
     * @return
     */
    public list<object> rangelist(string listkey, long start, long end) {
        //绑定操作
        boundlistoperations<string, object> boundvalueoperations = redistemplate.boundlistops(listkey);
        //查询数据
        return boundvalueoperations.range(start, end);
    }
 
    /**
     * 弹出右边的值 --- 并且移除这个值
     *
     * @param listkey
     */
    public object rightpop(string listkey) {
        //绑定操作
        boundlistoperations<string, object> boundvalueoperations = redistemplate.boundlistops(listkey);
        return boundvalueoperations.rightpop();
    }
 
    //=========boundlistoperations 用法 end============
 
}

然后这是对应的redis工具类,记得自己配置序列化反序列化,或者直接用默认的。

另一种思路

涉及数,redis,统计,大家能想到什么?没错--zset

可以采用一种滑动窗口的思想,(key同上文)每次请求往滑动窗口里存一条记录,zset的score为这个接口请求时的时间戳,然后用当前时间戳减去规定的限制时间的时间戳获得一个窗口边界,用zsetoperations.zcount(key, minscore, maxscore),请求在边界窗口到现在的请求的数量,有多少条就是在限制的时间下发了多少次请求(比如过期时间是10分钟,就是看过期时间到现在的请求的数量);这种方法个人感觉性能上不一定有提升,没有进行测试,不过这个方法对思维上的帮助和对rediszset用法的理解上都是挺有好处的,大家可以自己实践一下。

结语

总之,幂等和接口防刷都是业务中常见的场景,redis,aop也是非常常用的技术栈,希望大家通过这个文章加深对业务、redis、springaop的使用,后面考虑更ddd重构老项目,mq等,不过时间不一定,敬请期待。

以上就是redis+aop实现接口防刷(幂等)的解决方案的详细内容,更多关于redis aop接口防刷的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com