溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Sentinel-Go中怎么利用Nacos 實(shí)現(xiàn)外部動態(tài)數(shù)據(jù)源

發(fā)布時(shí)間:2021-08-09 14:21:18 來源:億速云 閱讀:139 作者:Leah 欄目:云計(jì)算

本篇文章給大家分享的是有關(guān)Sentinel-Go中怎么利用Nacos 實(shí)現(xiàn)外部動態(tài)數(shù)據(jù)源,小編覺得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

1. Sentinel

隨著微服務(wù)的流行,服務(wù)和服務(wù)之間的穩(wěn)定性變得越來越重要。Sentinel 以流量為切入點(diǎn),從流量控制、熔斷降級、系統(tǒng)負(fù)載保護(hù)等多個(gè)維度保護(hù)服務(wù)的穩(wěn)定性。

Sentinel 具有以下特征:

  • 豐富的應(yīng)用場景:Sentinel 承接了阿里巴巴近 10 年的雙十一大促流量的核心場景,例如秒殺(即突發(fā)流量控制在系統(tǒng)容量可以承受的范圍)、消息削峰填谷、集群流量控制、實(shí)時(shí)熔斷下游不可用應(yīng)用等。

  • 完備的實(shí)時(shí)監(jiān)控:Sentinel 同時(shí)提供實(shí)時(shí)的監(jiān)控功能。您可以在控制臺中看到接入應(yīng)用的單臺機(jī)器秒級數(shù)據(jù),甚至 500 臺以下規(guī)模的集群的匯總運(yùn)行情況。

  • 廣泛的開源生態(tài):Sentinel 提供開箱即用的與其它開源框架/庫的整合模塊,例如與 Spring Cloud、Dubbo、gRPC 的整合。您只需要引入相應(yīng)的依賴并進(jìn)行簡單的配置即可快速地接入 Sentinel。

  • 完善的 SPI 擴(kuò)展點(diǎn):Sentinel 提供簡單易用、完善的 SPI 擴(kuò)展接口。您可以通過實(shí)現(xiàn)擴(kuò)展接口來快速地定制邏輯。例如定制規(guī)則管理、適配動態(tài)數(shù)據(jù)源等。

1.1 Sentinel 的歷史

  • 2012年,Sentinel 誕生,主要功能為入口流量控制。

  • 2013-2017年,Sentinel 在阿里巴巴集團(tuán)內(nèi)部迅速發(fā)展,成為基礎(chǔ)技術(shù)模塊,覆蓋了所有的核心場景。Sentinel 也因此積累了大量的流量歸整場景以及生產(chǎn)實(shí)踐。

  • 2018年,Sentinel 開源,并持續(xù)演進(jìn)。

  • 2019年,Sentinel 在多語言擴(kuò)展的方向上逐步探索,陸續(xù)推出 C++ 原生版本、Envoy 集群流量控制支持。

2. Nacos

Nacos是一個(gè)更易于構(gòu)建云原生應(yīng)用的動態(tài)服務(wù)發(fā)現(xiàn)、配置管理和服務(wù)管理的平臺,Nacos脫胎于阿里巴巴內(nèi)部的ConfigServer和Diamond,是它們的開源實(shí)現(xiàn)。經(jīng)歷過雙十一流量峰值和阿里巴巴經(jīng)濟(jì)體超大規(guī)模容量的考驗(yàn),沉淀了阿里巴巴軟負(fù)載團(tuán)隊(duì)在這個(gè)領(lǐng)域十年的經(jīng)驗(yàn),在穩(wěn)定性和功能性上都有很好的保障。

Sentinel-Go中怎么利用Nacos 實(shí)現(xiàn)外部動態(tài)數(shù)據(jù)源

(Sentinel-Go集成Nacos動態(tài)數(shù)據(jù)源架構(gòu))

