在 quarkus 中检索客户端 IP 地址

正如标题所说,我需要帮助才能在 quarkus 资源中获取客户端的本地 IP ¿任何想法?

我已经尝试过了,但它不起作用

import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.container.ResourceContext;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

@Path("/auth")
@RequestScoped
public class AuthResource {

        @GET
    @Path("/getIpAddres")
    @Produces(MediaType.TEXT_PLAIN)
    public String getIpAddres(@Context HttpServletRequest request){
       String ip = request.getRemoteAddr();
       return ip;
    }
stack overflow retrieving client IP address in quarkus
原文答案

答案:

作者头像

Pretty simple. Instead of using @Context HttpServletRequest request. do this instead:

@Path("/auth")
@RequestScoped
public class AuthResource {

    @Inject
    RoutingContext context;
    
    @GET
    @Path("/getIpAddres")
    @Produces(MediaType.TEXT_PLAIN)
    public String getIpAddres(){
       String ip = context.request().host();
       return ip;
    }

I faced this problem myself. Cool thing about this RoutingContext is that this class can be injected into the Service layer, and it will have all the context of the ip, and other stuff, given that the Service was called by the Controller.

Hope this helps!