使用Feign實作消費者
-
-
- 1.建立普通springboot 工程
- 2.添加依賴
- 3.在入口類 添加注解 @EnableFeignClients
- 4.聲明服務
- 5.使用Controller中調用服務
- 6.屬性配置 yml檔案
- 7.測試 (沒有在新 消費者中設定hystrix熔斷配置)
-
1.建立普通springboot 工程

2.添加依賴
<!-- springcloud 版本-->
<properties>
<spring.cloud-version>2020.0.0</spring.cloud-version>
</properties>
<dependencies>
<!-- eureka依賴 用戶端 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!-- feign 整合了 ribbon負載均衡政策 和 hystrix 熔斷器 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!-- hystrix包 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
</dependencies>
<!-- 需要添加依賴管理 管理springcloud -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring.cloud-version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<!-- 如果在maven中找不到 就去springcloud倉庫找 -->
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/libs-milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
3.在入口類 添加注解 @EnableFeignClients
/*//SpringBoot注解
@SpringBootApplication
//激活Eureka用戶端
@EnableEurekaClient
//開啟斷路器功能
@EnableCircuitBreaker*/
@SpringCloudApplication
@EnableFeignClients
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
4.聲明服務
定義一個HelloService接口,通過@FeignClient注解來指定服務名稱;進而綁定服務,然
後再通過SpringMVC中提供的注解來綁定服務提供者提供的接口,
如下:
Feign消費者 Service 聲明遠端服務
// Feign的用戶端注解 綁定 遠端服務提供者名稱
@FeignClient("01-springcloud-service-provider")
public interface HelloService {
/**
* 聲明一個方法,這個方法就是遠端的服務提供者提供的那個方法
* @return
*/
@RequestMapping("/service/hello")
public String hello();
}
被聲明的遠端服務提供者 Controller中
@RestController
public class HelloController {
@RequestMapping("/service/hello")
public String hello(){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("服務提供者---- 1");
return "服務提供者---- 1";
}
}
5.使用Controller中調用服務
feign這裡主要是controller層,調用serivice層接口,service層具體實作遠端調用服務提供者
@RestController
public class FeignController {
@Autowired
private HelloService helloService;
@RequestMapping("/web/hello")
public String hello(){
//調用聲明式的接口方法,實作對遠端服務的調用
//實際上就是調用service中聲明的方法
return helloService.hello();
}
}
6.屬性配置 yml檔案
server:
port: 8087
spring:
application:
# 配置服務的名稱
name: 05-springcloud-service-feign
eureka:
client:
# 注冊中心連接配接位址 http://eureka8083:8083/eureka/,http://eureka8084:8084/eureka/
service-url.defaultZone: http://eureka8083:8083/eureka/,http://eureka8084:8084/eureka/
7.測試 (沒有在新 消費者中設定hystrix熔斷配置)
依次啟動注冊中心 服務提供者 和 feign實作服務消費,然後通路位址:
**确實有一個提供者裡面有被0除 **
再來一次