![](/img/trans.png)
[英]SPRING: Unable to pass parameters in a post request using rest template
[英]Multi post Request using Rest Template
我正在研究 spring 引导微服务项目
我在主要的 class 中有两种方法:
@Bean
public void Testing(){
BinServiceImpl binService = new BinServiceImpl() ;
binService.start();//start run ()
}
@Bean
@LoadBalanced
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
BinServiceImpl class:
@Service
public class BinServiceImpl extends Thread implements BinService{
@Autowired private RestTemplate restTemplate;
@Override
public void run() {
try {
Thread.sleep(120000);
} catch (InterruptedException e) {
e.printStackTrace();
}
while (true) {
try {
System.out.println("Run Thread");
Thread.sleep(30000);
TestingMicroServicesCom();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void TestingMicroServicesCom() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("subject", "Testing");
jsonObject.put("body", "Testing");
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Object> requestEntity = new HttpEntity<>(jsonObject, requestHeaders);
String notificationUrl = String.format("MyUrl");
ResponseEntity<String> userDetailsResponse =
restTemplate.postForEntity(notificationUrl, requestEntity, String.class);
System.out.println(userDetailsResponse.getBody());
}
我测试了我的应用程序,它可以毫无问题地发送请求,当我使用线程每 30 秒发出多个请求时,它停止工作。
您使用注释 @service 声明了 bean BinServiceImpl 而不使用它,同时您在方法 Testing() 中创建了相同 class 的另一个实例,而不保留对它的任何引用。
您可以远程方法 Testing() 并在 BinServiceImpl 中添加一个新的公共方法,以运行不推荐的线程
@PostConstruct
public void initThread(){
this.start();
}
或者以适当的方式使用基于 TaskExecutor 的 @Scheduled 注释
@Scheduled(fixedDelay = 30000)
public void testingMicroServicesCom() {
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.