当前位置:   article > 正文

SpringBoot使用异步线程处理热点接口提高接口并发_异步线程接口

异步线程接口

环境参数

SpringBoot版本 :2.1.0.RELEASE

<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.0.RELEASE</version>
		<relativePath />
</parent>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

配置步骤

1.配置项 @Configuration SysConfigure

自定义一个@Configuration 配置项
配置异步线程池
例如
/配置核心线程数/
/配置最大线程数/
/配置队列大小/
/活跃时间/
/配置线程池中的线程的名称前缀/
/设置拒绝策略:当pool已经达到max size的时候,如何处理新任务/

package com.xzk6.config;

import com.github.pagehelper.PageHelper;
import com.xzk6.config.async.AsyncTaskProperties;
import com.xzk6.constant.IConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.servlet.MultipartConfigElement;
import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author xzk
 */
@Configuration
@Slf4j
public class SysConfigure {
	/** 注入配置类 */
    private final AsyncTaskProperties config;

    public SysConfigure(AsyncTaskProperties config) {
        this.config = config;
    }

	/** 可定义注入Bean名称  和后续需要sync的方法使用 */
	@Bean(IConstants.ASYNC_POOL)
	public Executor asyncServiceExecutor() {
		log.info("start asyncServiceExecutor(狗头保命)");
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		/**配置核心线程数**/
		executor.setCorePoolSize(config.getCorePoolSize());
		/**配置最大线程数**/
		executor.setMaxPoolSize(config.getMaxPoolSize());
		/**配置队列大小**/
		executor.setQueueCapacity(config.getQueueCapacity());
		/**活跃时间**/
        executor.setKeepAliveSeconds(config.getKeepAliveSeconds());
		/**配置线程池中的线程的名称前缀**/
		executor.setThreadNamePrefix("xzk6-syncThread-");
		/** 设置拒绝策略:当pool已经达到max size的时候,如何处理新任务**/
		/** CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行**/
		executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
		/**执行初始化**/
		executor.initialize();
		return executor;
	}

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54

异步线程池Bean
在这里插入图片描述

线程池参数 AsyncTaskProperties

package com.xzk6.config.async;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * 线程池配置属性类
 * @author xzk
 * @date 2020年6月2日23:36:20
 */
@Data
@Component
@ConfigurationProperties(prefix = "task.pool")
public class AsyncTaskProperties {

    private int corePoolSize;

    private int maxPoolSize;

    private int keepAliveSeconds;

    private int queueCapacity;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

2.配置文件 application.yml

task:
  pool:
    # 核心线程池大小
    core-pool-size: 10
    # 最大线程数
    max-pool-size: 30
    # 活跃时间
    keep-alive-seconds: 60
    # 队列容量
    queue-capacity: 3000
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

3.控制器 Controller

package com.xzk6.test.controller;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xzk6.config.redis.RedisUtil;
import com.xzk6.controller.BaseController;
import com.xzk6.test.entity.Test5;
import com.xzk6.test.service.ITest5Service;
import com.xzk6.utils.PageUtil;
import com.xzk6.utils.ResultUtil;
import com.xzk6.utils.Util;
import com.xzk6.utils.UuidUtil;
import com.xzk6.utils.common.CommonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author xzk
 * @date 2020年6月2日23:47:46
 */

@Api(description = "测试")
@RestController
@RequestMapping("api/pub/test5")
@Slf4j
public class Test5Controller extends BaseController {

