- 代码:demo.7z
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.UUID;
@RestController
@RequestMapping("/")
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@GetMapping("/hello")
private String sayHello() throws InterruptedException {
String id = UUID.randomUUID().toString();
System.out.println("进入 1: " + id + " 时间: " + System.currentTimeMillis() + " 线程 id: " + Thread.currentThread().getId());
// 模拟耗时操作
Thread.sleep(5000);
System.out.println("进入 2: " + id + " 时间: " + System.currentTimeMillis() + " 线程 id: " + Thread.currentThread().getId());
return "hello2";
}
}
- 使用
ab -c 5 -n 5 http://localhost:8080/hello模拟 5 个并发请求,输出如下:
进入 1: 26ae2ea9-7e5c-4bd7-bc2d-8c4d0907d18a 时间: 1566302327095 线程 id: 28
进入 2: 26ae2ea9-7e5c-4bd7-bc2d-8c4d0907d18a 时间: 1566302332099 线程 id: 28
进入 1: 82768b68-3a05-4768-8290-8b43a176a57e 时间: 1566302332125 线程 id: 30
进入 1: 05337b19-9a5a-41e9-8c9b-944d8ceeb06c 时间: 1566302332125 线程 id: 29
进入 1: 3b7eea0a-4d8c-4878-9e21-741f1e6d2e76 时间: 1566302332125 线程 id: 32
进入 1: 587305cd-89fc-441d-a575-ab436a63ad40 时间: 1566302332125 线程 id: 31
进入 2: 3b7eea0a-4d8c-4878-9e21-741f1e6d2e76 时间: 1566302337127 线程 id: 32
进入 2: 05337b19-9a5a-41e9-8c9b-944d8ceeb06c 时间: 1566302337127 线程 id: 29
进入 2: 587305cd-89fc-441d-a575-ab436a63ad40 时间: 1566302337127 线程 id: 31
进入 2: 82768b68-3a05-4768-8290-8b43a176a57e 时间: 1566302337127 线程 id: 30
- 但是我的预期应该是:
进入 1
进入 1
进入 1
进入 1
进入 1
进入 2
进入 2
进入 2
进入 2
进入 2
- 查找了一些资料,描述都与我这个场景不符,例如 https://stackoverflow.com/questions/47938265/does-spring-create-new-thread-per-request-in-rest-controllers 我按照提问者的代码,测试了一下,发现其输出和提问者描述的不同
- 不知道是哪里做错了,和朋友讨论了一会儿无解,因此请教一下大家,感谢~~