- 创建线程类,继承 Tread 类
package com.example.header1.utils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import java.sql.Time;
public class MyThread extends Thread{
private String name;
public MyThread(String name) {
this.name = name;
}
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8081";
String api = url + "/hello?name=" + this.name;
ResponseEntity<String> responseEntity = restTemplate.getForEntity(api, String.class);
String responseEntityBody = responseEntity.getBody();
System.out.println(responseEntityBody);
}
}
- 创建对象,启动线程
package com.example.header1.demos.web;
import com.example.header1.utils.MyThread;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
@Controller
public class BasicController {
@RequestMapping("/hello")
@ResponseBody
public String hello(@RequestParam(name = "name", defaultValue = "unknown user") String name) {
for (int i = 0; i <3; i++) {
MyThread myThread = new MyThread(name + "thread" + i);
myThread.start();
}
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8081";
String api = url + "/hello?name=" + name;
ResponseEntity<String> responseEntity = restTemplate.getForEntity(api, String.class);
String responseEntityBody = responseEntity.getBody();
System.out.println(responseEntityBody);
return "Hello " + name + " header1";
}
}
- 调用接口