4.7 调用Sentinel

4.7.1 简介

对官方库的二次封装。

4.7.2 配置规范

配置说明4.7 调用Sentinel - 图1 (opens new window)

4.7.3 用法

访问redis示例4.7 调用Sentinel - 图2 (opens new window)

  1. // run: go run main.go --config=config.toml
  2. package main
  3. import (
  4. "fmt"
  5. "math/rand"
  6. "time"
  7. "github.com/douyu/jupiter/pkg/util/xgo"
  8. "github.com/douyu/jupiter"
  9. "github.com/douyu/jupiter/pkg/sentinel"
  10. "github.com/douyu/jupiter/pkg/util/xtime"
  11. "github.com/douyu/jupiter/pkg/xlog"
  12. )
  13. type Engine struct {
  14. jupiter.Application
  15. }
  16. func NewEngine() *Engine {
  17. eng := &Engine{}
  18. if err := eng.Startup(
  19. eng.exampleSentinel,
  20. ); err != nil {
  21. xlog.Panic("startup", xlog.Any("err", err))
  22. }
  23. return eng
  24. }
  25. func main() {
  26. app := NewEngine()
  27. if err := app.Run(); err != nil {
  28. panic(err)
  29. }
  30. }
  31. func (eng *Engine) exampleSentinel() (err error) {
  32. err = sentinel.StdConfig("test").Build()
  33. if err != nil {
  34. panic(fmt.Sprintf("sentinel init failed: %s", err.Error()))
  35. }
  36. for k := 0; k < 20; k++ {
  37. xgo.Go(func() {
  38. e, b := sentinel.Entry("some-test")
  39. if b != nil {
  40. // 请求被拒绝,在此处进行处理
  41. time.Sleep(time.Duration(rand.Uint64()%10) * time.Millisecond)
  42. } else {
  43. // 请求允许通过,此处编写业务逻辑
  44. fmt.Println(xtime.CurrentTimeMillis(), "Passed")
  45. time.Sleep(time.Duration(rand.Uint64()%10) * time.Millisecond)
  46. // 务必保证业务结束后调用 Exit
  47. e.Exit()
  48. }
  49. })
  50. }
  51. return
  52. }

执行 go run main.go —config=config.toml,可以看到如下图结果 image