Created
June 15, 2016 19:42
-
-
Save alexandrebl/f99421b0dc8e72eb1f6a434f6ae89b44 to your computer and use it in GitHub Desktop.
Gerenciador de conexão com o Redis Cache
This file contains hidden or 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
| using DNAuth.FrameworkUtility.Configs.Interfaces; | |
| using RedisBoost; | |
| using System.Threading.Tasks; | |
| namespace FrameworkUtility.Clients { | |
| /// <summary> | |
| /// Gerenciador de conexão do Redis | |
| /// </summary> | |
| public class CacheConnectionManager { | |
| /// <summary> | |
| /// Pool de conexão do Redis | |
| /// </summary> | |
| private static IRedisClientsPool _redisClientsPool; | |
| /// <summary> | |
| /// Objeto de sincronismo do Redis | |
| /// </summary> | |
| private static readonly object SyncObj = new object(); | |
| /// <summary> | |
| /// Utilitário de configuração do Redis | |
| /// </summary> | |
| private readonly IRedisConfigurationUtility _redisConfigurationUtility; | |
| /// <summary> | |
| /// Método construtor | |
| /// </summary> | |
| public CacheConnectionManager(IRedisConfigurationUtility redisConfigurationUtility) { | |
| //Utilitário de configuração do Redis | |
| this._redisConfigurationUtility = redisConfigurationUtility; | |
| } | |
| /// <summary> | |
| /// Obtem uma nova conexão do Redis | |
| /// </summary> | |
| /// <returns></returns> | |
| public IRedisClient GetConnection() { | |
| //Cliente Redis | |
| IRedisClient redisClient = null; | |
| //Verifica se o pool de conexão do Redis existe | |
| if (_redisClientsPool == null) { | |
| //Efetua o lock do Redis | |
| lock (SyncObj) { | |
| //Verifica se o pool de conexão do Redis existe | |
| if (_redisClientsPool == null) { | |
| //Cria o pool de conexão | |
| _redisClientsPool = RedisClient.CreateClientsPool(); | |
| } | |
| } | |
| } | |
| //Instancia o cliente do Redis | |
| var connectionTask = _redisClientsPool.CreateClientAsync( | |
| this._redisConfigurationUtility.Address, this._redisConfigurationUtility.Port).ContinueWith( | |
| //Cria a conexão | |
| connection => { | |
| if ((connection.Status != TaskStatus.Faulted) && (connection.Status != TaskStatus.Canceled)) { | |
| //Obtem o cliente | |
| redisClient = connection.Result; | |
| } | |
| }, TaskContinuationOptions.LongRunning); | |
| //Aguarda o processamento | |
| connectionTask.Wait(); | |
| //Retorna o cliente Redis | |
| return redisClient; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment