Java's serial number generator

Source: Internet
Author: User

Have a nice smile

Ask questions

How to use Java to generate serial numbers while supporting configurable and high concurrency???

solve the problem

Suppose your project has integrated the caching technology
If you have a certain Java foundation
If......

The following code implements a high-concurrency, configurable, high-efficiency serial number generator, can be used for multiple modules of a project, the serial number supports caching, that is, each time a certain number of pre-generated serial number stored in the cache, when needed, priority to the cache , after the sequence number in the cache is used, regenerate a certain number of serial numbers into the cache, so loop, improve efficiency ...
At the same time, the serial number generator is thread-safe , protected with the thread lock, and has been really put into use in the project ...

database table Design

CREATE TABLE sys_serial_number2 (    "id" varchar(32) COLLATE "default" NOT NULL,    "module_name" varchar(50) COLLATE "default",    "module_code" varchar(50) COLLATE "default",    "config_templet" varchar(50) COLLATE "default",    "max_serial" varchar(32) COLLATE "default",    "pre_max_num" varchar(32) COLLATE "default",    "is_auto_increment" char(1) COLLATE "default")

Description

module_name:模块名称module_code:模块编码config_templet:当前模块 使用的序列号模板max_serial:存放当前序列号的值pre_max_num:预生成序列号存放到缓存的个数is_auto_increment:是否自动增长模式,0:否  1:是

Note: The current serial number template only supports letters, dynamic numbers (0000 for 1-9999), and dates in combination with ${date}
Is_auto_increment is configured to 1, the serial number generated by the configuration template for CX000000 is: CX1, cx2,cx3 .....
Configured to 0, the serial number generated by the configuration template for CX0000000 is: cx00000001,cx00000002,cx00000003

Database Configuration Note: If you need a project number for the project module, you need to configure a record in the database table Sys_serial_number:

|  id   |  module_name |  module_code |  config_templet | max_serial  | pre_max_num |  is_auto_increment|-------|--------------|--------------|-----------------|-------------|-------------|--------------------/|  xxxx |  项目         |  PJ         |CX00000000${DATE}|  2650       |  100        |    1

Cx00000000${date} generates a sequence number similar to: CX0000000120160522, cx0000000220160522,cx0000000320160522 ...

Serial Number model entity design:

Package Com.evada.de.serialnum.model;import Com.evada.de.common.model.basemodel;import Javax.persistence.Column; Import Javax.persistence.entity;import javax.persistence.table;/** * Function Description: Serial number Table model * * @author: Ay 2015/11/23 */@ Entity@table (name= "Sys_serial_number") public class Systemserialnumber extends Basemodel {/** * module name */@Col    Umn (name = "Module_name", columndefinition = "VARCHAR") private String modulename;    /** * Module Code */@Column (name = "Module_code", columndefinition = "VARCHAR") private String Modulecode; /** * Serial Number configuration template */@Column (name = "Config_templet", columndefinition = "VARCHAR") Private String Configtemplet    ;    /** * The maximum value of the serial number */@Column (name = "Max_serial", columndefinition = "VARCHAR") private String maxserial; /** * Whether the automatic growth indicator */@Column (name = "Is_auto_increment", columndefinition = "VARCHAR") Private String Isautoinc    Rement;   Public String getisautoincrement () {return isautoincrement; } public void Setisautoincrement (String isautoincrement) {this.isautoincrement = isautoincrement;     }/** * Pre-generated number of serial number */@Column (name = "Pre_max_num", columndefinition = "VARCHAR") private String premaxnum;    Public String Getpremaxnum () {return premaxnum;    } public void Setpremaxnum (String premaxnum) {this.premaxnum = Premaxnum;    } public String Getmodulename () {return modulename;    } public void Setmodulename (String modulename) {this.modulename = ModuleName;    } public String Getmodulecode () {return modulecode;    } public void Setmodulecode (String modulecode) {this.modulecode = Modulecode;    } public String Getconfigtemplet () {return configtemplet;    } public void Setconfigtemplet (String configtemplet) {this.configtemplet = Configtemplet;    } public String getmaxserial () {return maxserial; } public void Setmaxserial (String maxserial) {THis.maxserial = maxserial;    } public Systemserialnumber (String id) {this.id = ID;        } public Systemserialnumber (String id,string modulecode) {this.id = ID;    This.modulecode = Modulecode; } public Systemserialnumber () {}}

