【问题标题】:micronaut redirect httprequest to different servicemicronaut 将 httprequest 重定向到不同的服务
【发布时间】:2020-05-25 14:40:20
【问题描述】:

在 micronaut 中有声明式客户端:

@Client("http://localhost:5000")
public interface ServiceB {

    @Get("/ping")
    HttpResponse ping(HttpRequest httpRequest);
}

在我的controller 类中,我想将传入请求重定向到ServiceB

@Controller("/api")
public class ServiceA {

    @Inject
    private ServiceB serviceB;

    @Get("/ping)
    HttpResponse pingOtherService(HttpRequest httpRequest){
        return serviceB.ping(httpRequest)
    }

}

但是,由于请求中编码的信息,ServiceB 似乎永远不会收到请求。如何将请求从ServiceA 转发到ServiceB

【问题讨论】:

    标签: micronaut micronaut-client


    【解决方案1】:

    客户端不能直接发送和HttpRequest。他将根据客户端的参数构建一个。

    我尝试在客户端的主体中发送重定向请求,但出现堆栈溢出错误:jackson can't convert it to string.

    不幸的是,您无法更改请求中的 URI 以将其发回,没有 HttpRequest 实现在 URI 上具有设置器。

    如果您真的想发送完整的请求(标​​头、正文、参数...),您可以尝试配置代理。

    否则,如果您不必传递完整的请求,您可以通过客户端传递您需要的内容:

    客户端示例:

    @Client("http://localhost:8080/test")
    public interface RedirectClient {
    
      @Get("/redirect")
      String redirect(@Header(value = "test") String header);
    
    }
    

    控制器:

    @Slf4j
    @Controller("/test")
    public class RedirectController {
    
      @Inject
      private RedirectClient client;
    
      @Get
      public String redirect(HttpRequest request){
        log.info("headers : {}", request.getHeaders().findFirst("test"));
        return client.redirect(request.getHeaders().get("test"));
      }
    
      @Get("/redirect")
      public String hello(HttpRequest request){
        log.info("headers : {}", request.getHeaders().findFirst("test"));
        return "Hello from redirect";
      }
    }
    

    我是为一个标头做的,但你可以用正文(如果不是 GET 方法)、请求参数等等来做。

    【讨论】:

    • 我认为客户端会在ServiceA 中调用pingOtherService 方法,您将在那里陷入无限循环。我从问题中假设ServiceA 在 1 个应用程序中,并且客户端应该调用不同的应用程序。
    • 你说得对,这不是关于 URI 而是关于无法与客户端传递的请求。我已经编辑了答案。
    猜你喜欢
    • 2011-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-26
    • 2015-05-29
    • 2014-08-05
    • 2018-08-22
    • 2010-10-10
    相关资源
    最近更新 更多