解决服务间调用的三种传统方式
生活随笔
收集整理的這篇文章主要介紹了
解决服务间调用的三种传统方式
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
第一種方法:使用HttpRequest第三方工具
第一步:pom依賴
<dependency><groupId>com.github.kevinsawicki</groupId><artifactId>http-request</artifactId><version>6.0</version> </dependency>第二步:在代碼中直接使用HttpRequest類
String body = HttpRequest.post(new StringBuilder(GuojiaoInfo.guojiaoHttp).append("facsp/auth/AuthLogin")).contentType(MediaType.APPLICATION_JSON_UTF8_VALUE).send(JSON.toJSONString(param)).body();如果是發(fā)post請求,就調(diào)用
HttpRequest.post()方法如果發(fā)get請求,就調(diào)用
HttpRequest.get()方法。
?第二種方法:使用RestTemplate(Spring框架封裝)
springcloud中服務間兩種restful調(diào)用方式
RestTemplate和Feign
RestTemplate是一個Http客戶端,
使用RestTemplate的幾種方式:
一、RestTemplate template = new RestTemplate();使用服務ip或者域名訪問
二、使用LoadBalancerClient的choose()獲得ServiceInstance
三、注入RestTemplate bean,使用服務名稱訪問
第三種方法:使用HttpClient(Apache提供)
代碼示例:
public static int sendToSanMingJSON(String url, String paramJson) throws Exception {int status;CloseableHttpClient httpClient = HttpClients.createDefault();HttpPost httpPost = new HttpPost(SANMING_SERVICE_URL+url);logger.debug("三明服務地址是==> "+SANMING_SERVICE_URL+url); // ArrayList<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>(); // parameters.add(new BasicNameValuePair("Connection", "keep-alive")); // parameters.add(new BasicNameValuePair("Content-Type", "application/json")); // parameters.add(new BasicNameValuePair("Accept-Encoding", "gzip")); // parameters.add(new BasicNameValuePair("Accept-Charset", "utf-8")); // parameters.add(new BasicNameValuePair("Accept", "*/*"));httpPost.setHeader("Connection","keep-alive");httpPost.setHeader("Content-Type","application/json");httpPost.setHeader("Accept-Encoding","gzip");httpPost.setHeader("Accept-Charset","utf-8");StringEntity requestEntity = new StringEntity(paramJson,"utf-8");requestEntity.setContentEncoding("UTF-8");httpPost.setEntity(requestEntity);String jsonData=null;try { // httpPost.setEntity(new UrlEncodedFormEntity(parameters));CloseableHttpResponse response = httpClient.execute(httpPost);jsonData = EntityUtils.toString(response.getEntity(), Charset.forName("utf-8"));} catch (Exception e) {logger.info("調(diào)三明服務異常 ==> "+e.getMessage());}Map map = JSON.parseObject(jsonData);status = Integer.parseInt(map.get("code").toString());return status;}?
總結(jié)
以上是生活随笔為你收集整理的解决服务间调用的三种传统方式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MySQL数据库优化实战
- 下一篇: RestTemplate设置通用head