SpringCloud-基于feign自带熔断器实现熔断

一、maven配置

 com.wk.sc
    springcloud-demo
    1.0-SNAPSHOT

    
        1.8
        Greenwich.SR1
    

    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.4.RELEASE
        
    

    
         
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.cloud
            spring-cloud-starter-netflix-eureka-client
        
        
            org.springframework.cloud
            spring-cloud-starter-openfeign
        
    

    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                ${spring-cloud.version}
                pom
                import
            
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

二、application.yml配置

server:
  port: 7071

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka
spring:
  application:
    name: service-feign
feign:
  hystrix:
    enabled: true  # feign自带熔断器,默认是关闭的,需要手动开启

三、启动类

@SpringBootApplication
@EnableDiscoveryClient
@EnableEurekaClient
@EnableFeignClients
public class ServiceFeignApplication {

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

}

四、服务调用

  • 接口定义
/**
 * feign服务调用示例
 *
 */
@FeignClient(value = "service-hi",fallback = HelloServiceImpl.class)  //配置feign自带熔断器,fallback指定熔断后调用方法
public interface IHelloService {
    /**
     * 调用服务
     *
     * @param name
     * @return
     */
    @RequestMapping(value = "/hi", method = RequestMethod.GET)
    String sayHi(@RequestParam("name") String name);
}

  • 接口实现
/**
 * Feign 熔断服务实现
 *
 */
@Component
public class HelloServiceImpl implements IHelloService {
    @Override
    public String sayHi(String name) {
        return "sorry  " + name;
    }
}

五、控制器调用服务

/**
 * feign远程调用
 *
 */
@RestController
public class HiController {

    @Autowired
    private IHelloService helloService;

    @GetMapping(value = "/hi")
    public String sayHi(@RequestParam String name) {
        return helloService.sayHi(name);
    }

}

你可能感兴趣的:(SpringCloud-基于feign自带熔断器实现熔断)