This is the 7th day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021
introduce
Through a complete example, the implementation of [limiting flow] middleware in a Gin framework based microservice.
We will use RK-boot to start the Gin framework microservice.
Please visit rkdocs.net lilify. app/cn for the full tutorial
The installation
go get github.com/rookie-ninja/rk-boot
go get github.com/rookie-ninja/rk-gin
Copy the code
Quick start
1. Create the boot. Yaml
To verify, we enabled the following options:
- CommonService: commonService contains a set of common apis. details
We limit the flow for/RK/V1 / HEALTHY, set it to 0, and set the other apis to 100.
---
gin:
- name: greeter # Required
port: 8080 # Required
enabled: true # Required
commonService:
enabled: true # Optional, default: false
interceptors:
rateLimit:
enabled: true
reqPerSec: 100
paths:
- path: "/rk/v1/healthy"
reqPerSec: 0
Copy the code
2. Create a main. Go
// Copyright (c) 2021 rookie-ninja
//
// Use of this source code is governed by an Apache-style
// license that can be found in the LICENSE file.
package main
import (
"context"
"github.com/rookie-ninja/rk-boot"
_ "github.com/rookie-ninja/rk-gin/boot"
)
// Application entrance.
func main(a) {
// Create a new boot instance.
boot := rkboot.NewBoot()
// Bootstrap
boot.Bootstrap(context.Background())
// Wait for shutdown sig
boot.WaitForShutdownSig(context.Background())
}
Copy the code
3. Folder structure
$tree. └── Go. ├─ go. ├─ goCopy the code
4. Start the main. Go
$ go run main.go
Copy the code
5. Verify
- Traffic is limited when/rK /v1/healthy requests are sent
$ curl -X GET localhost:8080/rk/v1/healthy
{
"error":{
"code":429,
"status":"Too Many Requests",
"message":"",
"details":[
"slow down your request"
]
}
}
Copy the code
- Send /rk/v1/info request, normal
$ curl -X GET localhost:8080/rk/v1/info
{
"appName":"rk-demo",
"version":"master-2c9c6fd",
"description":"Internal RK entry which describes application with fields of appName, version and etc.",
"keywords":[],
"homeUrl":"",
"iconUrl":"",
"docsUrl":[],
"maintainers":[],
"uid":"501",
"gid":"20",
"username":"Dongxun Yin",
"startTime":"2021-11-14T00:32:09+08:00",
"upTimeSec":123,
"upTimeStr":"2 minutes",
"region":"",
"az":"",
"realm":"",
"domain":""
}
Copy the code
YAML options
The name | describe | type | The default value |
---|---|---|---|
gin.interceptors.rateLimit.enabled | Start the traffic limiting middleware | boolean | false |
gin.interceptors.rateLimit.algorithm | The traffic limiting algorithm supports tokenBucket and leakyBucket | string | tokenBucket |
gin.interceptors.rateLimit.reqPerSec | Full limited flow value | int | 0 |
gin.interceptors.rateLimit.paths.path | The HTTP path | string | “” |
gin.interceptors.rateLimit.paths.reqPerSec | Traffic limiting value based on HTTP path | int | 0 |