skywalking 跟踪grpc的链路
skywalking对http请求实现了无代码入侵的跟踪,但是对grpc则需要修改相应的代码。
根据官方的提示:
https://github.com/SkyAPM/SkyAPM-dotnet/pull/236
1.由于Grpc没有Diagnostics机制,只能通过它本身提供的Interceptor拦截器去实现追踪,因此貌似没有办法做到代码无浸入,必须要注入该追踪拦截器
2.Grpc客户端需要在new Channel().Intercept()中传入ClientDiagnosticInterceptor实例对象
3.Grpc服务端需要在start()服务之前传入ServerDiagnosticInterceptor实例对象
详情可以参考示例代码,效果截图
以及官方提供的demo,我们在grpc的客户端代码进行调整:
1、构造函数注入一个拦截器 ClientDiagnosticInterceptor interceptor
2、构造函数创建client ,并且将该拦截器添加进来。
3、具体的代码如下,里面包含了 grpc和http这2种类型的简单实现。
[ApiController] [Route("api/[controller]/[action]")] public class WeatherForecastController : ControllerBase { private readonly IHttpClientFactory _clientFactory; private readonly ILogger<WeatherForecastController> _logger; private readonly Greeter.GreeterClient _client; public WeatherForecastController(ClientDiagnosticInterceptor interceptor,ILogger<WeatherForecastController> logger, IHttpClientFactory clientFactory) { _logger = logger; _clientFactory = clientFactory; var target = "localhost:5000"; var channel = new Channel(target, ChannelCredentials.Insecure); var invoker = channel.Intercept(interceptor); _client = new Greeter.GreeterClient(invoker).WithHost(target); } [HttpGet] public async Task<IActionResult> GetGrpc() { try { var reply = _client.SayHello(new HelloRequest { Name = "晓晨222" }); Console.WriteLine("Greeter 服务返回数据: " + reply.Message); } catch (Exception ex) { int i = 0; } return Ok("ok啦"); } [HttpPost] public async Task<IActionResult> PostHttp() { var request = new HttpRequestMessage(HttpMethod.Get, "http://10.10.1.204:31927/api/Health/Get"); request.Headers.Add("Accept", "application/vnd.github.v3+json"); request.Headers.Add("User-Agent", "HttpClientFactory-Sample"); var client = _clientFactory.CreateClient(); var response = await client.SendAsync(request); if (response.IsSuccessStatusCode) { return Ok(response.Content.ReadAsStringAsync()); } else { return Ok("error000001"); } return Ok("ok-post啦"); } }
作者:沐雪
文章均系作者原创或翻译,如有错误不妥之处,欢迎各位批评指正。本文版权归作者和博客园共有,如需转载恳请注明。
如果您觉得阅读这篇博客让你有所收获,请点击右下方【推荐】
为之网-热爱软件编程 http://www.weizhi.cc/