SpringCloud 学习笔记十 多模块搭建-pay服务(Feign)+熔断器Hystrix

上一章使用ribbon+hystrix实现了了方法的熔断,这里我们使用feign+hystrix来实现熔断

回顾什么是feign

Ribbon和Feign都是客户端负载均衡器,它的作用是在服务发生调用的时候帮我们将请求按照某种规则分发到多个目标服务器上,简单理解就是用来解决微服务之间的通信问题。
官方文档地址:
https://cloud.spring.io/spring-cloud-static/Greenwich.SR5/single/spring-cloud.html#spring-cloud-feign-hystrix

pay服务之前集成了Feign,在feign的jar包里面已经集成Hystrix。我们除了要给Feign开启Hystrix以外还需要为Feign接口编写托底类,在yml配置里面开启feign服务:

eureka:
  client:
    serviceUrl:  #注册中心地址
      defaultZone: http://peer1:1010/eureka/,http://peer2:1011/eureka/,http://peer3:1012/eureka/
  instance:
    prefer-ip-address: true  #使用ip地址注册
    instance-id: pay-server:1040   #实列id地址
spring:
  application:
    name:  pay-server  #服务名
server:
  port: 1040 #端口
feign:
   hystrix:
       enabled: true #开启熔断支持
hystrix:
  command:
      default:
        execution:
          isolation:
            thread:
              timeoutInMilliseconds: 6000   #hystrix超时时间

fengn接口实现熔断有两种方式:
在这里插入图片描述
我们这里先使用fallback方式,那么需要新建一个托底类去实现UserFeignClient接口,复写方法,代码如下:

@Component //记得加上此注解,让spring扫描该类,并管理
public class UserFallBack implements UserFeignClient {

    @Override
    public User getUserById(Long id) {
        return new User(-1L,"找不到用户","用户服务异常","");
    }
}

然后再接口类上面指定fallback方法:

/**
 * url路径要与user服务的路径一致,
 * 服务名要一致 ,
 * 参数要一致 ,
 * 返回值类型要一致。
 */
@FeignClient(value = "user-server",fallback = UserFallBack.class) //这里指定要访问的服务名
public interface UserFeignClient {

    @GetMapping("/user/{id}")
    public User getUserById(@PathVariable("id") Long id);
}

重启pay服务,访问peer1:1040/pay/1
SpringCloud 学习笔记十 多模块搭建-pay服务(Feign)+熔断器Hystrix_第1张图片
熔断功能实现成功,虽然触发了托底方法,但是看不到异常日志,所以我们这里使用第二种指定fallBackFactory的方式实现熔断
新建一个factctory实现 FallBackFactroy接口,这里需要指定泛型,
指定UserFeignClient的接口类型,返回一个该类型的对象,使用匿名内部类的方式,别忘了该类加上@Component 注解,实现代码:

@Component
public class UserFallBackFactory implements FallbackFactory {
    @Override
    public UserFeignClient create(Throwable throwable) {
        throwable.printStackTrace(); //打印异常信息到控制台
        return new UserFeignClient() {
            @Override
            public User getUserById(Long id) {
                return new User(-1L,"找不到用户","用户服务异常","");
            }
        };
    }
}

UserFeignClient 接口上注解修改为:

@FeignClient(value = "user-server",fallbackFactory = UserFallBackFactory.class) //这里指定要访问的服务名
public interface UserFeignClient {

    @GetMapping("/user/{id}")
    public User getUserById(@PathVariable("id") Long id);
}

重启pay服务,访问 http://peer1:1040/pay/1
SpringCloud 学习笔记十 多模块搭建-pay服务(Feign)+熔断器Hystrix_第2张图片
熔断成功,看控制台
Caused by: com.netflix.client.ClientException: Load balancer does not have available server for client: user-server
提示访问user-server服务失败

你可能感兴趣的:(SpringCloud学习笔记,java,spring,boot)