目前 Sentinel 內(nèi)部的限流、熔斷等策略都是基于規(guī)則來實(shí)現(xiàn)的,提供動態(tài)數(shù)據(jù)源擴(kuò)展的目的,就是希望將規(guī)則數(shù)據(jù)的加載以及更新操作通過一些配置中心中間件(比如 nacos,etcd,conful,等等)來實(shí)現(xiàn)動態(tài)更新。

3. Sentinel-Go 限流 Demo

未集成nacos時(shí) 規(guī)則定義在代碼內(nèi)部,沒有使用外部數(shù)據(jù)源。

3.1 安裝

go get http://github.com/alibaba/sentinel-golang

3.2 Demo樣例

使用 Sentinel 主要分為以下幾步:

  1. 對 Sentinel 進(jìn)行相關(guān)配置并進(jìn)行初始化

  2. 埋點(diǎn)(定義資源)

  3. 配置規(guī)則

package main

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

    sentinel "github.com/alibaba/sentinel-golang/api"
    "github.com/alibaba/sentinel-golang/core/base"
    "github.com/alibaba/sentinel-golang/core/flow"
    "github.com/alibaba/sentinel-golang/util"
)

func main() {
    // We should initialize Sentinel first.
    err := sentinel.InitDefault()
    if err != nil {
        log.Fatalf("Unexpected error: %+v", err)
    }

    _, err = flow.LoadRules([]*flow.FlowRule{
        {
            Resource:        "some-test",
            MetricType:      flow.QPS,
            Count:           10,
            ControlBehavior: flow.Reject,
        },
    })
    if err != nil {
        log.Fatalf("Unexpected error: %+v", err)
        return
    }

    ch := make(chan struct{})

    for i := 0; i < 10; i++ {
        go func() {
            for {
                e, b := sentinel.Entry("some-test", sentinel.WithTrafficType(base.Inbound))
                if b != nil {
                    // Blocked. We could get the block reason from the BlockError.
                    time.Sleep(time.Duration(rand.Uint64()%10) * time.Millisecond)
                } else {
                    // Passed, wrap the logic here.
                    fmt.Println(util.CurrentTimeMillis(), "passed")
                    time.Sleep(time.Duration(rand.Uint64()%10) * time.Millisecond)

                    // Be sure the entry is exited finally.
                    e.Exit()
                }

            }
        }()
    }
    <-ch
}

4. Sentinel-Go 集成Nacos

Sentinel-Go集成Nacos實(shí)現(xiàn)外部動態(tài)數(shù)據(jù)源功能.

4.1 部署Nacos

4.1.1 版本選擇

您可以在Nacos的release notes及博客中找到每個(gè)版本支持的功能的介紹,當(dāng)前推薦的穩(wěn)定版本為1.3.1。

4.1.2 預(yù)備環(huán)境準(zhǔn)備

Nacos 依賴 Java 環(huán)境來運(yùn)行。如果您是從代碼開始構(gòu)建并運(yùn)行Nacos,還需要為此配置 Maven環(huán)境,請確保是在以下版本環(huán)境中安裝使用:

  1. 64 bit OS,支持 Linux/Unix/Mac/Windows,推薦選用 Linux/Unix/Mac。

  2. 64 bit JDK 1.8+;下載 & 配置。

  3. Maven 3.2.x+;下載 & 配置。

4.1.3 下載源碼或者安裝包

你可以通過源碼和發(fā)行包兩種方式來獲取 Nacos。

從 Github 上下載源碼方式

git clone https://github.com/alibaba/nacos.git
cd nacos/
mvn -Prelease-nacos -Dmaven.test.skip=true clean install -U  
ls -al distribution/target/
// change the $version to your actual path
cd distribution/target/nacos-server-$version/nacos/bin

下載編譯后壓縮包方式

您可以從 最新穩(wěn)定版本 下載 nacos-server-$version.zip 包。

unzip nacos-server-$version.zip 或者 tar -xvf nacos-server-$version.tar.gz
  cd nacos/bin

4.1.4 啟動服務(wù)器

