Skip to content

Instantly share code, notes, and snippets.

@jalaziz
Created September 30, 2013 20:01
Show Gist options
  • Save jalaziz/6769315 to your computer and use it in GitHub Desktop.
Save jalaziz/6769315 to your computer and use it in GitHub Desktop.
Booksleeve Redis Connection Manager
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BookSleeve;
namespace Redis
{
public class RedisConnectionManager : IDisposable
{
private volatile RedisConnection _connection;
private readonly object _connectionLock = new object();
public string Host { get; set; }
public int Port { get; set; }
public int IOTimeout { get; set; }
public string Password { get; set; }
public int MaxUnsent { get; set; }
public bool AllowAdmin { get; set; }
public int SyncTimeout { get; set; }
public RedisConnectionManager(string host, int port = 6379, int ioTimeout = -1, string password = null, int maxUnsent = 2147483647, bool allowAdmin = false, int syncTimeout = 10000)
{
Host = host;
Port = port;
IOTimeout = ioTimeout;
Password = password;
MaxUnsent = maxUnsent;
AllowAdmin = allowAdmin;
SyncTimeout = syncTimeout;
}
public RedisConnection GetConnection(bool waitOnOpen = false)
{
var connection = _connection;
if (connection == null)
{
lock (_connectionLock)
{
if (_connection == null)
{
_connection = new RedisConnection(Host, Port, IOTimeout, Password, MaxUnsent, AllowAdmin, SyncTimeout);
_connection.Shutdown += ConnectionOnShutdown;
var openTask = _connection.Open();
if (waitOnOpen) { _connection.Wait(openTask); }
}
connection = _connection;
}
}
return connection;
}
private void ConnectionOnShutdown(object sender, ErrorEventArgs errorEventArgs)
{
lock (_connectionLock)
{
_connection.Shutdown -= ConnectionOnShutdown;
_connection = null;
}
}
public void Reset(bool abort = false)
{
lock (_connectionLock)
{
if (_connection != null)
{
_connection.Close(abort);
_connection = null;
}
}
}
public void Dispose()
{
lock (_connectionLock)
{
if (_connection != null)
{
_connection.Dispose();
_connection = null;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment