springCloud服务的熔断和降级

      首先声明:服务的熔断和降级是两个完全不同的概念,实现方式也不同。熔断是在服务的提供者那里,降级是在fegin那么远程调用的时候用的。

好了不多bb直接上熔断代码:

	<!--熔断依赖 -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
		</dependency>

代码:所用注解 @HystrixCommand(fallbackMethod = "getEmpBackup")  fallbackMethod 是指熔断时候所用的方法

/*
	 * 服务的熔断是在服务提供方
	 * 降级是在消费方
	 */
	// @HystrixCommand 注解通过 fallbackMethod 属性指定断路情况下要调用的备份方法
	@HystrixCommand(fallbackMethod = "getEmpBackup")
	@RequestMapping("/provider/circuit/breaker/get/emp")
	public ResultEntity<Employee> getEmp(@RequestParam("signal") String signal) {
		if ("bang".equals(signal)) {
			throw new RuntimeException();
		}
		return ResultEntity
				.successWithData(new Employee(666, "sam666", 666.66));
	}

	public ResultEntity<Employee> getEmpBackup(
			@RequestParam("signal") String signal) {
		return ResultEntity.failed("circuit break workded,with signal="
				+ signal);
	}

好了熔断就是这么简单,不要忘记在启动类上加注解@EnableCircuitBreaker

@SpringBootApplication
@EnableCircuitBreaker
public class AtguiguMainType {
	public static void main(String[] args) {
		SpringApplication.run(AtguiguMainType.class, args);
	}

}

接下来看降级: 降级是在远程调用的时候fegin、通常会把fegin单独抽离出来,就是为了好维护。

先加依赖

		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
		</dependency>
	</dependencies>

写方法:

@Component
public class MyFallBackFactory implements
		FallbackFactory<EmployeeRemoteService> {

	/**
	 * cause是异常的原因
	 * 
	 */
	@Override
	public EmployeeRemoteService create(Throwable cause) {
		return new EmployeeRemoteService() {

			@Override
			@RequestMapping("/provider/get/employee/remote")
			public Employee getEmployeeRemote() {
				return null;
			}

			@Override
			@RequestMapping("/provider/get/employee/by/id")
			public Employee getEmployeeById(Integer empId) {
				return null;
			}

			@Override
			@RequestMapping("/provider/save/emp")
			public Employee saveEmp(Employee employee) {
				return new Employee(444,
						"call provider failed,fall back here, reason is "
								+ cause.getClass().getName() + " "
								+ cause.getMessage(), 444.444);
			}
		};

	}

}

要想实现降级首先要实现 FallbackFactory<EmployeeRemoteService> 里面的类型填写你需要降级的远程调用类,

然后实现create方法,里面会重新你的接口的所有方法,在里面可以定义,在降级是返回给前端的各种。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值