使⽤SpringBoot跨系统调⽤接⼝的⽅案
⼀、简介
项⽬开发中存在系统之间互调问题,⼜不想⽤dubbo,这⾥提供⼏种springboot⽅案:
1、使⽤Feign进⾏消费(推荐)
2、使⽤原始httpClient请求
3、使⽤RestTemplate⽅法
⼆、⽅案
⽅案⼀:使⽤Feign进⾏消费(推荐)
1、在maven中添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.2.2</version>
</dependency>
2、启动类上加上@EnableFeignClients
@EnableHystrix
@EnableDiscoveryClient
@EnableFeignClients(basePackages = {"com.aaa.aurora"})
@SpringBootApplication
@EnableTransactionManagement
@ComponentScan(basePackages = "com.aaa.aurora")
@ImportResource(locations= {"l","l"})
@MapperScan("com.aaa.aurora.mapper")
public class AuroraWebApplication {
public static void main(String[] args) {
SpringApplication.run(AuroraWebApplication.class, args);
}
}
3、编写service接⼝
@FeignClient(url = "${pangu.url}",name = "panguUrl")
public interface PanGuService {
@RequestMapping(value = "/pangu/restful/check",method = RequestMethod.POST)
JSONObject check(@RequestParam(name="queryEngine") String queryEngine, @RequestParam(n
ame="querySql") String querySql, @RequestParam(name="jobNo") String jobNo);
}spring mvc和boot区别
其中:pangu.url是配置在application.properties中的ip及端⼝
pangu.url = 192.168.1.3:8080
/pangu/restful/check是要调的接⼝名
4、代码中调⽤
@Autowired
private PanGuService panGuService;
JSONObject jsonObject = null;
try {
jsonObject = panGuService.auroraPriviledge(PRESTO_DRIVER, ("sql"), WorkNo());
} catch (Exception e) {
throw new Exception("请求系统异常");
}
if (PANGU_FAIL.("code"))) {
LOG.("msg").toString());
throw new ("msg").toString());
}
⽅案⼆:使⽤原始httpClient请求
使⽤HttpClient发送请求、接收响应很简单,⼀般需要如下⼏步即可。
1. 创建HttpClient对象。
2. 创建请求⽅法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
3. 如果需要发送请求参数,可调⽤HttpGet、HttpPost共同的setParams(HttpParams params)⽅法来添加请求参数;对于HttpPost对象⽽⾔,也可调⽤setEntity(HttpEntity entity)⽅法来设置请求参数。
4. 调⽤HttpClient对象的execute(HttpUriRequest request)发送请求,该⽅法返回⼀个HttpResponse。
5. 调⽤HttpResponse的getAllHeaders()、getHeaders(String name)等⽅法可获取服务器的响应头;调⽤HttpResponse的getEntity()⽅法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
6. 释放连接。⽆论执⾏⽅法是否成功,都必须释放连接。
public JSONObject doPost(String queryEngine, String querySql, String jobNo) {
JSONObject jsonObject = null;
//1.创建httpClient对象
CloseableHttpClient client = ateDefault();
//2.创建请求⽅法的实例,并指定请求URL
String url = "192.168.1.11:8080";
HttpPost post = new HttpPost(url);
post.setHeader("Content-Type", "application/json;charset=utf8");
//3.参数
AuroraPriviledge auroraPriviledge = new AuroraPriviledge();
auroraPriviledge.setQueryEngine(queryEngine);
auroraPriviledge.setQuerySql(querySql);
auroraPriviledge.setJobNo(jobNo);
String jsonString = JSONString(auroraPriviledge);
StringEntity entity = new StringEntity(jsonString, "UTF-8");
post.setEntity(entity);
/
/4.调⽤execute,返回response
CloseableHttpResponse response = null;
try {
response = ute(post);
HttpEntity responseEntity = Entity();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (client != null) {
client.close();
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return jsonObject;
}
⽅案三:使⽤RestTemplate⽅法
<请求:getForObject(...)和getForEntity(...)两个⽅法,区别在于前者直接返回预期的对象,即返回体中的body对象,后者返回的是ResponseEntity封装类,⾥⾯包含了HTTP请求的头信息。
2.post请求:与get请求类似,只是多⼀个request参数,request对象会作为httpEntity进⾏处理。
aurora;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import java.URI;
import java.util.HashMap;
import java.util.Map;
/**
* Description
*
* @author Bob
* @date 2020/4/15
**/
public class TestRest {
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
//get请求
//⽅法⼀:getForEntity(String url, Class<T> responseType, uriVariables),没有参数
String url = "restapi.amap/v3/ip?key=075b6eddd825148a674dfa8a8558ac62";
ResponseEntity<String> forEntity = ForEntity(url, String.class);
System.out.println(forEntity);
// <200,{"status":"1","info":"OK","infocode":"10000","province":"上海市","city":"上海市","adcode":"310000","rectangle":"120.8397067,30.77980118;122.1137989,31.66889673"},{Server=[Tengine], Date=[Sat, 18 Apr 2020 02:47:38 GMT], Content-Type=[applicati String s = ForObject(url, String.class);
System.out.println(s);
// {"province":"上海市","city":"上海市","adcode":"310000","infocode":"10000","rectangle":"120.8397067,30.77980118;122.1137989,31.66889673","status":"1","info":"OK"}
//⽅法⼀:getForEntity(String url, Class<T> responseType, uriVariables),url中⽤占位符,传⼊参数
//该⽅法提供了三个参数,其中var1为请求的地址(即url),var2为请求响应body的包装类型,var3为url中的参数绑定
url = "restapi.amap/v3/ip?key={?}";
forEntity = ForEntity(url, String.class, "075b6eddd825148a674dfa8a8558ac62");
//⽅法⼆:getForEntity(String url, Class<T> responseType, Map<String, ?> uriVariables),map传参
url = "restapi.amap/v3/ip?key={key}";
Map<String, Object> map = new HashMap<>();
map.put("key", "075b6eddd825148a674dfa8a8558ac62");
forEntity = ForEntity(url, String.class, map);
//⽅法三:getForEntity(URI url, Class<T> responseType),uri传参
URI uri = ate("restapi.amap/v3/ip?key=075b6eddd825148a674dfa8a8558ac62");
forEntity = ForEntity(uri, String.class);
//post请求,与get请求类型,只是多⼀个必填request对象
//postForEntity(String url, @Nullable Object request, Class<T> responseType, uriVariables)
forEntity = restTemplate.postForEntity(url, null, String.class, "075b6eddd825148a674dfa8a8558ac62");
s = restTemplate.postForObject(url, null, String.class, "075b6eddd825148a674dfa8a8558ac62");
}
}
补充:SpringBoot关于系统之间的远程互相调⽤
1、SpringBoot关于系统之间的远程互相调⽤
可以采⽤RestTemplate⽅式发起Rest Http调⽤,提供有get、post等⽅式。
1、1远程⼯具类
此处使⽤Post⽅式,参考下⾯封装的HttpClient类 1.1
/**
* Created by @kai on 2018/12/24/024.
* Time: 13:54
* Desc: 远程连接⼯具类
*/
@Service
public class HttpClient {
/**
* 根据远程地址发起访问-参数类型为form表单
* @param url 远程地址
* @param method 远程⽅法
* @param params ⽅法参数
* @return
*/
public Object client(String url,HttpMethod method,MultiValueMap<String,String> params){
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/x-www-form-urlencoded");
HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(params, headers);
ResponseEntity<String> responseEntity = restTemplate.postForEntity(url,httpEntity,String.class);
String body = Body();
JSONObject jsonObject = JSONObject.parseObject(body);
("data");
}
/**
* 根据远程地址发起访问-参数类型为JSON
* @param url 远程地址
* @param method 远程⽅法
* @param params ⽅法参数
* @return
*/
public Object clientJson(String url,HttpMethod method,Map<String,Object> params){
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
cn.hutool.json.JSONObject jsonObject = JSONUtil.parseFromMap(params);
HttpEntity<cn.hutool.json.JSONObject> httpEntity = new HttpEntity<>(jsonObject, headers);
ResponseEntity<String> responseEntity = restTemplate.postForEntity(url,httpEntity,String.class);
String body = Body();
JSONObject jsonObjectResult = JSONObject.parseObject(body);
("data");
}
}
1、2远程参数说明
⼯具类中提供了远程过程中传递参数的两种格式:
其中 headers.add("Content-Type", "application/x-www-form-urlencoded") 为form表单格式,⽀持键值对数据传输;
当参数类型为form表单时,数据需要封装成MultiValueMap<String,String>格式,前台使⽤controller接受时,可以直接使⽤ MultiValueMap 变量接收,参照代码如下 1.2
/**
* 保存分组策略对象
* @param
* @return
*/
@RequestMapping(value = "/saveDocGroupPolicy",method = RequestMethod.POST)
public ApiResult saveGroupPolicy(@RequestParam MultiValueMap<String,String> paramMap,@Valid GroupStrategyIO groupStrategyIO){
Integer userId = ExamUserId();
List<String> userList = new ArrayList<>();
userList.add(userId+"");
paramMap.put("userId",userList);
Object jsonObject = httpClient.client(ExamConfigConstants.url+"/exam/configPolicy/saveDocGroupPolicy", HttpMethod.POST, paramMap);
return ApiResult.success(jsonObject);
}
[ 1.2] 接受参数为form对象
headers.setContentType(MediaType.APPLICATION_JSON_UTF8)
为json数据格式
当参数为json格式时,远程服务器接受参数需加上注解@RequestBody,对于复杂参数可以使⽤对象接受,将对象转为Map,对数据进⾏加⼯,再将map转化为JSONObject,参照代码如下:1.3 /**
* 保存试卷策略
* @param paperStrategyIO 试卷策略对象
* @return
*/
@RequestMapping(value = "/savePaperConfig")
public ApiResult savePaperConfig(@RequestBody PaperStrategyIO paperStrategyIO){
Map<String, Object> paramMap = BeanUtil.beanToMap(paperStrategyIO);
Integer userId = ExamUserId();
paramMap.put("userId",userId);
Object jsonObject = httpClient.clientJson(ExamConfigConstants.url+"/exam/paper/savePaperConfigWithMap", HttpMethod.POST, paramMap);
return ApiResult.success(jsonObject);
}
[ 1.3]接收参数为复杂json串
2、后记
关于RestTemplate还有很多可调⽤的API,可以查看官⽅⽹站了解
以上为个⼈经验,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。如有错误或未考虑完全的地⽅,望不吝赐教。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论