并发环境下会出现什么问题?
上一篇已经测试过,单个请求是能正常执行并且返回的。但是,系统部署在公网上往往不可能一个人使用,因此必须经过并发测试,不求多规范,至少简单的并发测试也是要进行的。
Apifox图形化界面测试十分简单,还能添加变量。如下所示,简单点,两个线程循环两遍。
修改测试代码,Thread.sleep(1000)模拟测试程序需多耗时一秒。编辑一个自增变量(Apifox文档一使用说明,每次请求id+1)
{
"code": "public class Main {\n public static void main(String[] args) throws Exception{ Thread.sleep(1000); System.out.println(\"hello world----自增id {% mock 'increment', 1 %} \");}}"
}
下面给出我的测试结果:
线程1第一轮:
{
"code": "public class Main {\n public static void main(String[] args) throws Exception{ Thread.sleep(1000); System.out.println(\"hello world----自增id 3 \");}}"
}
{
"error": 0,
"reason": "运行成功",
"stderr": "",
"stdout": "hello world----自增id 4 \n"
}
线程1第二轮:
{
"code": "public class Main {\n public static void main(String[] args) throws Exception{ Thread.sleep(1000); System.out.println(\"hello world----自增id 5 \");}}"
}
{
"error": 0,
"reason": "运行成功",
"stderr": "",
"stdout": "hello world----自增id 6 \n"
}
线程2第一轮:
{
"code": "public class Main {\n public static void main(String[] args) throws Exception{ Thread.sleep(1000); System.out.println(\"hello world----自增id 4 \");}}"
}
{
"error": 0,
"reason": "运行成功",
"stderr": "",
"stdout": "hello world----自增id 4 \n"
}
线程2第二轮:
{
"code": "public class Main {\n public static void main(String[] args) throws Exception{ Thread.sleep(1000); System.out.println(\"hello world----自增id 6 \");}}"
}
{
"error": 0,
"reason": "运行成功",
"stderr": "",
"stdout": "hello world----自增id 6 \n"
}
可知四次网络请求,分别发送了3,4,5,6。而执行结果为(4,4)(6,6)。此时已经出现问题了。
Spring默认单例(后发现与本次无关)
用的的应该都知道SpringMVC(SpringBoot还是有的MVC)的Controller,默认是单例的,可以进行如下测试:
先修改一下TestController的代码,输出对象且直接返回:
@RequestMapping(value = "/run")
public String run(@RequestBody JSONObject json){
System.out.println(this+"---"+service