一、自定义注解

import java.lang.annotation.retention;
import java.lang.annotation.target;

import static java.lang.annotation.elementtype.method;
import static java.lang.annotation.retentionpolicy.runtime;

/**
 * @author yang
 * @version 1.0
 * @date 2021/2/22 10:28
 */
@retention(runtime)
@target(method)
public @interface accesslimit {

    int seconds();

    int maxcount();

    boolean needlogin() default true;

}

二、定义拦截器

import com.alibaba.fastjson.json;
import com.mengxiangnongfu.payment.annotation.accesslimit;
import com.mengxiangnongfu.payment.commons.redisutil;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.context.annotation.configuration;
import org.springframework.stereotype.component;
import org.springframework.web.method.handlermethod;
import org.springframework.web.servlet.handler.handlerinterceptoradapter;

import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import java.io.outputstream;

/**
 * @author yang
 * @version 1.0
 * @date 2021/2/22 10:29
 */
@component
public class fangshuainterceptor extends handlerinterceptoradapter {

    @autowired
    private redisutil redisutil;

    @override
    public boolean prehandle(httpservletrequest request, httpservletresponse response, object handler) throws exception {
        //判断请求是否属于方法的请求
        if (handler instanceof handlermethod) {
            handlermethod hm = (handlermethod) handler;
            //获取方法中的注解,看是否有该注解
            accesslimit accesslimit = hm.getmethodannotation(accesslimit.class);
            if (accesslimit == null) {
                return true;
            }
            int seconds = accesslimit.seconds();
            int maxcount = accesslimit.maxcount();
            boolean login = accesslimit.needlogin();
            string key = "1";
            //如果需要登录
            if (login) {
                //获取登录的session进行判断
                //.....
                key += "" + "1";  //这里假设用户是1,项目中是动态获取的userid
            }

            //从redis中获取用户访问的次数
            integer count = (integer) redisutil.get(key);
            if (count == null) {
                //第一次访问
                redisutil.set(key, 1, seconds);
            } else if (count < maxcount) {
                //加1
                redisutil.incr(key, 1);
            } else {
                //超出访问次数
                render(response, "请求过于频繁~请稍后再试~"); //这里的codemsg是一个返回参数
                return false;
            }
        }

        return true;

    }

    private void render(httpservletresponse response, string cm) throws exception {
        response.setcontenttype("application/json;charset=utf-8");
        outputstream out = response.getoutputstream();
        string str = json.tojsonstring(cm);
        out.write(str.getbytes("utf-8"));
        out.flush();
        out.close();
    }

}

三、redis工具类

import lombok.extern.slf4j.slf4j;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.data.redis.core.redistemplate;
import org.springframework.stereotype.component;
import org.springframework.util.collectionutils;
import java.util.list;
import java.util.map;
import java.util.set;
import java.util.concurrent.timeunit;
/**
* @author yang
* @version 1.0
* @date 2020/11/29 17:06
*/
@component
@slf4j
public class redisutil {
@autowired
redistemplate redistemplate;
// =============================common============================
/**
* 指定缓存失效时间
*
* @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) {
log.error(key, e);
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) {
log.error(key, e);
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(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) {
log.error(key, e);
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) {
log.error(key, e);
return false;
}
}
/**
* 递增 适用场景: https://blog.csdn.net/y_y_y_k_k_k_k/article/details/79218254 高并发生成订单号,秒杀类的业务逻辑等。。
*
* @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) {
log.error(key, e);
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) {
log.error(key, e);
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) {
log.error(key, e);
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) {
log.error(key, e);
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) {
log.error(key, e);
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) {
log.error(key, e);
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) {
log.error(key, e);
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) {
log.error(key, e);
return 0;
}
}
/**
* 获取set缓存的长度
*
* @param key 键
* @return
*/
public long sgetsetsize(string key) {
try {
return redistemplate.opsforset().size(key);
} catch (exception e) {
log.error(key, e);
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) {
log.error(key, e);
return 0;
}
}
// ============================zset=============================
/**
* 根据key获取set中的所有值
*
* @param key 键
* @return
*/
public set<object> zsget(string key) {
try {
return redistemplate.opsforset().members(key);
} catch (exception e) {
log.error(key, e);
return null;
}
}
/**
* 根据value从一个set中查询,是否存在
*
* @param key   键
* @param value 值
* @return true 存在 false不存在
*/
public boolean zshaskey(string key, object value) {
try {
return redistemplate.opsforset().ismember(key, value);
} catch (exception e) {
log.error(key, e);
return false;
}
}
public boolean zsset(string key, object value, double score) {
try {
return redistemplate.opsforzset().add(key, value, 2);
} catch (exception e) {
log.error(key, e);
return false;
}
}
/**
* 将set数据放入缓存
*
* @param key    键
* @param time   时间(秒)
* @param values 值 可以是多个
* @return 成功个数
*/
public long zssetandtime(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) {
log.error(key, e);
return 0;
}
}
/**
* 获取set缓存的长度
*
* @param key 键
* @return
*/
public long zsgetsetsize(string key) {
try {
return redistemplate.opsforset().size(key);
} catch (exception e) {
log.error(key, e);
return 0;
}
}
/**
* 移除值为value的
*
* @param key    键
* @param values 值 可以是多个
* @return 移除的个数
*/
public long zsetremove(string key, object... values) {
try {
long count = redistemplate.opsforset().remove(key, values);
return count;
} catch (exception e) {
log.error(key, e);
return 0;
}
}
// ===============================list=================================
/**
* 获取list缓存的内容
*
* @param key   键
* @param start 开始 0 是第一个元素
* @param end   结束 -1代表所有值
* @return
* @取出来的元素 总数 end-start+1
*/
public list<object> lget(string key, long start, long end) {
try {
return redistemplate.opsforlist().range(key, start, end);
} catch (exception e) {
log.error(key, e);
return null;
}
}
/**
* 获取list缓存的长度
*
* @param key 键
* @return
*/
public long lgetlistsize(string key) {
try {
return redistemplate.opsforlist().size(key);
} catch (exception e) {
log.error(key, e);
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) {
log.error(key, e);
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) {
log.error(key, e);
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) {
log.error(key, e);
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) {
log.error(key, e);
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) {
log.error(key, e);
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) {
log.error(key, e);
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) {
log.error(key, e);
return 0;
}
}
}

四、pom文件

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

记得配置redis的连接

在需要拦截的地方加入注解即可@accesslimit(seconds = 5, maxcount = 1, needlogin = false) seconds重置访问频率时间 maxcount 最多请求次数

到此这篇关于springboot项目中接口防刷的完整代码的文章就介绍到这了,更多相关springboot接口防刷内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!