springboot开启异步

1,配置

①,pom依赖

<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.0.2.RELEASE</version>
</parent>

<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
</dependencies>

②,启用异步

@EnableAsync//开启异步
@SpringBootApplication
public class TaskApplication {

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

2,编写异步业务代码

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

@Service
public class AsyncService {
    /*@Async 注明这是个异步方法*/
    @Async
    public void sync(){
        try {
            //假设这里是耗时的业务操作
            Thread.sleep(3000);
            System.out.println("睡够了");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

3,测试

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

@RestController
public class AsyncController {

    @Autowired
    private AsyncService asyncService;

    @RequestMapping("/")
    public String index(){
        asyncService.sync();
        return "success";
    }
}

①,访问springboot应用,会快速在页面给出响应

②,3s后,控制台输出“睡够了”

猜你喜欢

转载自my.oschina.net/u/3574106/blog/1815526