国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

聊聊spring的async注解

Steve_Wang_ / 587人閱讀

摘要:序本文主要聊聊中的注解。這里從獲取注解有個(gè)可以標(biāo)注使用哪個(gè),這里的就是尋找這個(gè)標(biāo)識。推薦注解指定,然后的返回,讓它去尋找默認(rèn)的自己應(yīng)用里頭都默認(rèn)定義一個(gè)給托管

本文主要聊聊spring中的async注解。

AsyncConfigurer
@EnableAsync(proxyTargetClass = true)
@Configuration
public class AsyncConfig implements AsyncConfigurer{

    private static final Logger LOGGER = LoggerFactory.getLogger(AsyncConfig.class);

    @Override
    public Executor getAsyncExecutor() {
        return null;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new AsyncUncaughtExceptionHandler() {
            @Override
            public void handleUncaughtException(Throwable throwable, Method method, Object... params) {
                LOGGER.error(throwable);
            }
        };
    }
}
getAsyncExecutor

這里討論一下getAsyncExecutor這里定義null的情況。
spring-context-4.3.9.RELEASE-sources.jar!/org/springframework/scheduling/annotation/AbstractAsyncConfiguration.java

@Configuration
public abstract class AbstractAsyncConfiguration implements ImportAware {

    protected AnnotationAttributes enableAsync;

    protected Executor executor;

    protected AsyncUncaughtExceptionHandler exceptionHandler;


    @Override
    public void setImportMetadata(AnnotationMetadata importMetadata) {
        this.enableAsync = AnnotationAttributes.fromMap(
                importMetadata.getAnnotationAttributes(EnableAsync.class.getName(), false));
        if (this.enableAsync == null) {
            throw new IllegalArgumentException(
                    "@EnableAsync is not present on importing class " + importMetadata.getClassName());
        }
    }

    /**
     * Collect any {@link AsyncConfigurer} beans through autowiring.
     */
    @Autowired(required = false)
    void setConfigurers(Collection configurers) {
        if (CollectionUtils.isEmpty(configurers)) {
            return;
        }
        if (configurers.size() > 1) {
            throw new IllegalStateException("Only one AsyncConfigurer may exist");
        }
        AsyncConfigurer configurer = configurers.iterator().next();
        this.executor = configurer.getAsyncExecutor();
        this.exceptionHandler = configurer.getAsyncUncaughtExceptionHandler();
    }

}

這里從AsyncConfigurer獲取executor

AsyncExecutionInterceptor

spring-aop-4.3.9.RELEASE-sources.jar!/org/springframework/aop/interceptor/AsyncExecutionInterceptor.java

/**
     * Intercept the given method invocation, submit the actual calling of the method to
     * the correct task executor and return immediately to the caller.
     * @param invocation the method to intercept and make asynchronous
     * @return {@link Future} if the original method returns {@code Future}; {@code null}
     * otherwise.
     */
    @Override
    public Object invoke(final MethodInvocation invocation) throws Throwable {
        Class targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);
        Method specificMethod = ClassUtils.getMostSpecificMethod(invocation.getMethod(), targetClass);
        final Method userDeclaredMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);

        AsyncTaskExecutor executor = determineAsyncExecutor(userDeclaredMethod);
        if (executor == null) {
            throw new IllegalStateException(
                    "No executor specified and no default executor set on AsyncExecutionInterceptor either");
        }

        Callable task = new Callable() {
            @Override
            public Object call() throws Exception {
                try {
                    Object result = invocation.proceed();
                    if (result instanceof Future) {
                        return ((Future) result).get();
                    }
                }
                catch (ExecutionException ex) {
                    handleError(ex.getCause(), userDeclaredMethod, invocation.getArguments());
                }
                catch (Throwable ex) {
                    handleError(ex, userDeclaredMethod, invocation.getArguments());
                }
                return null;
            }
        };

        return doSubmit(task, executor, invocation.getMethod().getReturnType());
    }
AsyncExecutionAspectSupport.determineAsyncExecutor

spring-aop-4.3.9.RELEASE-sources.jar!/org/springframework/aop/interceptor/AsyncExecutionAspectSupport.java

