![](/img/trans.png)
[英]Calling Python machine learning service from Java as an OS process or micro service via REST
[英]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实例并将其注入应用程序的多个位置。
@Configuration
public class MyConfiguration {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate(new HttpComponentsClientHttpRequestFactory());
}
}
看看萨根对此的看法 。
您可以使用AsyncRestTemplate ; 非常有用,特别是如果您的控制器需要发出多个请求,并且您不想阻止您的webapp线程。 您的Controller甚至可以返回DeferredResult
或ListenableFuture
,这将使您的webapp更具可扩展性。
您还可以查看Spring Cloud和Spring Cloud Netflix 。 你会看到有趣的功能:负载平衡,恢复,断路器等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.