�ᰮ�ƽ� - 52pojie.cn

 �һ�����
 ע��[Register]

QQ��¼

ֻ��һ�������ٿ�ʼ

����
�鿴: 2755|�ظ�: 8
��������

[Java ת��] SpringBoot�첽������¼

[��������]
mobaijun ������ 2022-1-25 10:29

����

ͻ�����룬������һ���첽���񣬼ǵ�֮ǰ��Ŀ�и�������Ҫʹ���첽ִ�У������첽����û�гɹ������������˶��߳�ȥִ�У�������ϵͳ��ѧϰ���첽ִ�����񡣼�¼һ��

��ʱ������Ŀ�У������������˵Ľӿڽ�����������ʱ����ʱ����������һֱ���ں�ʱ�����ϣ��������ܹ�����ִ�У� ���ǿ���ʹ�ö��߳������еĴ���������Ҳ����ʹ�� spring �ṩ���첽������ʽ @Async ��

���첽�����ķ���������ע�� @Async ���ͻ�����һ���µ��߳�ȥִ�С�

  1. Spring ͨ������ִ���� TaskExecutor ����ʵ�ֶ��̺߳Ͳ������̣�ʹ�� ThreadPoolTaskExecutor ��ʵ��һ�������̳߳ص� TaskExecutor ;

  2. �첽��Ҫ�������������� @EnableAsync  ���������첽������֧������Ҫ�첽ִ�еķ��������� @Async  ����������������һ����Ҫ�첽ִ�еķ���;

  3. ��������ʵ�� AsyncConfigurer �ӿڣ�����д getAsyncExecutor ������������һ�� ThreasPoolTaskExecutor ���Ϳ��Ի�ȡһ�������̳߳ص� TaskExecutor ;

  4. @Async ���ڷ����ϣ���ʾ����������һ���첽�ķ������������������棬�����������е����з��������첽�ķ�����

����

  • �½� SpringBoot ��Ŀ��������������
<!--SpringBoot�汾-->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.5.3</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<!--���ز���-->
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>
  • ����һ�������࣬�����̳߳ز���
package com.mobaijun.config;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Software��IntelliJ IDEA 2021.1.1 x64
 * Author: https://www.mobaijun.com
 * Date: 2021/8/2 11:07
 * ClassName:AsyncConfig
 * ���������첽������
 */
@Configuration
@EnableAsync // @EnableAsync��ͨ��������������������Main�����ϼ�@EnableAsync�������첽������֧�֡�
public class TaskExecutorConfig implements AsyncConfigurer {

    /**
     * 1.������ʵ��AsyncConfigurer�ӿڲ���дgetAsyncExcutor������������һ��ThreadPoolTaskExevutor
     * 2.ͨ����дgetAsyncExecutor�������ƶ�Ĭ�ϵ�����ִ���ɸ÷�������
     * 3.�������Ǿͻ�����һ�������̳߳ص�TaskExecutor
     */

    /**
     * ����ThreadPoolExecutor�ĺ��ijش�С��
     */
    private static final int CORE_POOL_SIZE = 5;

    /**
     * ����ThreadPoolExecutor�������ش�С��
     */
    private static final int MAX_POOL_SIZE = 20;

    /**
     * ����ThreadPoolExecutor��BlockingQueue��������
     */
    private static final int QUEUE_CAPACITY = 10;
    /**
     * �߳�ǰ׺����
     */
    private static final String THREAD_NAME_PREFIX = "task��";

    /**
     * Ĭ���̳߳�����ִ����
     */
    @Bean
    public Executor getAsyncExecutor() {
        // 1.Spring Ĭ�������Ǻ����߳�����СΪ1�������߳�������С�������ƣ���������Ҳ�������ơ�
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        // 2.�����߳���
        taskExecutor.setCorePoolSize(CORE_POOL_SIZE);
        // 3.�����߳���
        taskExecutor.setMaxPoolSize(MAX_POOL_SIZE);
        // 4.���д�С
        taskExecutor.setQueueCapacity(QUEUE_CAPACITY);
        // 5.�߳�ǰ׺����
        taskExecutor.setThreadNamePrefix(THREAD_NAME_PREFIX);
        // 6.������������ʱ���˲��Ա�֤���ᶪʧ�������󣬵��ǿ��ܻ�Ӱ��Ӧ�ó����������ܡ�
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 7.��ʼ���̳߳�
        taskExecutor.initialize();
        return taskExecutor;
    }

