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