zoukankan      html  css  js  c++  java
  • RNGCryptoServiceProvider 生成订单号

    先生成1~1000的随机数

    class Program
        {
            // Create a new instance of the RNGCryptoServiceProvider.  
            private static System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
    
            static void Main(string[] args)
            {
                for (int i = 0; i < 100; i++)
                {
                    int a = NextRandom(1000, 1, rng);
                    Console.WriteLine(string.Format("{0}{1}", DateTime.Now.ToString("yyyyMMddHHmmssfff"), a.ToString().PadLeft(4, '0')));
                }
                Console.Read();
            }
            private static int NextRandom(int numSeeds, int length, System.Security.Cryptography.RNGCryptoServiceProvider rng)
            {
                // Create a byte array to hold the random value.  
                byte[] randomNumber = new byte[length];
                // Fill the array with a random value.  
                rng.GetBytes(randomNumber);
                // Convert the byte to an uint value to make the modulus operation easier.  
                uint randomResult = 0x0;
                for (int i = 0; i < length; i++)
                {
                    randomResult |= ((uint)randomNumber[i] << ((length - 1 - i) * 8));
                }
                return (int)(randomResult % numSeeds) + 1;
            }
        }
    View Code

    注意将RNGCryptoServiceProvider定义为循环外的静态变量。

    经测试,这样在并发不大的时候能保证订单号的唯一性。

  • 相关阅读:
    FTP协议操作
    [转贴]SQL2005数据类型
    传智博客学习0512
    20120515传智学习
    20120516分析三层中的null的处理
    20120520晚
    你懂不懂我不知道,反正我是晕了
    20120509小记
    javascript 循环语句 while、dowhile、forin、for用法区别
    C#的一些学习方法
  • 原文地址:https://www.cnblogs.com/tylertang/p/11183303.html
Copyright © 2011-2022 走看看