    /**
     * �Զ�������ִ�������ڶ����˶�������ִ�����������£�����ʹ��@Async("getMineAsync")���趨
     */
    @Bean
    public Executor getMineAsync() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(CORE_POOL_SIZE - 4);
        executor.setMaxPoolSize(MAX_POOL_SIZE - 10);
        executor.setQueueCapacity(QUEUE_CAPACITY - 5);
        executor.setThreadNamePrefix(THREAD_NAME_PREFIX);
        // rejection-policy����pool�Ѿ��ﵽmax size��ʱ�������δ���������
        // CALLER_RUNS���������߳���ִ�����񣬶����е��������ڵ��߳���ִ��
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}
  • ��дһ��αʵ����
package com.mobaijun.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.concurrent.Future;

/**
 * Software��IntelliJ IDEA 2021.1.1 x64
 * Author: https://www.mobaijun.com
 * Date: 2021/8/2 17:00
 * ClassName:ArithmeticService
 * ���������������� service �ࣺ����ʵ���й��첽��ͬ�����ּ��㷽ʽ�����ܱȽ�
 */
@Slf4j
@Component
public class ArithmeticService implements Serializable {

    /**
     * ����ʱ��
     */
    public static final int DoTime = 5000;

    /**
     * 1.�첽����ֻ��Ҫ������ʵ���첽�ķ����ϼ���@Asyncע�⣬ ��ͨ��Future<E>�������첽�����Ĵ�������
     * 2.ͨ��@Asyncע�������÷����Ǹ��첽����������ע�����༶�����������������еķ��������첽����
     */
    @Async
    public Future<Long> subByAsync() throws Exception {
        long start = System.currentTimeMillis();
        long sum = 0;
        Thread.sleep(DoTime);
        long end = System.currentTimeMillis();
        sum = end - start;
        log.info("\t ��������һ");
        return new AsyncResult<>(sum);
    }

    /**
     * ��ʹ���첽ע���ķ�ʽʵ���첽����
     */
    @Async
    public void subByVoid() throws Exception {
        long start = System.currentTimeMillis();
        long sum = 0;
        Thread.sleep(DoTime);
        long end = System.currentTimeMillis();
        sum = end - start;
        log.info("\t ����������   ");
        log.info("ע������ִ�е�ʱ���ǣ� " + sum + "�����룩");
    }

    /**
     * ʹ��ͬ�������ķ�ʽ--ͬ������
     */
    public long subBySync() throws Exception {
        long start = System.currentTimeMillis();
        long sum = 0;
        Thread.sleep(DoTime);
        long end = System.currentTimeMillis();
        sum = end - start;
        log.info("\t ����������   ");
        return sum;
    }

    @Async("getMineAsync")
    public void doMineAsync(int i) throws Exception {
        System.out.println("------\t:" + i);
        Thread.sleep(10000);
    }
}
  • web�ӿ�
package com.mobaijun.controller;

import com.mobaijun.service.ArithmeticService;
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.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.Future;

/**
 * Software��IntelliJ IDEA 2021.1.1 x64
 * Author: https://www.mobaijun.com
 * Date: 2021/8/2 17:06
 * ClassName:AsyncController
 * ��������
 */
@Slf4j
@RestController
public class AsyncController {

    @Autowired
    private ArithmeticService arithmeticService;