**
     * Determine the specific executor to use when executing the given method.
     * Should preferably return an {@link AsyncListenableTaskExecutor} implementation.
     * @return the executor to use (or {@code null}, but just if no default executor is available)
     */
    protected AsyncTaskExecutor determineAsyncExecutor(Method method) {
        AsyncTaskExecutor executor = this.executors.get(method);
        if (executor == null) {
            Executor targetExecutor;
            String qualifier = getExecutorQualifier(method);
            if (StringUtils.hasLength(qualifier)) {
                targetExecutor = findQualifiedExecutor(this.beanFactory, qualifier);
            }
            else {
                targetExecutor = this.defaultExecutor;
                if (targetExecutor == null) {
                    synchronized (this.executors) {
                        if (this.defaultExecutor == null) {
                            this.defaultExecutor = getDefaultExecutor(this.beanFactory);
                        }
                        targetExecutor = this.defaultExecutor;
                    }
                }
            }
            if (targetExecutor == null) {
                return null;
            }
            executor = (targetExecutor instanceof AsyncListenableTaskExecutor ?
                    (AsyncListenableTaskExecutor) targetExecutor : new TaskExecutorAdapter(targetExecutor));
            this.executors.put(method, executor);
        }
        return executor;
    }

@Aync注解有個(gè)value可以標(biāo)注使用哪個(gè)executor,這里的getExecutorQualifier就是尋找這個(gè)標(biāo)識。

這里如果defaultExecutor為null的話,則獲取找默認(rèn)的executor

/**
     * Retrieve or build a default executor for this advice instance.
     * An executor returned from here will be cached for further use.
     * 

The default implementation searches for a unique {@link TaskExecutor} bean * in the context, or for an {@link Executor} bean named "taskExecutor" otherwise. * If neither of the two is resolvable, this implementation will return {@code null}. * @param beanFactory the BeanFactory to use for a default executor lookup * @return the default executor, or {@code null} if none available * @since 4.2.6 * @see #findQualifiedExecutor(BeanFactory, String) * @see #DEFAULT_TASK_EXECUTOR_BEAN_NAME */ protected Executor getDefaultExecutor(BeanFactory beanFactory) { if (beanFactory != null) { try { // Search for TaskExecutor bean... not plain Executor since that would // match with ScheduledExecutorService as well, which is unusable for // our purposes here. TaskExecutor is more clearly designed for it. return beanFactory.getBean(TaskExecutor.class); } catch (NoUniqueBeanDefinitionException ex) { logger.debug("Could not find unique TaskExecutor bean", ex); try { return beanFactory.getBean(DEFAULT_TASK_EXECUTOR_BEAN_NAME, Executor.class); } catch (NoSuchBeanDefinitionException ex2) { if (logger.isInfoEnabled()) { logger.info("More than one TaskExecutor bean found within the context, and none is named " + ""taskExecutor". Mark one of them as primary or name it "taskExecutor" (possibly " + "as an alias) in order to use it for async processing: " + ex.getBeanNamesFound()); } } } catch (NoSuchBeanDefinitionException ex) { logger.debug("Could not find default TaskExecutor bean", ex); try { return beanFactory.getBean(DEFAULT_TASK_EXECUTOR_BEAN_NAME, Executor.class); } catch (NoSuchBeanDefinitionException ex2) { logger.info("No task executor bean found for async processing: " + "no bean of type TaskExecutor and no bean named "taskExecutor" either"); } // Giving up -> either using local default executor or none at all... } } return null; }

如果工程里頭沒有定義默認(rèn)的task executor的話,則獲取bean的時(shí)候會拋出NoSuchBeanDefinitionException

AsyncExecutionInterceptor.getDefaultExecutor

spring-aop-4.3.9.RELEASE-sources.jar!/org/springframework/aop/interceptor/AsyncExecutionInterceptor.java

protected Executor getDefaultExecutor(BeanFactory beanFactory) {
        Executor defaultExecutor = super.getDefaultExecutor(beanFactory);
        return (defaultExecutor != null ? defaultExecutor : new SimpleAsyncTaskExecutor());
    }

AsyncExecutionInterceptor重寫了getDefaultExecutor方法,先調(diào)用AsyncExecutionAspectSupport的getDefaultExecutor,如果默認(rèn)的找不到,這里new一個(gè)SimpleAsyncTaskExecutor

Executor關(guān)閉問題

如果是在AsyncConfigurer定義的executor,沒有受spring托管,貌似是不會在spring context關(guān)閉的時(shí)候主動(dòng)shutdown,這個(gè)可能是個(gè)問題。

public class ThreadPoolTaskExecutor extends ExecutorConfigurationSupport
        implements AsyncListenableTaskExecutor, SchedulingTaskExecutor {
        //...
}        

spring-context-4.3.9.RELEASE-sources.jar!/org/springframework/scheduling/concurrent/ExecutorConfigurationSupport.java

public abstract class ExecutorConfigurationSupport extends CustomizableThreadFactory
        implements BeanNameAware, InitializingBean, DisposableBean {

    //...
    /**
     * Perform a shutdown on the underlying ExecutorService.
     * @see java.util.concurrent.ExecutorService#shutdown()
     * @see java.util.concurrent.ExecutorService#shutdownNow()
     * @see #awaitTerminationIfNecessary()
     */
    public void shutdown() {
        if (logger.isInfoEnabled()) {
            logger.info("Shutting down ExecutorService" + (this.beanName != null ? " "" + this.beanName + """ : ""));
        }
        if (this.waitForTasksToCompleteOnShutdown) {
            this.executor.shutdown();
        }
        else {
            this.executor.shutdownNow();
        }
        awaitTerminationIfNecessary();
    }

    /**
     * Wait for the executor to terminate, according to the value of the
     * {@link #setAwaitTerminationSeconds "awaitTerminationSeconds"} property.
     */
    private void awaitTerminationIfNecessary() {
        if (this.awaitTerminationSeconds > 0) {
            try {
                if (!this.executor.awaitTermination(this.awaitTerminationSeconds, TimeUnit.SECONDS)) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Timed out while waiting for executor" +
                                (this.beanName != null ? " "" + this.beanName + """ : "") + " to terminate");
                    }
                }
            }
            catch (InterruptedException ex) {
                if (logger.isWarnEnabled()) {
                    logger.warn("Interrupted while waiting for executor" +
                            (this.beanName != null ? " "" + this.beanName + """ : "") + " to terminate");
                }
                Thread.currentThread().interrupt();
            }
        }
    }
}        

ExecutorConfigurationSupport實(shí)現(xiàn)了DisposableBean接口,重寫了destory方法,在里頭調(diào)用shutdown

因此,最好將ThreadPoolTaskExecutor的定義托管給spring,這樣可以優(yōu)化關(guān)閉。

小結(jié) async注解沒有指定executor

如果AsyncConfigurer沒有定義executor,則會去尋找spring托管的名為taskExecutor的executor,如果沒有,則拋出NoSuchBeanDefinitionException,返回null,然后由AsyncExecutionInterceptor.getDefaultExecutor去new一個(gè)SimpleAsyncTaskExecutor,不過這個(gè)不是spring托管的

如果AsyncConfigurer定義了executor,則這個(gè)也不是spring托管的

不是spring托管的executor,需要自己額外去監(jiān)聽事件,然后優(yōu)雅關(guān)閉

async注解指定executor

比如

@Async("myTaskExecutor")
public void xxxx(){
    
}

這個(gè)則使用指定的myTaskExecutor,而不是AsyncConfigurer中定義的executor。

推薦async注解指定task executor,然后AsyncConfigurer的getAsyncExecutor返回null,讓它去尋找默認(rèn)的taskExecutor(自己應(yīng)用里頭都默認(rèn)定義一個(gè)taskExecutor給spring托管)

doc

Task Execution and Scheduling

文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://specialneedsforspecialkids.com/yun/70551.html

