前言:
首先說下feign 跟 openfeign 差別:前者了解為一個簡約版,後者支援 spring 的一些注解并且内置了 hystrix 熔斷;如果想使用 hystrix,前者需要額外配置 hystrix。在沒用 feign 之前,服務調用可以使用 RestTemplate,當然前者優點更多;預設大家已經了解 eureka 這些,如果不了解參考 SpringCloud 之 Eureka 服務的使用場景和搭建。
版本聲明:
springboot:2.3.2.RELEASE
springcloud:Hoxton.SR11
1. 服務提供者資訊
首先看一下服務提供者的接口檔案:
@RestController
@RequestMapping("/client")
public class ControllerTest {
@GetMapping("/test")
public String name() {
return "this is from client-1";
}
}
2. 服務調用者內建 openfeign
pom 檔案:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.test</groupId>
<artifactId>eureka-customer</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.2.RELEASE</version>
<relativePath/>
</parent>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency> <!-- openfeign 依賴 -->
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Hoxton.SR11</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
服務調用接口 ClientService 聲明:
@FeignClient(name = "eureka-client", fallback = ClientServiceFallback.class)
@Component
public interface ClientService {
@GetMapping(value = "/client/test")
String getClientService();
}
其中 fallback 參數是服務熔斷(服務提供者服務故障)需要調用的類,在類面實作了 ClientService 所有的接口,ClientServiceFallback 實作如下:
@Component
public class ClientServiceFallback implements ClientService {
public String getClientService() {
return "服務出現故障......";
}
}
測試接口檔案:
@RestController
@RequestMapping("/customer")
public class ControllerTest {
@Autowired
ClientService clientService;
@GetMapping("/test")
public String get() {
return clientService.getClientService();
}
}
啟動類加上 @EnableFeignClients 注解
配置檔案加上開啟 hystrix 配置,如下:
feign:
hystrix:
enabled: true
至此,內建完成,下面開始測試。
3. 測試服務調用和熔斷
依次開啟注冊中心、服務提供者、服務調用者,浏覽器輸入 http://localhost:8003/customer/test,顯示:
關閉服務提供者,重新整理頁面:
再次打開服務提供者,調用又恢複正常。