首页 > 解决方案 > Micronaut RxHttpClient 空

问题描述

我正在测试 RxHttpClient 功能。

我创建了一个在 上运行的简单服务http://localhost:8086,我正在从另一个在其上运行的服务访问它http://localhost:8080。按照 micronaut 文档初始化 RxHttpClient 后,我​​看到 RxHttpClient 仍然为 NULL。这是客户端实现

import io.micronaut.http.client.RxHttpClient;
import io.micronaut.http.client.annotation.Client;
import io.reactivex.Flowable;

import javax.inject.Inject;
import javax.inject.Singleton;

@Singleton
public class TestClient {

    @Inject
    @Client("http://localhost:8086")
    RxHttpClient httpClient;

    public Flowable<String> getRandomName(){

        System.out.println("getRandomName invoked => " + httpClient);

        return Flowable.just("test");
    }
}

可能我在这里遗漏了一些东西,关于这里可能缺少什么的任何建议?

标签: javamicronaut

解决方案


如果没有看到演示问题的项目,很难说出了什么问题,但我预计项目中配置错误,或者您自己创建 bean 的实例,而不是让 DI 容器为您创建它。

请参阅https://github.com/jeffbrown/mithrandirclient上的项目。

https://github.com/jeffbrown/mithrandirclient/blob/2c86d361db42f9beff4bb7620789fd4e422941d0/src/main/java/mithrandirclient/TestClient.java

package mithrandirclient;

import io.micronaut.http.client.RxHttpClient;
import io.micronaut.http.client.annotation.Client;

import javax.inject.Inject;
import javax.inject.Singleton;

@Singleton
public class TestClient {

    @Inject
    @Client("http://localhost:8086")
    RxHttpClient httpClient;

    public String getRandomName(){

        System.out.println("getRandomName invoked => " + httpClient);

        return "Some Random Name";
    }
}

https://github.com/jeffbrown/mithrandirclient/blob/master/src/main/java/mithrandirclient/DemoController.java

package mithrandirclient;

import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;

@Controller("/demo")
public class DemoController {

    private TestClient testClient;

    public DemoController(TestClient testClient) {
        this.testClient = testClient;
    }

    @Get("/")
    public String index() {
        return testClient.getRandomName();
    }
}

当我向控制器发送请求时,我得到了预期的结果:

$ curl http://localhost:8080/demo
Some Random Name

服务器控制台显示客户端实际上不是null

getRandomName invoked => io.micronaut.http.client.DefaultHttpClient@39ce2d3d

更新:

https://github.com/jeffbrown/mithrandirclient/commit/0ba0216bca4f31ee3ff296579b829ab4615fa6db的提交使代码更像原始问题中的代码,但结果是一样的。注入确实有效,而客户端则无效null


推荐阅读