Skip to content
This repository was archived by the owner on May 14, 2024. It is now read-only.

Commit 1ff4fb0

Browse files
authored
Merge pull request #88 from ren8179/master
兼容配置项被修改(重命名/嵌套)的情况
2 parents 65e4cf0 + 1b0de6d commit 1ff4fb0

File tree

5 files changed

+132
-131
lines changed

5 files changed

+132
-131
lines changed

example/HttpReports.Collector.Demo/Startup.cs

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1+
using HttpReports.Transport.Http;
12
using Microsoft.AspNetCore.Builder;
23
using Microsoft.AspNetCore.Hosting;
34
using Microsoft.AspNetCore.Http;
5+
using Microsoft.Extensions.Configuration;
46
using Microsoft.Extensions.DependencyInjection;
57
using Microsoft.Extensions.Hosting;
68
using System;
@@ -12,10 +14,21 @@ namespace HttpReports.Collector.Demo
1214
{
1315
public class Startup
1416
{
15-
17+
public Startup(IConfiguration configuration)
18+
{
19+
Configuration = configuration;
20+
}
21+
/// <summary>
22+
///
23+
/// </summary>
24+
public IConfiguration Configuration { get; }
25+
1626
public void ConfigureServices(IServiceCollection services)
1727
{
18-
services.AddHttpReports().AddHttpTransport();
28+
//services.AddHttpReports().AddHttpTransport();
29+
services.Configure<HttpReportsOptions>(Configuration.GetSection("HttpReports"));
30+
services.Configure<HttpTransportOptions>(Configuration.GetSection("HttpReports").GetSection("Transport"));
31+
services.AddHttpReports(Configuration).AddHttpTransport(Configuration);
1932
}
2033

2134
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,58 +1,57 @@
1-
using System;
2-
using System.Collections.Generic;
3-
using System.Net.Http.Headers;
4-
using System.Text;
5-
using HttpReports;
1+
using HttpReports;
62
using HttpReports.Core;
73
using HttpReports.Transport.Http;
84
using Microsoft.Extensions.Configuration;
9-
using Microsoft.Extensions.DependencyInjection.Extensions;
5+
using Microsoft.Extensions.DependencyInjection.Extensions;
6+
using System;
107

118
namespace Microsoft.Extensions.DependencyInjection
129
{
1310
public static class DependencyInjectionExtensions
14-
{
11+
{
1512
[Obsolete("Use AddHttpTransport instead")]
1613
public static IHttpReportsBuilder UseHttpTransport(this IHttpReportsBuilder builder)
1714
{
1815
builder.Services.AddOptions().Configure<HttpTransportOptions>(builder.Configuration.GetSection("Transport"));
1916
return builder.AddHttpTransportService();
2017
}
2118

22-
2319
[Obsolete("Use AddHttpTransport instead")]
2420
public static IHttpReportsBuilder UseHttpTransport(this IHttpReportsBuilder builder, Action<HttpTransportOptions> options)
2521
{
2622
builder.Services.AddOptions().Configure(options);
2723
return builder.AddHttpTransportService();
28-
}
29-
24+
}
3025

3126
public static IHttpReportsBuilder AddHttpTransport(this IHttpReportsBuilder builder)
32-
{
27+
{
3328
builder.Services.AddOptions().Configure<HttpTransportOptions>(builder.Configuration.GetSection("Transport"));
3429
return builder.AddHttpTransportService();
3530
}
3631

32+
public static IHttpReportsBuilder AddHttpTransport(this IHttpReportsBuilder builder, IConfiguration configuration)
33+
{
34+
return builder.AddHttpTransportService();
35+
}
36+
3737
public static IHttpReportsBuilder AddHttpTransport(this IHttpReportsBuilder builder, Action<HttpTransportOptions> options)
38-
{
38+
{
3939
builder.Services.AddOptions().Configure(options);
4040
return builder.AddHttpTransportService();
4141
}
4242

4343
private static IHttpReportsBuilder AddHttpTransportService(this IHttpReportsBuilder builder)
4444
{
45-
builder.Services.AddHttpClient(BasicConfig.HttpReportsHttpClient,client => {
46-
47-
client.DefaultRequestHeaders.Clear();
45+
builder.Services.AddHttpClient(BasicConfig.HttpReportsHttpClient, client =>
46+
{
47+
client.DefaultRequestHeaders.Clear();
4848
client.Timeout = TimeSpan.FromSeconds(5);
4949

5050
});
5151

5252
builder.Services.RemoveAll<IReportsTransport>();
53-
builder.Services.AddSingleton<IReportsTransport, HttpTransport>();
53+
builder.Services.AddSingleton<IReportsTransport, HttpTransport>();
5454
return builder;
5555
}
5656
}
57-
5857
}
Lines changed: 47 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
using HttpReports.Core;
1+
using HttpReports.Core;
22
using HttpReports.Core.Models;
33
using Microsoft.Extensions.Logging;
4-
using Microsoft.Extensions.Options;
4+
using Microsoft.Extensions.Options;
55
using System;
66
using System.Collections.Generic;
77
using System.Net;
8-
using System.Net.Http;
8+
using System.Net.Http;
99
using System.Text.Json;
1010
using System.Threading;
1111
using System.Threading.Tasks;
@@ -15,14 +15,13 @@ namespace HttpReports.Transport.Http
1515
{
1616
public class HttpTransport : IReportsTransport
1717
{
18-
public HttpTransportOptions _options { get; }
18+
public HttpTransportOptions _options { get; }
1919

20-
private readonly AsyncCallbackDeferFlushCollection<RequestBag> _RequestBagCollection;
20+
private readonly AsyncCallbackDeferFlushCollection<RequestBag> _RequestBagCollection;
2121

2222
private readonly ILogger<HttpTransport> _logger;
2323
private readonly IHttpClientFactory _httpClientFactory;
2424
private readonly JsonSerializerOptions _jsonSetting;
25-
private readonly JsonSerializerOptions jsonSerializer;
2625

2726

2827
public HttpTransport(IOptions<HttpTransportOptions> options, JsonSerializerOptions jsonSetting, ILogger<HttpTransport> logger, IHttpClientFactory httpClientFactory)
@@ -31,31 +30,35 @@ public HttpTransport(IOptions<HttpTransportOptions> options, JsonSerializerOptio
3130
_logger = logger;
3231
_httpClientFactory = httpClientFactory;
3332
_jsonSetting = jsonSetting;
34-
_RequestBagCollection = new AsyncCallbackDeferFlushCollection<RequestBag>(Push, _options.DeferThreshold,_options.DeferSecond);
35-
}
33+
if (_options.CollectorAddress != null)
34+
_RequestBagCollection = new AsyncCallbackDeferFlushCollection<RequestBag>(Push, _options.DeferThreshold, _options.DeferSecond);
35+
}
3636

3737
public Task SendDataAsync(RequestBag bag)
38-
{
39-
_RequestBagCollection.Flush(bag);
38+
{
39+
if (_RequestBagCollection != null)
40+
_RequestBagCollection.Flush(bag);
4041

4142
return Task.CompletedTask;
42-
}
43+
}
4344

4445
public async Task SendDataAsync(Performance performance)
4546
{
46-
await Retry(async () => {
47+
if (_options.CollectorAddress == null) return;
48+
await Retry(async () =>
49+
{
4750

4851
try
4952
{
50-
HttpContent content = new StringContent(HttpUtility.HtmlEncode(System.Text.Json.JsonSerializer.Serialize(performance,_jsonSetting)), System.Text.Encoding.UTF8, "application/json");
53+
HttpContent content = new StringContent(HttpUtility.HtmlEncode(System.Text.Json.JsonSerializer.Serialize(performance, _jsonSetting)), System.Text.Encoding.UTF8, "application/json");
5154

5255
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
5356
content.Headers.Add(BasicConfig.TransportType, typeof(Performance).Name);
5457

5558
var response = await _httpClientFactory.CreateClient(BasicConfig.HttpReportsHttpClient).PostAsync(_options.CollectorAddress + BasicConfig.TransportPath.Substring(1), content);
5659

5760
return response.StatusCode == HttpStatusCode.OK;
58-
}
61+
}
5962
catch (Exception ex) when (ex is HttpRequestException || ex is TaskCanceledException)
6063
{
6164
_logger.LogWarning("HttpReports transport failed...");
@@ -65,57 +68,59 @@ await Retry(async () => {
6568
{
6669
//_logger.LogError(ex, "performance push failed:" + ex.ToString());
6770
return false;
68-
}
71+
}
6972

7073
});
7174

72-
}
75+
}
7376

7477
private async Task Push(List<RequestBag> list, CancellationToken token)
75-
{
76-
await Retry(async () => {
78+
{
79+
if (_options.CollectorAddress == null) return;
80+
await Retry(async () =>
81+
{
7782

78-
try
79-
{
80-
HttpContent content = new StringContent(HttpUtility.HtmlEncode( System.Text.Json.JsonSerializer.Serialize(list,_jsonSetting)), System.Text.Encoding.UTF8);
83+
try
84+
{
85+
HttpContent content = new StringContent(HttpUtility.HtmlEncode(System.Text.Json.JsonSerializer.Serialize(list, _jsonSetting)), System.Text.Encoding.UTF8);
8186

82-
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
83-
content.Headers.Add(BasicConfig.TransportType, typeof(RequestBag).Name);
84-
var response = await _httpClientFactory.CreateClient(BasicConfig.HttpReportsHttpClient).PostAsync(_options.CollectorAddress + BasicConfig.TransportPath.Substring(1), content);
87+
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
88+
content.Headers.Add(BasicConfig.TransportType, typeof(RequestBag).Name);
89+
var response = await _httpClientFactory.CreateClient(BasicConfig.HttpReportsHttpClient).PostAsync(_options.CollectorAddress + BasicConfig.TransportPath.Substring(1), content);
8590

86-
var result = await response.Content.ReadAsStringAsync();
91+
var result = await response.Content.ReadAsStringAsync();
8792

88-
return response.StatusCode == HttpStatusCode.OK;
93+
return response.StatusCode == HttpStatusCode.OK;
8994

90-
}
91-
catch (Exception ex) when (ex is HttpRequestException || ex is TaskCanceledException)
92-
{
93-
_logger.LogWarning("HttpReports transport failed...");
94-
return false;
95-
}
96-
catch (Exception ex)
97-
{
98-
_logger.LogWarning("HttpReports transport failed:" + ex.ToString());
99-
return false;
100-
}
95+
}
96+
catch (Exception ex) when (ex is HttpRequestException || ex is TaskCanceledException)
97+
{
98+
_logger.LogWarning("HttpReports transport failed...");
99+
return false;
100+
}
101+
catch (Exception ex)
102+
{
103+
_logger.LogWarning("HttpReports transport failed:" + ex.ToString());
104+
return false;
105+
}
101106

102-
});
103-
}
107+
});
108+
}
104109

105110
private async Task<bool> Retry(Func<Task<bool>> func, int retry = 3)
106-
{
111+
{
107112
for (int i = 0; i < 3; i++)
108113
{
109114
await Task.Delay(200);
110115

111116
if (await func.Invoke())
112117
{
113118
return true;
114-
}
119+
}
115120
}
116121

117122
return false;
118-
}
123+
}
119124

120125
}
121126
}

0 commit comments

Comments
 (0)