关于.Net 6使用 IAsyncEnumerable 流式处理 JSON 响应

介绍

接下来我将给大家重点介绍一下.Net 6 之后的一些新的变更,文章都是来自于外国大佬的文章,我这边进行一个翻译,并加上一些自己的理解和解释。

源作者链接:https://anthonygiretti.com/2021/09/22/asp-net-core-6-streaming-json-responses-with-iasyncenumerable-example-with-angular/

正文

服务器端

我传递了CountryServices服务和 dbContext CountryService的依赖注入的详细信息,代码应如下所示:

如您所见,我异步输出国家/地区,JSON 序列化程序将它们发送到客户端。不要忘记设置您的 CORS 规则!

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddScoped<ICountryServices, CountryServices>();
builder.Services.AddDbContext<CountryContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("CountryService")));
builder.Services.AddCors(o => o.AddPolicy("AllowAll", builder =>
{
    builder.AllowAnyOrigin()
           .AllowAnyMethod()
           .AllowAnyHeader();
}));

var app = builder.Build();

app.UseCors("AllowAll");

app.MapGet("/stream/countries", async (ICountryServices countryServices) =>
{
    async IAsyncEnumerable<CountryModel> StreamCountriesAsync()
    {
        var countries = await countryServices.GetAllAsync();
        foreach (var country in countries)
        {
            await Task.Delay(500);
            yield return country;
        }
    }
    return StreamCountriesAsync();
});

// Run the app
app.Run();

客户端

所以这里很特别,不可能用RxJs和它著名的Observable流式传输。您在这里要做的是使用一个能够管理流式 JSON 响应的库。该库称为oboe.js。

创建 Angular 项目后,使用以下命令下载必要的包:

npm install oboe
npm install --save @types/oboe

您需要做的是设置您的 API 调用配置,实例化双簧管对象并调用节点方法,如下所示:

import { Component, OnInit } from '@angular/core';
import { CountryModel } from '../models/countryModel';
import * as oboe from 'oboe';

@Component({
  selector: 'app-json-streaming',
  templateUrl: './json-streaming.component.html',
  styleUrls: ['./json-streaming.component.css']
})
export class JsonStreamingComponent implements OnInit {

  public countries: CountryModel[] = [];
  constructor() { }

  ngOnInit(): void {
    var config = {
      'url': "https://localhost:5001/stream/countries",
      'method': "GET",              
      'cached': false      
    }            
    const oboeService = oboe(config);
    var that = this;
    oboeService.node('!.*', function (country: CountryModel) {            
      that.countries.push(country);
    });
  }
}

请注意,节点方法的第一个参数允许使用以下值处理每个流式 JSON 项:!.*。换句话说,每次客户端收到流式传输的国家/地区时,都会调用第二个参数回调。如果您想在回调处理后面等待整个响应被流式处理,请改用以下值:!.

结语

联系作者:加群:867095512 @MrChuJiu

公众号

posted @ 2022-01-25 13:03  初久的私房菜  阅读(2899)  评论(1编辑  收藏  举报
作者:初久的私房菜
好好学习,天天向上
返回顶部小火箭
好友榜:
如果愿意,把你的博客地址放这里
张弛:https://blog.zhangchi.fun/