Apollo Server开箱支持Apollo Engine,只是由于某些不可知的原因Apollo Engine的 API 在国内不可访问(我是真不知道为什么这个 API 会被墙的),所以只能另外想办法了.
Apollo Server本身有一个Apollo Tracing可以用于性能监控的扩展,通过扩展Apollo Tracing收集指标传输到分布式跟踪系统中.
另外有一个开源库Apollo Opentracing可以收集指标,传输到Jaeger或者Zipkin中,通过Jaeger或Zipkin实现性能监控和分析.
秉着方便,直接使用Apollo Opentracing.分布式跟踪系统使用Jaeger.
使用 Docker 搭建Jaeger
搭建Apollo Server
mkdir apollo-opentracing-demo
cd apollo-opentracing-demo
yarn init -y
yarn add apollo-server
// index.js
const { ApolloServer, gql } = require('apollo-server')
const typeDefs = gql`
type Query {
hello: String
}
`
const resolvers = {
Query: {
hello: () => 'world',
},
}
const server = new ApolloServer({
typeDefs,
resolvers,
})
server.listen().then(({ url }) => {
console.log(` Server ready at ${url}`)
})
运行
node index.js
集成Apollo Opentracing
yarn add apollo-opentracing jaeger-client
// tracer.js
const { default: OpentracingExtension } = require('apollo-opentracing')
const { initTracer } = require('jaeger-client')
const config = {
serviceName: 'apollo-opentracing-demo',
sampler: {
type: 'const',
param: 1,
},
reporter: {
logSpans: true,
collectorEndpoint: 'http://localhost:14268/api/traces',
},
}
const options = {
logger: {
info(msg) {
console.log('INFO ', msg)
},
error(msg) {
console.log('ERROR', msg)
},
},
}
const tracer = initTracer(config, options)
const opentracingExtension = () => {
console.log(123)
return new OpentracingExtension({
local: tracer,
server: tracer,
})
}
module.exports = {
opentracingExtension,
}
const { opentracingExtension } = require('./tracer.js') // 引入扩展
...
const server = new ApolloServer({
typeDefs,
resolvers,
extensions: [opentracingExtension], // 使用扩展
})
...
使用
使用以下语句查询
query {
hello
}
点击Find Traces就能看到刚刚查询的指标
参考