使用 Rest 模板的多 post 请求

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 中添加一个新的 public 方法,以便 运行 未被推荐的线程

   @PostConstruct
   public void initThread(){
      this.start();
   }

或者以适当的方式使用基于 TaskExecutor 的 @Scheduled 注解

   @Scheduled(fixedDelay = 30000)
   public void testingMicroServicesCom() {
       ...
   }