• 【java】单实例下的 流水号【21位】


    单实例环境,不是分布式

    需要流水号

    /**
     * 流水号生成器
     *
     * 年+天号+毫秒+随机数
     * 2019+134+480+11位随机数
     * 4+3+3+11 = 21位
     *
     * 
     * @author sxd
     * @date 2019/5/14 9:55
     */
    public class SerialCreater {
    
        public static final String SERIAL_FROMAT = "%s%s%s%s";
    
        private String serialNum;
    
        public SerialCreater() {
            this.serialNum = String.format(
                    SERIAL_FROMAT,
                    DateUtil.thisYear(),
                    Calendar.getInstance().get(Calendar.DAY_OF_YEAR),
                    DateUtil.thisMillsecond(),
                    random());
        }
    
        public static String getSerial(){
            return  new SerialCreater().serialNum;
        }
    
    
    
        private  String random(){
            Long a = new Random().nextLong();
            Long b = DateUtil.current(false);
            Long c = (a-b)>>>16;
            return autoGenericCode(c);
        }
    
    
        private  String autoGenericCode(Long old){
            String result = old.toString();
            int length = result.length();
            if (length > 11){
                result = result.substring(0,11);
            }else if (length < 11){
                result = String.format("%011d", old);
            }
            return result;
        }
    
    
    }
    View Code

    调用:

    System.out.println(SerialCreater.getSerial());

    测试生成100W,查看是否重复:

    public static void main(String[] args) {
    
            Set<String> set = new HashSet<>();
            System.out.println(set.size());
            int a = 1000000;
            for (int i = 0; i < a; i++) {
                set.add(SerialCreater.getSerial());
            }
    
            System.out.println(set.size());
        }
    View Code

    并发100W,100W个线程测试是否重复:

    /**
     * @author sxd
     * @date 2019/5/14 13:35
     */
    public class RUnTest {
    
        static final ConcurrentHashMap<String,Integer> concurrentHashMap = new ConcurrentHashMap<>();
    
        public static void main(String[] args) {
    
    
            System.out.println(concurrentHashMap.size());
            int a = 1000000;
            for (int i = 0; i < a; i++) {
                MyThread my = new MyThread();
                my.run();
            }
    
            System.out.println(concurrentHashMap.size());
        }
    
    
        static class MyThread implements Runnable{
    
            @Override
            public void run() {
                concurrentHashMap.put(SerialCreater.getSerial(),1);
            }
        }
    }
    View Code
  • 相关阅读:
    环境变量不重启生效
    egret list不显示问题
    批处理收集
    吐槽阿里云数据库的备份还原
    一次没清缓存的坑
    imagepng或imagejpeg浏览器无显示问题
    xdebug调试一直等待连接
    Python快速学习07:文本文件的操作
    Python快速学习06:词典
    纸上谈兵: AVL树[转]
  • 原文地址:https://www.cnblogs.com/sxdcgaq8080/p/10861797.html
Copyright © 2020-2023  润新知