springboot 基于异步线程池来提升接口查询性能

1、可以通过 设置异步线程池任务任务,这样可以大大提升接口性能

import com.facebook.presto.jdbc.internal.guava.collect.Lists;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.vip.vman.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.common.errors.ApiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

@Slf4j
@RestController
@RequestMapping(value = "/vman/thread")
public class ThreadController {

    @Autowired
    RedisService redisService;

    ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("thread-get-all-test-%d").build();
    private  final ExecutorService executorService =  new ThreadPoolExecutor(50,60, 180L, TimeUnit.SECONDS,new LinkedBlockingQueue(),namedThreadFactory);

    //针对不要求接口返回的数据。可以通过异步执行代码来加快接口执行
    @RequestMapping(value = "/getTestAsync", method = RequestMethod.GET)
    public void executeTask(String id) {
        log.info("接受参数,id:{}",id);
        // 使用异步线程池执行任务
        executorService.execute(() -> {
            // 可以在此处编写需要异步执行的业务代码
            // 注意处理异常情况和释放资源
            // 示例:模拟耗时操作
            try {
                log.info("异常任务开始执行,id:{}", id);
                // 异步执行的任务逻辑,比如耗时10ms
                Thread.sleep(10);
                log.info("异步任务执行完成,id:{}", id);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }

}

你可能感兴趣的:(spring,boot,后端,java)