Feign的成果:这是个消费者,按照处事注册在Eureka的ID去找到该处事,并调用接口
Hystrix的成果:熔断器,假如A处事需要调用B处事的/cities接口获取数据,那就在A处事的controller里声明@HystrixCommand,如果B处事的/cities接口挂了,就返回一个自界说的值
项目布局
[root@node01 cloud]# tree weather/
weather/
├── Application.java #主措施启动入口
├── controller
│ ├── CityController.java #控制路由,好比会见127.0.0.1:8080/cities, 这里调用cityClient要领
└── service
└── CityClient.java #具体要领的实现,这里就具体实现cityClient要领(interface)
|
Application.java
package com.waylau.spring.cloud.weather;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; #引入熔断器
import org.springframework.cloud.client.discovery.EnableDiscoveryClient; #让eureka能发明本身
import org.springframework.cloud.netflix.feign.EnableFeignClients; #引入feign
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients #声明这个措施引入FeignClient
@EnableCircuitBreaker #声明这个措施引入熔断器
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
|
controller/CityController.java
package com.waylau.spring.cloud.weather.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.waylau.spring.cloud.weather.service.CityClient; #引用service/CityClient.java
@RestController
public class CityController {
@Autowired
private CityClient cityClient;
@GetMapping("/cities") #控制路由,好比会见127.0.0.1:8080/cities
@HystrixCommand(fallbackMethod="defaultCities") #给另外一个处事设置hystrix熔断器,并声明fallbackMethod(回调要领)假如另外一个处事挂了,就调用defaultCities要领
public String listCity() {
// 通过Feign客户端来查找
String body = cityClient.listCity(); #调用service里CityClient.java的cityClient要领,获取都市数据
return body; #返回,会见127.0.0.1:8080/cities就能返回都市数据
}
public String defaultCities() {
return "City Data Server is down!";
}
}
|
service/CityClient.java(消费者)
用Feign去另一个接口获取数据
package com.waylau.spring.cloud.weather.service;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
@FeignClient("msa-weather-city") #msa-weather-city是msa-weather-city处事注册到eureka的ID,通过这个ID就能会见到msa-weather-city微处事
public interface CityClient {
@GetMapping("/cities") #调用msa-weather-city微处事里的/cities接口
String listCity(); #调用msa-weather-city微处事里的/cities接口里的listCity()要领
}
|
application.properties
spring.application.name: micro-weather-eureka-client-feign-hystrix
eureka.client.serviceUrl.defaultZone: http://localhost:8761/eureka/
feign.client.config.feignName.connectTimeout: 5000
feign.client.config.feignName.readTimeout: 5000
|
测试,条件为另一个处事可用时,我们是能调用的
测试.条件为另一个处事不行以时,我们是不能调用的,所以fallback
,
|