springboot中的异步操作,就是多线程操作
1.直接在service的方法上面加上@Async注解,就可以标明该方法是一个异步方法,也就是如果controller中调用了service中的这个方法,就会开启另一个线程来运行这个方法。
service.java
package com.anlysqx.service;
import java.util.Date;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncService {
@Async
public String asyncService(){
System.out.println("async开始执行");
StringBuilder stringBuilder = new StringBuilder();
for(int i=0;i<5;i++){
try {
Thread.sleep(1000);
String str = "i = "+i;
System.out.println(str);
stringBuilder.append(str);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("async执行结束");
return stringBuilder.toString();
}
}
controller.java
package com.anlysqx.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.anlysqx.service.AsyncService;
@Controller
public class AsyncController {
@Autowired
private AsyncService asyncService;
@Value("${name}")
private String name;
@ResponseBody
@RequestMapping("/async")
public String getAsyncService(){
System.out.println("async controller start ...");
String msg = asyncService.asyncService();
// System.out.println(msg);
System.out.println("async controller end ...");
return msg;
}
@RequestMapping("/name")
@ResponseBody
public String getName(){
return name;
}
}