【问题标题】:How to call another rest api from my controller in Micronaut like in Spring-Boot RestTemplate?如何像在 Spring-Boot RestTemplate 中一样从 Micronaut 中的控制器调用另一个 rest api?
【发布时间】:2019-07-12 07:53:20
【问题描述】:

我有来自 Spring Boot 的以下功能。我不能使用声明式客户端来做到这一点,因此我的 uri 域在每次调用后都会改变,所以我需要像 Spring Boot 中一样的 RestTemplate。

如何在 Micronaut 中实现同样的效果?

private static void getEmployees()
{
   final String uri = "http://localhost:8080/springrestexample/employees.xml";

   RestTemplate restTemplate = new RestTemplate();
   String result = restTemplate.getForObject(uri, String.class);

   System.out.println(result);
}

【问题讨论】:

    标签: resttemplate micronaut


    【解决方案1】:

    这样的事情是一个很好的起点......

    import io.micronaut.http.HttpResponse;
    import io.micronaut.http.annotation.Controller;
    import io.micronaut.http.annotation.Get;
    import io.micronaut.http.client.RxHttpClient;
    import io.micronaut.http.client.annotation.Client;
    
    import javax.inject.Inject;
    
    @Controller("/")
    public class SomeController {
        // The url does not have to be
        // hardcoded here.  Could be
        // something like
        // @Client("${some.config.setting}")
        @Client("http://localhost:8080")
        @Inject
        RxHttpClient httpClient;
    
        @Get("/someuri")
        public HttpResponse someMethod() {
            String result = httpClient.toBlocking().retrieve("/springrestexample/employees.xml");
            System.out.println(result);
    
            // ...
    
            return HttpResponse.ok();
        }
    }
    

    希望对你有帮助。

    编辑

    另一种类似的方法:

    import io.micronaut.http.HttpResponse;
    import io.micronaut.http.annotation.Controller;
    import io.micronaut.http.annotation.Get;
    import io.micronaut.http.client.RxHttpClient;
    import io.micronaut.http.client.annotation.Client;
    
    @Controller("/")
    public class SomeController {
        private final RxHttpClient httpClient;
    
        public SomeController(@Client("http://localhost:8080") RxHttpClient httpClient) {
            this.httpClient = httpClient;
        }
    
        @Get("/someuri")
        public HttpResponse someMethod() {
            String result = httpClient.toBlocking().retrieve("/springrestexample/employees.xml");
            System.out.println(result);
    
            // ...
    
            return HttpResponse.ok();
        }
    }
    

    【讨论】:

    • 更多信息请参阅我们的用户指南docs.micronaut.io/1.1.4/guide/index.html#httpClient
    • 是否有可能以编程方式更改客户端的 url?因为我从另一个 api 获取 url 并且它可以改变?谢谢
    • 客户端的基本URL创建后不能更改。但是,您仍然可以使用完全限定的 URL 执行请求,它将忽略最初提供的基本 URL
    猜你喜欢
    • 1970-01-01
    • 2017-03-22
    • 2017-07-10
    • 2020-07-17
    • 1970-01-01
    • 2020-08-23
    • 2018-02-11
    • 1970-01-01
    • 2017-10-14
    相关资源
    最近更新 更多