    @Autowired
    private ITest5Service iTest5Service;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 热点接口测试
     *
     * @param request
     * @param bean
     * @return JSONObject
     */
    @ApiOperation(value = "查看测试列表(分页)", notes = "查看测试列表(分页)", httpMethod = "POST")
    @ApiImplicitParams({})
    @ResponseBody
    @RequestMapping(value = "/testList", produces = "application/json;charset=utf-8")
    public Object findPageList(HttpServletRequest request,  Test5 bean) throws Exception {
        long timer1 = System.currentTimeMillis();
        String uuid = UuidUtil.get32UUID();
        Map<String, Object> param = Util.getRequestParams( request );
        log.info( "执行流水:开始[" + uuid + "]" + in_pageList + bean );
        Integer page = PageUtil.getPage( param );// 获取页码
        Integer size = PageUtil.getSize( param );// 获取条数
        PageHelper.startPage( page, size );
        List<Map<String, Object>> List = iTest5Service.findList( param );
        /** 假如我们这个 iTest5Service.test  操作是非同步实时处理。
        	我们可以异步处理来提高接口响应速度提高性能,
		        if(牛逼接口){
		       		 牛逼的技术驱动业务,
		        	 吊炸天的业务给公司带来利益,
		        	 然后我们升职加薪,隐去白富美,走上人生巅峰。
		        }else{
					菜鸡单体应用思维驱动不了互联网业务
					业务凉凉,项目不验收。
					老板开除你,
					你露宿接头,饥肠辘辘
					然后不小心吃了野味
					然后。。。
				}
				哈哈哈,
				我这只是一个小小的逻辑方式。提升性能方式、方法还很多。
				大家一起学习。然后一起发财
         **/
        iTest5Service.test(bean);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>( List );
        int count = (int) pageInfo.getTotal();
        pageInfo = new PageInfo<Map<String, Object>>( ResultUtil.Listvaluechangenull( List ) );
        log.info( "执行流水:结束[" + uuid + "] 总耗时 " + (System.currentTimeMillis() -timer1) );
        return  CommonUtil.successJson( count,pageInfo.getList() );
    }

}


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96

4.业务接口 Service

package com.xzk6.test.service;

import com.xzk6.test.entity.Test5;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务类接口
 * </p>
 *
 * @author xzk
 * @since 2020年6月2日23:47:46
 */
public interface ITest5Service extends IService<Test5> {

    /**
     * <p>
     * 列表
     * </p>
     *
     * @param map
     * @return List<Map < String, Object>>
     * @author xzk
     * @date 2020-05-20
     */
    List<Map<String, Object>> findList(Map<String, Object> map) throws Exception;


    /**
     * <p>
     * 异步测试接口
     * </p>
     *
     * @param bean
     * @return void
     * @author xzk
     * @date 2020年6月2日23:47:46
     */
    void test(Test5 bean) throws Exception;

  

}


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
package com.xzk6.test.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xzk6.constant.IConstants;
import com.xzk6.mapper.test.Test5Mapper;
import com.xzk6.test.entity.Test5;
import com.xzk6.test.service.ITest5Service;
import com.xzk6.utils.UuidUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xzk
 * @since 2020年6月2日23:47:46
 */
@Service
@Slf4j
public class Test5ServiceImpl extends ServiceImpl<Test5Mapper, Test5> implements ITest5Service {

    /**
     * <p>
     * 列表
     * </p>
     *
     * @param map
     * @return List<Map < String, Object>>
     * @author xzk
     * @date 2020年6月2日23:47:46
     */
    @Override
    public List<Map<String, Object>> findList(Map<String, Object> map) throws Exception {
        return baseMapper.findList( map );
    }

   
    /**
     * <p>
     * 异步测试接口
     * </p>
     *
     * @param bean
     * @return void
     * @author xzk
     * @date 2020年6月2日23:47:46
     */
    @Async(IConstants.ASYNC_POOL)
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void test(Test5 bean) throws Exception {
       log.info("进入----异步 "+ bean);
       Thread.sleep(3000);
       log.info("结束----异步");
    }

    

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67

核心是 在调用方法加上 @Async
核心是 在启动主类加上 @EnableAsync

package com.xzk6;

import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
import com.xzk6.config.Init;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;


/**
 * @author xzk
 */
@EnableAsync
@SpringBootApplication // boot
@EnableTransactionManagement// 事务
@EnableScheduling // 启用定时器
@EnableSwaggerBootstrapUI // swagger
//@ComponentScan("com.xzk6")
@MapperScan(basePackages = {"com.xzk6.mapper"})
@Slf4j
public class ApiApplication {

    /**
     * Start
     */
    public static void main(String[] args) {
        long timer = System.currentTimeMillis();
        SpringApplication springapplication = new SpringApplication( ApiApplication .class );
        ApplicationContext applicationContext = springapplication.run( args );
        log.info( "------------------Bean Nums" + applicationContext.getBeanDefinitionCount() );
        Init.init();// 启动私有服务
        log.info( "服务启动[成功] 耗时:[" + ((System.currentTimeMillis() - timer) / 1000) + " 秒]" );
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39

完成! 是不是很简单 来验证结果

5.结果

在这里插入图片描述
瞌睡。睡觉。大家晚安。
我是一个莫得感情努力赚钱的工具人
在这里插入图片描述

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/blog/article/detail/52451
推荐阅读
相关标签
  

闽ICP备14008679号