栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

@Async注解测试用例附源码

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

@Async注解测试用例附源码

@Async注解测试用例附源码
  • 问题背景
  • @Async测试用例
  • 问题总结
  • 测试用例源码下载
  • Lyric: 我在哑口聆听传说

问题背景

项目开发会用到异步线程去处理一些事情,这个时候使用注解 @Async 非常的简单方便

@Async测试用例
  1. 新建一个 springboot 工程,复制一下pom文件的依赖


    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.6.2
         
    
    com.example
    AsyncTest
    0.0.1-SNAPSHOT
    AsyncTest
    AsyncTest
    
        1.8
    
    
        
            org.springframework.boot
            spring-boot-starter
        

        
            org.springframework.boot
            spring-boot-starter-test
            
        
        
            junit
            junit
            4.12
            compile
        
        
            org.projectlombok
            lombok
            true
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


  • 可以看到我把 test 注释掉了,因为我是在 main.java 文件夹下使用 @SpringTest ,如果不注释掉,那么就不能使用该注解,只能在 test 文件夹下使用,所以 scope 指的就是一个使用的范围
  • 我添加了 junit 依赖,因为测试类的 @Test 注解必须使用这个类
  1. 添加 @EnableAsync 注解在启动类上面
package com.yg.asynctest;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@EnableAsync
@SpringBootApplication
public class AsyncTestApplication {
    public static void main(String[] args) {
        SpringApplication.run(AsyncTestApplication.class, args);
    }
}
  1. 创建异步和同步的方法类
package com.yg.asynctest;

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import java.util.concurrent.Future;

@Component
public class Method {
    public int syncMethod() {
        System.out.println("SyncMethod thread: "+Thread.currentThread().getName());
        return 1;
    }
    @Async
    public Future asyncMethod() throws InterruptedException {
        System.out.println("AsyncMethod thread: "+Thread.currentThread().getName());
        // 异步线程延时 5s 返回结果
        Thread.sleep(5000);
        return new AsyncResult<>(2);
    }
}
  • 异步方法延时了5s,查看异步调用方法的效果
  1. 创建测试类
package com.yg.asynctest;


import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class AsyncTest {
    @Autowired
    Method method;

    @Test
    public void test() throws ExecutionException, InterruptedException {
        log.info("Sync is {}", method.syncMethod());
        Future future = method.asyncMethod();
        log.info("Async is {}", future.get());
    }
}
  • 如果导入 @Test 注解的包错了,会出现如下错误
import org.junit.jupiter.api.Test; // 错误包
java.lang.Exception: No runnable methods

	at org.junit.runners.BlockJUnit4ClassRunner.validateInstanceMethods(BlockJUnit4ClassRunner.java:191)
	at org.junit.runners.BlockJUnit4ClassRunner.collectInitializationErrors(BlockJUnit4ClassRunner.java:128)
	at org.junit.runners.ParentRunner.validate(ParentRunner.java:416)
	at org.junit.runners.ParentRunner.(ParentRunner.java:84)
	at org.junit.runners.BlockJUnit4ClassRunner.(BlockJUnit4ClassRunner.java:65)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.(SpringJUnit4ClassRunner.java:137)
	at org.springframework.test.context.junit4.SpringRunner.(SpringRunner.java:49)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
  • 使用正确的 @Test 包
import org.junit.Test;
  1. 运行 test() 方法,查看日志打印
SyncMethod thread: main
2021-12-24 11:41:40.400  INFO 70184 --- [main] com.yg.asynctest.AsyncTest: Sync is 1
AsyncMethod thread: task-1
2021-12-24 11:41:45.456  INFO 70184 --- [main] com.yg.asynctest.AsyncTest: Async is 2
  • 同步方法使用的是 main 线程,异步方法使用的是 task-1 线程,五秒之后再打印
问题总结
  • 工程中会用到很多异步方法,当然也有使用 Future 线程池的
测试用例源码下载

直接复制文章的代码也是可以的,想少事就直接下载源码:AsyncTest下载链接




作为程序员第七篇文章,每次写一句歌词记录一下,看看人生有几首歌的时间,wahahaha …

Lyric: 我在哑口聆听传说
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/677868.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号