package com.sf.vertx;

import com.sf.vertx.api.pojo.VertxConfig;
import com.sf.vertx.service.impl.AppConfigServiceImpl;

import io.vertx.circuitbreaker.CircuitBreaker;
import io.vertx.circuitbreaker.CircuitBreakerOptions;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpMethod;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TestCircuitBreaker {
	private static int port;
	public static void main(String[] args) {

		VertxConfig vertxConfig = AppConfigServiceImpl.getVertxConfig();
		// TODO 编解码线程池,后面优化协程等方式
		VertxOptions vertxOptions = new VertxOptions();

		Vertx VERTX = Vertx.vertx(vertxOptions);

		CircuitBreakerOptions options = new CircuitBreakerOptions().setMaxFailures(3).setTimeout(5000)
				.setFallbackOnFailure(true);

		CircuitBreaker breaker = CircuitBreaker.create("my-circuit-breaker", VERTX, options).openHandler(v -> {
			System.out.println("Circuit opened");
		}).closeHandler(v -> {
			System.out.println("Circuit closed");
		});
		for (int i = 0; i < 20; i++) {
			port = 9199;
			if(i % 2 == 0) {
				port = 9198;
				log.info("i:{},port:{}", i, port);
			}
			breaker.executeWithFallback(promise -> {
				VERTX.createHttpClient().request(HttpMethod.POST, port, "localhost", "/vertx/body").compose(req -> {
					return req.send("body").compose(resp -> {
						if (resp.statusCode() != 200) {
							return Future.failedFuture("HTTP error");
						} else {
							log.info("success req:{}", req.getPort());
							return resp.body().map(Buffer::toString);
						}
					});
				}).onComplete(promise);
			}, v -> {
				// Executed when the circuit is opened
				return "Hello (fallback)";
			}, ar -> {
				// Do something with the result
				System.out.println("Result: " + ar.result());
			});
		}
	}
}
