I am working on a spring boot-microservices project
I have two methods in the main 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());
}
I tested my application and it can send requests without any problem and when I use thread to make multiple requests every 30 seconds it stopped working.
You declared the bean BinServiceImpl using the annotation @service without using it, and at the same time you created another instance of the same class it in method Testing() without keeping any reference to it.
you can remote the method Testing() and add a new public method in BinServiceImpl in order to run the thread which is not recommanded
@PostConstruct
public void initThread(){
this.start();
}
Or in a proper way using @Scheduled annotation which is based on TaskExecutor
@Scheduled(fixedDelay = 30000)
public void testingMicroServicesCom() {
...
}