?
目錄
RestTemplate
OpenFeign
1.引入依賴open-feign
2.聲明要調用的服務和接口
3.注入FeignClient啟用
4驗證
RestTemplate
在微服務架構中,使用RestTemplate
是一種常見的方式進行服務間的HTTP通信。以下是一個簡單的示例,演示如何使用RestTemplate
進行微服務之間的RESTful調用。
首先,確保你的項目中引入了Spring Boot和RestTemplate
的依賴。在pom.xml
中添加如下依賴:
<dependencies><!-- Spring Boot Starter Web包含了RestTemplate --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency>
</dependencies>
接下來,創建一個使用RestTemplate
進行RESTful調用的服務類。以下是一個簡單的示例,其中假設你有兩個微服務,分別是ServiceA
和ServiceB
,它們之間通過RESTful調用:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;@Service
public class MicroserviceClient {private final RestTemplate restTemplate;@Autowiredpublic MicroserviceClient(RestTemplate restTemplate) {this.restTemplate = restTemplate;}public String callServiceA() {String serviceAUrl = "http://service-a/api/data";ResponseEntity<String> response = restTemplate.getForEntity(serviceAUrl, String.class);return response.getBody();}public String callServiceB() {String serviceBUrl = "http://service-b/api/data";ResponseEntity<String> response = restTemplate.getForEntity(serviceBUrl, String.class);return response.getBody();}
}
最后,確保在你的Spring Boot應用程序主類(通常是帶有@SpringBootApplication
注解的類)中創建一個RestTemplate
的Bean:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;@Configuration
public class AppConfig {@Beanpublic RestTemplate restTemplate() {return new RestTemplate();}
}
以上示例是一個簡單的演示,實際中你可能需要更多的配置和異常處理。此外,現代的微服務架構中,通常會使用更先進的工具如Feign或者WebClient來簡化和優化微服務之間的通信。
OpenFeign
OpenFeign是一個聲明式的Web服務客戶端,使得編寫HTTP客戶端變得更加簡單。通過使用OpenFeign,你可以更輕松地聲明和實現服務間的RESTful調用,而不必顯式地創建RestTemplate
實例。
還是使用項目進行說明,mall-product想要調用mall-order的獲取訂單列表接口。
1.引入依賴open-feign
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId></dependency>
2.聲明要調用的服務和接口
在mall-product中聲明OrderFeignService的order接口
3.注入FeignClient啟用
4驗證
調用http://localhost:10010/product/brand/order,返回order列表信息
如果運行報錯:
?No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc?
pom中需要添加spring-cloud-loadbalancer依賴,排除沖突的spring-cloud-starter-netflix-ribbon
<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId><exclusions><exclusion><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-ribbon</artifactId></exclusion></exclusions></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-loadbalancer</artifactId><version>2.2.2.RELEASE</version></dependency>