欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

.NET6接入Skywalking鏈路追蹤詳細(xì)過程

 更新時間:2022年06月28日 10:25:44   作者:包子wxl  
Skywalking是一款分布式鏈路追蹤組件,隨著微服務(wù)架構(gòu)的流行,服務(wù)按照不同的維度進(jìn)行拆分,一次請求往往需要涉及到多個服務(wù),這篇文章主要介紹了.NET6接入Skywalking鏈路追蹤完整流程,需要的朋友可以參考下

.NET6接入Skywalking鏈路追蹤完整流程

一、Skywalking介紹

Skywalking是一款分布式鏈路追蹤組件,什么是鏈路追蹤?

隨著微服務(wù)架構(gòu)的流行,服務(wù)按照不同的維度進(jìn)行拆分,一次請求往往需要涉及到多個服務(wù)?;ヂ?lián)網(wǎng)應(yīng)用構(gòu)建在不同的軟件模塊集上,這些軟件模塊,有可能是由不同的團(tuán)隊(duì)開發(fā)、可能使用不同的編程語言來實(shí)現(xiàn)、有可能布在了幾千臺服務(wù)器,橫跨多個不同的數(shù)據(jù)中心。

然后微服務(wù)面臨了這些問題:

  • 某個核心服務(wù)掛了,導(dǎo)致大量報錯,如何快速確定哪里出了問題?
  • 用戶請求響應(yīng)延遲高,怎么確定是哪些服務(wù)導(dǎo)致的?
  • 應(yīng)用程序有性能瓶頸,怎樣確定瓶頸在哪里?
  • 如何準(zhǔn)實(shí)時的了解應(yīng)用部署環(huán)境(CPU、內(nèi)存、進(jìn)程、線程、網(wǎng)絡(luò)、帶寬)情況,以便快速擴(kuò)容/縮容、流量控制、業(yè)務(wù)遷移
  • 如何統(tǒng)計(jì)各個調(diào)用的性能指標(biāo),比如:吞吐量(TPS)、響應(yīng)時間及錯誤記錄等

分布式鏈路跟蹤系統(tǒng)就是為了解決這些問題應(yīng)運(yùn)而生。

分布式鏈路追蹤組件

  • 阿里巴巴鷹眼(EagleEye)
  • 美團(tuán)CAT
  • 京東Hydra
  • Twitter Zipkin (Java經(jīng)常用到) 【.NET Java】
  • Apache SkyWalking (APM) 【go,python,.NET, Java】
  • Pinpoint(APM)

.NET用的最多的兩款是SkyWalking、Zipkin。這里介紹Skywalking使用。

Skywalking有哪些功能?

  • 多種監(jiān)控手段??梢酝ㄟ^語言探針和 service mesh 獲得監(jiān)控是數(shù)據(jù)。
  • 多個語言自動探針。包括 Java,.NET Core 和 Node.JS。
  • 輕量高效。無需大數(shù)據(jù)平臺,和大量的服務(wù)器資源。
  • 模塊化。UI、存儲、集群管理都有多種機(jī)制可選。
  • 支持告警。
  • 優(yōu)秀的可視化解決方案。

**Skywalking整體架構(gòu) **

整個架構(gòu),分成上、下、左、右四部分:

  • 探針基于不同的來源可能是不一樣的, 但作用都是收集數(shù)據(jù), 將數(shù)據(jù)格式化為 SkyWalking 適用的格式.
  • 平臺后端是一個支持集群模式運(yùn)行的后臺, 用于數(shù)據(jù)聚合, 數(shù)據(jù)分析以及驅(qū)動數(shù)據(jù)流從探針到用戶界面的流程. 平臺后端還提供了各種可插拔的能力, 如不同來源數(shù)據(jù)(如來自 Zipkin)格式化, 不同存儲系統(tǒng)以及集群管理. 你甚至還可以使用觀測分析語言來進(jìn)行自定義聚合分析.
  • 存儲是開放式的. 你可以選擇一個既有的存儲系統(tǒng), 如 ElasticSearch, H2 或 MySQL 集群(Sharding-Sphere 管理), 也可以選擇自己實(shí)現(xiàn)一個存儲系統(tǒng). 當(dāng)然, 我們非常歡迎你貢獻(xiàn)新的存儲系統(tǒng)實(shí)現(xiàn).
  • 用戶界面對于 SkyWalking 的最終用戶來說非常炫酷且強(qiáng)大. 同樣它也是可定制以匹配你已存在的后端的

Tracing、Logging和Metrics

在微服務(wù)領(lǐng)域,很早以來就形成了Tracing、Logging和Metrics相輔相成,合力支撐多維度、多形態(tài)的監(jiān)控體系,三類監(jiān)控各有側(cè)重:

Tracing:它在單次請求的范圍內(nèi),處理信息。 任何的數(shù)據(jù)、元數(shù)據(jù)信息都被綁定到系統(tǒng)中的單個事務(wù)上。例如:一次調(diào)用遠(yuǎn)程服務(wù)的RPC執(zhí)行過程;一次實(shí)際的SQL查詢語句;一次HTTP請求的業(yè)務(wù)性ID;

Logging:日志,不知道大家有沒有想過它的定義或者邊界。Logging即是記錄處理的離散事件,比如我們應(yīng)用的調(diào)試信息或者錯誤信息等發(fā)送到ES;審計(jì)跟蹤時間信息通過Kafka處理送到BigTable等數(shù)據(jù)倉儲等等,大多數(shù)情況下記錄的數(shù)據(jù)很分散,并且相互獨(dú)立,也許是錯誤信息,也許僅僅只是記錄當(dāng)前的事件狀態(tài),或者是警告信息等等。

Metrics:當(dāng)我們想知道我們服務(wù)的請求QPS是多少,或者當(dāng)天的用戶登錄次數(shù)等等,這時我們可能需要將一部分事件進(jìn)行聚合或計(jì)數(shù),也就是我們說的Metrics??删酆闲约词荕etrics的特征,它們是一段時間內(nèi)某個度量(計(jì)數(shù)器或者直方圖)的原子或者是元數(shù)據(jù)。例如接收的HTTP數(shù)量可以被建模為計(jì)數(shù)器,每次的HTTP請求即是我們的度量元數(shù)據(jù),可以進(jìn)行簡單的加法聚合,當(dāng)持續(xù)了一段時間我們又可以建模為直方圖。

二、Skywalking搭建

這里用Docker搭建

數(shù)據(jù)存儲用ES,搭建ES

docker run -d -p 9200:9200 -p 9300:9300 --name es -e "discovery.type=single-node" -e ES_JAVA_OPTS="-Xms128m -Xmx256m" elasticsearch:7.16.3

搭建skywalking-oap服務(wù),這里用的是8.9.1版本,oap服務(wù)需要關(guān)聯(lián)ES

docker run --name skywalking-oap \
--restart always \
-p 11800:11800 -p 12800:12800 -d \
-e TZ=Asia/Shanghai \
-e SW_ES_USER= \
-e SW_ES_PASSWORD= \
-e SW_STORAGE=elasticsearch \
-e SW_STORAGE_ES_CLUSTER_NODES=192.168.101.10:9200 \
-v /etc/localtime:/etc/localtime:ro \
apache/skywalking-oap-server:8.9.1

搭建skywalking-ui界面,需要關(guān)聯(lián)oap服務(wù)

docker run -d \
--name skywalking-ui \
--restart always \
-p 8080:8080 \
--link skywalking-oap:skywalking-oap \
-e TZ=Asia/Shanghai \
-e SW_OAP_ADDRESS=http://skywalking-oap:12800 \
-v /etc/localtime:/etc/localtime:ro \
apache/skywalking-ui:8.9.1

搭建完成,打開ip:8080查看skywalking界面

三、.NET6接入Skywalking

1、單個服務(wù)接入

新建一個.NET6站點(diǎn),安裝Nuget包

SkyAPM.Agent.AspNetCore

Properties下launchSettings.json增加

"ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "SkyAPM.Agent.AspNetCore", //必須配置
"SKYWALKING__SERVICENAME": "Service1" // 必須配置,在skywalking做標(biāo)識,服務(wù)名稱

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:6413",
      "sslPort": 44308
    }
  },
  "profiles": {
    "NET6AndSkyWalking": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "http://localhost:5025",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "SkyAPM.Agent.AspNetCore", //必須配置
        "SKYWALKING__SERVICENAME": "Service1" // 必須配置,在skywalking做標(biāo)識,服務(wù)名稱 
      }
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

如果不在launchSettings.json加,也可以在Program.cs加

Environment.SetEnvironmentVariable("ASPNETCORE_HOSTINGSTARTUPASSEMBLIES", "SkyAPM.Agent.AspNetCore");
Environment.SetEnvironmentVariable("SKYWALKING__SERVICENAME", "Service1");

生成skywalking.json文件

1、安裝CLI(SkyAPM.DotNet.CLI),cmd命令:

dotnet tool install -g SkyAPM.DotNet.CLI

2、自動生成skyapm.json文件,cmd命令:

1.dotnet skyapm config [service name] [server]:11800
2.eg: dotnet skyapm config service1 192.168.101.10:11800

執(zhí)行了命令會生成skywalking.json文件,把skywalking.json放到項(xiàng)目根目錄,設(shè)置較新復(fù)制到輸出目錄,然后修改ServiceName設(shè)置為項(xiàng)目名,和上面的SKYWALKING__SERVICENAME一致。

skyapm.json文件

{
  "SkyWalking": {
    "ServiceName": "service1",
    "Namespace": "",
    "HeaderVersions": [
      "sw8"
    ],
    "Sampling": {
      "SamplePer3Secs": -1,
      "Percentage": -1.0
    },
    "Logging": {
      "Level": "Information",
      "FilePath": "logs\\skyapm-{Date}.log"
    },
    "Transport": {
      "Interval": 3000,
      "ProtocolVersion": "v8",
      "QueueSize": 30000,
      "BatchSize": 3000,
      "gRPC": {
        "Servers": "192.168.101.10:11800",
        "Timeout": 10000,
        "ConnectTimeout": 10000,
        "ReportTimeout": 600000,
        "Authentication": ""
      }
    }
  }
}

SamplePer3Secs:每三秒采樣的Trace數(shù)量 ,默認(rèn)為負(fù)數(shù),代表在保證不超過內(nèi)存Buffer區(qū)的前提下,采集所有的Trace

Percentage:采樣率,默認(rèn)負(fù)數(shù),采集全部,其它數(shù)值格式:0.5,0.8...

這時候運(yùn)行項(xiàng)目已經(jīng)有基本的鏈路追蹤功能了!

試一下運(yùn)行,項(xiàng)目,然后看鏈路追蹤界面(注意一下時間搜索的時間范圍向后選一些),這個可能會延遲幾秒鐘才顯示出來。
儀表盤


追蹤

自定義鏈路日志

自定義鏈路日志可以在重要的地方加上,這樣就能知道程序跑到這個地方時的關(guān)鍵信息了。

  public class HomeController : Controller
    {
        private readonly IEntrySegmentContextAccessor _segContext;
        public HomeController(IEntrySegmentContextAccessor segContext)
        {
            _segContext = segContext;
        }

        public IActionResult Index()
        {
            return View();
        }
        
        /// <summary>
        /// 自定鏈路日志
        /// </summary>
        /// <returns></returns>
        public string SkywalkingLog()
        {
            //獲取全局traceId
            var traceId = _segContext.Context.TraceId;
            _segContext.Context.Span.AddLog(LogEvent.Message("自定義日志1"));
            Thread.Sleep(1000);
            _segContext.Context.Span.AddLog(LogEvent.Message("自定義日志2"));
            return traceId;
        }
    }

調(diào)用/Home/SkywalkingLog后Skywalking界面效果,看到了程序添加的日志

2、多服務(wù)追蹤

鏈路追蹤在多服務(wù)的時候才能體現(xiàn)它的精髓,一個鏈路能跟蹤到請求涉及的所有服務(wù)。

這里新增一個.NET6的web項(xiàng)目,前面的步驟和上面的Service1一樣,只是把服務(wù)名改為Service2。

然后在Service2增加一個接口 /UserInfo/GetUserInfo

 public class UserInfoController : Controller
    {
        private readonly IEntrySegmentContextAccessor _segContext;
        public UserInfoController(IEntrySegmentContextAccessor segContext)
        {
            _segContext = segContext;
        }
        [HttpGet]
        public string GetUserInfo(string userId)
        {
            string result = $"userId:{userId},userName:張三";
            _segContext.Context.Span.AddLog(LogEvent.Message(result));

            return result;
        }
    }

然后在Service1增加一個接口/Home/GetUser調(diào)用Service2
后在Service2增加一個接口 /UserInfo/GetUserInfo

public class UserInfoController : Controller
    {
        private readonly IEntrySegmentContextAccessor _segContext;
        public UserInfoController(IEntrySegmentContextAccessor segContext)
        {
            _segContext = segContext;
        }
        [HttpGet]
        public string GetUserInfo(string userId)
        {
            string result = $"userId:{userId},userName:張三";
            _segContext.Context.Span.AddLog(LogEvent.Message(result));

            return result;
        }
    }

然后在Service1增加一個接口/Home/GetUser調(diào)用Service2

public async Task<string> GetUser()
        {
            var client = new HttpClient();
            //調(diào)用Service2
           var response=await client.GetAsync("http://localhost:5199/UserInfo/GetUserInfo");
            var result = await response.Content.ReadAsStringAsync();
            return result;
        }

然后調(diào)用Service1的接口/Home/GetUser

然后看鏈路追蹤,會顯示出對應(yīng)的Service對應(yīng)的耗時,點(diǎn)進(jìn)去還能看到當(dāng)前服務(wù)的詳情和打的日志。

多服務(wù)的時候還能看到服務(wù)之間對應(yīng)的調(diào)用關(guān)系

四、微服務(wù)網(wǎng)關(guān)接入Skywalking

新建一個.NET6的Web項(xiàng)目,引用Nuget包

SkyAPM.Agent.AspNetCore
Ocelot

把Web項(xiàng)目改為Ocelot網(wǎng)關(guān)

首先在根目錄新增ocelot.json文件

{
  "Routes": [
    {
      //轉(zhuǎn)發(fā)到下游服務(wù)地址--url變量
      "DownstreamPathTemplate": "/{url}",
      //下游http協(xié)議
      "DownstreamScheme": "http",
      //負(fù)載方式,
      "LoadBalancerOptions": {
        "Type": "RoundRobin" // 輪詢
      },
      "DownstreamHostAndPorts": [
        {
          "Host": "127.0.0.1",
          "Port": 5025 //服務(wù)端口
        } //可以多個,自行負(fù)載均衡

      ],
      //上游地址
      "UpstreamPathTemplate": "/T1/{url}", //網(wǎng)關(guān)地址--url變量   //沖突的還可以加權(quán)重Priority
      "UpstreamHttpMethod": [ "GET", "POST", "DELETE", "PUT" ]
    },
    {
      //轉(zhuǎn)發(fā)到下游服務(wù)地址--url變量
      "DownstreamPathTemplate": "/{url}",
      //下游http協(xié)議
      "DownstreamScheme": "http",
      //負(fù)載方式,
      "LoadBalancerOptions": {
        "Type": "RoundRobin" // 輪詢
      },
      "DownstreamHostAndPorts": [
        {
          "Host": "127.0.0.1",
          "Port": 5199 //服務(wù)端口
        } //可以多個,自行負(fù)載均衡

      ],
      //上游地址
      "UpstreamPathTemplate": "/T2/{url}", //網(wǎng)關(guān)地址--url變量   //沖突的還可以加權(quán)重Priority
      "UpstreamHttpMethod": [ "GET", "POST", "DELETE", "PUT" ]
    }
  ]
}

然后把Program.cs修改為Ocelot網(wǎng)關(guān)

using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using SkyApm.Utilities.DependencyInjection;
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true);//ocelot
builder.Services.AddSkyApmExtensions(); // 添加Skywalking相關(guān)配置
builder.Services.AddOcelot(); //ocelot
var app = builder.Build();
app.UseOcelot().Wait(); //ocelot
app.Run();

修改Properties下的launchSettings.json文件

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:5127",
      "sslPort": 44306
    }
  },
  "profiles": {
    "Ocelot.Web": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "https://localhost:7019;http://localhost:5019",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "SkyAPM.Agent.AspNetCore", //skywalking必須配置
        "SKYWALKING__SERVICENAME": "Ocelot.Web" // 必須配置,在skywalking做標(biāo)識
      }
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

把skyapm.json復(fù)制過來修改一下

{
  "SkyWalking": {
    "ServiceName": "Ocelot.Web",
    "Namespace": "",
    "HeaderVersions": [
      "sw8"
    ],
    "Sampling": {
      "SamplePer3Secs": -1,
      "Percentage": -1.0
    },
    "Logging": {
      "Level": "Information",
      "FilePath": "logs\\skyapm-{Date}.log"
    },
    "Transport": {
      "Interval": 3000,
      "ProtocolVersion": "v8",
      "QueueSize": 30000,
      "BatchSize": 3000,
      "gRPC": {
        "Servers": "192.168.101.10:11800",
        "Timeout": 10000,
        "ConnectTimeout": 10000,
        "ReportTimeout": 600000,
        "Authentication": ""
      }
    }
  }
}

到這里就完成了,啟動網(wǎng)關(guān)項(xiàng)目,Service1項(xiàng)目,Service2項(xiàng)目,訪問/T1/Home/GetUser

訪問成功,看Skywalking追蹤界面,三個站點(diǎn)都追蹤到了

五、配置Skywalking告警

進(jìn)入容器

 docker exec -it 7c21 /bin/bash

如果報文件夾不存在就用下面的,因?yàn)榘姹静灰粯涌赡軙灰粯?/p>

 docker exec -it 7c21 /bin/sh

進(jìn)入config目錄

配置文件規(guī)則解讀

通過cat alarm-settings.yml可以查閱文件內(nèi)容,如下:

# Sample alarm rules.
rules:
  # Rule unique name, must be ended with `_rule`.
  service_resp_time_rule:
    metrics-name: service_resp_time
    op: ">"
    threshold: 1000
    period: 10
    count: 3
    silence-period: 5
    message: Response time of service {name} is more than 1000ms in 3 minutes of last 10 minutes.
  service_sla_rule:
    # Metrics value need to be long, double or int
    metrics-name: service_sla
    op: "<"
    threshold: 8000
    # The length of time to evaluate the metrics
    period: 10
    # How many times after the metrics match the condition, will trigger alarm
    count: 2
    # How many times of checks, the alarm keeps silence after alarm triggered, default as same as period.
    silence-period: 3
    message: Successful rate of service {name} is lower than 80% in 2 minutes of last 10 minutes
  service_resp_time_percentile_rule:
    # Metrics value need to be long, double or int
    metrics-name: service_percentile
    op: ">"
    threshold: 1000,1000,1000,1000,1000
    period: 10
    count: 3
    silence-period: 5
    message: Percentile response time of service {name} alarm in 3 minutes of last 10 minutes, due to more than one condition of p50 > 1000, p75 > 1000, p90 > 1000, p95 > 1000, p99 > 1000
  service_instance_resp_time_rule:
    metrics-name: service_instance_resp_time
    op: ">"
    threshold: 1000
    period: 10
    count: 2
    silence-period: 5
    message: Response time of service instance {name} is more than 1000ms in 2 minutes of last 10 minutes
  database_access_resp_time_rule:
    metrics-name: database_access_resp_time
    threshold: 1000
    op: ">"
    period: 10
    count: 2
    message: Response time of database access {name} is more than 1000ms in 2 minutes of last 10 minutes
  endpoint_relation_resp_time_rule:
    metrics-name: endpoint_relation_resp_time
    threshold: 1000
    op: ">"
    period: 10
    count: 2
    message: Response time of endpoint relation {name} is more than 1000ms in 2 minutes of last 10 minutes
#  Active endpoint related metrics alarm will cost more memory than service and service instance metrics alarm.
#  Because the number of endpoint is much more than service and instance.
#
#  endpoint_avg_rule:
#    metrics-name: endpoint_avg
#    op: ">"
#    threshold: 1000
#    period: 10
#    count: 2
#    silence-period: 5
#    message: Response time of endpoint {name} is more than 1000ms in 2 minutes of last 10 minutes

webhooks:
#  - http://127.0.0.1/notify/
#  - http://127.0.0.1/go-wechat/

規(guī)則常用指標(biāo)解讀:
rule name: 規(guī)則名稱,必須唯一,必須以 _rule結(jié)尾;
metrics name: oal(Observability Analysis Language)腳本中的度量名;名稱在SkyWalking后端服務(wù)中已經(jīng)定義,進(jìn)入容器skywalking-oap之后,進(jìn)入如下目錄就可以找到。

include names: 本規(guī)則告警生效的實(shí)體名稱,如服務(wù)名,終端名;
exclude-names:將此規(guī)則作用于不匹配的實(shí)體名稱上,如服務(wù)名,終端名;
threshold: 閾值,可以是一個數(shù)組,即可以配置多個值;
op: 操作符, 可以設(shè)定 >, <, =;
period: 多久檢查一次當(dāng)前的指標(biāo)數(shù)據(jù)是否符合告警規(guī)則;以分鐘為單位
count: 超過閾值條件,達(dá)到count次數(shù),觸發(fā)告警;
silence period:在同一個周期,指定的silence period時間內(nèi),忽略相同的告警消息;
更多告警規(guī)則詳情,請參照這個地址:

https://github.com/apache/skywalking/blob/master/docs/en/setup/backend/backend-alarm.md

修改告警規(guī)則

rules:
	service_sal_rule:
		# 指定指標(biāo)名稱
    	metrics-name: service_sal
    	# 小于
    	op: "<"
    	# 指定閾值
    	threshold: 8000
    	# 每10分鐘檢測告警該規(guī)則
    	period: 10
    	# 觸發(fā)2次規(guī)則就告警
    	count: 2
    	# 設(shè)置三分鐘內(nèi)容相同告警,不重復(fù)告警
    	silence-period: 3
    	# 配置告警信息
    	message: Successful rate of service {name} is lower than 80% in 2 minutes of last 10 minutes

概要:服務(wù)成功率在過去2分鐘內(nèi)低于80%

告警API編寫

這個本質(zhì)還是SkyWalking根據(jù)規(guī)則進(jìn)行檢查,如果符合規(guī)則條件,就通過WebHook、gRPCHook、WeChat Hook、Dingtalk Hook、Feishu Hook等方式進(jìn)行消息通知;接收到告警數(shù)據(jù)信息之后,可以自行處理消息。這里為了方便,就采用WebHook的方式進(jìn)行演示,即觸發(fā)告警條件之后,SkyWalking會調(diào)用配置的WebHook 接口,并傳遞對應(yīng)的告警信

定義數(shù)據(jù)模型

public class AlarmMsg
{
    public int scopeId { get; set; }
    public string? scope { get; set; }
    public string? name { get; set; }
    public string? id0 { get; set; }
    public string? id1 { get; set; }
    public string? ruleName { get; set; }
    public string? alarmMessage { get; set; }
}

定義WebHook調(diào)用API,這里在Service1下的HomeController里加接口接收告警信息

	/// <summary>
        /// 故意報錯測試告警
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public  string Error()
        {
            //故意報錯
            throw new Exception($"出錯啦:{DateTime.Now}");
        }
        /// <summary>
        /// 告警
        /// </summary>
        /// <param name="msgs"></param>
        [HttpPost]
        public void AlarmMsg([FromBody]List<AlarmMsg>List<AlarmMsg> msgs)
        {
           string msg = $"{DateTime.Now},觸發(fā)告警:";
            msg += msgs.FirstOrDefault()?.alarmMessage;
            Console.WriteLine(msg);
           //todo 發(fā)郵件或發(fā)短信
        }

配置webkook

webhooks:
- http://192.168.101.9:5025/Home/AlarmMsg

重啟 Skywalking-oap服務(wù)

請求幾次/Home/Error產(chǎn)生錯誤請求

等待告警webhook調(diào)用

到這里,告警據(jù)完成了。

六、Skywalking無入侵原理解密

為什么要在launchSettings.json文件里面加SkyAPM.Agent.AspNetCore呢,為什么加了就可以了呢?

其實(shí)用的是.NET Core框架里面的擴(kuò)展,它是怎做到的呢,舉個例子

在Service1做測試,建一個CustomHostingStartup.cs

namespace NET6AndSkyWalking.Models
{
    /// <summary>
    /// 必須實(shí)現(xiàn)IHostingStartup 接口
    /// 必須標(biāo)記HostingStartup特性
    /// 發(fā)生在HostBuild時候,IOC容器初始化之前,無侵入式擴(kuò)展
    /// </summary>
    public class CustomHostingStartup : IHostingStartup
    {
        public void Configure(IWebHostBuilder builder)
        {
            Console.WriteLine("自定義擴(kuò)展執(zhí)行...");
            //拿到IWebHostBuilder,一切都可做
        }
    }
}

啟動Service1,可以看到新增的擴(kuò)展打印了


如果這個擴(kuò)展是在其他類庫呢?

新建一個Common類庫,把剛才的類移到Common類庫,然后Service添加對Common的引用。

這時候就要修改launchsettings.json文件,加入Common的程序集了

啟動Service1,成功執(zhí)行


同樣的道理,通過查看源碼可以看到,SkyAPM.Agent.AspNetCore組件里面也有這樣的一個類,把Skywalking的代碼無侵入擴(kuò)展進(jìn)來了。

演示源碼:https://github.com/weixiaolong325/NET6AndSkyWalking

到此這篇關(guān)于.NET6接入Skywalking鏈路追蹤完整流程的文章就介紹到這了,更多相關(guān).NET6 Skywalking鏈路追蹤內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論