springboot開啓異步

1,配置

①,pom依賴java

<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>

②,啓用異步web

@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應用,會快速在頁面給出響應spring

②,3s後,控制檯輸出「睡夠了」springboot

相關文章
相關標籤/搜索