SpringBoot项目中统计所有Controller中的方法

对接口方法进行抽象 

@Data
public class ControllerMethodItem {
	public String controllerName;
    public String methodName;
    public String requestType;
    public String requestUrl;
    public Class<?>[] methodParmaTypes;    
    
    public RequestToMethodItem(String requestUrl, String requestType, String controllerName, String requestMethodName, Class<?>[] methodParmaTypes){
        this.requestUrl = requestUrl;
        this.requestType = requestType;
        this.controllerName = controllerName;
        this.methodName = requestMethodName;
        this.methodParmaTypes = methodParmaTypes;
    }
}

获取Controller类型的Bean

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.condition.RequestMethodsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author be.insighted
 * @Date 2022/5/7 12:09
 */
@RestController
@Slf4j
public class ListAllMethodController {
    @Autowired
    private WebApplicationContext applicationContext;

    @GetMapping("list/all/methods")
    public Ret getAllUrl() {
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        // 获取url与类和方法的对应信息
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();

        List<Map<String, String>> list = new ArrayList<>();
        for (Map.Entry<RequestMappingInfo, HandlerMethod> m : map.entrySet()) {
            Map<String, String> map1 = new HashMap<>();
            RequestMappingInfo info = m.getKey();
            HandlerMethod method = m.getValue();
            //获取当前方法所在类名
            Class<?> bean = method.getBeanType();
            log.info("当前类名称:{}, 精简名称:{}", bean.toString(), bean.toString().substring(bean.toString().lastIndexOf(".") + 1));
            //使用反射获取当前类注解内容
            Api api = bean.getAnnotation(Api.class);
            log.info("api: {}", api == null ? "没有类相关描述" : api);
            RequestMapping requestMapping = bean.getAnnotation(RequestMapping.class);

            Annotation[] annotations = bean.getAnnotations();
            for (Annotation a : annotations) {
                log.info("注解全称: {}", a);
            }
            if (requestMapping != null) {
                String[] value = requestMapping.value();
                map1.put("parent", value[0]);
            }
            //获取方法上注解以及注解值
            ApiOperation methodAnnotation = method.getMethodAnnotation(ApiOperation.class);
            if (methodAnnotation != null) {
                String notes = methodAnnotation.notes();
                log.info("注释: {}", notes);
            } else {
                log.info("当前方法没有相关注释");
            }
            PatternsRequestCondition p = info.getPatternsCondition();
            for (String url : p.getPatterns()) {
                map1.put("url", url);
            }
            map1.put("className", method.getMethod().getDeclaringClass().getName()); // 类名
            map1.put("method", method.getMethod().getName()); // 方法名
            RequestMethodsRequestCondition methodsCondition = info.getMethodsCondition();
            for (RequestMethod requestMethod : methodsCondition.getMethods()) {
                map1.put("type", requestMethod.toString());
            }

            list.add(map1);
        }
        return Ret.success(list);
    }
}
{
  "code": 0,
  "message": "请求成功!",
  "data": [
    {
      "method": "saveLeaseUseRange",
      "className": "com.hkwl.hkboot.smp.controller.LeaseUseRangeController",
      "type": "POST",
      "url": "/lease/use/range/save"
    },
    {
      "method": "getAllUrl",
      "className": "com.hkwl.hkboot.smp.controller.ListAllMethodController",
      "type": "GET",
      "url": "/list/all/methods"
    },
    {
      "method": "downloadExcelTemplate",
      "className": "com.hkwl.hkboot.smp.controller.NioFileTransmitController",
      "type": "GET",
      "url": "/nio/download"
    },
    {
      "parent": "/promethues/",
      "method": "online",
      "className": "com.hkwl.hkboot.smp.controller.PromethuesController",
      "url": "/promethues/online"
    },
    {
      "parent": "/promethues/",
      "method": "testIsUsable",
      "className": "com.hkwl.hkboot.smp.controller.PromethuesController",
      "type": "GET",
      "url": "/promethues/testIsUsable"
    },
    {
      "parent": "/promethues/",
      "method": "testIsCore",
      "className": "com.hkwl.hkboot.smp.controller.PromethuesController",
      "type": "GET",
      "url": "/promethues/testIsCore"
    },
    {
      "method": "getPictureInfo",
      "className": "com.hkwl.hkboot.smp.controller.ReadPictureInfoController",
      "type": "GET",
      "url": "/picture/info"
    },
    {
      "method": "test",
      "className": "com.hkwl.hkboot.smp.controller.SmpPcConcController",
      "type": "POST",
      "url": "/test"
    },
    {
      "method": "wrong",
      "className": "com.hkwl.hkboot.smp.controller.SmpPcConcController",
      "type": "GET",
      "url": "/threadLocal/wrong"
    },
    {
      "method": "correct",
      "className": "com.hkwl.hkboot.smp.controller.SmpPcConcController",
      "type": "GET",
      "url": "/threadLocal/correct"
    },
    {
      "method": "concurrentHashMapWrong",
      "className": "com.hkwl.hkboot.smp.controller.SmpPcConcController",
      "type": "GET",
      "url": "/concurrentHashMap/wrong"
    },
    {
      "method": "concurrentHashMapCorrect",
      "className": "com.hkwl.hkboot.smp.controller.SmpPcConcController",
      "type": "GET",
      "url": "/concurrentHashMap/correct"
    },
    {
      "method": "testDefaultAccess",
      "className": "com.hkwl.hkboot.smp.controller.SmpPcConcController",
      "type": "POST",
      "url": "/test/default/access"
    },
    {
      "method": "updateFileName",
      "className": "com.hkwl.hkboot.smp.controller.UpdateFileNameController",
      "type": "POST",
      "url": "/file/name/update"
    },
    {
      "method": "updateFileNameRegex",
      "className": "com.hkwl.hkboot.smp.controller.UpdateFileNameController",
      "type": "POST",
      "url": "/file/name/regex/update"
    },
    {
      "parent": "/swagger-resources",
      "method": "securityConfiguration",
      "className": "springfox.documentation.swagger.web.ApiResourceController",
      "url": "/swagger-resources/configuration/security"
    },
    {
      "parent": "/swagger-resources",
      "method": "uiConfiguration",
      "className": "springfox.documentation.swagger.web.ApiResourceController",
      "url": "/swagger-resources/configuration/ui"
    },
    {
      "parent": "/swagger-resources",
      "method": "swaggerResources",
      "className": "springfox.documentation.swagger.web.ApiResourceController",
      "url": "/swagger-resources"
    },
    {
      "method": "apiSorts",
      "className": "com.github.xiaoymin.swaggerbootstrapui.web.SwaggerBootstrapUiController",
      "type": "GET",
      "url": "/v2/api-docs-ext"
    },
    {
      "parent": "/swagger-resources-ext",
      "method": "swaggerResources",
      "className": "com.github.xiaoymin.swaggerbootstrapui.web.SwaggerBootstrapUiResourceExtController",
      "url": "/swagger-resources-ext"
    },
    {
      "parent": "${server.error.path:${error.path:/error}}",
      "method": "error",
      "className": "org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController",
      "url": "/error"
    },
    {
      "parent": "${server.error.path:${error.path:/error}}",
      "method": "errorHtml",
      "className": "org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController",
      "url": "/error"
    }
  ]
}

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用Spring AOP和Scheduled定时任务来实现统计所有接口每秒钟请求次数的功能。具体实现步骤如下: 1. 定义一个切面类,使用@Aspect注解标识该类为切面类,并使用@Pointcut注解定义切入点表达式,表示对所有Controller接口进行拦截。 ```java @Aspect @Component public class RequestCountAspect { private static final int INTERVAL = 1; // 时间间隔,单位:秒 private Map<String, Integer> requestCountMap = new ConcurrentHashMap<>(); // 存储接口请求次数 @Pointcut("execution(public * com.example.controller..*.*(..))") public void requestCount() {} } ``` 2. 在切面类定义一个计时器,使用Scheduled注解标识方法为定时任务,在每个时间间隔结束时打印接口每秒钟请求次数,并清空计数器。 ```java @Aspect @Component public class RequestCountAspect { private static final int INTERVAL = 1; // 时间间隔,单位:秒 private Map<String, Integer> requestCountMap = new ConcurrentHashMap<>(); // 存储接口请求次数 private Map<String, Integer> requestCountPerSecondMap = new ConcurrentHashMap<>(); // 存储每秒钟接口请求次数 private int count = 0; // 计数器 @Pointcut("execution(public * com.example.controller..*.*(..))") public void requestCount() {} @Around("requestCount()") public Object around(ProceedingJoinPoint joinPoint) throws Throwable { // 获取方法名 String methodName = joinPoint.getSignature().getName(); // 统计接口请求次数 if (requestCountMap.containsKey(methodName)) { requestCountMap.put(methodName, requestCountMap.get(methodName) + 1); } else { requestCountMap.put(methodName, 1); } count++; // 计数器加1 // 执行方法 Object result = joinPoint.proceed(); return result; } @Scheduled(fixedRate = INTERVAL * 1000) public void printRequestCountPerSecond() { for (Map.Entry<String, Integer> entry : requestCountMap.entrySet()) { String methodName = entry.getKey(); int requestCount = entry.getValue(); requestCountPerSecondMap.put(methodName, requestCount / INTERVAL); // 计算每秒钟请求次数 } System.out.println(requestCountPerSecondMap); requestCountMap.clear(); // 清空计数器和存储接口请求次数的Map requestCountPerSecondMap.clear(); count = 0; } } ``` 3. 在Spring Boot应用启动类添加@EnableScheduling注解启用定时任务功能。 ```java @SpringBootApplication @EnableScheduling public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 需要注意的是,以上代码仅为示例代码,具体实现需要根据实际业务需求进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值