利用自定义注解,AOP + redis限制ip访问接口次数

首先来一个注解
 

package co.yiiu.module.bountyHunter.pay.wxpay.core;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import java.lang.annotation.*;

/**
 * Created date on 2018/12/10
 * Author Zy
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
@Order(Ordered.HIGHEST_PRECEDENCE)
public @interface RequestLimit {

    /**
     * 允许访问的次数,默认值MAX_VALUE
     */
    int count() default Integer.MAX_VALUE;

    /**
     * 时间段,单位为毫秒,默认值一分钟
     */
    long time() default 60000;
}

利用AOP前置增强做逻辑处理

package co.yiiu.module.bountyHunter.pay.wxpay.core;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
@Aspect
public class RequestLimitAop {


    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Before("within(@org.springframework.stereotype.Controller *) && @annotation(limit)")
    public void requestLimit(JoinPoint joinPoint, RequestLimit limit) throws RequestLimitException {
        try {
            Object[] args = joinPoint.getArgs();
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
            String ip = getIpAddress(request);
            String url = request.getRequestURL().toString();
            String key = "req_limit_".concat(url).concat("_").concat(ip);
            boolean checkResult = checkWithRedis(limit, key);
            if (!checkResult) {
                log.debug("requestLimited," + "[用户ip:{}],[访问地址:{}]超过了限定的次数[{}]次", ip, url, limit.count());
                throw new RequestLimitException("请求过于频繁,超出限制!");
            }
        } catch (RequestLimitException e) {
            throw e;
        } catch (Exception e) {
            log.error("RequestLimitAop.requestLimit has some exceptions: ", e);
        }
    }

    /**
     * 以redis实现请求记录
     *
     * @param limit
     * @param key
     * @return
     */
    private boolean checkWithRedis(RequestLimit limit, String key) {
        long count = stringRedisTemplate.opsForValue().increment(key, 1);
        if (count == 1) {
            stringRedisTemplate.expire(key, limit.time(), TimeUnit.MILLISECONDS);
        }
        if (count > limit.count()) {
            return false;
        }
        return true;
    }

