ribbon加入断路器hyxtrix

14 篇文章 0 订阅
14 篇文章 0 订阅

首先,要在POM里加入如下配置:

		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-hystrix</artifactId>
			<version>1.4.6.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>

实现一个HelloService:

package com.sc.consumerribbon.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.ribbon.proxy.annotation.Hystrix;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class HelloService {

    @Autowired
    private RestTemplate restTemplate;

    private String serviceName = "http://HELLO-SERVICE/hello/";

    @HystrixCommand(fallbackMethod = "helloFallback")
    public String getHello() {
        return this.restTemplate.getForEntity(this.serviceName, String.class).getBody();
    }

    public String helloFallback() {
        return "error\n";
    }
}

关键是其中的     @HystrixCommand(fallbackMethod = "helloFallback") ,意思是调用HELLO-SERVICE失败时,会执行helloFallback方法,返回error。

然后,在真正的Controller层实现对HelloService的调用:

package com.sc.consumerribbon.controller;

import com.sc.consumerribbon.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ConsumerController {

    @Autowired
    private HelloService helloService;

    @GetMapping("/ribbon-consumer")
    public String helloConsumer() {
        return this.helloService.getHello();
    }

}

注意,还要在Application层面加入注解@EnableCircuitBreaker

@EnableCircuitBreaker
@SpringBootApplication
@EnableDiscoveryClient
public class ConsumerRibbonApplication {

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

	@Bean
	@LoadBalanced
	public RestTemplate restTemplate(){
		return new RestTemplate();
	}

}

实现效果如下:

明显的,远端服务接口HELLO-SERVICE随机休眠,如果超过1000毫秒,触发断路器,则会执行fallback方法,放回error。如果随机休眠在1000毫秒以内,则正常返回结果!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值