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

前提

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,此时会触发熔断,截图如下:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值