    /**
     * 获取用户真实IP地址,不使用request.getRemoteAddr()的原因是有可能用户使用了代理软件方式避免真实IP地址,
     * 可是,如果通过了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP值
     *
     * @return ip
     */
   

private String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        log.info("x-forwarded-for ip: " + ip);
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值,第一个ip才是真实ip
            if( ip.indexOf(",")!=-1 ){
                ip = ip.split(",")[0];
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
            log.info("Proxy-Client-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
            log.info("WL-Proxy-Client-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
            log.info("HTTP_CLIENT_IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            log.info("HTTP_X_FORWARDED_FOR ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
            log.info("X-Real-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            log.info("getRemoteAddr ip: " + ip);
        }
        log.info("获取客户端ip: " + ip);
        return ip;
    }

}

利用AOP后置捕获web请求的异常

**

package co.yiiu.core.exception;

import co.yiiu.core.base.BaseController;
import co.yiiu.core.bean.Result;
import co.yiiu.module.user.pojo.User;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

 
@Slf4j
@Aspect
@Component
public class WebExceptionAspect extends BaseController{

    private Exception e;
 
 //切入点
    @Pointcut("execution(* co.yiiu.web.bountyHunter..*.*(..))")
    private void bountyHunterPointcut() {
    }
 
    /**
     * 拦截web层异常,记录异常日志,并返回友好信息到前端
     *
     * @param e
     *            异常对象
     */
    @AfterThrowing(pointcut = "bountyHunterPointcut()", throwing = "e")
    public void handleThrowing(JoinPoint joinPoint,Exception e) {
        User user = getUserFromSession();
        this.e = e;
        //e.printStackTrace();
        if (null != user){
            log.error("发现异常!操作用户手机号:"+user.getMobile());
        }
        log.error("发现异常!方法:"+  joinPoint.getSignature().getName()+"--->异常",e);
        //这里输入友好性信息
        if (!StringUtils.isEmpty(e.getMessage())){
            log.error("异常",e.getMessage());
            writeContent(500,e.getMessage());
        }else {
            writeContent(500,"十分抱歉,出现异常!程序猿小哥正在紧急抢修...");
        }
    }

    /**
     * 将内容输出到浏览器
     *
     * @param content
     *            输出内容
     */
    public static void writeContent(Integer code,String content) {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getResponse();
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Type", "text/json;charset=UTF-8");
        response.setHeader("icop-content-type", "exception");
        PrintWriter writer = null;
        JsonGenerator jsonGenerator = null;
        try {
            writer = response.getWriter();
            jsonGenerator = (new ObjectMapper()).getFactory().createGenerator(writer);
            jsonGenerator.writeObject(Result.error(code,content));
        } catch (IOException e1) {
            e1.printStackTrace();
        }finally {
            writer.flush();
            writer.close();
        }
    }

}


现在我们进行简单的测试

  @PostMapping("/test")
    @RequestLimit(count = 2)
    @ResponseBody
    public Result test(){


        return Result.success();
    }


postman测试

postman测试
控制台打印信息

在这里插入图片描述

--------------------- 
作者:IT界的奇葩 
来源:CSDN 
原文:https://blog.csdn.net/a309220728/article/details/84937630 
版权声明:本文为博主原创文章,转载请附上博文链接!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
### 回答1: 首先,您需要在 Spring Boot 应用中开启 AOP 支持。这可以在应用的主类上通过添加 `@EnableAspectJAutoProxy` 注解实现。 然后,您可以创建一个切面类来实现防刷逻辑。切面类中可以包含多个通知方法,每个通知方法都可以使用不同的注解来指定执行时机。例如,您可以使用 `@Before` 注解来在目标方法执行之前执行通知方法。 下面是一个示例切面类,该类使用了 `@Before` 注解实现防刷逻辑: ```java @Aspect @Component public class AntiBrushAspect { @Before("@annotation(antiBrush)") public void doBefore(JoinPoint joinPoint, AntiBrush antiBrush) { // 获取目标方法的参数 Object[] args = joinPoint.getArgs(); // 执行防刷逻辑 // ... } } ``` 接下来,您可以创建一个注解类来标记需要进行防刷检查的方法。 ```java @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface AntiBrush { } ``` 最后,在需要进行防刷检查的方法上添加 `@AntiBrush` 注解即可。例如: ```java @AntiBrush @GetMapping("/test") public String test() { // 省略其他代码 } ``` 这样,在请求 `/test` 接口时,切面类的通知方法就会被执行,从而实现防刷功能。 ### 回答2: 实现一个Spring Boot接口防刷的切面和注解操作如下: 1. 创建一个自定义注解 `@AccessLimit`,用于标记需要进行接口防刷的方法。 ```java @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface AccessLimit { int limit() default 10; // 设置访问限制次数,默认为10次 int seconds() default 60; // 设置时间窗口,默认为60秒 } ``` 2. 创建一个自定义切面类 `AccessLimitAspect`,用于拦截带有 `@AccessLimit` 注解的方法,并进行接口防刷的逻辑判断。 ```java @Aspect @Component public class AccessLimitAspect { @Autowired private HttpServletRequest request; @Around("@annotation(accessLimit)") public Object doAccessLimit(ProceedingJoinPoint joinPoint, AccessLimit accessLimit) throws Throwable { // 获取请求的 IP 地址和请求路径 String ip = getIpAddress(request); String url = request.getRequestURL().toString(); // 根据 IP 地址和请求路径限制访问次数 String key = "access:" + ip + ":" + url; int limit = accessLimit.limit(); int seconds = accessLimit.seconds(); // 设置 Redis 计数器 RedisAtomicInteger counter = new RedisAtomicInteger(key, RedisServerConfig.redisTemplate.getConnectionFactory()); // 定义初始访问次数 if (counter.get() == 0) { counter.set(1); counter.expire(seconds, TimeUnit.SECONDS); } else { counter.incrementAndGet(); } // 判断访问次数是否超过限制 if (counter.get() > limit) { // 超过访问次数限制,抛出自定义异常信息 throw new RuntimeException("请求过于频繁,请稍后再试"); } // 执行原有方法逻辑 Object result = joinPoint.proceed(); return result; } // 获取请求的 IP 地址 public String getIpAddress(HttpServletRequest request) { String ip = request.getHeader("X-Forwarded-For"); if (StringUtils.isNotEmpty(ip) && !"unknown".equalsIgnoreCase(ip)) { // 多次反向代理后会有多个 IP 值,第一个为真实 IP int index = ip.indexOf(","); if (index != -1) { return ip.substring(0, index); } else { return ip; } } ip = request.getHeader("X-Real-IP"); if (StringUtils.isNotEmpty(ip) && !"unknown".equalsIgnoreCase(ip)) { return ip; } return request.getRemoteAddr(); } } ``` 3. 在需要进行接口防刷的方法上添加 `@AccessLimit` 注解。 ```java @RestController public class ExampleController { @AccessLimit(limit = 5, seconds = 60) // 限制访问次数为5次,在60秒时间窗口内 @GetMapping("/example") public String example() { return "Success"; } } ``` 通过以上操作,即可实现对指定接口的防刷控制,当超过指定次数时,会抛出自定义异常,可以根据需要进行处理。注意,以上代码还需在Spring Boot启动类上加上 `@EnableAspectJAutoProxy` 注解,以开启AOP自动代理功能。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值