Spring Boot Hystrix Sample
昨日までの、Spring Cloud Eureka server, service discovery, Ribbon に今回はHystrix(Circuit Breaker)を追加してみました。
tomotaka.hatenablog.com
イメージは、こんな感じかな?
work service
1,2,3,4 and 5秒かかるサービスのapi(port:8001,8002 で公開)
package com.example.eurekaclinet.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Random; import java.util.concurrent.TimeUnit; @RestController public class WorkServiceController { private static final Logger logger = LoggerFactory.getLogger(WorkServiceController.class); @Value("${server.port}") private int port; private Random random = new Random(); @RequestMapping("/work") public String work() { int i = random.nextInt(5) + 1; logger.info("start work with {} sec", i); try { TimeUnit.SECONDS.sleep(Long.valueOf(i)); } catch (InterruptedException e) { logger.error("work error", e); throw new RuntimeException(e.getMessage()); } String work = String.format("%d sec work done. port=[%d]", i, port); return work; } }
call work service
sample アプリが、上記のapiをcall
@ HystrixCommand annotationで、タイムアウト3100 millisecを設定しているので、4,5秒の処理では、レスポンスがfallbackMethodメソッドで設定している固定値「work not yet done.」を返却。
package com.example.eurekafeign.controller; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @RestController public class WorkController { private static final Logger logger = LoggerFactory.getLogger(WorkController.class); @Autowired private RestTemplate restTemplate; @RequestMapping("/work/eureka") @HystrixCommand(fallbackMethod = "workFallback", commandProperties = { @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3100") }) public String work() { logger.info("start work from eureka"); String work = restTemplate.getForObject("http://greeting-service/work", String.class); logger.info("end work from eureka"); return work; } public String workFallback() { return "work not yet done."; } }
Dashboard
まだ見かたがよくわかっていませんが、、、
タイムアウトの他にもHysteriaは、いろいろ設定できるよう。
まだまだ、勉強することが山積みです(汗)
コードは、アップ
github.com