Skip to content

Commit

Permalink
Add ReconnectAsync method
Browse files Browse the repository at this point in the history
  • Loading branch information
pzajaczkowski committed Nov 28, 2024
1 parent 3771b04 commit 353b93d
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/NATS.Client.Core/INatsClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -115,4 +115,12 @@ ValueTask<NatsMsg<TReply>> RequestAsync<TReply>(
INatsDeserialize<TReply>? replySerializer = default,
NatsSubOpts? replyOpts = default,
CancellationToken cancellationToken = default);

/// <summary>
/// Force a reconnection to the NATS server.
/// </summary>
/// <remarks>
/// This method doesn't wait for the connection to be established.
/// </remarks>
ValueTask ReconnectAsync();
}
18 changes: 18 additions & 0 deletions src/NATS.Client.Core/NatsConnection.Reconnect.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using Microsoft.Extensions.Logging;

namespace NATS.Client.Core;

public partial class NatsConnection
{
/// <inheritdoc/>
public async ValueTask ReconnectAsync()
{
if (ConnectionState != NatsConnectionState.Open)
{
return;
}

_logger.LogInformation(NatsLogEvents.Connection, "Forcing reconnection to NATS server");
await _socket!.AbortConnectionAsync(CancellationToken.None).ConfigureAwait(false);
}
}
3 changes: 3 additions & 0 deletions src/NATS.Client.Simplified/NatsClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,9 @@ public ValueTask<NatsMsg<TReply>> RequestAsync<TRequest, TReply>(string subject,
public ValueTask<NatsMsg<TReply>> RequestAsync<TReply>(string subject, INatsDeserialize<TReply>? replySerializer = default, NatsSubOpts? replyOpts = default, CancellationToken cancellationToken = default)
=> Connection.RequestAsync(subject, replySerializer, replyOpts, cancellationToken);

/// <inheritdoc />
public ValueTask ReconnectAsync() => Connection.ReconnectAsync();

/// <inheritdoc />
public ValueTask DisposeAsync() => Connection.DisposeAsync();
}
2 changes: 2 additions & 0 deletions tests/NATS.Client.JetStream.Tests/NatsJsContextFactoryTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,8 @@ public ValueTask<NatsSub<TReply>> CreateRequestSubAsync<TRequest, TReply>(string

public ValueTask ConnectAsync() => throw new NotImplementedException();

public ValueTask ReconnectAsync() => throw new NotImplementedException();

public ValueTask DisposeAsync() => throw new NotImplementedException();
}
}
Expand Down

0 comments on commit 353b93d

Please sign in to comment.