example_instrumentation_test.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package redis_test
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/go-redis/redis/v7"
  6. )
  7. type redisHook struct{}
  8. var _ redis.Hook = redisHook{}
  9. func (redisHook) BeforeProcess(ctx context.Context, cmd redis.Cmder) (context.Context, error) {
  10. fmt.Printf("starting processing: <%s>\n", cmd)
  11. return ctx, nil
  12. }
  13. func (redisHook) AfterProcess(ctx context.Context, cmd redis.Cmder) error {
  14. fmt.Printf("finished processing: <%s>\n", cmd)
  15. return nil
  16. }
  17. func (redisHook) BeforeProcessPipeline(ctx context.Context, cmds []redis.Cmder) (context.Context, error) {
  18. fmt.Printf("pipeline starting processing: %v\n", cmds)
  19. return ctx, nil
  20. }
  21. func (redisHook) AfterProcessPipeline(ctx context.Context, cmds []redis.Cmder) error {
  22. fmt.Printf("pipeline finished processing: %v\n", cmds)
  23. return nil
  24. }
  25. func Example_instrumentation() {
  26. rdb := redis.NewClient(&redis.Options{
  27. Addr: ":6379",
  28. })
  29. rdb.AddHook(redisHook{})
  30. rdb.Ping()
  31. // Output: starting processing: <ping: >
  32. // finished processing: <ping: PONG>
  33. }
  34. func ExamplePipeline_instrumentation() {
  35. rdb := redis.NewClient(&redis.Options{
  36. Addr: ":6379",
  37. })
  38. rdb.AddHook(redisHook{})
  39. rdb.Pipelined(func(pipe redis.Pipeliner) error {
  40. pipe.Ping()
  41. pipe.Ping()
  42. return nil
  43. })
  44. // Output: pipeline starting processing: [ping: ping: ]
  45. // pipeline finished processing: [ping: PONG ping: PONG]
  46. }
  47. func ExampleWatch_instrumentation() {
  48. rdb := redis.NewClient(&redis.Options{
  49. Addr: ":6379",
  50. })
  51. rdb.AddHook(redisHook{})
  52. rdb.Watch(func(tx *redis.Tx) error {
  53. tx.Ping()
  54. tx.Ping()
  55. return nil
  56. }, "foo")
  57. // Output:
  58. // starting processing: <watch foo: >
  59. // finished processing: <watch foo: OK>
  60. // starting processing: <ping: >
  61. // finished processing: <ping: PONG>
  62. // starting processing: <ping: >
  63. // finished processing: <ping: PONG>
  64. // starting processing: <unwatch: >
  65. // finished processing: <unwatch: OK>
  66. }