本案例基于order服务去调用product服务的一些接口基础上实现的,大家可以类比实现。
1.在order服务里application.yml文件里添加:
feign:
hystrix:
enabled: true
2.在启动类里添加对product包服务的扫描
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan;
@EnableFeignClients(basePackages = "com.imooc.product.client")
@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
@ComponentScan(basePackages = "com.imooc") //起到对product服务的包扫描的效果
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
}
3.在product服务的ProductClient接口里声明fallback。代码如下:
import com.imooc.product.common.DecreaseStockInput;
import com.imooc.product.common.ProductInfoOutput;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.List;
@FeignClient(name="product",fallback = ProductClient.ProductClientFallback.class)
@Component
public interface ProductClient {
/*
获取商品列表,给订单服务用的
*/
@PostMapping("/product/listForOrder")
List<ProductInfoOutput> listForOrder(@RequestBody List<String> productIdList);
@PostMapping("/product/decreaseStock")
void decreaseStock(@RequestBody List<DecreaseStockInput> decreaseStockInputList);
@Component
static class ProductClientFallback implements ProductClient{
@Override
public List<ProductInfoOutput> listForOrder(List<String> productIdList) {
System.out.println("之行到了");
return null;
}
@Override
public void decreaseStock(List<DecreaseStockInput> decreaseStockInputList) {
}
}
}
4.在不启动product服务时,单独启动order服务,在order服务里调用product服务的listForOrder时会服务降级。返回空,模拟了服务降级场景。