In the SpringBoot project, quickly create a simple asynchronous processing function

Asynchronous processing

1. First create a springboot project

提示:选择的java版本不要太高

Insert image description here

I chose Spring Web here

Insert image description here


2.Write AswncService code in the service layer

指定异步内容,在方法上面加注解@Async,为了告诉Spring这是一个异步的方法

/**
 * @Author liuyun
 * @Date 2023/3/6 9:30
 * @Version 1.0
 */
@Service
public class AswncService {
    
    
    
    //@Async告诉spring这是一个异步的方法
    @Async
    public void hello(){
    
    
        try {
    
    
        	//调取这个方法后让休眠三秒
            Thread.sleep(3000);
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
		
        System.out.println("数据正在处理");
    }
}

3.Write AswncController code in the controller layer

在该controller上加注解@EnableAsync,也可以加在启动类上,开启异步注解功能

/**
 * @Author liuyun
 * @Date 2023/3/6 9:30
 * @Version 1.0
 */

@EnableAsync//开启异步注解功能
@RestController
public class AswncController {
    
    
	
	//引入service
    @Autowired
    AswncService aswncService;
	
    @RequestMapping("/hello")
    public String hello(){
    
    
    	//调取service中的方法
        aswncService.hello();
        //返回OK
        return "OK";
    }
}

4. Project start

如果没有启动异步功能,访问页面会等待三秒(转圈),然后才显示;开启异步功能以后则不会受方法影响,直接显示OK

Insert image description here
Three seconds later, the method aswncService.hello() called in the background displays the following content:

Insert image description here

This is a simple asynchronous processing function; refer to


Hope it helps you

~感谢您的光临~

Insert image description here

Guess you like

Origin blog.csdn.net/m0_50762431/article/details/129358595