繁体   English   中英

致电微服务

[英]Calling a micro service

我找了类似的问题,却找不到任何问题。 我有一个使用drop-wizard创建的微服务,该服务在localhost:9000中运行。

我正在8080中运行另一个项目(使用spring mvc)。我想调用上面的服务,它让我从主项目中的任何控制器返回字符串.lets说路径是“localhost:9000 / giveMeString”。

您可以使用Apache的HTTP客户端。 从他们的文档中借用这个例子:

  // Create an instance of HttpClient.
  HttpClient client = new HttpClient();

  // Create a method instance.
  GetMethod method = new GetMethod("http://localhost:9000/giveMeString");

  // Execute the method.
  int statusCode = client.executeMethod(method);

  // Read the response body.
  byte[] responseBody = method.getResponseBody();

  //Print the response
  System.out.println(new String(responseBody));

如果您真的要走微服务路径,请注意为每个请求创建一个HTTP客户端并进行同步阻塞请求将无法真正扩展。

如果你使用Spring,这里有一些想法:

创建一个RestTemplate实例

您可以创建一个RestTemplate实例并将其注入应用程序的多个位置。

@Configuration
public class MyConfiguration {
  @Bean
  public RestTemplate restTemplate() {
    return new RestTemplate(new HttpComponentsClientHttpRequestFactory());
  }
}

更好的是,使用Cache包装该REST客户端

看看萨根对此的看法

更好的是,去异步

您可以使用AsyncRestTemplate ; 非常有用,特别是如果您的控制器需要发出多个请求,并且您不想阻止您的webapp线程。 您的Controller甚至可以返回DeferredResultListenableFuture ,这将使您的webapp更具可扩展性。

和Spring Cloud + Netflix

您还可以查看Spring CloudSpring Cloud Netflix 你会看到有趣的功能:负载平衡,恢复,断路器等。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM