简体   繁体   English

ASP.Net Core 中的 NATS JetStream 订阅

[英]NATS JetStream subscription in ASP.Net Core

I am subscribing to a NATS Jetstream channel and process the messages received from NATS Server.我正在订阅 NATS Jetstream 频道并处理从 NATS 服务器收到的消息。 I can do it in a console app by connecting to NATS Server and subscribing to a subject.我可以通过连接到 NATS 服务器并订阅主题在控制台应用程序中完成此操作。 Now I am trying to configure the subscription in ASP.Net core app, so that it will always listen to the channel and process the messages it received.现在我正在尝试在 ASP.Net 核心应用程序中配置订阅,以便它始终侦听频道并处理它收到的消息。 Could someone help me how and where to configure in ASP.Net core app?有人可以帮助我如何以及在哪里配置 ASP.Net 核心应用程序? TIA. TIA。

You can implement and mount a hosted service to your core app.您可以实施托管服务并将其安装到您的核心应用程序。 See docs查看文档

Rough sample:粗样本:

public class NatsConsumerHostedService : IHostedService
{
    private IAsyncSubscription? _subscription;
    
    public async Task StartAsync(CancellationToken cancellationToken)
    {
        if (!cancellationToken.IsCancellationRequested)
        {
            // _subscription = await natsClient.Subscribe(...);
        }
    }

    public async Task StopAsync(CancellationToken cancellationToken)
    {
        await _subscription?.DrainAsync();
        _subscription?.Unsubscribe();
    }
}

Mounting it:安装它:

var builder = WebApplication.CreateBuilder(args);
// myriad of service registrations could go here...    
builder.Services.AddHostedService<NatsConsumerHostedService>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM