调用组件Feign

有服务消费方调用提供方,之前采用的是restTemplate。

(1)在pom.xml中引入openfeign的启动器

<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

(2)在application.yml中开启feign的熔断功能

feign:
  hystrix:
    enabled: true # 开启Feign的熔断功能

  (3)在引导类上加上feign的注解

@SpringBootApplication
@EnableDiscoveryClient // 开启Eureka客户端
@EnableCircuitBreaker  //开启熔断器
@EnableFeignClients // 开启feign客户端
public class ConsumerApplication {

   public static void main(String[] args) {

      SpringApplication.run(ConsumerApplication.class, args);
   }

}

(4)创建一个接口com..client.UserClient,在接口上添加@FeignClient

@FeignClient(value = "service-provider", fallback = UserClientFallback.class) // 标注该类是一个feign接口
public interface UserClient {

    @GetMapping("user/{id}")
    User queryById(@PathVariable("id") Integer id);
}

(5)在接口中定义一些方法,这些方法来自服务提供方,但是不用写方法的具体实现见

(6)创建一个熔断类,实现feign的接口,实现对应的方法,这些方法就是熔断方法。

@Component
public class UserClientFallback implements UserClient {
    @Override
    public User queryById(Integer id) {

        User user = new User();
        user.setUsername("服务器繁忙,请稍后再试!");
        return user;
    }
}

(7)关闭服务提供方,访问页面会触发熔断方法,显示熔断方法里面的信息。

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值