Created
October 26, 2017 06:08
-
-
Save anonymous/c7c741b8a97e2c77e4bc3eeb9d4781ec to your computer and use it in GitHub Desktop.
This is a Singleton Redis Helpr I am using that creates a bunch of Connection issues. Is there a better way?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public sealed class RedisHelper | |
{ | |
private static RedisHelper _instance; | |
private static readonly Lazy<RedisHelper> Lazy = new Lazy<RedisHelper>(() => new RedisHelper()); | |
private static readonly object SyncRoot = new object(); | |
private static string RedisSource = string.Empty; | |
public static ConnectionMultiplexer RedisConnection; | |
public IDatabase RedisDb; | |
private RedisHelper() | |
{ | |
var connStr = ConfigurationManager.AppSettings[TsConstants.AppSettingKeyNames.RedisCacheConnection]; | |
if (connStr == null) throw new ArgumentException("Redis Connection not setup."); | |
//creating this RedisSource to track a connection in logs to see if multiple connections are being created or not | |
RedisSource = ConfigurationManager.AppSettings[TsConstants.AppSettingKeyNames.RedisSource]; | |
RedisSource = $"{RedisSource}-{new Random().Next(int.MaxValue)}"; | |
if (RedisConnection == null || !RedisConnection.IsConnected) | |
{ | |
RedisConnection = ConnectionMultiplexer.Connect(configOptions); | |
Log.Logger.Information($"Source: {RedisSource} - Built a new Redis Connection"); | |
} | |
RedisConnection.PreserveAsyncOrder = true; | |
RedisDb = RedisConnection.GetDatabase(); | |
} | |
public static RedisHelper Instance | |
{ | |
get | |
{ | |
if (_instance == null) | |
lock (SyncRoot) | |
{ | |
return Lazy.Value; | |
} | |
return _instance; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment