【第23章】spring-async(异步)


前言

在原生Java中,我们想要实现异步需要新建线程或线程池提交任务的方式,spring提供了一种基于注解的方式实现异步。


一、业务类

1. controller

package org.example.async.controller;

import org.example.async.service.AsyncService;
import org.example.async.service.impl.AsyncServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

/**
 * Create by zjg on 2024/4/21
 */
@Controller
public class AsyncController {
    private Logger logger = LoggerFactory.getLogger(AsyncServiceImpl.class);
    @Autowired
    AsyncService asyncService;
    public void run(){
        logger.debug("AsyncController开始执行");
        asyncService.run();
        logger.debug("AsyncController执行结束");
        //主线程到这里已经处理完成了,但不能过早结束,否则看不到后面日志输出
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

2. service

package org.example.async.service;

/**
 * Create by zjg on 2024/4/21
 */
public interface AsyncService {
    public void run();
}

package org.example.async.service.impl;

import org.example.async.dao.AsyncDao;
import org.example.async.service.AsyncService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * Create by zjg on 2024/4/21
 */
@Service
public class AsyncServiceImpl implements AsyncService {
    private Logger logger = LoggerFactory.getLogger(AsyncServiceImpl.class);
    @Autowired
    AsyncDao asyncDao;
    @Async
    @Override
    public void run(){
        logger.debug("AsyncService开始执行");
        try {
            Thread.sleep(2000);
            asyncDao.run();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        logger.debug("AsyncService执行结束");
    }
}

3. dao

package org.example.async.dao;

/**
 * Create by zjg on 2024/4/21
 */
public interface AsyncDao {
    public void run();
}

package org.example.async.dao.impl;

import org.example.async.dao.AsyncDao;
import org.example.async.service.impl.AsyncServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

/**
 * Create by zjg on 2024/4/21
 */
@Repository
public class AsyncDaoImpl implements AsyncDao {
    private Logger logger = LoggerFactory.getLogger(AsyncServiceImpl.class);

    @Override
    public void run() {
        logger.debug("AsyncDao开始执行");
        logger.debug("AsyncDao执行结束");
    }
}

二、核心配置

1.配置类

package org.example.async.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;

/**
 * Create by zjg on 2024/4/20
 */
@ComponentScan("org.example.async")
@EnableAsync
public class SpringConfig {
    @Bean
    public TaskExecutor taskExecutor(){
        return new SimpleAsyncTaskExecutor();
    }
}

2.测试类

package org.example.async;

import org.example.async.config.SpringConfig;
import org.example.async.controller.AsyncController;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;

/**
 * Create by zjg on 2024/4/21
 */
@SpringJUnitConfig(SpringConfig.class)
public class SpringTest {
    @Autowired
    AsyncController asyncController;
    @Test
    public void async(){
        asyncController.run();
    }
}

3.测试结果

[2024-04-21 19:28:45.146][main][DEBUG]- org.example.async.controller.AsyncController.run(AsyncController.java:19) - AsyncController开始执行
[2024-04-21 19:28:45.163][main][DEBUG]- org.example.async.controller.AsyncController.run(AsyncController.java:21) - AsyncController执行结束
[2024-04-21 19:28:45.163][SimpleAsyncTaskExecutor-1][DEBUG]- org.example.async.service.impl.AsyncServiceImpl.run(AsyncServiceImpl.java:22) - AsyncService开始执行
[2024-04-21 19:28:47.168][SimpleAsyncTaskExecutor-1][DEBUG]- org.example.async.dao.impl.AsyncDaoImpl.run(AsyncDaoImpl.java:18) - AsyncDao开始执行
[2024-04-21 19:28:47.168][SimpleAsyncTaskExecutor-1][DEBUG]- org.example.async.dao.impl.AsyncDaoImpl.run(AsyncDaoImpl.java:19) - AsyncDao执行结束
[2024-04-21 19:28:47.169][SimpleAsyncTaskExecutor-1][DEBUG]- org.example.async.service.impl.AsyncServiceImpl.run(AsyncServiceImpl.java:29) - AsyncService执行结束

可以看到controller由main线程执行,service和dao由线程池中的线程负责执行。


总结

回到顶部

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值