在Java中统计接口调用次数可以通过多种方式实现,以下是使用Redis和Spring AOP两种方法的简要说明:
使用Redis统计接口调用次数
创建Redis计数器
使用Redis的`RAtomicLong`来记录接口调用次数。
使用`RLock`实现分布式锁,确保同一时刻只有一个服务可以更新计数器。
代码示例
```java
import org.redisson.RedissonClient;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClientBuilder;
import org.redisson.config.Config;
public class ApiCounter {
private RedissonClient redissonClient;
public ApiCounter(RedissonClient redissonClient) {
this.redissonClient = redissonClient;
}
public void recordApiCall(String apiName) {
String lockKey = "api-call-lock-" + apiName;
RLock lock = redissonClient.getLock(lockKey);
try {
lock.lock(); // 获取分布式锁
String counterKey = "api-call-counter-" + apiName;
RAtomicLong counter = redissonClient.getAtomicLong(counterKey);
counter.incrementAndGet(); // 接口调用次数加1
} finally {
lock.unlock(); // 释放分布式锁
}
}
}
使用Spring AOP统计接口调用次数
添加依赖
需要添加Spring AOP和AspectJ的依赖。
定义切面
使用`@Aspect`注解定义一个切面类,通过`@Pointcut`指定需要统计的方法。
在切面中,使用`@Before`或`@After`注解在方法执行前后进行调用次数的统计。
代码示例
```java
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class ApiVisitHistory {
private static final Logger log = LoggerFactory.getLogger(ApiVisitHistory.class);
@Pointcut("@annotation(com.cmict.oneconstruction.microservice.system.document.aspect.Action)")
public void apiCallPointcut() {
// 定义切点
}
@Before("apiCallPointcut()")
public void countApiCall(JoinPoint joinPoint) {
// 获取方法名
String methodName = joinPoint.getSignature().getName();
// 进行调用次数的统计,可以持久化到数据库或进行其他处理
log.info("API called: {} - Count: 1", methodName);
}
}
以上两种方法都可以有效地统计接口的调用次数,选择哪一种取决于具体的应用场景和需求。使用Redis的方法适合需要分布式协调的场景,而使用Spring AOP的方法则更加轻量级,易于集成到现有的Spring应用中