Spring Boot Zuul Sample

前回Spring Boot Hystrix Sample - tomoTaka’s blog
までのSpring Boot Eureka, Ribbon, HystrixにZuul Proxyの機能を追加してみました。

イメージは、こんか感じかな?

f:id:tomoTaka:20180103113050p:plain

serviceをcall

curl "http://localhost:8888/sample/zuulwork"

backend serviceが正常な場合

zuul work done. from server port is [8001]

backend serviceが停止していた(異常)な場合

zuul work failed. due to [Load balancer does not have available server for client: greeting-service]

backend service(ZuulWorkServiceController.java)

@RestController
public class ZuulWorkServiceController {
    private static final Logger logger = LoggerFactory.getLogger(ZuulWorkServiceController.class);
    @Value("${server.port}")
    private int port;

    @RequestMapping("zuulwork")
    public String zuulwork() {
        String greeting = String.format("zuul work done. from server port is [%d]", port);
        return greeting;
    }
}

zulu setting(application.yml)

zuul:
  ignoredServices: '*'
  routes:
    works:
      path: /zuulwork
      serviceId: greeting-service

front component for circuit breaker(WorkFallback.java)

ZuulFallbackProviderは、非推奨になっていました。
それとgetRouteで、特定のroute[works]を指定しても聞かなかったので、全部*を対象にしています。

@Component
public class WorkFallback implements FallbackProvider {
    @Override
    public ClientHttpResponse fallbackResponse(Throwable cause) {
        ClientHttpResponse response = new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return HttpStatus.OK.value();
            }

            @Override
            public String getStatusText() throws IOException {
                return "Ok";
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {
                return new ByteArrayInputStream(("zuul work failed. due to [" + cause.getMessage() + "]").getBytes());
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders httpHeaders = new HttpHeaders();
                httpHeaders.setContentType(MediaType.TEXT_PLAIN);
                return httpHeaders;
            }
        };
        return response;
    }

    @Override
    public String getRoute() {
        return "*";
//        return "works";
    }
...
}

Front Application(EurekaFeignApplication.java)

@SpringBootApplication
@EnableCircuitBreaker
@EnableZuulProxy  // 追加
public class EurekaFeignApplication {

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

github.com

Spring Boot Cloudいろいろ楽しいです!