SpringBoot自定义注解(AOP)

本文介绍了如何在SpringBoot项目中通过自定义注解和AOP实现接口限频功能,防止重复提交。主要步骤包括创建自定义注解`@AccessLimit`,设置时间间隔和最大请求次数,然后编写切面类处理请求,利用Redis存储和检查请求次数,最终实现对特定接口的限频控制。
摘要由CSDN通过智能技术生成

SpringBoot自定义注解(AOP)

实例:做一个java后端限制重复提交的功能。
项目背景:SpringBoot Maven
思路:自定义标签,在接口(controller)加上注解@AccessLimit(参数:时间、最大次数)控制单位时间内的请求次数redis 的hashMap中存某用户或者sessionId请求的次数,有值则比较,超出最大次数提交失败;其他情况正常提交

应用(TopicController.java)

 	@AccessLimit(seconds = 1,maxCount = 1)  // 同一用户1秒内只允许一次请求
    @ApiOperation(value = "专题列表", notes="专题列表")
    @RequestMapping(value = "findTopics",method = RequestMethod.POST)
    public RestResponse findTopics(@RequestBody TopicQto qto) throws RestException {
        
        return RestResponse.success();
    }

引入依赖(pom.xml)

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
		</dependency>

AOP实体

package com.xxx域名xxx.xxx项目名xx.annotation;

import java.lang.annotation.*;

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AccessLimit {
    int seconds();
    int maxCount();
}

AOP切面类(具体逻辑实现doAround方法)

package com.xxxxx.xxxxx.aspect;

import com.xxxxx.xxxxx.base.response.RestResponse;
import com.xxxxx.xxxxx.security.BdpSecurityManager;
import com.xxxxx.xxxxx.security.model.User;
import com.xxxxx.xxxxx.util.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
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 javax.servlet.http.HttpSession;

@Aspect
@Component
@SuppressWarnings({"unused"})
@Slf4j
public class AccessLimitAspect {
    @Resource
    private RedisUtil redisUtil;
    @Pointcut("@annotation(com.xxxxx.xxxxx.annotation.AccessLimit)")
    public void annotationPointcut() {

    }

    @Before("annotationPointcut()")
    public void beforePointcut(JoinPoint joinPoint) {
        // 此处进入到方法前  可以实现一些业务逻辑
    }

    @Around("annotationPointcut()")
    public Object doAround(ProceedingJoinPoint joinPoint) {
        ServletRequestAttributes attributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        //获取request
        HttpServletRequest request = attributes.getRequest();
        HttpSession session = request.getSession();

        User user = BdpSecurityManager.getLoginedUser();

        //组装redis key 从redis中获取对应的值
        String key = "accessLimit";
        String item = session.getId();
        if(user != null){
            item = user.getId();
        }

        Object flag = redisUtil.hget(key,item);
        //如果redis中不存在对应的值,则执行原有的代码逻辑(插入文章操作)
        if (flag == null) {
            //redis设置key,value ,1秒有效
            redisUtil.hset(key, item,"",5);
            try {
                return joinPoint.proceed();
            } catch (Throwable throwable) {
                redisUtil.hdel(key, item);
                // RestResponse 为自定义的而返回对象
                return RestResponse.valid("204", "系统错误,请联系管理员!");
            }
        } else {
            //如果redis中存在对应的值,则证明重复提交,返回对应的信息
            log.info("{}:重复提交", key+"_"+item);
            return RestResponse.valid("204", "操作过于频繁,稍后请重新提交!");
        }
    }

    /**
     * 在切入点return内容之后切入内容(可以用来对处理返回值做一些加工处理)
     * @param joinPoint
     */
    @AfterReturning("annotationPointcut()")
    public void doAfterReturning(JoinPoint joinPoint) {
        
    }

}

如有错漏之处,敬请指正	
						——东东E
好的,关于SpringBoot自定义注解AOP的问题,我可以为您提供一些基本的介绍和示例代码。 首先,AOP(Aspect-Oriented Programming)是一种编程范式,它可以在不修改业务逻辑代码的情况下,对应用程序进行横切关注点的切面处理。而Spring AOP作为Spring框架的一部分,提供了一种基于代理模式的AOP实现。 在使用Spring AOP的过程中,自定义注解可以作为切点表达式的一部分,通过对注解的解析,实现对被注解的方法或类的切面处理。下面是一个简单的示例代码,演示如何通过自定义注解实现对方法的AOP处理: 首先,定义一个自定义注解: ```java @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface MyAnnotation { String value() default ""; } ``` 然后,在需要被拦截的方法上添加该注解: ```java @Service public class MyService { @MyAnnotation("myAnnotation") public void doSomething() { System.out.println("do something..."); } } ``` 接下来,使用AspectJ的@Aspect注解定义一个切面类,并在该类中定义一个切点,用于匹配被@MyAnnotation注解的方法: ```java @Aspect @Component public class MyAspect { @Pointcut("@annotation(com.example.demo.annotation.MyAnnotation)") public void myAnnotationPointcut() {} @Before("myAnnotationPointcut()") public void beforeMyAnnotation() { System.out.println("before myAnnotation..."); } } ``` 最后,启动SpringBoot应用程序,调用MyService的doSomething方法,就可以看到输出结果: ```java before myAnnotation... do something... ``` 以上就是一个简单的SpringBoot自定义注解AOP的示例。通过使用自定义注解,可以更加方便地实现对应用程序的切面处理。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值