import lombok.SneakyThrows;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class main {
public static ScheduledThreadPoolExecutor spool;
public static void main(String[] args) throws ExecutionException, InterruptedException {
spool = new ScheduledThreadPoolExecutor(2);
CountDownLatch cdl = new CountDownLatch(5);
HttpEntity<Map<String, Object>> request = new HttpEntity<Map<String, Object>>(_meidi,headers);
ConcurrentHashMap<String, Future> futureMap = new ConcurrentHashMap<String, Future>();
requestTask requestTask = new requestTask(warnUrl,request,cdl,restTemplate,futureMap);
ScheduledFuture<?> scheduledFuture = spool.scheduleAtFixedRate(requestTask, 0, 5, TimeUnit.MINUTES);
futureMap.put("scheduledFuture",scheduledFuture);
spool.shutdownNow();
}
}
public class requestTask implements Runnable{
private AtomicInteger ait = new AtomicInteger(0);
private volatile CountDownLatch cdl;
private HttpEntity<Map<String, Object>> request;
private String url ;
private ConcurrentHashMap<String, Future> futureMap;
RestTemplate restTemplate;
public requestTask(String url ,HttpEntity<Map<String, Object>> request,CountDownLatch cdl,RestTemplate restTemplate,ConcurrentHashMap<String, Future> futureMap){
this.request = request;
this.url = url;
this.cdl = cdl;
this.restTemplate = restTemplate;
this.futureMap = futureMap;
}
@SneakyThrows
@Override
public void run() {
System.out.println("调用初始化流程");
cdl.countDown();
int i = ait.incrementAndGet();
ResponseEntity<String> entity = restTemplate.postForEntity(url, request, String.class);
String json = entity.getBody();
JSONObject jsonObject = JSONUtil.parseObj(json);
System.out.println(jsonObject);
String error = jsonObject.get("error", String.class);
if(!"success".equals(error)){
log.error("告警失败次数:{}",i);
if(i == 5){
Future scheduledFuture = futureMap.remove("scheduledFuture");
scheduledFuture.cancel(true);
}
}else {
log.warn("报警成功");
log.warn("报警发送结果集: {}",JSONUtil.parseObj(request.getBody()).toString());
Future scheduledFuture = futureMap.remove("scheduledFuture");
scheduledFuture.cancel(true);
}
}
}