iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 25
0
Software Development

30天從零開始 使用 Spring Boot 跟 Spring Cloud 建構完整微服務架構系列 第 25

Day 25 - 斷路器 Hystrix

增加服務中斷時的回覆訊息

有時候還是會有意外,但是出現問題如果跑出奇怪的錯有可能讓前端措手不及,或是稍微偽裝一下,可以讓客戶端無感異常

修改 reservation-client 專案

起動程式增加 @EnableCircuitBreaker ,然後在需要此功能的方法上增加 @HystrixCommand(fallbackMethod = "getReservationNamesFallback") 當失敗時他就會使用你指定的方法 getReservationNamesFallback 來回覆前端

@EnableZuulProxy
@EnableBinding(Source.class)
@EnableCircuitBreaker
@EnableDiscoveryClient
@SpringBootApplication
public class ReservationClientApplication {

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

@RestController
@RequestMapping("/reservations")
class ReservationApiGatewayRestController{

	@Autowired
	@LoadBalanced
	private RestTemplate restTemplate;
	
	@Autowired
	@Output(Source.OUTPUT)
	private MessageChannel messageChannel;
	
	@RequestMapping( method = RequestMethod.POST)
	public void write(@RequestBody Reservation r){
		this.messageChannel.send(MessageBuilder.withPayload(r.getReservationName()).build());
	}
	
	public Collection<String> getReservationNamesFallback(){
		return Collections.emptyList();
	}
	
	@HystrixCommand(fallbackMethod = "getReservationNamesFallback")
	@RequestMapping("names")
	public Collection<String> getReservationNames(){

		ParameterizedTypeReference<Resources<Reservation>> ptr = 
				new ParameterizedTypeReference<Resources<Reservation>>(){};

				ResponseEntity<Resources<Reservation>> responseEntity = 
						this.restTemplate.exchange("http://reservation-service/reservations", 
								HttpMethod.GET, null, ptr);
				
				Collection<String> nameList = responseEntity
						.getBody()
						.getContent()
						.stream()
						.map(Reservation::getReservationName)
						.collect(Collectors.toList());

				return nameList;
	}
}

reservation-client 起動後,把 reservation-service 關掉,這麼一來通常應用程式就會發生異常回傳 500 之類的,但是你可以試著呼叫 http://localhost:8050/reservations/names,你可以發現你只是得到一個空集合,不影響你的前端程式

[]

上一篇
Day 24 - 分散式追蹤系統視覺化介面 Zipkin UI
下一篇
Day 26 - 斷路器視覺化 Hystrix Dashboard
系列文
30天從零開始 使用 Spring Boot 跟 Spring Cloud 建構完整微服務架構35
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言