Gb1400GenerateIDUtil.java 2.72 KB
package com.viontech.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class Gb1400GenerateIDUtil {
    //公安机关机构代码
    @Value("${gb1400.gongan.orgcode:}")
    private String gonganOrgcode;
    //
    private volatile Long notificationSequence = 0L;
    private volatile Long sourceIdSequence = 0L;
    private volatile Long motorVehicleIDSequence = 0L;
    // 序列号的最大值
    private final int sequenceMax = 99999;

    /**
     * 自动生成NotificationID
     * @return NotificationID
     */
    public String generateNotificationID() {
        StringBuilder idstr = new StringBuilder();
        String currentTime = DateUtil.format(new Date(), DateUtil.DATE_TIME_FORMAT_NO_DELIMITER);
        idstr.append(gonganOrgcode);
        idstr.append("04");
        idstr.append(currentTime);
        idstr.append(nextNotificationId());
        return idstr.toString();
    }

    /**
     * 自动生成SourceID
     * @return SourceID
     */
    public String generateSourceID(String DeviceID, String type, String PassTime) {
        StringBuilder idstr = new StringBuilder();
        idstr.append(DeviceID);
        idstr.append(type);
        idstr.append(PassTime);
        idstr.append(nextSourceId());
        return idstr.toString();
    }

    /**
     * 自动生成MotorVehicleID
     * @return MotorVehicleID
     */
    public String generateMotorVehicleID(String SourceID, String type) {
        StringBuilder idstr = new StringBuilder();
        idstr.append(SourceID);
        idstr.append(type);
        idstr.append(nextMotorVehicleId());
        return idstr.toString();
    }

    public String nextNotificationId(){
        synchronized (this.notificationSequence) {
            this.notificationSequence = (this.notificationSequence + 1) % this.sequenceMax;
            return String.format("%05d", this.notificationSequence.longValue());
        }
    }

    public String nextSourceId(){
        synchronized (this.sourceIdSequence) {
            this.sourceIdSequence = (this.sourceIdSequence + 1) % this.sequenceMax;
            return String.format("%05d", this.sourceIdSequence.longValue());
        }
    }

    public String nextMotorVehicleId(){
        synchronized (this.motorVehicleIDSequence) {
            this.motorVehicleIDSequence = (this.motorVehicleIDSequence + 1) % this.sequenceMax;
            return String.format("%05d", this.motorVehicleIDSequence.longValue());
        }
    }

    public static void main(String[] args) {
        Gb1400GenerateIDUtil xx = new Gb1400GenerateIDUtil();
        for (int i = 0; i < 10; i++) {
            System.out.println(xx.generateNotificationID());
        }
    }
}