java代码片段

  1. 简单处理5位自增序列

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    import java.util.concurrent.atomic.AtomicInteger;

    AtomicInteger atomicInt = new AtomicInteger(1);

    // 自增数据超过5位的处理
    public String autoIncrementSeq() {
    int incrementNum = 1;
    if (atomicInt.get() > 99999) {
    atomicInt = new AtomicInteger(1);
    }
    incrementNum = atomicInt.getAndIncrement();
    // 数字长度为5位,长度不够前面补0
    return String.format("%05d", incrementNum);
    }
  2. 通过更新监控文件时间,来处理心跳,是一个简单巧妙的方法

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
      // 片段来自titan-runner的MonitorClinet.java,runner与taskmanager程序约定的监控程序心跳的方式
    public void heartbeat() throws IOException {
    com.google.common.io.Files.touch(this.monitorFile);
    }

    使用场景,可以sleep一段时间,更新一下文件时间,来表示程序还存活,然后另外一个程序通过计算该文件的更新时间来判断监控的程序是否正常
    int idleSleepMs = this.configuration.getInt("task.idle_sleep.ms", 500);
    while(!this.stoped) {
    this.monitorClient.checkParentAlive();
    this.monitorClient.heartbeat();
    ...
    Thread.sleep((long)idleSleepMs);
    }
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2022-2023 ligongzhao
  • 访问人数: | 浏览次数:

请我喝杯咖啡吧~

支付宝
微信