使用rest模板的java多post请求

shyt4zoc  于 2021-07-14  发布在  Java
关注(0)|答案(1)|浏览(324)

我在做一个springboot微服务项目
我在主类中有两种方法:

@Bean
  public void Testing(){
    BinServiceImpl binService =  new BinServiceImpl() ;

   binService.start();//start run ()

  }
  @Bean
  @LoadBalanced
  public RestTemplate getRestTemplate() {
    return new RestTemplate();
  }

binserviceimpl类:

@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秒发出多个请求时,它停止工作。

sd2nnvve

sd2nnvve1#

您使用annotation@service声明了bean binserviceimpl,但没有使用它,同时在method testing()中创建了同一类的另一个示例,而没有保留对它的任何引用。
您可以远程方法testing()并在binserviceimpl中添加一个新的公共方法,以便运行不推荐的线程

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

或者以适当的方式使用基于taskexecutor的@scheduled注解

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

相关问题