相關(guān)文章

  • 聊聊Dubbo - Dubbo可擴(kuò)展機(jī)制實(shí)戰(zhàn)

    摘要:今天我想聊聊的另一個(gè)很棒的特性就是它的可擴(kuò)展性。的擴(kuò)展機(jī)制在的官網(wǎng)上,描述自己是一個(gè)高性能的框架。接下來的章節(jié)中我們會慢慢揭開擴(kuò)展機(jī)制的神秘面紗。擴(kuò)展擴(kuò)展點(diǎn)的實(shí)現(xiàn)類。的定義在配置文件中可以看到文件中定義了個(gè)的擴(kuò)展實(shí)現(xiàn)。 摘要: 在Dubbo的官網(wǎng)上,Dubbo描述自己是一個(gè)高性能的RPC框架。今天我想聊聊Dubbo的另一個(gè)很棒的特性, 就是它的可擴(kuò)展性。 Dubbo的擴(kuò)展機(jī)制 在Dub...

    techstay 評論0 收藏0
  • SpringCloud(第 047 篇)注解Async配置異步任務(wù)

    摘要:耗時(shí)毫秒耗時(shí)毫秒耗時(shí)毫秒添加異步任務(wù)控制器測試異步任務(wù)控制器。 SpringCloud(第 047 篇)注解式Async配置異步任務(wù) - 一、大致介紹 1、有時(shí)候我們在處理一些任務(wù)的時(shí)候,需要開啟線程去異步去處理,原有邏輯繼續(xù)往下執(zhí)行; 2、當(dāng)遇到這種場景的時(shí)候,線程是可以將我們完成,然后在SpringCloud中也有這樣的注解來支撐異步任務(wù)處理; 二、實(shí)現(xiàn)步驟 2.1 添加 mave...

    StonePanda 評論0 收藏0
  • Spring定時(shí)任務(wù)@scheduled多線程使用(@Async注解

    摘要:下面我們稍稍改下代碼來證實(shí)一下這次我讓任務(wù)執(zhí)行的時(shí)間等于,大于條線程總間隔時(shí)間來耗盡線程池中的線程。 1.開篇 在Spring定時(shí)任務(wù)@Scheduled注解使用方式淺窺這篇文章里面提及過,spring的定時(shí)任務(wù)默認(rèn)是單線程的,他在某些場景下會造成堵塞,那么如果我們想讓每一個(gè)任務(wù)都起一條線程去執(zhí)行呢? 2.使用@Async 我們可以使用Spring的@Async注解十分容易的實(shí)現(xiàn)多線程...

    klivitamJ 評論0 收藏0
  • 又被面試官問設(shè)計(jì)模式了,我真

    摘要:面試官要不你來手寫下單例模式唄候選者單例模式一般會有好幾種寫法候選者餓漢式簡單懶漢式在方法聲明時(shí)加鎖雙重檢驗(yàn)加鎖進(jìn)階懶漢式靜態(tài)內(nèi)部類優(yōu)雅懶漢式枚舉候選者所謂餓漢式指的就是還沒被用到,就直接初始化了對象。面試官:我看你的簡歷寫著熟悉常見的設(shè)計(jì)模式,要不你來簡單聊聊你熟悉哪幾個(gè)吧?候選者:常見的工廠模式、代理模式、模板方法模式、責(zé)任鏈模式、單例模式、包裝設(shè)計(jì)模式、策略模式等都是有所了解的候選者:...

    不知名網(wǎng)友 評論0 收藏0
  • Spring Boot 異步執(zhí)行方法

    摘要:最近遇到一個(gè)需求,就是當(dāng)服務(wù)器接到請求并不需要任務(wù)執(zhí)行完成才返回結(jié)果,可以立即返回結(jié)果,讓任務(wù)異步的去執(zhí)行。指定從上面執(zhí)行的日志可以猜測到默認(rèn)使用來異步執(zhí)行任務(wù)的,可以搜索到這個(gè)類。 最近遇到一個(gè)需求,就是當(dāng)服務(wù)器接到請求并不需要任務(wù)執(zhí)行完成才返回結(jié)果,可以立即返回結(jié)果,讓任務(wù)異步的去執(zhí)行。開始考慮是直接啟一個(gè)新的線程去執(zhí)行任務(wù)或者把任務(wù)提交到一個(gè)線程池去執(zhí)行,這兩種方法都是可以的。但...

    jiekechoo 評論0 收藏0

發(fā)表評論

0條評論

最新活動(dòng)
閱讀需要支付1元查看
<