關於.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

公眾號


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM