最近项目在和其他系统有联调,我们都是一个系统的两个微服务。故此处简单介绍下微服务之间相互调用的三种方法。
第一种,也是最简单的。使用@FeignClient注解。
首先,需要在自己微服务的主启动类添加自动开启Feign服务注解@EnableFeignClients;
其次,定义一个接口,接口添加@FeignClient注解,将要调用的微服务的controller层方法抽象为抽象方法,路径、参数、请求类型保持一致。
最后,在需要调用微服务的地方,注入这个抽象类,直接使用,和调用自己方法一样。代码如下
package com.example.demo;
import java.util.Map;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@FeignClient(“要调用的微服务在eurake注册的名称”)
@RequestMapping(value = “要调用的微服务的controller类相同”)
public interface IMsService {
// 此处的路径和要调用的微服务的controller配置的路径一致
@RequestMapping(value = "/search/getRes", method = RequestMethod.POST)
Map<String,Object> getRes(@RequestBody Map<String,Object> map);
}
第二种,用RestTemplate 方法。定义一个restTemplate 方法,传参使用。代码如下。
import java.net.URI;
import java.net.URISyntaxException;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
public class RestTemplateService {
private String requestCloudRest(String url,String para,HttpMethod method) throws URISyntaxException {
HttpHeaders headers = new HttpHeaders();
RestTemplate restTemplate = new RestTemplate();
headers.setContentType(MediaType.valueOf("application/json;charset=utf-8"));
ParameterizedTypeReference<String> responseType
= new ParameterizedTypeReference<String>() {};
RequestEntity<String> request = null;
ResponseEntity<String> response = null;
if (HttpMethod.GET.equals(method) && StringUtils.isEmpty(para)) {
request = new RequestEntity<String>(headers,method,new URI(url));
response = restTemplate.exchange(request,responseType);
} else {
request = new RequestEntity<String>(para,headers,method,new URI(url));
response = restTemplate.exchange(request,responseType);
}
String res = response.getBody();
return res ;
}
}
第三种就是走soap管控。