1
0
mirror of synced 2024-09-28 19:56:09 +00:00
Tapeti/Tapeti/TapetiConnection.cs

124 lines
3.2 KiB
C#
Raw Normal View History

using System;
using System.Linq;
using System.Threading.Tasks;
2016-12-11 14:08:58 +00:00
using Tapeti.Config;
using Tapeti.Connection;
// ReSharper disable UnusedMember.Global
namespace Tapeti
{
public delegate void DisconnectedEventHandler(object sender, DisconnectedEventArgs e);
public class TapetiConnection : IDisposable
{
2016-12-11 14:08:58 +00:00
private readonly IConfig config;
public TapetiConnectionParams Params { get; set; }
private readonly Lazy<TapetiWorker> worker;
private TapetiSubscriber subscriber;
2016-12-11 14:08:58 +00:00
public TapetiConnection(IConfig config)
{
2016-12-11 14:08:58 +00:00
this.config = config;
(config.DependencyResolver as IDependencyContainer)?.RegisterDefault(GetPublisher);
2016-12-11 14:08:58 +00:00
2017-02-12 20:43:30 +00:00
worker = new Lazy<TapetiWorker>(() => new TapetiWorker(config)
{
ConnectionParams = Params ?? new TapetiConnectionParams(),
ConnectionEventListener = new ConnectionEventListener(this)
});
}
public event EventHandler Connected;
public event DisconnectedEventHandler Disconnected;
public event EventHandler Reconnected;
public async Task<ISubscriber> Subscribe(bool startConsuming = true)
{
if (subscriber == null)
{
subscriber = new TapetiSubscriber(() => worker.Value, config.Queues.ToList());
await subscriber.BindQueues();
}
if (startConsuming)
await subscriber.Resume();
return subscriber;
}
public ISubscriber SubscribeSync(bool startConsuming = true)
{
return Subscribe(startConsuming).Result;
}
public IPublisher GetPublisher()
{
return new TapetiPublisher(() => worker.Value);
}
public async Task Close()
{
if (worker.IsValueCreated)
await worker.Value.Close();
}
public void Dispose()
{
Close().Wait();
}
private class ConnectionEventListener: IConnectionEventListener
{
private readonly TapetiConnection owner;
internal ConnectionEventListener(TapetiConnection owner)
{
this.owner = owner;
}
public void Connected()
{
owner.OnConnected(new EventArgs());
}
public void Disconnected(DisconnectedEventArgs e)
{
owner.OnDisconnected(e);
}
public void Reconnected()
{
owner.OnReconnected(new EventArgs());
}
}
protected virtual void OnConnected(EventArgs e)
{
Task.Run(() => Connected?.Invoke(this, e));
}
protected virtual void OnReconnected(EventArgs e)
{
Task.Run(() =>
{
subscriber?.RebindQueues().ContinueWith((t) =>
{
Reconnected?.Invoke(this, e);
});
});
}
protected virtual void OnDisconnected(DisconnectedEventArgs e)
{
Task.Run(() => Disconnected?.Invoke(this, e));
}
}
}