Service Interface Design:

package com.evada.de.serialnum.service;import com.evada.de.serialnum.dto.SystemSerialNumberDTO;/** * 序列号service接口 * Created by huangwy on 2015/11/24. */public interface ISerialNumService {    public SystemSerialNumberDTO find(SystemSerialNumberDTO systemSerialNumberDTO);    public String generateSerialNumberByModelCode(String moduleCode);    /**     * 设置最小值     * @param value 最小值,要求:大于等于零     * @return      流水号生成器实例     */    ISerialNumService setMin(int value);    /**     * 设置最大值     * @param value 最大值,要求:小于等于Long.MAX_VALUE ( 9223372036854775807 )     * @return      流水号生成器实例     */    ISerialNumService setMax(long value);    /**     * 设置预生成流水号数量     * @param count 预生成数量     * @return      流水号生成器实例     */    ISerialNumService setPrepare(int count);}

Service implementations:

Package Com.evada.de.serialnum.service.impl;import Com.evada.de.common.constants.serialnumconstants;import Com.evada.de.serialnum.dto.systemserialnumberdto;import Com.evada.de.serialnum.model.systemserialnumber;import Com.evada.de.serialnum.repository.serialnumberrepository;import Com.evada.de.serialnum.repository.mybatis.serialnumberdao;import Com.evada.de.serialnum.service.iserialnumservice;import Com.evada.inno.common.util.beanutils;import Com.evada.inno.common.util.dateutils;import Org.slf4j.logger;import Org.slf4j.loggerfactory;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.cache.annotation.CachePut; Import Org.springframework.stereotype.service;import Java.text.decimalformat;import Java.util.*;import java.util.concurrent.locks.reentrantlock;/** * Created by Ay on 2015/11/24. */@Service ("Serialnumberservice") public class Serialnumberserviceimpl implements Iserialnumservice {private static fi nal Logger Logger = Loggerfactory.getlogger (SeRialnumberserviceimpl.class);    @Autowired private Serialnumberdao Serialnumberdao;    @Autowired private Serialnumberrepository serialnumberrepository;    /** format */private String pattern = "";    /** Generator Lock */private final reentrantlock lock = new Reentrantlock ();    /** Serial Number Formatter */private DecimalFormat format = null;    /** pre-generated lock */private final Reentrantlock Preparelock = new Reentrantlock ();    /** minimum */private int min = 0;    /** Maximum */private long max = 0;    /** has generated a serial number (SEED) */private long seed = min;    /** pre-generated quantity */private int prepare = 0;    /** the current maximum sequence number stored by the database **/long maxserialint = 0;    /** whether the current serial number is a single-digit auto-increment mode **/private String isautoincrement = "0";    Systemserialnumberdto systemserialnumberdto = new Systemserialnumberdto ();    /** pre-generated serial number */hashmap<string,list<string>> Prepareserialnumbermap = new hashmap<> (); /** * Query single serial number configuration information * @param systemserialnumberdto * @return */@Override publicSystemserialnumberdto Find (Systemserialnumberdto systemserialnumberdto) {return Serialnumberdao.find (SystemSerialN    UMBERDTO); }/** * Generates a pre-number sequence number based on module code into map * @param modulecode Module Code * @return */@CachePut (value = "Serialnu        Mber ", key=" #moduleCode ") public list<string> generateprepareserialnumbers (String modulecode) {//Temp List variable        list<string> resultlist = new arraylist<string> (prepare);        Lock.lock ();                try{for (int i=0;i<prepare;i++) {maxserialint = maxserialint + 1;                if (Maxserialint > Min && (maxserialint + ""). Length () < max) {seed = Maxserialint; }else{//If the dynamic number length is greater than the length example in the template: Template CF000 maxserialint-Maxseriali                    NT = 0;                    Update data, reset Maxserialint to 0 systemserialnumberdto.setmaxserial ("0"); Systemserialnumber SystemserialnuMber = new Systemserialnumber ();                    Beanutils.copyproperties (systemserialnumber,systemserialnumberdto);                Serialnumberrepository.save (Systemserialnumber);                }//Dynamic number generation String Formatserialnum = Format.format (seed); Generation of dynamic dates if (Pattern.contains (Serialnumconstants.date_symbol)) {String currentdate = Dat                    Eutils.format (New Date (), "yyyyMMdd");                Formatserialnum = Formatserialnum.replace (serialnumconstants.date_symbol,currentdate);            } resultlist.add (Formatserialnum);            }//Update data systemserialnumberdto.setmaxserial (Maxserialint + "");            Systemserialnumber systemserialnumber = new Systemserialnumber ();            Beanutils.copyproperties (systemserialnumber,systemserialnumberdto);        Serialnumberrepository.save (Systemserialnumber);       }finally{Lock.unlock (); } return resultlist; }/** * Generates serial number according to module code * @param modulecode module code * @return Serial Number */public String Generateserialnumb        Erbymodelcode (String modulecode) {//Pre-serial number plus lock Preparelock.lock (); try{//Determine if there is a serial number in memory if (null! = Prepareserialnumbermap.get (modulecode) && Prepareserialnumber Map.get (Modulecode). Size () > 0) {//if any, return to the first, and remove the return Prepareserialnumbermap.get (Modulec            ODE). Remove (0);        }}finally {//Pre-serial number unlocked preparelock.unlock ();        } systemserialnumberdto = new Systemserialnumberdto ();        Systemserialnumberdto.setmodulecode (Modulecode);        Systemserialnumberdto = Serialnumberdao.find (systemserialnumberdto); Prepare = Integer.parseint (Systemserialnumberdto.getpremaxnum (). Trim ());//pre-generated serial number number pattern = Systemserialnumberdto. Getconfigtemplet (). Trim ();//configuration template String maxserial = Systemserialnumberdto.getmaxsErial (). Trim ();        Stores the current maximum value isautoincrement = Systemserialnumberdto.getisautoincrement (). Trim (); Maxserialint = Long.parselong (Maxserial.trim ());//The maximum serial number stored by the database max = This.counter (pattern, ' 0 ') + 1;//determines the number of current serial numbers according to the template        The large value if (Isautoincrement.equals ("1")) {pattern = Pattern.replace ("0", "#");        } format = new DecimalFormat (pattern);        Generate a pre-sequence number, save in cache list<string> resultlist = generateprepareserialnumbers (Modulecode);        Preparelock.lock ();            try {prepareserialnumbermap.put (Modulecode, resultlist);        Return Prepareserialnumbermap.get (Modulecode). Remove (0);        } finally {Preparelock.unlock (); }}/** * Set minimum value * * @param value Minimum, required: greater than or equal to zero * @return Serial number Generator instance */Public Iserialnumservice        Setmin (int value) {lock.lock ();        try {this.min = value;        }finally {lock.unlock ();    } return this;     }    /*** Maximum Value * * @param value maximum, required: less than or equal to Long.max_value (9223372036854775807) * @return Serial Number Generator instance */Public I        Serialnumservice Setmax (Long value) {Lock.lock ();        try {This.max = value;        }finally {lock.unlock ();    } return this; }/** * Set number of pre-generated serial number * @param count pre-build quantity * @return Serial number Generator instance */Public Iserialnumservice Setprepa        Re (int count) {lock.lock ();        try {this.prepare = count;        }finally {lock.unlock ();    } return this; }/** * Counts the number of occurrences of a character * @param the character that Str looks for * @param c * @return */private int counter (String str,c        Har c) {int count=0;            for (int i = 0;i < Str.length (); i++) {if (Str.charat (i) ==c) {count++;    }} return count; }}
Reading Comprehension
    • Life is bad to a certain extent will be better, because it can not be worse. After the effort, only to know many things, insist on, came.
    • Some troubles, lost, only the chance of cloud light wind.
    • When a fat paper is nothing bad, at least can warm the other people.
other

If there is a little bit of happiness for you, let happiness continue to pass, welcome reprint, Praise, top, welcome to leave valuable comments, thank you for your support!

Java's serial number generator

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.