ribbon加入斷路器hyxtrix

首先,要在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毫秒以內,則正常返回結果!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章