# 4.7 调用Sentinel

# 4.7.1 简介

对官方库的二次封装。

# 4.7.2 配置规范

配置说明 (opens new window)

# 4.7.3 用法

访问redis示例 (opens new window)

// run: go run main.go --config=config.toml

package main

import (
    "fmt"
    "math/rand"
    "time"

    "github.com/douyu/jupiter/pkg/util/xgo"
    "github.com/douyu/jupiter"
    "github.com/douyu/jupiter/pkg/sentinel"
    "github.com/douyu/jupiter/pkg/util/xtime"
    "github.com/douyu/jupiter/pkg/xlog"
)

type Engine struct {
    jupiter.Application
}

func NewEngine() *Engine {
    eng := &Engine{}
    if err := eng.Startup(
        eng.exampleSentinel,
    ); err != nil {
        xlog.Panic("startup", xlog.Any("err", err))
    }
    return eng
}

func main() {
    app := NewEngine()
    if err := app.Run(); err != nil {
        panic(err)
    }
}

func (eng *Engine) exampleSentinel() (err error) {
    err = sentinel.StdConfig("test").Build()
    if err != nil {
        panic(fmt.Sprintf("sentinel init failed: %s", err.Error()))
    }

    for k := 0; k < 20; k++ {
        xgo.Go(func() {
            e, b := sentinel.Entry("some-test")
            if b != nil {
                // 请求被拒绝,在此处进行处理
                time.Sleep(time.Duration(rand.Uint64()%10) * time.Millisecond)
            } else {
                // 请求允许通过,此处编写业务逻辑
                fmt.Println(xtime.CurrentTimeMillis(), "Passed")
                time.Sleep(time.Duration(rand.Uint64()%10) * time.Millisecond)

                // 务必保证业务结束后调用 Exit
                e.Exit()
            }
        })
    }

    return
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63

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