SpringBoot 异步任务

SpringBoot 异步任务

介绍
在Java应用中,绝大多数情况下都是通过同步的方式来实现交互处理的;但是在
处理与第三方系统交互的时候,容易造成响应迟缓的情况,之前大部分都是使用
多线程来完成此类任务,其实,在Spring 3.x之后,就已经内置了@Async来完
美解决这个问题。

两个注解:
@EnableAysnc、 @Aysnc

1.主启动类

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

@EnableAsync  //开启异步注解功能
@SpringBootApplication
public class Springboot04TaskApplication {

	public static void main(String[] args) {
		SpringApplication.run(Springboot04TaskApplication.class, args);
	}
}

2.控制器

import com.atguigu.task.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AsyncController {

    @Autowired
    AsyncService asyncService;

    @GetMapping("/hello")
    public String hello(){
        asyncService.hello();
        return "success";
    }
}

3.服务类

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncService {

    //告诉Spring这是一个异步方法
    @Async
    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("处理数据中...");
    }
}

猜你喜欢

转载自blog.csdn.net/xinzai245/article/details/84913985