redis/example/otel/example-client.go

86 lines
1.8 KiB
Go
Raw Permalink Normal View History

package main
import (
"context"
2020-07-16 09:52:07 +03:00
"log"
"sync"
"time"
"github.com/go-redis/redis/v8"
2020-11-21 10:56:52 +03:00
"github.com/go-redis/redis/v8/extra/redisotel"
"go.opentelemetry.io/otel"
2021-01-16 22:20:03 +03:00
"go.opentelemetry.io/otel/exporters/stdout"
2021-02-04 11:38:54 +03:00
controller "go.opentelemetry.io/otel/sdk/metric/controller/basic"
processor "go.opentelemetry.io/otel/sdk/metric/processor/basic"
2021-01-16 22:20:03 +03:00
"go.opentelemetry.io/otel/sdk/metric/selector/simple"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
)
func main() {
2021-02-04 11:38:54 +03:00
ctx := context.Background()
stop := runExporter(ctx)
defer stop(ctx)
rdb := redis.NewClient(&redis.Options{
Addr: ":6379",
})
2020-11-21 10:56:52 +03:00
rdb.AddHook(redisotel.TracingHook{})
2020-11-21 10:56:52 +03:00
tracer := otel.Tracer("Example tracer")
ctx, span := tracer.Start(ctx, "start-test-span")
rdb.Set(ctx, "First value", "value_1", 0)
rdb.Set(ctx, "Second value", "value_2", 0)
var group sync.WaitGroup
for i := 0; i < 20; i++ {
group.Add(1)
go func() {
defer group.Done()
val := rdb.Get(ctx, "Second value").Val()
if val != "value_2" {
log.Fatalf("val was not set. expected: %s but got: %s", "value_2", val)
}
}()
}
group.Wait()
rdb.Del(ctx, "First value")
rdb.Del(ctx, "Second value")
// Wait some time to allow spans to export
<-time.After(5 * time.Second)
span.End()
}
2021-01-16 22:20:03 +03:00
2021-02-04 11:38:54 +03:00
func runExporter(ctx context.Context) func(context.Context) error {
2021-01-16 22:20:03 +03:00
exporter, err := stdout.NewExporter(stdout.WithPrettyPrint())
if err != nil {
2021-02-04 11:38:54 +03:00
log.Fatal(err)
2021-01-16 22:20:03 +03:00
}
tp := sdktrace.NewTracerProvider(
sdktrace.WithSyncer(exporter),
sdktrace.WithConfig(sdktrace.Config{DefaultSampler: sdktrace.AlwaysSample()}),
)
otel.SetTracerProvider(tp)
2021-02-04 11:38:54 +03:00
ctrl := controller.New(
processor.New(
2021-01-16 22:20:03 +03:00
simple.NewWithExactDistribution(),
exporter,
),
2021-02-04 11:38:54 +03:00
controller.WithPusher(exporter),
controller.WithCollectPeriod(1*time.Second),
2021-01-16 22:20:03 +03:00
)
2021-02-04 11:38:54 +03:00
if err := ctrl.Start(ctx); err != nil {
log.Fatal(err)
}
return ctrl.Stop
2021-01-16 22:20:03 +03:00
}