/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved.
 * <a>http://www.crunii.com</a>
 */
package com.crunii.micro.core.service.impl;

import com.crunii.micro.core.service.Resilience4jTestService;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import io.github.resilience4j.ratelimiter.annotation.RateLimiter;
import io.github.resilience4j.timelimiter.annotation.TimeLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;

/**
 * @author 田平 create 2023-02-15 10:51:26
 */
@Service
@Slf4j
public class Resilience4jTestServiceImpl implements Resilience4jTestService {
	/**
	 * core_testTimeout，对应的设置需要配置，默认是60秒
	 *
	 * @return
	 */
	@Override
	@TimeLimiter(name = "core_testTimeout", fallbackMethod = "testTimeoutFallback")
	public CompletionStage<String> testTimeout() {
		return CompletableFuture.supplyAsync(() -> {
			try {
				TimeUnit.SECONDS.sleep(2);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			return "resilience4j_testTimeout";
		});
	}

	/**
	 * 保持和testTimeout的参数一样，多一个异常
	 *
	 * @param e
	 * @return
	 */
	public CompletionStage<String> testTimeoutFallback(Exception e) {
		log.error("testTimeoutFallback", e);
		return CompletableFuture.supplyAsync(() -> "resilience4j_timeout_fallback");
	}

	@Override
	@CircuitBreaker(name = "core_testBreaker", fallbackMethod = "testBreakerFallback")
	public String testBreaker() {
		log.info("call testBreaker!");
		int a = 1 / 0;
		return "testBreaker";
	}

	public String testBreakerFallback(Exception e) {
		log.error("testBreakerFallback", e);
		return "testBreakerFallback";
	}

	/**
	 * 限流
	 *
	 * @return
	 */
	@Override
	@RateLimiter(name = "core_testRate", fallbackMethod = "testRateFallback")
	public String testRate() {
		log.info("call testRate!");
		return "testRate";
	}

	public String testRateFallback(Exception e) {
		log.error("testRateFallback", e);
		return "testRate call Too Many Requests 429 ";
	}

}
