我正在测试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");
    }
}


可能我在这里缺少什么,关于这里可能缺少什么的任何建议?

最佳答案

在看不到演示问题的项目的情况下很难说出什么问题,但是我希望项目中配置错误,或者您自己创建了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

08-28 17:56