restTemplate實現(xiàn)跨服務API調(diào)用方式
restTemplate跨服務API調(diào)用
同時使用ribbon,實現(xiàn)接口調(diào)用的負載均衡。
1 注冊中心
略…
2 消費端
2.1 pom
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Brixton.SR5</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>2.2 application.properties
spring.application.name=ribbon-consumer server.port=9000 # 本地啟動注冊中心 eureka.client.service-url.defaultZone=http://localhost:1111/eureka/
2.3 啟動類
package com.example.lei;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@EnableDiscoveryClient
@SpringBootApplication
public class RibbonConsumerApplication {
@Bean
@LoadBalanced
RestTemplate restTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(RibbonConsumerApplication.class, args);
}
}2.4 消費
package com.example.lei.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* @Author: leimin
* @Description: new class
* @Date: 2020/6/8 16:04
* @Version: 1.0
*/
@RestController
public class ConsumerController {
/**
* xx
*/
@Autowired
RestTemplate restTemplate;
/**
* yyy
* @return rr
*/
@RequestMapping(value = "/ribbon-consumer", method = RequestMethod.GET)
private String helloConsumer(){
return restTemplate.getForEntity("http://HELLO-SERVICE/hello",String.class).getBody();
}
}3 服務端
3.1 pom
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
<version>2.2.0.RELEASE</version>
</dependency>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Brixton.SR5</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>3.2 application.properties
spring.application.name=hello-service # 服務注冊到兩臺注冊中心 eureka.client.service-url.defaultZone=http://peer1:1111/eureka/,http://peer2:1112/eureka
3.3 啟動類
package com.didispace.springboothello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/**
* 能夠被發(fā)現(xiàn)為客戶端
*/
@EnableDiscoveryClient
@SpringBootApplication
public class SpringBootHelloApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootHelloApplication.class, args);
}
}3.4 服務
package com.didispace.springboothello.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.logging.Logger;
/**
* @Author: leimin
* @Description: new class
* @Date: 2020/6/8 9:08
* @Version: 1.0
*/
@RestController
public class HelloController {
/**
* xx
*/
private final Logger logger = Logger.getLogger(String.valueOf(getClass()));
/**
* xx
*/
@Autowired
private DiscoveryClient client;
/**
* xx
* @return xx
*/
@RequestMapping(value = "/hello",method = RequestMethod.GET)
public String index(){
ServiceInstance instance = client.getLocalServiceInstance();
logger.info("/hello,host:" + instance.getHost()+", service_id:" +instance.getServiceId());
return "hello World !";
}
}restTemplate實現(xiàn)跨域調(diào)用接口
本文主要針對post方式,發(fā)送請求。
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
/**
* 調(diào)用mufly_api接口
* Created by 耿洪生 on 2016/10/17.
*/
@Component
public class HttpEntityServiceImpl {
@Value("${muflyapi.appid}")
private String appID;
public ResponseEntity<String> responseHttpEntity(String url, Object parameters) {
Map<String, Object> requestObject = new HashMap<>();
requestObject.put("appID", appID);
requestObject.put("parameters", parameters);
//轉(zhuǎn)json字符串
JSONObject jsonObject = (JSONObject) JSONObject.toJSON(requestObject);
String jsonStr = jsonObject.toJSONString();
//設置HttpHeader
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "application/json;charset=UTF-8");
//設置HttpEntity
HttpEntity<String> entity = new HttpEntity<String>(jsonStr, headers);
//設置連接、讀取超時時間
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(30 * 1000);
factory.setReadTimeout(60 * 1000);
//接口調(diào)用
RestTemplate temp = new RestTemplate(factory);
ResponseEntity<String> output = temp.postForEntity(url, entity, String.class);
return output;
}
}如果,你不想new,可以使用@Autowired直接引入:
@Autowired private RestTemplate restTemplate;
/**
* post請求
*
* @param url
* @param data map類型
* @param token
* @return 實體
*/
public ResponseEntity<String> post(String url, Map data, String token) {
HttpHeaders headers = new HttpHeaders();
headers.add("Accept", "application/json");
headers.add("Accept-Encoding", "gzip");
headers.add("Content-Encoding", "UTF-8");
headers.add("Content-Type", "application/json;charset=UTF-8");
headers.add("Token", token);
String dataStr = JsonUtil.toJSon(data);
HttpEntity<String> postEntity = new HttpEntity<>(dataStr, headers);
return restTemplate.postForEntity(url, postEntity, String.class);
}至于設置restTemplate bean 的超時:
@Bean(name="restTemplate")
RestTemplate restTemplate() {
ClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
//設置連接、讀取超時時間
((SimpleClientHttpRequestFactory) factory).setConnectTimeout(30 * 1000);
((SimpleClientHttpRequestFactory) factory).setReadTimeout(60 * 1000);
return new RestTemplate();
}spring自帶的restTemplate里有很多實用的方法,

其底層還是ClientHttpRequest,

總結(jié)
以此記錄。以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
java常用工具類之數(shù)據(jù)庫連接類(可以連接多種數(shù)據(jù)庫)
這篇文章主要介紹了java常用工具類之數(shù)據(jù)庫連接類,可以連接多種數(shù)據(jù)庫,代碼中包含詳細注釋,需要的朋友可以參考下2014-07-07
IntelliJ IDEA 2019.3激活破解的詳細方法(親測有效,可激活至 2089&
本教程適用于 JetBrains 全系列產(chǎn)品,包括 Pycharm、IDEA、WebStorm、Phpstorm、Datagrip、RubyMine、CLion、AppCode 等,本教程無需修改 hosts 文件,對IntelliJ IDEA 2019.3激活破解的詳細方法的相關知識感興趣的朋友一起看看吧2020-09-09
Spring Boot中RedisTemplate的使用示例詳解
RedisTemplate.opsForHash()是RedisTemplate類提供的用于操作Hash類型的方法,它可以用于對Redis中的Hash數(shù)據(jù)結(jié)構(gòu)進行各種操作,如設置字段值、獲取字段值、刪除字段值等,本文介紹Spring Boot中RedisTemplate的使用,感興趣的朋友一起看看吧2023-10-10

