我正在使用 Jakarta EE 创建 Quarkus Web 应用程序。我有一些
@GET
和 @POST
方法,我想记录它们的用法。为此,我使用这样的拦截器:
@Loggable
@Interceptor
@Priority(1)
public class Logger {
@Inject
private LogService logService;
@AroundInvoke
public Object logMethodEntry(InvocationContext context) throws Exception {
Date currentDateAndTime = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String dateAndTime = dateFormat.format(currentDateAndTime);
String methodName = context.getTarget().getClass().getName() + "." + context.getMethod().getName();
String ipAddress = "";
Log log = new Log(dateAndTime, ipAddress, methodName);
logService.addLog(log);
return context.proceed();
}
}
此拦截器使用
@Loggable
注册到目标类。我的问题是,如何检索客户端 IP 地址?我尝试使用 HttpServletRequest
但出现依赖编译错误。
注意:这仅用于 @GET
和 @POST
方法,因此始终存在 HTTP 请求。
我已经弄清楚了,你不能使用
HttpServletRequest
来实现这一点,因为存在依赖错误。您可以只使用 IP 抓取外部 REST API 并从拦截器调用它,因为从拦截器调用该方法与从 JAX-RS 资源方法调用它是相同的。