Spring Cloud Feign中使用断路器

本文介绍了如何在Spring Cloud Feign中启用断路器功能,通过配置文件开启断路器,并逐步展示了从创建新模块、编写配置文件、定义接口及实现类,到启动应用的过程。当服务提供者关闭时,断路器能够起到容错作用,避免服务雪崩。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Feign自带断路器,在配置文件中将其打开就可以

application.properties

feign.hystrix.enabled=true

application.yml

feign:
  hystrix:
    enabled : true

同样的,我们要先搞定服务注册中心,并将其启动。在我的项目中它的位置是

接着我将我的服务提供者启动

接下来我们开始Feign实现断路器

一、新建module

接下来next-finish。

之后feign这个module里面的架构这样的

先看配置文件application.yml

server:
  port: 8764
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8760/eureka/
spring:
  application:
    name: service-feign
feign:
  hystrix:
    enabled : true

接着看SchedualServiceHello.java,其中value是微服务的名称这里指定是上诉服务提供者的服务名称可看下图。fallback标记容错后执行的类。

package com.feign.feign.service;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @Author zhaomengxia
 * @create 2019/8/27 20:42
 */
@FeignClient(value = "service-producer",fallback = SchedualServiceHelloHystric.class)
public interface SchedualServiceHello {

    @RequestMapping(value = "/hello",method = RequestMethod.GET)
    String sayHello(@RequestParam("name") String name);
}

再看SchedualServiceHello接口的实现类SchedualServiceHelloHystric.java

package com.feign.feign.service;

import org.springframework.stereotype.Component;

/**
 * @Author zhaomengxia
 * @create 2019/8/27 20:52
 */
@Component
public class SchedualServiceHelloHystric implements SchedualServiceHello{
    @Override
    public String sayHello(String name) {
        return "sorry,"+name;
    }
}

最后是启动类FeignApplication.java

package com.feign.feign;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableFeignClients
@EnableEurekaClient
public class FeignApplication {

	public static void main(String[] args) {
		SpringApplication.run(FeignApplication.class, args);
	}

}

下面就启动FeignApplication

此时浏览器访问http://localhost:8764/sayHello?name=xia

将服务提供者service-producer关闭

之后访问http://localhost:8764/sayHello?name=xia

源代码

https://github.com/zhaomengxia/springboot_mybatis.git

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值