Linux/Unix/Mac
啟動命令(standalone代表著單機(jī)模式運(yùn)行,非集群模式):
sh startup.sh -m standalone
如果您使用的是ubuntu系統(tǒng),或者運(yùn)行腳本報(bào)錯提示[[符號找不到,可嘗試如下運(yùn)行:
bash startup.sh -m standalone

Windows
啟動命令:
cmd startup.cmd
或者雙擊startup.cmd運(yùn)行文件。

部署成功訪問 http://127.0.0.1:8848/nacos
用戶名/密碼:nacos/nacos

4.2 Sentinel限流配置到Nacos

  1. 登錄到nacos web

  2. 在配置管理中,新建配置

  3. 輸入dataId,group(dataId,group 創(chuàng)建時(shí)可以自定義,本文創(chuàng)建的dataId=flow,group=sentinel-go)

  4. 將數(shù)據(jù)源樣例粘貼到配置內(nèi)容中。

4.2.1 Nacos 外部數(shù)據(jù)源樣例

此樣例是流量控制的Demo配置。當(dāng)流量并發(fā)數(shù)大于100直接拒絕。

[
    {
        "resource": "some-test",
        "metricType": 1,
        "count": 100.0,
        "controlBehavior":0
    }
]

創(chuàng)建完成后,在nacos配置列表中可以看到對應(yīng)的限流配置。

Sentinel-Go中怎么利用Nacos 實(shí)現(xiàn)外部動態(tài)數(shù)據(jù)源

4.3 Nacos數(shù)據(jù)源集成

4.3.1 創(chuàng)建項(xiàng)目

  • 版本

  1. sentinel-golang 版本使用0.6.0,nacos-sdk-go 使用1.0.0

  • go.mod

module sentinel-go-nacos-example

go 1.13

require (
    github.com/alibaba/sentinel-golang v0.6.0
    github.com/nacos-group/nacos-sdk-go v1.0.0
)
  • main.go

package main

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

    sentinel "github.com/alibaba/sentinel-golang/api"
    "github.com/alibaba/sentinel-golang/core/base"
    "github.com/alibaba/sentinel-golang/ext/datasource/nacos"
    "github.com/alibaba/sentinel-golang/util"
    "github.com/nacos-group/nacos-sdk-go/clients"

    "github.com/alibaba/sentinel-golang/ext/datasource"
    "github.com/nacos-group/nacos-sdk-go/common/constant"
)

type Counter struct {
    pass  *int64
    block *int64
    total *int64
}

func main() {
    //流量計(jì)數(shù)器,為了流控打印日志更直觀,和集成nacos數(shù)據(jù)源無關(guān)。
    counter := Counter{pass: new(int64), block: new(int64), total: new(int64)}

    //nacos server地址
    sc := []constant.ServerConfig{
        {
            ContextPath: "/nacos",
            Port:        8848,
            IpAddr:      "127.0.0.1",
        },
    }
    //nacos client 相關(guān)參數(shù)配置,具體配置可參考https://github.com/nacos-group/nacos-sdk-go
    cc := constant.ClientConfig{
        TimeoutMs: 5000,
    }
    //生成nacos config client(配置中心客戶端)
    client, err := clients.CreateConfigClient(map[string]interface{}{
        "serverConfigs": sc,
        "clientConfig":  cc,
    })
    if err != nil {
        fmt.Printf("Fail to create client, err: %+v", err)
        return
    }
    //注冊流控規(guī)則Handler
    h := datasource.NewFlowRulesHandler(datasource.FlowRuleJsonArrayParser)
    //創(chuàng)建NacosDataSource數(shù)據(jù)源
    //sentinel-go 對應(yīng)在nacos中創(chuàng)建配置文件的group
    //flow 對應(yīng)在nacos中創(chuàng)建配置文件的dataId
    nds, err := nacos.NewNacosDataSource(client, "sentinel-go", "flow", h)
    if err != nil {
        fmt.Printf("Fail to create nacos data source client, err: %+v", err)
        return
    }
    //nacos數(shù)據(jù)源初始化
    err = nds.Initialize()
    if err != nil {
        fmt.Printf("Fail to initialize nacos data source client, err: %+v", err)
        return
    }
    //啟動統(tǒng)計(jì)
    go timerTask(&counter)

    //模擬流量
    ch := make(chan struct{})
    for i := 0; i < 10; i++ {
        go func() {
            for {
                atomic.AddInt64(counter.total, 1)
                //some-test 對應(yīng)在nacos 流控配置文件中的resource
                e, b := sentinel.Entry("some-test", sentinel.WithTrafficType(base.Inbound))
                if b != nil {
                    atomic.AddInt64(counter.block, 1)
                    // Blocked. We could get the block reason from the BlockError.
                    time.Sleep(time.Duration(rand.Uint64()%10) * time.Millisecond)
                } else {
                    atomic.AddInt64(counter.pass, 1)
                    time.Sleep(time.Duration(rand.Uint64()%10) * time.Millisecond)

                    // Be sure the entry is exited finally.
                    e.Exit()
                }

            }
        }()
    }
    <-ch
}

//statistic print
func timerTask(counter *Counter) {
    fmt.Println("begin to statistic!!!")
    var (
        oldTotal, oldPass, oldBlock int64
    )
    for {
        time.Sleep(1 * time.Second)
        globalTotal := atomic.LoadInt64(counter.total)
        oneSecondTotal := globalTotal - oldTotal
        oldTotal = globalTotal

        globalPass := atomic.LoadInt64(counter.pass)
        oneSecondPass := globalPass - oldPass
        oldPass = globalPass

        globalBlock := atomic.LoadInt64(counter.block)
        oneSecondBlock := globalBlock - oldBlock
        oldBlock = globalBlock
        fmt.Println(util.CurrentTimeMillis()/1000, "total:", oneSecondTotal, " pass:", oneSecondPass, " block:", oneSecondBlock)
    }
}

4.3.2 運(yùn)行結(jié)果

Sentinel-Go中怎么利用Nacos 實(shí)現(xiàn)外部動態(tài)數(shù)據(jù)源

4.3.3 動態(tài)更新限流配置

在項(xiàng)目啟動過程中,在nacos中修改流控配置參數(shù)。將count 從100->400

Sentinel-Go中怎么利用Nacos 實(shí)現(xiàn)外部動態(tài)數(shù)據(jù)源

可以看到打印了重新loadRule的日志,流量控制動態(tài)的由100->400

Sentinel-Go中怎么利用Nacos 實(shí)現(xiàn)外部動態(tài)數(shù)據(jù)源

總結(jié)

在sentinel-go中使用nacos作為外部動態(tài)數(shù)據(jù)源,只需要將原來聲明Rule以及加載Rule的部分 變成從nacos數(shù)據(jù)源讀取。

在本文中只介紹了流量控制的集成,熔斷,warmup,熱點(diǎn)參數(shù)的集成也是相同的,只要按需修改配置的內(nèi)容即可

關(guān)鍵代碼:

h := datasource.NewFlowRulesHandler(datasource.FlowRulesJsonConverter)
    nds, err := nacos.NewNacosDataSource(client, "sentinel-go", "flow", h)
    if err != nil {
        fmt.Printf("Fail to create nacos data source client, err: %+v", err)
        return
    }
    err = nds.Initialize()
    if err != nil {
        fmt.Printf("Fail to initialize nacos data source client, err: %+v", err)
        return
    }

以上就是Sentinel-Go中怎么利用Nacos 實(shí)現(xiàn)外部動態(tài)數(shù)據(jù)源,小編相信有部分知識點(diǎn)可能是我們?nèi)粘9ぷ鲿姷交蛴玫降?。希望你能通過這篇文章學(xué)到更多知識。更多詳情敬請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI