├── .gitignore
├── ConsoleAppConsumoAPIs
├── ConsoleAppConsumoAPIs.csproj
├── ConsoleAppConsumoAPIs.sln
├── Endpoints.cs
├── Models
│ └── ResultadoContador.cs
└── Program.cs
├── DockerCompose
└── docker-compose.yml
├── Kafka
└── APIContagem
│ ├── .vscode
│ ├── launch.json
│ └── tasks.json
│ ├── APIContagem.csproj
│ ├── APIContagem.sln
│ ├── Contador.cs
│ ├── Controllers
│ └── ContadorController.cs
│ ├── Kafka
│ └── KafkaExtensions.cs
│ ├── Models
│ └── ResultadoContador.cs
│ ├── Program.cs
│ ├── Properties
│ └── launchSettings.json
│ ├── Tracing
│ └── OpenTelemetryExtensions.cs
│ ├── appsettings.Development.json
│ └── appsettings.json
├── README.md
├── Redis
└── APIContagem
│ ├── .vscode
│ ├── launch.json
│ └── tasks.json
│ ├── APIContagem.csproj
│ ├── APIContagem.sln
│ ├── Controllers
│ └── ContadorController.cs
│ ├── Logging
│ └── ContagemLogging.cs
│ ├── Models
│ └── ResultadoContador.cs
│ ├── Program.cs
│ ├── Properties
│ └── launchSettings.json
│ ├── Tracing
│ └── OpenTelemetryExtensions.cs
│ ├── appsettings.Development.json
│ └── appsettings.json
├── Scripts-SqlServer
└── BaseContagemKafka.sql
└── WorkerContagem
├── .vscode
├── launch.json
└── tasks.json
├── Data
├── ContagemRepository.cs
└── HistoricoContagem.cs
├── Kafka
└── KafkaExtensions.cs
├── Models
└── ResultadoContador.cs
├── Program.cs
├── Properties
└── launchSettings.json
├── Tracing
└── OpenTelemetryExtensions.cs
├── Worker.cs
├── WorkerContagem.csproj
├── WorkerContagem.sln
├── appsettings.Development.json
└── appsettings.json
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Aa][Rr][Mm]/
27 | [Aa][Rr][Mm]64/
28 | bld/
29 | [Bb]in/
30 | [Oo]bj/
31 | [Ll]og/
32 | [Ll]ogs/
33 |
34 | # Visual Studio 2015/2017 cache/options directory
35 | .vs/
36 | # Uncomment if you have tasks that create the project's static files in wwwroot
37 | #wwwroot/
38 |
39 | # Visual Studio 2017 auto generated files
40 | Generated\ Files/
41 |
42 | # MSTest test Results
43 | [Tt]est[Rr]esult*/
44 | [Bb]uild[Ll]og.*
45 |
46 | # NUnit
47 | *.VisualState.xml
48 | TestResult.xml
49 | nunit-*.xml
50 |
51 | # Build Results of an ATL Project
52 | [Dd]ebugPS/
53 | [Rr]eleasePS/
54 | dlldata.c
55 |
56 | # Benchmark Results
57 | BenchmarkDotNet.Artifacts/
58 |
59 | # .NET Core
60 | project.lock.json
61 | project.fragment.lock.json
62 | artifacts/
63 |
64 | # StyleCop
65 | StyleCopReport.xml
66 |
67 | # Files built by Visual Studio
68 | *_i.c
69 | *_p.c
70 | *_h.h
71 | *.ilk
72 | *.meta
73 | *.obj
74 | *.iobj
75 | *.pch
76 | *.pdb
77 | *.ipdb
78 | *.pgc
79 | *.pgd
80 | *.rsp
81 | *.sbr
82 | *.tlb
83 | *.tli
84 | *.tlh
85 | *.tmp
86 | *.tmp_proj
87 | *_wpftmp.csproj
88 | *.log
89 | *.vspscc
90 | *.vssscc
91 | .builds
92 | *.pidb
93 | *.svclog
94 | *.scc
95 |
96 | # Chutzpah Test files
97 | _Chutzpah*
98 |
99 | # Visual C++ cache files
100 | ipch/
101 | *.aps
102 | *.ncb
103 | *.opendb
104 | *.opensdf
105 | *.sdf
106 | *.cachefile
107 | *.VC.db
108 | *.VC.VC.opendb
109 |
110 | # Visual Studio profiler
111 | *.psess
112 | *.vsp
113 | *.vspx
114 | *.sap
115 |
116 | # Visual Studio Trace Files
117 | *.e2e
118 |
119 | # TFS 2012 Local Workspace
120 | $tf/
121 |
122 | # Guidance Automation Toolkit
123 | *.gpState
124 |
125 | # ReSharper is a .NET coding add-in
126 | _ReSharper*/
127 | *.[Rr]e[Ss]harper
128 | *.DotSettings.user
129 |
130 | # TeamCity is a build add-in
131 | _TeamCity*
132 |
133 | # DotCover is a Code Coverage Tool
134 | *.dotCover
135 |
136 | # AxoCover is a Code Coverage Tool
137 | .axoCover/*
138 | !.axoCover/settings.json
139 |
140 | # Visual Studio code coverage results
141 | *.coverage
142 | *.coveragexml
143 |
144 | # NCrunch
145 | _NCrunch_*
146 | .*crunch*.local.xml
147 | nCrunchTemp_*
148 |
149 | # MightyMoose
150 | *.mm.*
151 | AutoTest.Net/
152 |
153 | # Web workbench (sass)
154 | .sass-cache/
155 |
156 | # Installshield output folder
157 | [Ee]xpress/
158 |
159 | # DocProject is a documentation generator add-in
160 | DocProject/buildhelp/
161 | DocProject/Help/*.HxT
162 | DocProject/Help/*.HxC
163 | DocProject/Help/*.hhc
164 | DocProject/Help/*.hhk
165 | DocProject/Help/*.hhp
166 | DocProject/Help/Html2
167 | DocProject/Help/html
168 |
169 | # Click-Once directory
170 | publish/
171 |
172 | # Publish Web Output
173 | *.[Pp]ublish.xml
174 | *.azurePubxml
175 | # Note: Comment the next line if you want to checkin your web deploy settings,
176 | # but database connection strings (with potential passwords) will be unencrypted
177 | *.pubxml
178 | *.publishproj
179 |
180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
181 | # checkin your Azure Web App publish settings, but sensitive information contained
182 | # in these scripts will be unencrypted
183 | PublishScripts/
184 |
185 | # NuGet Packages
186 | *.nupkg
187 | # NuGet Symbol Packages
188 | *.snupkg
189 | # The packages folder can be ignored because of Package Restore
190 | **/[Pp]ackages/*
191 | # except build/, which is used as an MSBuild target.
192 | !**/[Pp]ackages/build/
193 | # Uncomment if necessary however generally it will be regenerated when needed
194 | #!**/[Pp]ackages/repositories.config
195 | # NuGet v3's project.json files produces more ignorable files
196 | *.nuget.props
197 | *.nuget.targets
198 |
199 | # Microsoft Azure Build Output
200 | csx/
201 | *.build.csdef
202 |
203 | # Microsoft Azure Emulator
204 | ecf/
205 | rcf/
206 |
207 | # Windows Store app package directories and files
208 | AppPackages/
209 | BundleArtifacts/
210 | Package.StoreAssociation.xml
211 | _pkginfo.txt
212 | *.appx
213 | *.appxbundle
214 | *.appxupload
215 |
216 | # Visual Studio cache files
217 | # files ending in .cache can be ignored
218 | *.[Cc]ache
219 | # but keep track of directories ending in .cache
220 | !?*.[Cc]ache/
221 |
222 | # Others
223 | ClientBin/
224 | ~$*
225 | *~
226 | *.dbmdl
227 | *.dbproj.schemaview
228 | *.jfm
229 | *.pfx
230 | *.publishsettings
231 | orleans.codegen.cs
232 |
233 | # Including strong name files can present a security risk
234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
235 | #*.snk
236 |
237 | # Since there are multiple workflows, uncomment next line to ignore bower_components
238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
239 | #bower_components/
240 |
241 | # RIA/Silverlight projects
242 | Generated_Code/
243 |
244 | # Backup & report files from converting an old project file
245 | # to a newer Visual Studio version. Backup files are not needed,
246 | # because we have git ;-)
247 | _UpgradeReport_Files/
248 | Backup*/
249 | UpgradeLog*.XML
250 | UpgradeLog*.htm
251 | ServiceFabricBackup/
252 | *.rptproj.bak
253 |
254 | # SQL Server files
255 | *.mdf
256 | *.ldf
257 | *.ndf
258 |
259 | # Business Intelligence projects
260 | *.rdl.data
261 | *.bim.layout
262 | *.bim_*.settings
263 | *.rptproj.rsuser
264 | *- [Bb]ackup.rdl
265 | *- [Bb]ackup ([0-9]).rdl
266 | *- [Bb]ackup ([0-9][0-9]).rdl
267 |
268 | # Microsoft Fakes
269 | FakesAssemblies/
270 |
271 | # GhostDoc plugin setting file
272 | *.GhostDoc.xml
273 |
274 | # Node.js Tools for Visual Studio
275 | .ntvs_analysis.dat
276 | node_modules/
277 |
278 | # Visual Studio 6 build log
279 | *.plg
280 |
281 | # Visual Studio 6 workspace options file
282 | *.opt
283 |
284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
285 | *.vbw
286 |
287 | # Visual Studio LightSwitch build output
288 | **/*.HTMLClient/GeneratedArtifacts
289 | **/*.DesktopClient/GeneratedArtifacts
290 | **/*.DesktopClient/ModelManifest.xml
291 | **/*.Server/GeneratedArtifacts
292 | **/*.Server/ModelManifest.xml
293 | _Pvt_Extensions
294 |
295 | # Paket dependency manager
296 | .paket/paket.exe
297 | paket-files/
298 |
299 | # FAKE - F# Make
300 | .fake/
301 |
302 | # CodeRush personal settings
303 | .cr/personal
304 |
305 | # Python Tools for Visual Studio (PTVS)
306 | __pycache__/
307 | *.pyc
308 |
309 | # Cake - Uncomment if you are using it
310 | # tools/**
311 | # !tools/packages.config
312 |
313 | # Tabs Studio
314 | *.tss
315 |
316 | # Telerik's JustMock configuration file
317 | *.jmconfig
318 |
319 | # BizTalk build output
320 | *.btp.cs
321 | *.btm.cs
322 | *.odx.cs
323 | *.xsd.cs
324 |
325 | # OpenCover UI analysis results
326 | OpenCover/
327 |
328 | # Azure Stream Analytics local run output
329 | ASALocalRun/
330 |
331 | # MSBuild Binary and Structured Log
332 | *.binlog
333 |
334 | # NVidia Nsight GPU debugger configuration file
335 | *.nvuser
336 |
337 | # MFractors (Xamarin productivity tool) working folder
338 | .mfractor/
339 |
340 | # Local History for Visual Studio
341 | .localhistory/
342 |
343 | # BeatPulse healthcheck temp database
344 | healthchecksdb
345 |
346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
347 | MigrationBackup/
348 |
349 | # Ionide (cross platform F# VS Code tools) working folder
350 | .ionide/
351 |
--------------------------------------------------------------------------------
/ConsoleAppConsumoAPIs/ConsoleAppConsumoAPIs.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net6.0
6 | enable
7 | enable
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/ConsoleAppConsumoAPIs/ConsoleAppConsumoAPIs.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.3.32708.82
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ConsoleAppConsumoAPIs", "ConsoleAppConsumoAPIs.csproj", "{B783A121-4913-4E1C-846D-E7B9F4672110}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {B783A121-4913-4E1C-846D-E7B9F4672110}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {B783A121-4913-4E1C-846D-E7B9F4672110}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {B783A121-4913-4E1C-846D-E7B9F4672110}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {B783A121-4913-4E1C-846D-E7B9F4672110}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | GlobalSection(ExtensibilityGlobals) = postSolution
23 | SolutionGuid = {5A8F60A2-81AB-4F65-9B81-E77982538D2C}
24 | EndGlobalSection
25 | EndGlobal
26 |
--------------------------------------------------------------------------------
/ConsoleAppConsumoAPIs/Endpoints.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 | using ConsoleAppConsumoAPIs.Models;
3 | using System.Net.Http.Json;
4 |
5 | namespace ConsoleAppConsumoAPIs;
6 |
7 | public static class Endpoints
8 | {
9 | public static string APIContagemKafka { get; } = "http://localhost:6900/contador";
10 | public static string APIContagemRedis { get; } = "http://localhost:6300/contador";
11 |
12 | public static void SendRequest(string tecnologia, string endpoint, HttpClient client)
13 | {
14 | using var activity = new ActivitySource(nameof(ConsoleAppConsumoAPIs), "1.0.0")
15 | .StartActivity($"{nameof(SendRequest)} APIContagem{tecnologia}");
16 | activity?.SetTag("endpoint", endpoint);
17 |
18 | var resultado = client.GetFromJsonAsync(endpoint).Result;
19 | activity?.SetTag("valorAtual", resultado!.ValorAtual);
20 |
21 | Console.WriteLine(
22 | $"{tecnologia}: {resultado!.Producer} | Valor atual = {resultado.ValorAtual}");
23 | }
24 | }
--------------------------------------------------------------------------------
/ConsoleAppConsumoAPIs/Models/ResultadoContador.cs:
--------------------------------------------------------------------------------
1 | namespace ConsoleAppConsumoAPIs.Models;
2 |
3 | public class ResultadoContador
4 | {
5 | public int ValorAtual { get; set; }
6 | public string? Producer { get; set; }
7 | }
--------------------------------------------------------------------------------
/ConsoleAppConsumoAPIs/Program.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 | using OpenTelemetry;
3 | using OpenTelemetry.Trace;
4 | using OpenTelemetry.Resources;
5 | using ConsoleAppConsumoAPIs;
6 |
7 | Console.WriteLine("***** Tracing Distribuído com .NET 6 + ASP.NET Core + Jaeger + OpenTelemetry + " +
8 | "Apache Kafka + SQL Server *****");
9 |
10 | using var tracerProvider = Sdk.CreateTracerProviderBuilder()
11 | .AddSource(nameof(ConsoleAppConsumoAPIs))
12 | .SetResourceBuilder(
13 | ResourceBuilder.CreateDefault()
14 | .AddService(serviceName: nameof(ConsoleAppConsumoAPIs), serviceVersion: "1.0.0"))
15 | .AddHttpClientInstrumentation()
16 | .AddJaegerExporter(exporter =>
17 | {
18 | exporter.AgentHost = "localhost";
19 | exporter.AgentPort = 6831;
20 | })
21 | .Build();
22 |
23 | using var client = new HttpClient();
24 | using var activitySource = new ActivitySource(nameof(ConsoleAppConsumoAPIs), "1.0.0");
25 |
26 | while (true)
27 | {
28 | using var activity = activitySource.StartActivity("SendRequests");
29 | activity?.SetTag("startPoint", "Program.cs");
30 |
31 | Endpoints.SendRequest("Kafka", Endpoints.APIContagemKafka, client);
32 | Endpoints.SendRequest("Redis", Endpoints.APIContagemRedis, client);
33 |
34 | activity?.Dispose();
35 |
36 | Console.WriteLine("Pressione ENTER para enviar uma nova requisição...");
37 | Console.ReadLine();
38 | }
--------------------------------------------------------------------------------
/DockerCompose/docker-compose.yml:
--------------------------------------------------------------------------------
1 | services:
2 | jaeger:
3 | image: jaegertracing/all-in-one:latest
4 | ports:
5 | - "6831:6831/udp"
6 | - "16686:16686"
7 | sqlserver:
8 | image: mcr.microsoft.com/mssql/server:2019-GA-ubuntu-16.04
9 | environment:
10 | SA_PASSWORD: "SqlServer2019!"
11 | ACCEPT_EULA: "Y"
12 | MSSQL_PID: "Developer"
13 | ports:
14 | - "1433:1433"
15 | redis:
16 | image: redis:alpine
17 | ports:
18 | - "6379:6379"
19 | zookeeper:
20 | image: confluentinc/cp-zookeeper:latest
21 | environment:
22 | ZOOKEEPER_CLIENT_PORT: 2181
23 | ZOOKEEPER_TICK_TIME: 2000
24 | kafka:
25 | image: confluentinc/cp-kafka:latest
26 | depends_on:
27 | - zookeeper
28 | ports:
29 | - 9092:9092
30 | environment:
31 | KAFKA_BROKER_ID: 1
32 | KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
33 | KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:29092,PLAINTEXT_HOST://localhost:9092
34 | KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
35 | KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT
36 | KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
--------------------------------------------------------------------------------
/Kafka/APIContagem/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "0.2.0",
3 | "configurations": [
4 | {
5 | // Use IntelliSense to find out which attributes exist for C# debugging
6 | // Use hover for the description of the existing attributes
7 | // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
8 | "name": ".NET Core Launch (web)",
9 | "type": "coreclr",
10 | "request": "launch",
11 | "preLaunchTask": "build",
12 | // If you have changed target frameworks, make sure to update the program path.
13 | "program": "${workspaceFolder}/bin/Debug/net6.0/APIContagem.dll",
14 | "args": [],
15 | "cwd": "${workspaceFolder}",
16 | "stopAtEntry": false,
17 | // Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser
18 | "serverReadyAction": {
19 | "action": "openExternally",
20 | "pattern": "\\bNow listening on:\\s+(https?://\\S+)"
21 | },
22 | "env": {
23 | "ASPNETCORE_ENVIRONMENT": "Development"
24 | },
25 | "sourceFileMap": {
26 | "/Views": "${workspaceFolder}/Views"
27 | }
28 | },
29 | {
30 | "name": ".NET Core Attach",
31 | "type": "coreclr",
32 | "request": "attach"
33 | }
34 | ]
35 | }
--------------------------------------------------------------------------------
/Kafka/APIContagem/.vscode/tasks.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "2.0.0",
3 | "tasks": [
4 | {
5 | "label": "build",
6 | "command": "dotnet",
7 | "type": "process",
8 | "args": [
9 | "build",
10 | "${workspaceFolder}/APIContagem.csproj",
11 | "/property:GenerateFullPaths=true",
12 | "/consoleloggerparameters:NoSummary"
13 | ],
14 | "problemMatcher": "$msCompile"
15 | },
16 | {
17 | "label": "publish",
18 | "command": "dotnet",
19 | "type": "process",
20 | "args": [
21 | "publish",
22 | "${workspaceFolder}/APIContagem.csproj",
23 | "/property:GenerateFullPaths=true",
24 | "/consoleloggerparameters:NoSummary"
25 | ],
26 | "problemMatcher": "$msCompile"
27 | },
28 | {
29 | "label": "watch",
30 | "command": "dotnet",
31 | "type": "process",
32 | "args": [
33 | "watch",
34 | "run",
35 | "${workspaceFolder}/APIContagem.csproj",
36 | "/property:GenerateFullPaths=true",
37 | "/consoleloggerparameters:NoSummary"
38 | ],
39 | "problemMatcher": "$msCompile"
40 | }
41 | ]
42 | }
--------------------------------------------------------------------------------
/Kafka/APIContagem/APIContagem.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net6.0
5 | enable
6 | enable
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/Kafka/APIContagem/APIContagem.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.3.32714.290
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "APIContagem", "APIContagem.csproj", "{E2488ACB-53FF-4D42-A72F-C9D4EB55E8D3}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {E2488ACB-53FF-4D42-A72F-C9D4EB55E8D3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {E2488ACB-53FF-4D42-A72F-C9D4EB55E8D3}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {E2488ACB-53FF-4D42-A72F-C9D4EB55E8D3}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {E2488ACB-53FF-4D42-A72F-C9D4EB55E8D3}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | GlobalSection(ExtensibilityGlobals) = postSolution
23 | SolutionGuid = {D6CA2BBC-1E95-4D9A-8031-A46E049BD040}
24 | EndGlobalSection
25 | EndGlobal
26 |
--------------------------------------------------------------------------------
/Kafka/APIContagem/Contador.cs:
--------------------------------------------------------------------------------
1 | using System.Runtime.InteropServices;
2 | using APIContagem.Kafka;
3 |
4 | namespace APIContagem;
5 |
6 | public class Contador
7 | {
8 | private static readonly string _LOCAL;
9 | private static readonly string _KERNEL;
10 | private static readonly string _FRAMEWORK;
11 |
12 | static Contador()
13 | {
14 | _LOCAL = Environment.MachineName;
15 | _KERNEL = Environment.OSVersion.VersionString;
16 | _FRAMEWORK = RuntimeInformation.FrameworkDescription;
17 | }
18 |
19 | public Contador()
20 | {
21 | _partition = KafkaExtensions.QtdPartitions > 1 ? -1 : 0;
22 | }
23 |
24 | private int _valorAtual = 89_999;
25 | private int _partition;
26 |
27 | public int ValorAtual { get => _valorAtual; }
28 | public int Partition { get => _partition; }
29 | public string Local { get => _LOCAL; }
30 | public string Kernel { get => _KERNEL; }
31 | public string Framework { get => _FRAMEWORK; }
32 |
33 | public void Incrementar()
34 | {
35 | _valorAtual++;
36 |
37 | if (KafkaExtensions.QtdPartitions > 1)
38 | {
39 | _partition++;
40 | if (_partition == KafkaExtensions.QtdPartitions)
41 | _partition = 0;
42 | }
43 | }
44 | }
--------------------------------------------------------------------------------
/Kafka/APIContagem/Controllers/ContadorController.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 | using System.Text;
3 | using System.Text.Json;
4 | using Microsoft.AspNetCore.Mvc;
5 | using Confluent.Kafka;
6 | using OpenTelemetry;
7 | using OpenTelemetry.Context.Propagation;
8 | using APIContagem.Models;
9 | using APIContagem.Kafka;
10 | using APIContagem.Tracing;
11 |
12 | namespace APIContagem.Controllers;
13 |
14 | [ApiController]
15 | [Route("[controller]")]
16 | public class ContadorController : ControllerBase
17 | {
18 | private static readonly TextMapPropagator Propagator = Propagators.DefaultTextMapPropagator;
19 | private static readonly Contador _CONTADOR = new Contador();
20 | private readonly ILogger _logger;
21 | private readonly IConfiguration _configuration;
22 |
23 | public ContadorController(ILogger logger,
24 | IConfiguration configuration)
25 | {
26 | _logger = logger;
27 | _configuration = configuration;
28 | }
29 |
30 | [HttpGet]
31 | public ResultadoContador Get()
32 | {
33 | // Solucao que serviu de base para a implementacao deste exemplo:
34 | // https://github.com/open-telemetry/opentelemetry-dotnet/tree/main/examples/MicroserviceExample
35 |
36 | int valorAtualContador;
37 | int partition;
38 |
39 | lock (_CONTADOR)
40 | {
41 | _CONTADOR.Incrementar();
42 | valorAtualContador = _CONTADOR.ValorAtual;
43 | partition = _CONTADOR.Partition;
44 | }
45 |
46 | using var activity = OpenTelemetryExtensions.CreateActivitySource()
47 | .StartActivity("Identificando");
48 | activity?.SetTag("valorAtual", valorAtualContador);
49 |
50 | var resultado = new ResultadoContador()
51 | {
52 | ValorAtual = valorAtualContador,
53 | Producer = _CONTADOR.Local,
54 | Kernel = _CONTADOR.Kernel,
55 | Framework = _CONTADOR.Framework,
56 | Mensagem = _configuration["MensagemVariavel"]
57 | };
58 |
59 | string topicName = _configuration["ApacheKafka:Topic"];
60 | string jsonContagem = JsonSerializer.Serialize(resultado);
61 |
62 | // Semantic convention - OpenTelemetry messaging specification:
63 | // https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/messaging.md#span-name
64 | var activityName = $"{topicName} send";
65 |
66 | using (var producer = KafkaExtensions.CreateProducer(_configuration))
67 | {
68 | var idMensagemContagem = Guid.NewGuid().ToString();
69 |
70 | using var sendActivity = OpenTelemetryExtensions.CreateActivitySource()
71 | .StartActivity(activityName, ActivityKind.Producer);
72 |
73 | ActivityContext contextToInject = default;
74 | if (sendActivity != null)
75 | {
76 | contextToInject = sendActivity.Context;
77 | }
78 | else if (Activity.Current != null)
79 | {
80 | contextToInject = Activity.Current.Context;
81 | }
82 |
83 | var headers = new Headers();
84 | Propagator.Inject(new PropagationContext(contextToInject, Baggage.Current), headers,
85 | InjectTraceContextIntoHeaders);
86 |
87 | sendActivity?.SetTag("messaging.system", "kafka");
88 | sendActivity?.SetTag("messaging.destination_kind", "topic");
89 | sendActivity?.SetTag("messaging.destination", topicName);
90 | sendActivity?.SetTag("messaging.operation", "process");
91 | sendActivity?.SetTag("messaging.kafka.client_id",
92 | $"{nameof(APIContagem)}-{Environment.MachineName}");
93 | sendActivity?.SetTag("message", jsonContagem);
94 | sendActivity?.SetTag("idMensagemContagem", idMensagemContagem);
95 | sendActivity?.SetTag("valorAtualContador", valorAtualContador);
96 |
97 | var result = producer.ProduceAsync(
98 | new TopicPartition(topicName, new Partition(partition)),
99 | new Message
100 | { Value = jsonContagem, Headers = headers }).Result;
101 |
102 | _logger.LogInformation(
103 | $"Apache Kafka - Envio para o topico {topicName} concluido | Particao: {partition} | " +
104 | $"{jsonContagem} | Id Mensagem: {idMensagemContagem} | Status: { result.Status.ToString()}");
105 | }
106 |
107 | return resultado;
108 | }
109 |
110 | private void InjectTraceContextIntoHeaders(Headers headers, string key, string value)
111 | {
112 | try
113 | {
114 | headers.Add(key, Encoding.UTF8.GetBytes(value));
115 | }
116 | catch (Exception ex)
117 | {
118 | this._logger.LogError(ex, "Falha de injecao com o trace context.");
119 | }
120 | }
121 | }
--------------------------------------------------------------------------------
/Kafka/APIContagem/Kafka/KafkaExtensions.cs:
--------------------------------------------------------------------------------
1 | using Confluent.Kafka;
2 |
3 | namespace APIContagem.Kafka;
4 |
5 | public static class KafkaExtensions
6 | {
7 | private static int _QtdPartitions = 1;
8 |
9 | public static int QtdPartitions
10 | {
11 | get => _QtdPartitions;
12 | }
13 |
14 | public static void CheckNumPartitions(
15 | IConfiguration configuration)
16 | {
17 | AdminClientConfig kafkaConfig;
18 | var password = configuration["ApacheKafka:Password"];
19 | if (!String.IsNullOrWhiteSpace(password))
20 | kafkaConfig = new ()
21 | {
22 | BootstrapServers = configuration["ApacheKafka:Host"],
23 | SecurityProtocol = SecurityProtocol.SaslSsl,
24 | SaslMechanism = SaslMechanism.Plain,
25 | SaslUsername = configuration["ApacheKafka:Username"],
26 | SaslPassword = password
27 | };
28 | else
29 | kafkaConfig = new ()
30 | {
31 | BootstrapServers = configuration["ApacheKafka:Host"],
32 | };
33 |
34 | using var adminClient = new AdminClientBuilder(kafkaConfig).Build();
35 |
36 | var infoTopic = adminClient.GetMetadata(configuration["ApacheKafka:Topic"],
37 | TimeSpan.FromSeconds(25)).Topics.FirstOrDefault();
38 | if (infoTopic is not null)
39 | _QtdPartitions = infoTopic.Partitions.Count;
40 | }
41 |
42 | public static IProducer CreateProducer(
43 | IConfiguration configuration)
44 | {
45 | var password = configuration["ApacheKafka:Password"];
46 | if (!String.IsNullOrWhiteSpace(password))
47 | return new ProducerBuilder(
48 | new ProducerConfig()
49 | {
50 | BootstrapServers = configuration["ApacheKafka:Host"],
51 | SecurityProtocol = SecurityProtocol.SaslSsl,
52 | SaslMechanism = SaslMechanism.Plain,
53 | SaslUsername = configuration["ApacheKafka:Username"],
54 | SaslPassword = password
55 | }).Build();
56 | else
57 | return new ProducerBuilder(
58 | new ProducerConfig()
59 | {
60 | BootstrapServers = configuration["ApacheKafka:Host"]
61 | }).Build();
62 | }
63 | }
--------------------------------------------------------------------------------
/Kafka/APIContagem/Models/ResultadoContador.cs:
--------------------------------------------------------------------------------
1 | namespace APIContagem.Models;
2 |
3 | public class ResultadoContador
4 | {
5 | public int ValorAtual { get; set; }
6 | public string? Producer { get; set; }
7 | public string? Kernel { get; set; }
8 | public string? Framework { get; set; }
9 | public string? Mensagem { get; set; }
10 | }
--------------------------------------------------------------------------------
/Kafka/APIContagem/Program.cs:
--------------------------------------------------------------------------------
1 | using OpenTelemetry.Resources;
2 | using OpenTelemetry.Trace;
3 | using APIContagem.Kafka;
4 | using APIContagem.Tracing;
5 |
6 | var builder = WebApplication.CreateBuilder(args);
7 |
8 | builder.Services.AddControllers();
9 | builder.Services.AddEndpointsApiExplorer();
10 | builder.Services.AddSwaggerGen();
11 |
12 | builder.Services.AddOpenTelemetryTracing(traceProvider =>
13 | {
14 | traceProvider
15 | .AddSource(OpenTelemetryExtensions.ServiceName)
16 | .SetResourceBuilder(
17 | ResourceBuilder.CreateDefault()
18 | .AddService(serviceName: OpenTelemetryExtensions.ServiceName,
19 | serviceVersion: OpenTelemetryExtensions.ServiceVersion))
20 | .AddHttpClientInstrumentation()
21 | .AddAspNetCoreInstrumentation()
22 | .AddJaegerExporter(exporter =>
23 | {
24 | exporter.AgentHost = builder.Configuration["Jaeger:AgentHost"];
25 | exporter.AgentPort = Convert.ToInt32(builder.Configuration["Jaeger:AgentPort"]);
26 | });
27 | });
28 |
29 | KafkaExtensions.CheckNumPartitions(builder.Configuration);
30 |
31 | var app = builder.Build();
32 |
33 | app.UseSwagger();
34 | app.UseSwaggerUI();
35 |
36 | app.UseHttpsRedirection();
37 |
38 | app.UseAuthorization();
39 |
40 | app.MapControllers();
41 |
42 | app.Run();
--------------------------------------------------------------------------------
/Kafka/APIContagem/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "https://json.schemastore.org/launchsettings.json",
3 | "iisSettings": {
4 | "windowsAuthentication": false,
5 | "anonymousAuthentication": true,
6 | "iisExpress": {
7 | "applicationUrl": "http://localhost:58703",
8 | "sslPort": 44348
9 | }
10 | },
11 | "profiles": {
12 | "APIContagem": {
13 | "commandName": "Project",
14 | "dotnetRunMessages": true,
15 | "launchBrowser": true,
16 | "launchUrl": "swagger",
17 | "applicationUrl": "https://localhost:7208;http://localhost:5062",
18 | "environmentVariables": {
19 | "ASPNETCORE_ENVIRONMENT": "Development"
20 | }
21 | },
22 | "IIS Express": {
23 | "commandName": "IISExpress",
24 | "launchBrowser": true,
25 | "launchUrl": "swagger",
26 | "environmentVariables": {
27 | "ASPNETCORE_ENVIRONMENT": "Development"
28 | }
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/Kafka/APIContagem/Tracing/OpenTelemetryExtensions.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 |
3 | namespace APIContagem.Tracing;
4 |
5 | public static class OpenTelemetryExtensions
6 | {
7 | public static string ServiceName { get; }
8 | public static string ServiceVersion { get; }
9 |
10 | static OpenTelemetryExtensions()
11 | {
12 | ServiceName = typeof(OpenTelemetryExtensions).Assembly.GetName().Name! + "Kafka";
13 | ServiceVersion = typeof(OpenTelemetryExtensions).Assembly.GetName().Version!.ToString();
14 | }
15 |
16 | public static ActivitySource CreateActivitySource() =>
17 | new ActivitySource(ServiceName, ServiceVersion);
18 | }
--------------------------------------------------------------------------------
/Kafka/APIContagem/appsettings.Development.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Information",
5 | "Microsoft.AspNetCore": "Warning"
6 | }
7 | }
8 | }
--------------------------------------------------------------------------------
/Kafka/APIContagem/appsettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "MensagemVariavel": "Testes com Kafka + OpenTelemetry + Jaeger",
3 | "Jaeger": {
4 | "AgentHost": "localhost",
5 | "AgentPort": "6831"
6 | },
7 | "ApacheKafka": {
8 | "Topic": "topic-contagem",
9 | "Host": "localhost:9092",
10 | "Username": "",
11 | "Password": ""
12 | },
13 | "Logging": {
14 | "LogLevel": {
15 | "Default": "Information",
16 | "Microsoft.AspNetCore": "Warning"
17 | }
18 | },
19 | "AllowedHosts": "*",
20 | "Kestrel": {
21 | "Endpoints": {
22 | "HTTP": {
23 | "Url": "http://localhost:6900"
24 | }
25 | }
26 | }
27 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # DistributedTracing-OpenTelemetry-Jaeger-DotNet6-Kafka-SqlServer-Redis
2 | Exemplos de implementação de tracing distribuído em .NET 6 com Jaeger e OpenTelemetry. Inclui o uso de Apache Kafka, SQL Server, Redis e Docker compose.
3 |
4 | Para saber mais sobre Distributed Tracing e Context Propagation com o OpenTelemetry acesse o artigo a seguir (o exemplo foi baseado em RabbitMQ e serviu de base para a implementação deste repositório):
5 |
6 | **[Jaeger + OpenTelemetry + RabbitMQ: tracing distribuído, dependências entre aplicações...](https://renatogroffe.medium.com/jaeger-opentelemetry-rabbitmq-tracing-distribu%C3%ADdo-depend%C3%AAncias-entre-aplica%C3%A7%C3%B5es-58d430a1ddd8)**
--------------------------------------------------------------------------------
/Redis/APIContagem/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "0.2.0",
3 | "configurations": [
4 | {
5 | // Use IntelliSense to find out which attributes exist for C# debugging
6 | // Use hover for the description of the existing attributes
7 | // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
8 | "name": ".NET Core Launch (web)",
9 | "type": "coreclr",
10 | "request": "launch",
11 | "preLaunchTask": "build",
12 | // If you have changed target frameworks, make sure to update the program path.
13 | "program": "${workspaceFolder}/bin/Debug/net6.0/APIContagem.dll",
14 | "args": [],
15 | "cwd": "${workspaceFolder}",
16 | "stopAtEntry": false,
17 | // Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser
18 | "serverReadyAction": {
19 | "action": "openExternally",
20 | "pattern": "\\bNow listening on:\\s+(https?://\\S+)"
21 | },
22 | "env": {
23 | "ASPNETCORE_ENVIRONMENT": "Development"
24 | },
25 | "sourceFileMap": {
26 | "/Views": "${workspaceFolder}/Views"
27 | }
28 | },
29 | {
30 | "name": ".NET Core Attach",
31 | "type": "coreclr",
32 | "request": "attach"
33 | }
34 | ]
35 | }
--------------------------------------------------------------------------------
/Redis/APIContagem/.vscode/tasks.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "2.0.0",
3 | "tasks": [
4 | {
5 | "label": "build",
6 | "command": "dotnet",
7 | "type": "process",
8 | "args": [
9 | "build",
10 | "${workspaceFolder}/APIContagem.csproj",
11 | "/property:GenerateFullPaths=true",
12 | "/consoleloggerparameters:NoSummary"
13 | ],
14 | "problemMatcher": "$msCompile"
15 | },
16 | {
17 | "label": "publish",
18 | "command": "dotnet",
19 | "type": "process",
20 | "args": [
21 | "publish",
22 | "${workspaceFolder}/APIContagem.csproj",
23 | "/property:GenerateFullPaths=true",
24 | "/consoleloggerparameters:NoSummary"
25 | ],
26 | "problemMatcher": "$msCompile"
27 | },
28 | {
29 | "label": "watch",
30 | "command": "dotnet",
31 | "type": "process",
32 | "args": [
33 | "watch",
34 | "run",
35 | "${workspaceFolder}/APIContagem.csproj",
36 | "/property:GenerateFullPaths=true",
37 | "/consoleloggerparameters:NoSummary"
38 | ],
39 | "problemMatcher": "$msCompile"
40 | }
41 | ]
42 | }
--------------------------------------------------------------------------------
/Redis/APIContagem/APIContagem.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net6.0
5 | enable
6 | enable
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/Redis/APIContagem/APIContagem.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.1.32104.313
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "APIContagem", "APIContagem.csproj", "{5F55B957-7374-4CE3-90D4-3C67BEF8A2F4}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {5F55B957-7374-4CE3-90D4-3C67BEF8A2F4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {5F55B957-7374-4CE3-90D4-3C67BEF8A2F4}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {5F55B957-7374-4CE3-90D4-3C67BEF8A2F4}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {5F55B957-7374-4CE3-90D4-3C67BEF8A2F4}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | GlobalSection(ExtensibilityGlobals) = postSolution
23 | SolutionGuid = {A1B8EE6D-E8D2-4194-9A83-E90580D205B8}
24 | EndGlobalSection
25 | EndGlobal
26 |
--------------------------------------------------------------------------------
/Redis/APIContagem/Controllers/ContadorController.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Mvc;
2 | using System.Diagnostics;
3 | using StackExchange.Redis;
4 | using APIContagem.Models;
5 | using APIContagem.Logging;
6 | using APIContagem.Tracing;
7 |
8 | namespace APIContagem.Controllers;
9 |
10 | [ApiController]
11 | [Route("[controller]")]
12 | public class ContadorController : ControllerBase
13 | {
14 | private readonly ILogger _logger;
15 | private readonly ConnectionMultiplexer _connectionRedis;
16 | private readonly ActivitySource _activitySource;
17 |
18 | public ContadorController(ILogger logger,
19 | ConnectionMultiplexer connectionRedis)
20 | {
21 | _activitySource = OpenTelemetryExtensions.CreateActivitySource();
22 | using var activity =
23 | _activitySource.StartActivity($"Construtor ({nameof(ContadorController)})");
24 | activity!.SetTag("horario", $"{DateTime.Now:HH:mm:ss dd/MM/yyyy}");
25 |
26 | _logger = logger;
27 | _connectionRedis = connectionRedis;
28 | }
29 |
30 | [HttpGet]
31 | public ResultadoContador Get()
32 | {
33 | using var activity =
34 | _activitySource.StartActivity($"{nameof(Get)} ({nameof(ContadorController)})");
35 |
36 | var valorAtualContador =
37 | (int)_connectionRedis.GetDatabase().StringIncrement("APIContagem");;
38 |
39 | _logger.LogValorAtual(valorAtualContador);
40 |
41 | activity!.SetTag("valorContador", valorAtualContador);
42 | activity!.SetTag("producer", OpenTelemetryExtensions.Local);
43 | activity!.SetTag("kernel", OpenTelemetryExtensions.Kernel);
44 | activity!.SetTag("framework", OpenTelemetryExtensions.Framework);
45 | activity!.SetTag("mensagem", OpenTelemetryExtensions.Local);
46 |
47 | return new ()
48 | {
49 | ValorAtual = valorAtualContador,
50 | Producer = OpenTelemetryExtensions.Local,
51 | Kernel = OpenTelemetryExtensions.Kernel,
52 | Framework = OpenTelemetryExtensions.Framework,
53 | Mensagem = OpenTelemetryExtensions.Local
54 | };
55 | }
56 | }
--------------------------------------------------------------------------------
/Redis/APIContagem/Logging/ContagemLogging.cs:
--------------------------------------------------------------------------------
1 | namespace APIContagem.Logging;
2 |
3 | public static partial class ContagemLogging
4 | {
5 | [LoggerMessage(EventId = 1, Level = LogLevel.Information,
6 | Message = "Contador - Valor atual: {valorAtual}")]
7 | public static partial void LogValorAtual(
8 | this ILogger logger, int valorAtual);
9 | }
--------------------------------------------------------------------------------
/Redis/APIContagem/Models/ResultadoContador.cs:
--------------------------------------------------------------------------------
1 | namespace APIContagem.Models;
2 |
3 | public class ResultadoContador
4 | {
5 | public int ValorAtual { get; set; }
6 | public string? Producer { get; set; }
7 | public string? Kernel { get; set; }
8 | public string? Framework { get; set; }
9 | public string? Mensagem { get; set; }
10 | }
--------------------------------------------------------------------------------
/Redis/APIContagem/Program.cs:
--------------------------------------------------------------------------------
1 | using OpenTelemetry.Resources;
2 | using OpenTelemetry.Trace;
3 | using StackExchange.Redis;
4 | using APIContagem.Tracing;
5 |
6 | var builder = WebApplication.CreateBuilder(args);
7 |
8 | builder.Services.AddControllers();
9 | builder.Services.AddEndpointsApiExplorer();
10 | builder.Services.AddSwaggerGen();
11 |
12 | using var connectionRedis = ConnectionMultiplexer.Connect(
13 | builder.Configuration.GetConnectionString("Redis"));
14 | builder.Services.AddSingleton(connectionRedis);
15 |
16 | // Documentacao do OpenTelemetry:
17 | // https://opentelemetry.io/docs/instrumentation/net/getting-started/
18 |
19 | // Integracaoo do OpenTelemetry com Jaeger:
20 | // https://opentelemetry.io/docs/instrumentation/net/exporters/
21 |
22 | // Documentacaoo do Jaeger:
23 | // https://www.jaegertracing.io/docs/1.33/
24 |
25 | builder.Services.AddOpenTelemetryTracing(traceProvider =>
26 | {
27 | traceProvider
28 | .AddSource(OpenTelemetryExtensions.ServiceName)
29 | .SetResourceBuilder(
30 | ResourceBuilder.CreateDefault()
31 | .AddService(serviceName: OpenTelemetryExtensions.ServiceName,
32 | serviceVersion: OpenTelemetryExtensions.ServiceVersion))
33 | .AddAspNetCoreInstrumentation()
34 | .AddRedisInstrumentation(connectionRedis,
35 | options => options.SetVerboseDatabaseStatements = true)
36 | .AddJaegerExporter(exporter =>
37 | {
38 | exporter.AgentHost = builder.Configuration["Jaeger:AgentHost"];
39 | exporter.AgentPort = Convert.ToInt32(builder.Configuration["Jaeger:AgentPort"]);
40 | });
41 | });
42 |
43 | var app = builder.Build();
44 |
45 | if (app.Environment.IsDevelopment())
46 | {
47 | app.UseSwagger();
48 | app.UseSwaggerUI();
49 | }
50 |
51 | app.UseHttpsRedirection();
52 |
53 | app.UseAuthorization();
54 |
55 | app.MapControllers();
56 |
57 | app.Run();
--------------------------------------------------------------------------------
/Redis/APIContagem/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "https://json.schemastore.org/launchsettings.json",
3 | "iisSettings": {
4 | "windowsAuthentication": false,
5 | "anonymousAuthentication": true,
6 | "iisExpress": {
7 | "applicationUrl": "http://localhost:29570",
8 | "sslPort": 44305
9 | }
10 | },
11 | "profiles": {
12 | "APIContagem": {
13 | "commandName": "Project",
14 | "dotnetRunMessages": true,
15 | "launchBrowser": true,
16 | "launchUrl": "swagger",
17 | "applicationUrl": "https://localhost:7117;http://localhost:5235",
18 | "environmentVariables": {
19 | "ASPNETCORE_ENVIRONMENT": "Development"
20 | }
21 | },
22 | "IIS Express": {
23 | "commandName": "IISExpress",
24 | "launchBrowser": true,
25 | "launchUrl": "swagger",
26 | "environmentVariables": {
27 | "ASPNETCORE_ENVIRONMENT": "Development"
28 | }
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/Redis/APIContagem/Tracing/OpenTelemetryExtensions.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 | using System.Runtime.InteropServices;
3 |
4 | namespace APIContagem.Tracing;
5 |
6 | public static class OpenTelemetryExtensions
7 | {
8 | public static string Local { get; }
9 | public static string Kernel { get; }
10 | public static string Framework { get; }
11 | public static string ServiceName { get; }
12 | public static string ServiceVersion { get; }
13 |
14 | static OpenTelemetryExtensions()
15 | {
16 | Local = "APIContagemRedis";
17 | Kernel = Environment.OSVersion.VersionString;
18 | Framework = RuntimeInformation.FrameworkDescription;
19 | ServiceName = "APIContagemRedis";
20 | ServiceVersion = typeof(OpenTelemetryExtensions).Assembly.GetName().Version!.ToString();
21 | }
22 |
23 | public static ActivitySource CreateActivitySource() =>
24 | new ActivitySource(ServiceName, ServiceVersion);
25 | }
--------------------------------------------------------------------------------
/Redis/APIContagem/appsettings.Development.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Information",
5 | "Microsoft.AspNetCore": "Warning"
6 | }
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/Redis/APIContagem/appsettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "Jaeger": {
3 | "AgentHost": "localhost",
4 | "AgentPort": "6831"
5 | },
6 | "ConnectionStrings": {
7 | "Redis": "localhost"
8 | },
9 | "Logging": {
10 | "LogLevel": {
11 | "Default": "Information",
12 | "Microsoft.AspNetCore": "Warning"
13 | }
14 | },
15 | "AllowedHosts": "*",
16 | "Kestrel": {
17 | "Endpoints": {
18 | "HTTP": {
19 | "Url": "http://localhost:6300"
20 | }
21 | }
22 | }
23 | }
--------------------------------------------------------------------------------
/Scripts-SqlServer/BaseContagemKafka.sql:
--------------------------------------------------------------------------------
1 | CREATE DATABASE BaseContagemKafka
2 | GO
3 |
4 | USE BaseContagemKafka
5 | GO
6 |
7 | CREATE TABLE dbo.HistoricoContagem(
8 | Id INT IDENTITY(1,1) NOT NULL,
9 | DataProcessamento DATETIME NOT NULL,
10 | ValorAtual INT NOT NULL,
11 | TopicName VARCHAR(120) NOT NULL,
12 | Producer VARCHAR(120) NOT NULL,
13 | Consumer VARCHAR(120) NOT NULL,
14 | PartitionNumber INT NOT NULL,
15 | Mensagem VARCHAR(500) NOT NULL,
16 | Kernel VARCHAR(80) NOT NULL,
17 | Framework VARCHAR(80) NOT NULL,
18 | CONSTRAINT PK_HistoricoContagem PRIMARY KEY (Id)
19 | )
20 | GO
--------------------------------------------------------------------------------
/WorkerContagem/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "0.2.0",
3 | "configurations": [
4 | {
5 | // Use IntelliSense to find out which attributes exist for C# debugging
6 | // Use hover for the description of the existing attributes
7 | // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
8 | "name": ".NET Core Launch (console)",
9 | "type": "coreclr",
10 | "request": "launch",
11 | "preLaunchTask": "build",
12 | // If you have changed target frameworks, make sure to update the program path.
13 | "program": "${workspaceFolder}/bin/Debug/net6.0/WorkerContagem.dll",
14 | "args": [],
15 | "cwd": "${workspaceFolder}",
16 | // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console
17 | "console": "internalConsole",
18 | "stopAtEntry": false
19 | },
20 | {
21 | "name": ".NET Core Attach",
22 | "type": "coreclr",
23 | "request": "attach"
24 | }
25 | ]
26 | }
--------------------------------------------------------------------------------
/WorkerContagem/.vscode/tasks.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "2.0.0",
3 | "tasks": [
4 | {
5 | "label": "build",
6 | "command": "dotnet",
7 | "type": "process",
8 | "args": [
9 | "build",
10 | "${workspaceFolder}/WorkerContagem.csproj",
11 | "/property:GenerateFullPaths=true",
12 | "/consoleloggerparameters:NoSummary"
13 | ],
14 | "problemMatcher": "$msCompile"
15 | },
16 | {
17 | "label": "publish",
18 | "command": "dotnet",
19 | "type": "process",
20 | "args": [
21 | "publish",
22 | "${workspaceFolder}/WorkerContagem.csproj",
23 | "/property:GenerateFullPaths=true",
24 | "/consoleloggerparameters:NoSummary"
25 | ],
26 | "problemMatcher": "$msCompile"
27 | },
28 | {
29 | "label": "watch",
30 | "command": "dotnet",
31 | "type": "process",
32 | "args": [
33 | "watch",
34 | "run",
35 | "${workspaceFolder}/WorkerContagem.csproj",
36 | "/property:GenerateFullPaths=true",
37 | "/consoleloggerparameters:NoSummary"
38 | ],
39 | "problemMatcher": "$msCompile"
40 | }
41 | ]
42 | }
--------------------------------------------------------------------------------
/WorkerContagem/Data/ContagemRepository.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Data.SqlClient;
2 | using Dapper.Contrib.Extensions;
3 | using WorkerContagem.Models;
4 |
5 | namespace WorkerContagem.Data;
6 |
7 | public class ContagemRepository
8 | {
9 | private readonly IConfiguration _configuration;
10 |
11 | public ContagemRepository(IConfiguration configuration)
12 | {
13 | _configuration = configuration;
14 | }
15 |
16 | public void Save(ResultadoContador resultado, int partition)
17 | {
18 | using var conexao = new SqlConnection(
19 | _configuration.GetConnectionString("BaseContagem"));
20 | conexao.Insert(new()
21 | {
22 | DataProcessamento = DateTime.UtcNow.AddHours(-3), // Horário padrão do Brasil
23 | ValorAtual = resultado.ValorAtual,
24 | Producer = resultado.Producer,
25 | Consumer = Environment.MachineName,
26 | TopicName = _configuration["ApacheKafka:Topic"],
27 | PartitionNumber = partition,
28 | Mensagem = resultado.Mensagem,
29 | Kernel = resultado.Kernel,
30 | Framework = resultado.Framework
31 | });
32 | }
33 | }
--------------------------------------------------------------------------------
/WorkerContagem/Data/HistoricoContagem.cs:
--------------------------------------------------------------------------------
1 | using Dapper.Contrib.Extensions;
2 |
3 | namespace WorkerContagem.Data;
4 |
5 | [Table("dbo.HistoricoContagem")]
6 | public class HistoricoContagem
7 | {
8 | [Key]
9 | public int Id { get; set; }
10 | public DateTime DataProcessamento { get; set; }
11 | public int ValorAtual { get; set; }
12 | public string? TopicName { get; set; }
13 | public string? Producer { get; set; }
14 | public string? Consumer { get; set; }
15 | public int PartitionNumber { get; set; }
16 | public string? Mensagem { get; set; }
17 | public string? Kernel { get; set; }
18 | public string? Framework { get; set; }
19 | }
--------------------------------------------------------------------------------
/WorkerContagem/Kafka/KafkaExtensions.cs:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/renatogroffe/DistributedTracing-OpenTelemetry-Jaeger-DotNet6-Kafka-SqlServer-Redis/55c9bab24564b1d450148e93b25cfa3959ec5143/WorkerContagem/Kafka/KafkaExtensions.cs
--------------------------------------------------------------------------------
/WorkerContagem/Models/ResultadoContador.cs:
--------------------------------------------------------------------------------
1 | namespace WorkerContagem.Models;
2 |
3 | public class ResultadoContador
4 | {
5 | public int ValorAtual { get; set; }
6 | public string? Producer { get; set; }
7 | public string? Kernel { get; set; }
8 | public string? Framework { get; set; }
9 | public string? Mensagem { get; set; }
10 | }
--------------------------------------------------------------------------------
/WorkerContagem/Program.cs:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/renatogroffe/DistributedTracing-OpenTelemetry-Jaeger-DotNet6-Kafka-SqlServer-Redis/55c9bab24564b1d450148e93b25cfa3959ec5143/WorkerContagem/Program.cs
--------------------------------------------------------------------------------
/WorkerContagem/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "profiles": {
3 | "WorkerContagem": {
4 | "commandName": "Project",
5 | "dotnetRunMessages": true,
6 | "environmentVariables": {
7 | "DOTNET_ENVIRONMENT": "Development"
8 | }
9 | }
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/WorkerContagem/Tracing/OpenTelemetryExtensions.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 | using System.Runtime.InteropServices;
3 |
4 | namespace WorkerContagem.Tracing;
5 |
6 | public static class OpenTelemetryExtensions
7 | {
8 | public static string Local { get; }
9 | public static string Kernel { get; }
10 | public static string Framework { get; }
11 | public static string ServiceName { get; }
12 | public static string ServiceVersion { get; }
13 |
14 | static OpenTelemetryExtensions()
15 | {
16 | Local = Environment.MachineName;
17 | Kernel = Environment.OSVersion.VersionString;
18 | Framework = RuntimeInformation.FrameworkDescription;
19 | ServiceName = typeof(OpenTelemetryExtensions).Assembly.GetName().Name! + "Kafka";
20 | ServiceVersion = typeof(OpenTelemetryExtensions).Assembly.GetName().Version!.ToString();
21 | }
22 |
23 | public static ActivitySource CreateActivitySource() =>
24 | new ActivitySource(ServiceName, ServiceVersion);
25 | }
--------------------------------------------------------------------------------
/WorkerContagem/Worker.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 | using System.Text;
3 | using System.Text.Json;
4 | using Confluent.Kafka;
5 | using Microsoft.Identity.Client;
6 | using OpenTelemetry;
7 | using OpenTelemetry.Context.Propagation;
8 | using WorkerContagem.Data;
9 | using WorkerContagem.Kafka;
10 | using WorkerContagem.Models;
11 | using WorkerContagem.Tracing;
12 |
13 | namespace WorkerContagem;
14 |
15 | public class Worker : BackgroundService
16 | {
17 | private readonly TextMapPropagator Propagator = Propagators.DefaultTextMapPropagator;
18 |
19 | private readonly ILogger _logger;
20 | private readonly IConfiguration _configuration;
21 | private readonly ContagemRepository _repository;
22 | private readonly string _topic;
23 | private readonly string _groupId;
24 | private readonly IConsumer _consumer;
25 | private readonly int _intervaloMensagemWorkerAtivo;
26 |
27 | public Worker(ILogger logger,
28 | IConfiguration configuration,
29 | ContagemRepository repository)
30 | {
31 | _logger = logger;
32 | _configuration = configuration;
33 | _repository = repository;
34 | _topic = _configuration["ApacheKafka:Topic"];
35 | _groupId = _configuration["ApacheKafka:GroupId"];
36 | _consumer = KafkaExtensions.CreateConsumer(_configuration);
37 | _intervaloMensagemWorkerAtivo =
38 | Convert.ToInt32(configuration["IntervaloMensagemWorkerAtivo"]);
39 | }
40 |
41 | protected override async Task ExecuteAsync(CancellationToken stoppingToken)
42 | {
43 | // Solução que serviu de base para a implementação deste exemplo:
44 | // https://github.com/open-telemetry/opentelemetry-dotnet/tree/main/examples/MicroserviceExample
45 |
46 | _logger.LogInformation($"Topic = {_topic}");
47 | _logger.LogInformation($"Group Id = {_groupId}");
48 | _logger.LogInformation("Aguardando mensagens...");
49 | _consumer.Subscribe(_topic);
50 |
51 | while (!stoppingToken.IsCancellationRequested)
52 | {
53 | await Task.Run(() =>
54 | {
55 | var result = _consumer.Consume(stoppingToken);
56 |
57 | // Extrai o PropagationContext de forma a identificar os message headers
58 | var parentContext = Propagator.Extract(default, result.Message.Headers, this.ExtractTraceContextFromHeaders);
59 | Baggage.Current = parentContext.Baggage;
60 |
61 | var messageContent = result.Message.Value;
62 | var partition = result.Partition.Value;
63 |
64 | // Semantic convention - OpenTelemetry messaging specification:
65 | // https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/messaging.md#span-name
66 | var activityName = $"{_topic} receive";
67 |
68 | using var activity = OpenTelemetryExtensions.CreateActivitySource()
69 | .StartActivity(activityName, ActivityKind.Consumer, parentContext.ActivityContext);
70 | activity?.SetTag("message", messageContent);
71 | activity?.SetTag("messaging.system", "kafka");
72 | activity?.SetTag("messaging.destination_kind", "topic");
73 | activity?.SetTag("messaging.destination", _topic);
74 | activity?.SetTag("messaging.operation", "process");
75 | activity?.SetTag("messaging.kafka.consumer_group", _groupId);
76 | activity?.SetTag("messaging.kafka.client_id",
77 | $"{nameof(WorkerContagem)}-{Environment.MachineName}");
78 | activity?.SetTag("messaging.kafka.partition", partition);
79 |
80 | _logger.LogInformation(
81 | $"[{_topic} | {_groupId} | Nova mensagem] " +
82 | messageContent);
83 |
84 | ProcessarResultado(messageContent, partition);
85 | });
86 | }
87 | }
88 |
89 | private void ProcessarResultado(string dados, int partition)
90 | {
91 | ResultadoContador? resultado;
92 | try
93 | {
94 | resultado = JsonSerializer.Deserialize(dados,
95 | new JsonSerializerOptions()
96 | {
97 | PropertyNameCaseInsensitive = true
98 | });
99 | }
100 | catch
101 | {
102 | _logger.LogError("Dados inválidos para o Resultado");
103 | resultado = null;
104 | }
105 |
106 | if (resultado is not null)
107 | {
108 | try
109 | {
110 | _repository.Save(resultado, partition);
111 | _logger.LogInformation("Resultado registrado com sucesso!");
112 | }
113 | catch (Exception ex)
114 | {
115 | _logger.LogError($"Erro durante a gravacao: {ex.Message}");
116 | }
117 | }
118 | }
119 |
120 | private IEnumerable ExtractTraceContextFromHeaders(Headers headers, string key)
121 | {
122 | try
123 | {
124 | var header = headers.FirstOrDefault(h => h.Key == key);
125 | if (header is not null)
126 | return new[] { Encoding.UTF8.GetString(header.GetValueBytes()) };
127 | }
128 | catch (Exception ex)
129 | {
130 | _logger.LogError(ex, $"Falha durante a extração do trace context: {ex.Message}");
131 | }
132 |
133 | return Enumerable.Empty();
134 | }
135 | }
--------------------------------------------------------------------------------
/WorkerContagem/WorkerContagem.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net6.0
5 | enable
6 | enable
7 | dotnet-WorkerContagem-563B2A8A-F276-43F9-91E7-FF5958093DC4
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/WorkerContagem/WorkerContagem.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.3.32611.2
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WorkerContagem", "WorkerContagem.csproj", "{45DC86D5-EF3A-408D-B38D-DD20D4DBD30D}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {45DC86D5-EF3A-408D-B38D-DD20D4DBD30D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {45DC86D5-EF3A-408D-B38D-DD20D4DBD30D}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {45DC86D5-EF3A-408D-B38D-DD20D4DBD30D}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {45DC86D5-EF3A-408D-B38D-DD20D4DBD30D}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | GlobalSection(ExtensibilityGlobals) = postSolution
23 | SolutionGuid = {FA3EEF70-8D1E-4092-AF7B-1832C3EE3DA7}
24 | EndGlobalSection
25 | EndGlobal
26 |
--------------------------------------------------------------------------------
/WorkerContagem/appsettings.Development.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Information",
5 | "Microsoft.Hosting.Lifetime": "Information"
6 | }
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/WorkerContagem/appsettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "Jaeger": {
3 | "AgentHost": "localhost",
4 | "AgentPort": "6831"
5 | },
6 | "ApacheKafka": {
7 | "Topic": "topic-contagem",
8 | "Host": "localhost:9092",
9 | "GroupId": "workercontagem",
10 | "Username": "",
11 | "Password": ""
12 | },
13 | "ConnectionStrings": {
14 | "BaseContagem": "Server=localhost;Database=BaseContagemKafka;User Id=sa;Password=SqlServer2019!;TrustServerCertificate=True;"
15 | },
16 | "Logging": {
17 | "LogLevel": {
18 | "Default": "Information",
19 | "Microsoft.Hosting.Lifetime": "Information"
20 | }
21 | }
22 | }
--------------------------------------------------------------------------------