茴香豆有几种写法?又名微服务相互调用的几种方法

最近项目在和其他系统有联调,我们都是一个系统的两个微服务。故此处简单介绍下微服务之间相互调用的三种方法。
第一种,也是最简单的。使用@FeignClient注解。
首先,需要在自己微服务的主启动类添加自动开启Feign服务注解;
其次,定义一个接口,接口添加@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 getRes(@RequestBody Map 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 responseType = new ParameterizedTypeReference() {};RequestEntity request = null;ResponseEntity response = null;if (HttpMethod.GET.equals(method) && StringUtils.isEmpty(para)) {request = new RequestEntity(headers,method,new URI(url));response = restTemplate.exchange(request,responseType);} else {request = new RequestEntity(para,headers,method,new URI(url));response = restTemplate.exchange(request,responseType);}String res = response.getBody();return res ;
}

}

第三种就是走soap管控。


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部