【问题标题】:Micronaut java httpclient creation with the existing server使用现有服务器创建 Micronaut java httpclient
【发布时间】:2021-06-12 08:05:51
【问题描述】:

我有一个使用以下配置运行的 Micronaut 应用程序:

micronaut:
  server:
    cors:
       enabled: true 
    port: 8080

现在我有一个增强功能,我想调用第 3 方 URL 并在我的应用程序(我的应用程序中的一个模块)中获取响应。我使用了下面的代码 sn-p:

    EmbeddedServer server = ApplicationContext.run(EmbeddedServer.class);
    HttpClient client = server .getApplicationContext() .createBean(HttpClient.class, server.getURL());
    HttpRequest req = HttpRequest.GET(urlHost);
    HttpResponse<String> response = client.toBlocking().exchange(req, String.class);

但这不起作用。我得到端口已经在使用。我在 google 中没有找到太多帮助,因为 Micronaut 的 HttpClient 通常用于 Micronaut 测试,而我的情况并非如此。这可以在我的应用程序中使用吗?如果有怎么办?提前致谢。

【问题讨论】:

  • 仅供参考...您的 CORS 配置与端口已在使用问题没有任何关系。

标签: java server micronaut micronaut-client


【解决方案1】:

这是因为您正在通过ApplicationContext.run(EmbeddedServer.class) 启动另一个服务器。

你不需要它。通过构造函数将HttpClient 注入你的类就足够了:

@Singleton 
public class MyClient {

    private final RxHttpClient client;

    public MyClient(@Client("https://some.third-party.com") RxHttpClient client) {  
        this.client = client;
    }

    HttpResponse<String> getSomething(Integer id) {
        URI uri = UriBuilder.of("/some-objects").path(id).build();
        return client.toBlocking().exchange(HttpRequest.GET(uri), String.class);
    }
}

如果您在应用程序配置中例如some-service.url路径下有第三方服务器URL,那么您可以使用@Client("${some-service.url}")


另一种选择是为第三方服务器定义声明式客户端,然后在需要时将其注入到您的类中。

首先为你的第三方服务定义客户端接口:

@Client("some-service")
public interface SomeServiceClient {

    @Get("/api/some-objects/{id}")
    String getSomeObject(@QueryValue("id") Integer id);
}

在应用程序配置(application.yaml)中为该服务添加客户端配置:

micronaut:
  http:
    services:
      some-service:
        url: "https://some.third-party.com"
        read-timeout: 1m

然后你可以在你需要的地方注入SomeServiceClient

@Singleton 
public class SomeServiceConsumer {

    private final SomeServiceClient client;

    public SomeServiceConsumer(SomeServiceClient client) {  
        this.client = client;
    }

    void doWithSomething(Integer id) {
        String object = client.getSomeObject(id);
        ... // processing of object here
    }
}

您可以在 Micronaut 文档中找到更多信息 https://guides.micronaut.io/latest/micronaut-http-client-gradle-java.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多