当前位置:   article > 正文

SpringBoot整合OpenFeign和Hystrix_springboot hystrix @feignclient threadpoolkey

springboot hystrix @feignclient threadpoolkey

Feign 和hystrix

开启hystrix 熔断器

application.yml

feign:
  hystrix:
    enabled: true
  • 1
  • 2
  • 3

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

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();
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

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 "";
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

被调用服务的控制器

@RestController
public class TestController {

    @GetMapping("/test")
    public String test() {
        throw new RuntimeException("服务端测试异常!");
//        return "test";
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

调用方服务的控制器

@RestController
public class TestController {

    @Resource
    MessageClient messageClient;

    @GetMapping("/test")
    public String test(){
        return messageClient.test();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

方式二:用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;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

修改@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();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

其他的不用修改

运行结果

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/68792
推荐阅读
相关标签
  

闽ICP备14008679号