SpringCloud 商城系统搭建之Hystrix(基于Feign)

java哥 阅读:674 2021-03-31 13:18:37 评论:0

前提

1、Feign在整合到Spring Cloud时已经自带了hystrix模块,所以pom.xml中不需要额外引入feign依赖。

2、本文是基于SpringCloud 商城系统搭建之eureka 

一、基于Feign使用熔断器

按照下面步骤改造之前的项目supermarker-feign-consume

1、application.properties中开启熔断器,添加如下代码:

#hystrix 配置:默认熔断器关闭false 
feign.hystrix.enabled=true

修改后完整application.properties 配置文件内容

server.port=8085 
spring.application.name=fegin 
# 
eureka.client.register-with-eureka=false 
# 和eureka服务器通讯的URL 
eureka.client.service-url.defaultZone=http://localhost:8081/eureka/ 
eureka.instance.instance-id=consumer-fegin 
 
#spring-boot-actuator配置 
#开放所有的web Endpoints 
management.endpoints.web.exposure.include=* 
 
#hystrix 配置:默认熔断器关闭false 
feign.hystrix.enabled=true 
 

2、修改FeignClient接口(FeignServiceInter.java) 并且指定FeignClient接口的fallback 属性,修改后FeignServiceInter. 接口代码:

package com.zzg.inter; 
 
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; 
 
import com.zzg.callback.FeignCallBack; 
import com.zzg.entity.User; 
 
@FeignClient(value = "provider",fallback = FeignCallBack.class) 
public interface FeignServiceInter { 
	 
	 
	@RequestMapping(value = "/user",method = RequestMethod.GET) 
    public User findById(@RequestParam(value = "id") Integer id);  
 
} 

@FeignClient注解参数说明:

  • name:指定FeignClient的名称,如果项目使用了Ribbon,name属性会作为微服务的名称,用于服务发现。

  • fallback: 定义容错的处理类,当调用远程接口失败或超时时,会调用对应接口的容错逻辑,fallback指定的类必须实现@FeignClient标记的接口。

  • fallbackFactory: 工厂类,用于生成fallback类示例,通过这个属性我们可以实现每个接口通用的容错逻辑,减少重复的代码

  • path: 定义当前FeignClient的统一前缀,类似于注解到类上的@RequestMapping的功能

3、添加熔断处理类FeignCallBack.java

package com.zzg.callback; 
 
import org.springframework.stereotype.Component; 
 
import com.zzg.entity.User; 
import com.zzg.inter.FeignServiceInter; 
 
@Component 
public class FeignCallBack implements  FeignServiceInter{ 
 
	@Override 
	public User findById(Integer id) { 
		// TODO Auto-generated method stub 
		 System.out.println("Feign 之Hystrix 断路器 生效"); 
	     return new User(); 
	} 
 
} 

4、开始测试

按顺序启动supermarker-eureka、supermarker-provider(生产者)和supermarker-feign-consume(消费者),此时打开浏览器访问http://localhost:8085/user?id=1,服务正常,截图如下

然后停服务supermarker-provider(生产者),再次访问访问http://localhost:8085/user?id=1,此时会触发熔断,截图如下:

标签:Spring Cloud
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号