Springboot - Async 异步任务

package com.shi.snyc;

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

/**
 *  @EnableAsync   开启异步注解
 */
@EnableAsync
@SpringBootApplication
public class SnycApplication {

	public static void main(String[] args) {
		SpringApplication.run(SnycApplication.class, args);
	}
}
package com.shi.snyc.service;

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

@Service
public class HelloService {

    /**
     * @Async  告诉spring这是一个异步方法
     */
    @Async
    public void hello(){
        try {
            Thread.sleep(10000);
        }catch (Exception e){

        }
        System.out.println("hello-service被调用");
    }
}

测试 

package com.shi.snyc;

import com.shi.snyc.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class controller {

    @Autowired
    HelloService helloService;

    @RequestMapping("hello")
    @ResponseBody
    public String hello(){
        System.out.println("hello-controller被调用");
        helloService.hello();

        return "hello";
    }
}

猜你喜欢

转载自my.oschina.net/u/3677987/blog/2413879
今日推荐