samedi 27 juin 2015

generate random string in load balanced app servers

Here is the code for my random string generator

private static string GetUniqueKey()
{
    int maxSize  = 15 ;
    char[] chars = new char[62];
    string a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    chars = a.ToCharArray();
    int size  = maxSize ;
    byte[] data = new byte[1];
    RNGCryptoServiceProvider  crypto = new RNGCryptoServiceProvider();
    crypto.GetNonZeroBytes(data) ;
    size =  maxSize ;
    data = new byte[size];
    crypto.GetNonZeroBytes(data);
    StringBuilder result = new StringBuilder(size) ;
    foreach(byte b in data )
    {
        result.Append(chars[b % (chars.Length - 1)]);
    }
    return result.ToString();

}

How do I write a unit test that would test for the following:

  1. checks the database and keeps generating random number until it does not exist in the database and updates the database
  2. 100% guarantee that no 2 threads will generate the same random number
  3. will work on different app servers in load balancer situation.

I don't want to lock thread because it creates performance night mare under extreme load tests.




Aucun commentaire:

Enregistrer un commentaire