    @SuppressWarnings("static-access")
    @RequestMapping(value = {"/"}, method = RequestMethod.GET)
    public void index() {
        long start = System.currentTimeMillis();
        try {
            log.info("--------------------------------------------\n");
            log.info("ÿ������ִ�е�ʱ���ǣ�" + arithmeticService.DoTime + "�����룩");
            Future<Long> task = arithmeticService.subByAsync();
            arithmeticService.subByVoid();
            long sync = arithmeticService.subBySync();
            while (true) {
                if (task.isDone()) {
                    long async = task.get();
                    log.info("�첽����ִ�е�ʱ���ǣ�" + async + "�����룩");
                    // log.info("ע������ִ�е�ʱ���ǣ� -- �����룩");
                    log.info("ͬ������ִ�е�ʱ���ǣ�" + sync + "�����룩");
                    break;
                }
            }
            log.info("--------------------------------------------\n");
        } catch (Exception e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        log.info("\t........������Ӧʱ��Ϊ��" + (end - start) + "�����룩");
    }

    /**
     * �Զ���ʵ���߳��첽
     */
    @RequestMapping(value = {"/mine", "/m*"}, method = RequestMethod.GET)
    public void mineAsync() {
        for (int i = 0; i < 100; i++) {
            try {
                arithmeticService.doMineAsync(i);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
2021-08-02 17:23:45.047  INFO 14376 --- [nio-8004-exec-1] com.mobaijun.controller.AsyncController  : ÿ������ִ�е�ʱ���ǣ�5000�����룩
2021-08-02 17:23:50.068  INFO 14376 --- [  thread-exec-1] com.mobaijun.service.ArithmeticService   :     ��������һ
2021-08-02 17:23:50.068  INFO 14376 --- [  thread-exec-2] com.mobaijun.service.ArithmeticService   :     ����������   
2021-08-02 17:23:50.068  INFO 14376 --- [nio-8004-exec-1] com.mobaijun.service.ArithmeticService   :     ����������   
2021-08-02 17:23:50.068  INFO 14376 --- [  thread-exec-2] com.mobaijun.service.ArithmeticService   : ע������ִ�е�ʱ���ǣ� 5014�����룩
2021-08-02 17:23:50.068  INFO 14376 --- [nio-8004-exec-1] com.mobaijun.controller.AsyncController  : �첽����ִ�е�ʱ���ǣ�5014�����룩
2021-08-02 17:23:50.068  INFO 14376 --- [nio-8004-exec-1] com.mobaijun.controller.AsyncController  : ͬ������ִ�е�ʱ���ǣ�5014�����룩
2021-08-02 17:23:50.069  INFO 14376 --- [nio-8004-exec-1] com.mobaijun.controller.AsyncController  : --------------------------------------------
------  :0
------  :6
------  :7
------  :8
------  :9
------  :10
------  :11
------  :12
------  :15
------  :13
------  :14

��������

�������� 1�ᰮ�� +1 ����ֵ +1 ���� ����
xianyuamiao123 + 1 + 1 �������ۣ�����������

�鿴ȫ������

����ǰҪ��������̳���������ܣ��������ܻ�����Ҫ�ҵĴ𰸻����Ѿ����˷�������ͬ�����ˣ������ظ�������

qsc2857132 ������ 2022-1-25 11:07
֧�ִ���
emAngell ������ 2022-1-25 11:50
�üһ������д����java�ĵ��������е㲻��
 ¥��| mobaijun ������ 2022-1-25 13:41
emAngell ������ 2022-1-25 11:50
�üһ������д����java�ĵ��������е㲻��

�ⲻ�DZ���������ô
xianyuamiao123 ������ 2022-1-26 14:04
֧��֧��
angel_bai ������ 2022-1-26 17:13
ѧϰѧϰ
����Խ ������ 2022-1-27 18:16
ѧϰһ�£���л����������
QZFCANBA ������ 2022-2-4 10:56
��spring�Դ���stopwatch�Ϳ���ͳ�ƺ�ʱ
 ¥��| mobaijun ������ 2022-2-19 10:11
QZFCANBA ������ 2022-2-4 10:56
��spring�Դ���stopwatch�Ϳ���ͳ�ƺ�ʱ

�ǵģ�����Ҳ����
����Ҫ��¼���ſ��Ի��� ��¼ | ע��[Register]

�������ֹ���

�����б�

RSS����|С����|������¼|��ϵ����|�ᰮ�ƽ� - LCG - LSG ( ��ICP��16042023�� | ���������� 11010502030087�� )

GMT+8, 2025-8-27 09:17

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

���ٻظ� ���ض��� �����б