1 回答
TA贡献1809条经验 获得超8个赞
最后通过更新所有依赖项来修复,必须升级 GRPC 版本及其各自的依赖项。
还更改了 redis 事务使用的上下文。
这是最终代码
1 - 函数使用示例
dbTransaction := newrelic.FromContext(ctx)
newRelicContext := newrelic.NewContext(context.Background(), dbTransaction)
data, err := tools.Client.Get(newRelicContext, id).Result()
2 - Redis单例
package tools
import (
"context"
"os"
"github.com/go-redis/redis/v8"
nrredis "github.com/newrelic/go-agent/v3/integrations/nrredis-v8"
newrelic "github.com/newrelic/go-agent/v3/newrelic"
)
var redisOpt = &redis.Options{
Addr: os.Getenv("****************") + ":" + os.Getenv("*****************"),
DB: 1,
Password: os.Getenv("******************"),
}
var Client *redis.Client = nil
var Ctx context.Context = nil
func getTransaction() *newrelic.Transaction { return nil }
func init() {
Client = redis.NewClient(redisOpt)
Client.AddHook(nrredis.NewHook(redisOpt))
txn := getTransaction()
Ctx = newrelic.NewContext(context.Background(), txn)
}
func GetRedis() (*redis.Client, context.Context) {
if Client == nil {
Client = redis.NewClient(redisOpt)
Client.AddHook(nrredis.NewHook(redisOpt))
txn := getTransaction()
Ctx = newrelic.NewContext(context.Background(), txn)
}
return Client, Ctx
}
3 - newRelic 单例
package tools
import (
"context"
"log"
"os"
newrelic "github.com/newrelic/go-agent/v3/newrelic"
)
var RelicApplication *newrelic.Application
var CurrentTransaction *newrelic.Transaction
func init() {
log.Println("INIT RELIC CREATING AT RUNTIME")
var err error
RelicApplication, err = newrelic.NewApplication(
newrelic.ConfigAppName("**********************"),
newrelic.ConfigLicense(os.Getenv("NRELIC_KEY")),
newrelic.ConfigDebugLogger(os.Stdout),
newrelic.ConfigDistributedTracerEnabled(true),
func(config *newrelic.Config) {
config.Enabled = true
},
)
if err != nil {
log.Println("ERROR INITING NEW RELIC: ", err)
}
log.Println("INIT RELIC = RETURNING")
}
func SetSubTransaction(txn *newrelic.Transaction) {
//set new current transaction
CurrentTransaction = txn
}
func SetSubTransactionByContext(ctx context.Context) {
txn := newrelic.FromContext(ctx)
SetSubTransaction(txn)
}
func InitRelic() (*newrelic.Application, error) {
if RelicApplication == nil {
var err error
writer, err := os.OpenFile("log_file", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
log.Println("ERROR OPENING LOG FILE: ", err)
return nil, err
}
RelicApplication, err = newrelic.NewApplication(
newrelic.ConfigAppName("**********************"),
newrelic.ConfigLicense(os.Getenv("NRELIC_KEY")),
newrelic.ConfigDebugLogger(os.Stdout),
newrelic.ConfigInfoLogger(writer),
newrelic.ConfigDistributedTracerEnabled(true),
func(config *newrelic.Config) {
config.Enabled = false
},
)
if err != nil {
log.Println("ERROR INITING NEW RELIC: ", err)
}
return RelicApplication, err
} else {
return RelicApplication, nil
}
}
- 1 回答
- 0 关注
- 92 浏览
添加回答
举报