Java 呼叫微服务
我寻找类似的问题,但没有找到。我有一个用drop wizard创建的微服务,它在localhost:9000中运行Java 呼叫微服务,java,spring-mvc,dropwizard,Java,Spring Mvc,Dropwizard,我寻找类似的问题,但没有找到。我有一个用drop wizard创建的微服务,它在localhost:9000中运行 我在另一个项目(使用SpringMVC)中工作,该项目运行于8080。我想调用上面的服务,从主项目中的任何控制器返回字符串。假设路径为“localhost:9000/giveMeString”。您可以使用Apache的HTTP客户端。请参见从其文档中借用的示例: // Create an instance of HttpClient. HttpClient client =
我在另一个项目(使用SpringMVC)中工作,该项目运行于8080。我想调用上面的服务,从主项目中的任何控制器返回字符串。假设路径为“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());
}
}
更好的方法是用缓存包装REST客户机
退房
更好的方法是异步
你可以使用;非常有用,特别是当您的控制器需要发出多个请求并且您不想阻止webapp线程时。您的控制器甚至可以返回延迟结果
或可列出未来
,这将使您的Web应用程序更具可扩展性
以及Spring Cloud+Netflix
你也可以检查和确认。
您将看到一些有趣的功能:负载平衡、恢复、断路器等。为了澄清这一点,您想从端口8080上运行的另一个应用程序向localhost:9000/giveMeString发出HTTP请求吗?