package com.tanpu.community.service;

import com.tanpu.community.feign.community.FeignClientForCommunity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.sleuth.instrument.async.LazyTraceAsyncTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.concurrent.atomic.AtomicInteger;

@Service
@Slf4j
public class TraceTestService {

    @Autowired
    private BeanFactory beanFactory;

    @Autowired
    private FeignClientForCommunity feignClientForCommunity;

    private LazyTraceAsyncTaskExecutor executor;
    private AtomicInteger count;

    @PostConstruct
    private void init() {
        ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
        pool.setMaxPoolSize(3);
        pool.setCorePoolSize(1);
        pool.setKeepAliveSeconds(3600);
        pool.initialize();
        executor = new LazyTraceAsyncTaskExecutor(beanFactory, pool);

        count = new AtomicInteger(0);
    }

    public void testTraceId() {
        Integer c = count.incrementAndGet();
        log.info("parent count is " + c);

        for (int i = 1; i <= 3; i++) {
            int subCount = i;
            executor.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1000);
                        log.info("child count is " + c + "-" + subCount);
                        feignClientForCommunity.testTraceId("" + c + "-" + subCount);
                    } catch (Exception e) {

                    }
                }
            });
        }

    }
}