java统计接口调用次数
时间: 2023-07-30 19:10:53 浏览: 126
要统计Java接口的调用次数,可以使用AOP(面向切面编程)技术,在接口调用时拦截请求,并记录接口调用次数。
具体实现步骤如下:
1. 定义一个注解,用于标记需要统计调用次数的接口方法。
例如:
```java
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Count {
}
```
2. 创建一个切面类,使用@Aspect注解标记,并在类中定义一个切点,用于匹配被@Count注解标记的方法。
例如:
```java
@Aspect
@Component
public class CountAspect {
private Map<String, Integer> countMap = new ConcurrentHashMap<>();
@Pointcut("@annotation(com.example.demo.annotation.Count)")
public void countPointcut() {
}
@Around("countPointcut()")
public Object countAround(ProceedingJoinPoint joinPoint) throws Throwable {
String methodName = joinPoint.getSignature().getName();
String className = joinPoint.getSignature().getDeclaringTypeName();
String key = className + "." + methodName;
Integer count = countMap.get(key);
if (count == null) {
count = 1;
} else {
count++;
}
countMap.put(key, count);
Object result = joinPoint.proceed();
return result;
}
}
```
在上述代码中,我们使用了ConcurrentHashMap来存储每个接口方法的调用次数,初始值为1,每次调用自增1。
3. 在需要统计调用次数的接口方法上添加@Count注解。
例如:
```java
@RestController
@RequestMapping("/demo")
public class DemoController {
@Autowired
private DemoService demoService;
@Count
@GetMapping("/hello")
public String hello() {
return "hello";
}
@GetMapping("/count")
public Map<String, Integer> count() {
return demoService.getCountMap();
}
}
```
在上述代码中,我们在hello()方法上添加了@Count注解,表示需要统计该方法的调用次数。
4. 创建一个服务类,用于获取调用次数的统计结果。
例如:
```java
@Service
public class DemoService {
@Autowired
private CountAspect countAspect;
public Map<String, Integer> getCountMap() {
return countAspect.getCountMap();
}
}
```
在上述代码中,我们通过@Autowired注解注入了CountAspect切面类,并通过该类的getCountMap()方法获取到统计结果。
最后,启动应用程序,在浏览器中访问/hello接口,多次刷新页面,然后访问/count接口,即可获取到接口方法调用次数的统计结果。