SpringBoot整合OpenFeign和Hystrix

Feign 和hystrix

开启hystrix 熔断器

application.yml

feign:
  hystrix:
    enabled: true

方式一:简单,但无法获取异常信息和状态号

FeignClient类

@FeignClient(value = "eureka-client-express-message", fallback = MessageClientHystrix.class)
public interface MessageClient {

    @GetMapping("/express-message/getMessageUnRead/{account}")
    R getMessageUnRead(@PathVariable String account);

    @GetMapping("/express-message/test")
    String test();
}

Hystrix类:重写方法用于当接口访问异常时,即调用的接口抛出异常时调用对应的重写方法,一般用于容错返回和输出异常

@Slf4j
@Component
public class MessageClientHystrix implements MessageClient {

    @Override
    public R getMessageUnRead(String account) {
        return R.failed();
    }

    @Override
    public String test() {
        log.error("Hystrix error ! ");
        return "";
    }
}

被调用服务的控制器

@RestController
public class TestController {

    @GetMapping("/test")
    public String test() {
        throw new RuntimeException("服务端测试异常!");
//        return "test";
    }
}

调用方服务的控制器

@RestController
public class TestController {

    @Resource
    MessageClient messageClient;

    @GetMapping("/test")
    public String test(){
        return messageClient.test();
    }
}

方式二:用Factory,可以获取异常信息和异常号

MessageFeignFactory类

@Component
public class MessageFeignFactory implements FallbackFactory<MessageClient> {

    private final MessageClientHystrix messageClientHystrix;

    public MessageFeignFactory(MessageClientHystrix messageClientHystrix) {
        this.messageClientHystrix = messageClientHystrix;
    }

    @Override
    public MessageClient create(Throwable throwable) {
        throwable.printStackTrace();
        return messageClientHystrix;
    }
}

修改@FeignClient 注解

@FeignClient(value = "eureka-client-express-message", fallbackFactory = MessageFeignFactory.class)
public interface MessageClient {

    @GetMapping("/express-message/getMessageUnRead/{account}")
    R getMessageUnRead(@PathVariable String account);

    @GetMapping("/express-message/test")
    String test();
}

其他的不用修改

运行结果

SpringBoot整合OpenFeign和Hystrix_第1张图片

可以看到抛出的异常有状态号信息等

你可能感兴趣的:(java,分布式,spring,boot,hystrix,后端)