springCloud Finchley 微服务架构从入门到精通【八】断路器 Hystrix(feign)
程序员文章站
2024-03-17 22:34:46
...
一、前言
上节写了ribbon 整合hystrix的实例,本节准备实现feign,由于比较简单,只写关键代码,具体看github源码
二、代码实现
创建fallback包存放feign的fallback处理类,包结构如下:
UserFeignApi为入口调用类
package com.mayi.springcloud.api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.mayi.springcloud.client.UserFeignClient;
@RestController
public class UserFeignApi {
@Autowired
private UserFeignClient userFeignClient;
@GetMapping("/listUsersByFeign")
public String ListUsers(){
String users = this.userFeignClient.listUsers();
return users;
}
}
UserFeignClient为实现feign的接口
package com.mayi.springcloud.client;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import com.mayi.springcloud.fallback.UserFallback;
@FeignClient(name="service-user", fallback=UserFallback.class)
public interface UserFeignClient {
@GetMapping("/listUsers")
public String listUsers();
}
UserFallback为节点故障处理类
package com.mayi.springcloud.fallback;
import org.springframework.stereotype.Component;
import com.mayi.springcloud.client.UserFeignClient;
@Component
public class UserFallback implements UserFeignClient{
@Override
public String listUsers() {
// TODO Auto-generated method stub
return "服务调用失败";
}
}
配置中心的service-feign-hystrix-dev.yml
server:
port: 1001
feign:
hystrix:
enabled: true
三、测试
依次启动下图服务
访问http://localhost:1001/listUsersByFeign,交替出现
手动停止其中一个service-user服务,当负载均衡至该节点,会转到自定义的fallback类
若干秒后,该故障节点会被剔除,之后不会被其他调用者访问到。
源码地址:https://github.com/tianyana/springcloud/tree/master/bussnessservice-user-client-feign-hystrix
欢迎加入JAVA架构师QQ群(初建):618578034
以上公众号从2018-5.1日 - 2019.5.1日期间,将要按照JAVA高级软件架构师实战培训的路线发布一期完整的架构文章,难度由浅入深,适合有一定开发基础想转架构和正在做初级架构开发的人员学习(springcloud更新完毕即开始)