AbstractHeartBeatCommand.java 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package net.lab1024.smartadmin.common.heartbeat;
  2. import com.google.common.util.concurrent.ThreadFactoryBuilder;
  3. import java.util.Date;
  4. import java.util.List;
  5. import java.util.concurrent.*;
  6. /**
  7. * @Description: 心跳服务
  8. * @Author: simajinqiang
  9. * @Date: 2018/7/9 16:26
  10. */
  11. public abstract class AbstractHeartBeatCommand implements HeartBeatRecordCommendInterface {
  12. ScheduledExecutorService executorService;
  13. int threadNum = 1;
  14. /**
  15. * 项目路径
  16. */
  17. private String projectPath;
  18. /**
  19. * 服务器ip(多网卡)
  20. */
  21. private List<String> serverIps;
  22. /**
  23. * 进程号
  24. */
  25. private Integer processNo;
  26. /**
  27. * 进程开启时间
  28. */
  29. private Date processStartTime;
  30. HeartBeatLogger logger;
  31. /**
  32. * 初始化
  33. */
  34. public void init(HeartBeatConfig config, HeartBeatLogger logger){
  35. this.handlerHeartBeat();
  36. ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("AbstractHeartBeatCommand-%s").build();
  37. executorService = Executors.newScheduledThreadPool(threadNum, threadFactory);
  38. executorService.scheduleWithFixedDelay(new DoHeartBeat(), config.getDelayHandlerTime(), config.getIntervalTime(), TimeUnit.MILLISECONDS);
  39. }
  40. public void handlerHeartBeat(){
  41. try {
  42. projectPath = HeatBeatRecordHelper.getProjectPath();
  43. serverIps = IpUtil.getLocalIPS();
  44. processNo = HeatBeatRecordHelper.getProcessID();
  45. processStartTime = HeatBeatRecordHelper.getStartTime();
  46. }catch (Throwable e){
  47. logger.error("get heart beat info error.", e);
  48. }
  49. }
  50. /**
  51. * 销毁线程池
  52. */
  53. public void destroy(){
  54. if (executorService != null && !executorService.isShutdown()) {
  55. executorService.shutdown();
  56. executorService = null;
  57. }
  58. }
  59. public class DoHeartBeat implements Runnable{
  60. @Override
  61. public void run() {
  62. try {
  63. HeartBeatRecordDTO heartBeatRecord = new HeartBeatRecordDTO();
  64. heartBeatRecord.setProjectPath(projectPath);
  65. heartBeatRecord.setServerIp(StringUtil.join(serverIps,";"));
  66. heartBeatRecord.setProcessNo(processNo);
  67. heartBeatRecord.setProcessStartTime(processStartTime);
  68. heartBeatRecord.setHeartBeatTime(new Date());
  69. handler(heartBeatRecord);
  70. }catch (Throwable t){
  71. logger.error("handler heartbeat error.", t);
  72. }
  73. }
  74. }
  75. }