-
Notifications
You must be signed in to change notification settings - Fork 0
/
Worker.cs
99 lines (85 loc) · 3.49 KB
/
Worker.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Google.Protobuf.WellKnownTypes;
using Grpc.Net.Client;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using static HeartbeatService.Heartbeat;
namespace WorkerService
{
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
private readonly IHttpClientFactory _httpClientFactory;
private HeartbeatClient _heartbeatClient;
private HttpClient _httpClient;
public Worker(ILogger<Worker> logger,
IHttpClientFactory httpClientFactory)
{
_logger = logger;
_httpClientFactory = httpClientFactory;
}
public override async Task StartAsync(CancellationToken stoppingToken)
{
try
{
// -----------------
// you'd want to remove this line for production use, once your certs are prod
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
// -----------------
var channel = GrpcChannel.ForAddress("http://grpcservice");
_heartbeatClient = new HeartbeatClient(channel);
_httpClient = _httpClientFactory.CreateClient("heartbeat");
}
catch(Exception x)
{
_logger.LogError(x, "Erorr during startup");
}
await base.StartAsync(stoppingToken);
}
public override async Task StopAsync(CancellationToken stoppingToken)
{
_httpClient?.Dispose();
await base.StopAsync(stoppingToken);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
#pragma warning disable CS4014
Task.Run(() => {
var json = _httpClient.GetStringAsync("http://heartbeat/").Result;
var instanceInfo = JsonSerializer.Deserialize<InstanceInfo>(json);
_logger.LogInformation($"Internal API from host {instanceInfo.HostName} received at {instanceInfo.HostTimeStamp}");
try
{
var reply = _heartbeatClient.ReceiveHeartbeat(new HeartbeatService.HeartbeatMessage
{
HostName = instanceInfo.HostName,
HostTimeStamp = Timestamp.FromDateTime(instanceInfo.HostTimeStamp)
});
_logger.LogInformation($"Heartbeat received with success: {reply.Success}");
}
catch(Exception x)
{
_logger.LogError(x, "Error calling gRPC service");
}
});
#pragma warning restore CS4014
}
catch(Exception ex)
{
_logger.LogError(ex, "Error during HTTP request");
}
await Task.Delay(500, stoppingToken);
}
}
}
}