Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 29 additions & 3 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,15 @@

## 🛠️ 管理脚本

本目录还提供了三个便捷的管理脚本,用于批量管理所有示例模块:
本目录还提供了四个便捷的管理脚本,用于批量管理所有示例模块:

### 脚本功能对比

| 脚本名称 | 主要功能 | 使用场景 | 执行效果 |
|---------|---------|---------|---------|
| **check_versions.sh** | 版本一致性检查 | 检查所有模块的依赖版本是否一致 | 显示版本分布统计,识别版本不一致问题 |
|---------|---------|---------|---------| | **check_versions.sh** | 版本一致性检查 | 检查所有模块的依赖版本是否一致 | 显示版本分布统计,识别版本不一致问题 |
| **update_polaris_versions.sh** | 批量版本更新 | 统一更新所有模块的polaris-go和Go版本 | 更新require依赖版本,忽略replace指令 |
| **batch_mod_tidy.sh** | 批量依赖整理 | 清理和整理所有模块的依赖关系 | 执行go mod tidy,统计成功/失败数量 |
| **batch_make_clean.sh** | 批量清理构建 | 清理所有子目录的构建产物 | 递归执行make clean,统计成功/失败数量 |

### 详细使用说明

Expand Down Expand Up @@ -109,6 +109,31 @@ chmod +x batch_mod_tidy.sh
- 成功/失败统计
- 详细的使用说明

#### 4. batch_make_clean.sh - 批量清理构建脚本

**功能**:批量执行 `make clean` 清理所有子目录的构建产物

**使用方法**:
```bash
# 给脚本执行权限
chmod +x batch_make_clean.sh

# 执行批量清理
./batch_make_clean.sh
```

**执行特点**:
- 🚀 自动发现所有包含Makefile的子目录
- 📁 跳过根目录的Makefile文件
- 🧹 递归执行make clean清理构建产物
- ✅/❌ 实时显示每个模块的执行状态
- 📊 提供执行结果统计

**输出信息**:
- 处理进度和状态
- 成功/失败统计
- 详细的使用说明

## 🚀 快速开始

1. **选择示例**:根据需要的功能选择对应的示例目录
Expand All @@ -122,6 +147,7 @@ chmod +x batch_mod_tidy.sh
- 建议先运行 `check_versions.sh` 检查版本一致性
- 如需更新版本,请使用 `update_polaris_versions.sh` 统一更新
- 定期使用 `batch_mod_tidy.sh` 整理依赖关系
- 使用 `batch_make_clean.sh` 可以快速清理所有子目录的构建产物

## 🔗 相关链接

Expand Down
68 changes: 68 additions & 0 deletions examples/batch_make_clean.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
#!/bin/bash

# 批量执行 make clean 脚本
# 用于递归清理所有包含 Makefile 的子目录

set -e # 遇到错误立即退出

echo "🚀 开始批量执行 make clean..."

# 计数器
success_count=0
fail_count=0
total_count=0

# 查找所有包含 Makefile 或 makefile 的目录
find . \( -name "Makefile" -o -name "makefile" \) -type f | while read -r makefile; do
# 获取目录路径
dir=$(dirname "$makefile")

# 跳过根目录的 Makefile(如果存在)
if [ "$dir" = "." ]; then
continue
fi

total_count=$((total_count + 1))

echo "📁 处理目录: $dir"

# 进入目录并执行 make clean
if cd "$dir"; then
echo " 🧹 执行: make clean"

if make clean 2>&1; then
echo " ✅ 成功: $dir"
success_count=$((success_count + 1))
else
echo " ❌ 失败: $dir"
fail_count=$((fail_count + 1))
fi

# 返回上级目录
cd - > /dev/null
else
echo " ❌ 无法进入目录: $dir"
fail_count=$((fail_count + 1))
fi

echo "---"
done

echo "📊 执行结果统计:"
echo " 总模块数: $total_count"
echo " 成功数: $success_count"
echo " 失败数: $fail_count"

if [ $fail_count -eq 0 ]; then
echo "🎉 所有模块的 make clean 执行成功!"
else
echo "⚠️ 有 $fail_count 个模块执行失败,请检查相关目录"
fi

# 可选:显示使用说明
echo ""
echo "💡 使用说明:"
echo " 1. 给脚本执行权限: chmod +x batch_make_clean.sh"
echo " 2. 运行脚本: ./batch_make_clean.sh"
echo " 3. 脚本会自动跳过根目录的 Makefile 文件(如果存在)"
echo " 4. 每个模块执行完成后会显示状态"
46 changes: 46 additions & 0 deletions examples/circuitbreaker/instance/consumer/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
* specific language governing permissions and limitations under the License.
*/

package main

Check warning on line 18 in examples/circuitbreaker/instance/consumer/main.go

View workflow job for this annotation

GitHub Actions / Run Revive Action (1.19.x)

should have a package comment

import (
"flag"
Expand All @@ -33,6 +33,7 @@
"time"

"github.com/polarismesh/polaris-go"
"github.com/polarismesh/polaris-go/api"
"github.com/polarismesh/polaris-go/pkg/config"
"github.com/polarismesh/polaris-go/pkg/model"
)
Expand All @@ -46,6 +47,7 @@
port int
token string
configPath string
debug bool
)

func initArgs() {
Expand All @@ -57,6 +59,7 @@
flag.IntVar(&port, "port", 18080, "port")
flag.StringVar(&token, "token", "", "token")
flag.StringVar(&configPath, "config", "./polaris.yaml", "path for config file")
flag.BoolVar(&debug, "debug", false, "debug")
}

// PolarisClient is a consumer of the circuit breaker calleeService.
Expand All @@ -69,6 +72,26 @@
webSvr *http.Server
}

// reportServiceCallResult 上报服务调用结果的辅助方法
func (svr *PolarisClient) reportServiceCallResult(instance model.Instance, retStatus model.RetStatus, statusCode int, delay time.Duration) {
ret := &polaris.ServiceCallResult{
ServiceCallResult: model.ServiceCallResult{
EmptyInstanceGauge: model.EmptyInstanceGauge{},
CalledInstance: instance,
Method: "/echo",
RetStatus: retStatus,
},
}
ret.SetDelay(delay)
ret.SetRetCode(int32(statusCode))
if err := svr.consumer.UpdateServiceCallResult(ret); err != nil {
log.Printf("do report service call result : %+v", err)
} else {
log.Printf("report service call result success: instance=%s:%d, status=%v, retCode=%d, delay=%v",
instance.GetHost(), instance.GetPort(), ret.RetStatus, ret.GetRetCode(), delay)
}
}

func (svr *PolarisClient) discoverInstance() (model.Instance, error) {
svr.printAllInstances()
getOneRequest := &polaris.GetOneInstanceRequest{}
Expand All @@ -90,7 +113,7 @@
}

func (svr *PolarisClient) runWebServer() {
http.HandleFunc("/echo", func(rw http.ResponseWriter, r *http.Request) {

Check warning on line 116 in examples/circuitbreaker/instance/consumer/main.go

View workflow job for this annotation

GitHub Actions / Run Revive Action (1.20.x)

parameter 'r' seems to be unused, consider removing or renaming it as _
log.Printf("start to invoke getOneInstance operation")
instance, err := svr.discoverInstance()
if err != nil || instance == nil {
Expand All @@ -111,6 +134,11 @@
instance.GetHost(), instance.GetPort(), err)))

time.Sleep(time.Millisecond * time.Duration(rand.Intn(10)))

// 上报服务调用结果
delay := time.Since(start)
svr.reportServiceCallResult(instance, model.RetFail, http.StatusInternalServerError, delay)

// 上报熔断结果,用于熔断计算
svr.reportCircuitBreak(instance, model.RetFail, strconv.Itoa(http.StatusInternalServerError), start)
return
Expand All @@ -119,6 +147,16 @@

defer resp.Body.Close()

// 上报服务调用结果
delay := time.Since(start)
retStatus := model.RetSuccess
if resp.StatusCode == http.StatusTooManyRequests {
retStatus = model.RetFlowControl
} else if resp.StatusCode != http.StatusOK {
retStatus = model.RetFail
}
svr.reportServiceCallResult(instance, retStatus, resp.StatusCode, delay)

// 上报熔断结果,用于熔断计算
if resp.StatusCode != http.StatusOK {
svr.reportCircuitBreak(instance, model.RetFail,
Expand Down Expand Up @@ -271,6 +309,14 @@
log.Print("calleeNamespace and calleeService are required")
return
}
if debug {
// 设置日志级别为DEBUG
if err := api.SetLoggersLevel(api.DebugLog); err != nil {
log.Printf("fail to set log level to DEBUG, err is %v", err)
} else {
log.Printf("successfully set log level to DEBUG")
}
}
cfg, err := config.LoadConfigurationByFile(configPath)
if err != nil {
log.Fatalf("load configuration by file %s failed: %v", configPath, err)
Expand Down
42 changes: 42 additions & 0 deletions examples/circuitbreaker/instance/consumer/polaris.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,45 @@ global:
type: push
address: ${POLARIS_SERVER}:9091
interval: 10s
#描述:主调端配置
consumer:
#描述:节点熔断相关配置
circuitBreaker:
#描述:是否启用节点熔断功能
#类型:bool
#默认值:true
enable: true
# 描述:是否启用默认熔断规则
#类型:bool
#默认值:true
defaultRuleEnable: true
# 描述:连续错误数熔断器默认连续错误数
#类型:int
#默认值:10
defaultErrorCount: 10
# 描述:错误率熔断器默认错误率
#类型:int
#默认值:50
defaultErrorPercent: 50
# 描述:错误率熔断器默认统计周期
#类型:int64
#默认值:60s
defaultInterval: 60s
# 描述:错误率熔断器默认最小请求数
#类型:int
#默认值:10
defaultMinimumRequest: 10
#描述:熔断周期,被熔断后多久可以变为半开
#类型:duration
#默认值:30s
sleepWindow: 30s
#描述:半开状态后多少个成功请求则恢复
#类型:int
#默认值:3
successCountAfterHalfOpen: 3
#描述:熔断策略,SDK会根据策略名称加载对应的熔断器插件
#类型:list
#范围:已注册的熔断器插件名
#默认值:composite 适配服务/接口/实例 熔断插件
chain:
- composite
3 changes: 3 additions & 0 deletions examples/quickstart/consumer/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,14 @@ import (
var (
namespace string
service string
hashkey string
port int64
)

func initArgs() {
flag.StringVar(&namespace, "namespace", "default", "namespace")
flag.StringVar(&service, "service", "DiscoverEchoServer", "service")
flag.StringVar(&hashkey, "hashkey", "", "")
flag.Int64Var(&port, "port", 18080, "port")
}

Expand Down Expand Up @@ -106,6 +108,7 @@ func (svr *PolarisConsumer) runWebServer() {
getOneRequest := &polaris.GetOneInstanceRequest{}
getOneRequest.Namespace = req.Namespace
getOneRequest.Service = req.Service
getOneRequest.HashKey = []byte(hashkey)
oneInstResp, err := svr.consumer.GetOneInstance(getOneRequest)
if err != nil {
log.Printf("[error] fail to getOneInstance, err is %v", err)
Expand Down
25 changes: 20 additions & 5 deletions pkg/config/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -432,16 +432,13 @@ type CircuitBreakerConfig interface {
// SetChain 设置熔断器插件链
SetChain([]string)
// GetCheckPeriod 熔断器定时检测时间
// Deprecated: 不在使用
GetCheckPeriod() time.Duration
// SetCheckPeriod 设置熔断器定时检测时间
// Deprecated: 不在使用
SetCheckPeriod(time.Duration)
// GetSleepWindow 获取熔断周期
// Deprecated: 不在使用
GetSleepWindow() time.Duration
// SetSleepWindow 设置熔断周期
// Deprecated: 不在使用
SetSleepWindow(interval time.Duration)
// GetRequestCountAfterHalfOpen 获取半开状态后最多分配多少个探测请求
// Deprecated: 不在使用
Expand All @@ -450,10 +447,8 @@ type CircuitBreakerConfig interface {
// Deprecated: 不在使用
SetRequestCountAfterHalfOpen(count int)
// GetSuccessCountAfterHalfOpen 获取半开状态后多少个成功请求则恢复
// Deprecated: 不在使用
GetSuccessCountAfterHalfOpen() int
// SetSuccessCountAfterHalfOpen 设置半开状态后多少个成功请求则恢复
// Deprecated: 不在使用
SetSuccessCountAfterHalfOpen(count int)
// GetRecoverWindow 获取半开后的恢复周期,按周期来进行半开放量的统计
// Deprecated: 不在使用
Expand All @@ -473,6 +468,26 @@ type CircuitBreakerConfig interface {
// GetErrorRateConfig 错误率熔断配置
// Deprecated: 不在使用
GetErrorRateConfig() ErrorRateConfig
// IsDefaultRuleEnable 是否启用默认实例级熔断规则
IsDefaultRuleEnable() bool
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

是否需要添加注释?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

加了,再看下

// SetDefaultRuleEnable 设置是否启用默认实例级熔断规则
SetDefaultRuleEnable(enable bool)
// GetDefaultErrorCount 获取默认实例级熔断连续错误数阈值
GetDefaultErrorCount() int
// SetDefaultErrorCount 设置默认实例级熔断连续错误数阈值
SetDefaultErrorCount(count int)
// GetDefaultErrorPercent 获取默认实例级熔断错误率阈值(百分比)
GetDefaultErrorPercent() int
// SetDefaultErrorPercent 设置默认实例级熔断错误率阈值(百分比)
SetDefaultErrorPercent(rate int)
// GetDefaultInterval 获取默认实例级熔断统计时间窗口
GetDefaultInterval() time.Duration
// SetDefaultInterval 设置默认实例级熔断统计时间窗口
SetDefaultInterval(interval time.Duration)
// GetDefaultMinimumRequest 获取默认实例级熔断最小请求数阈值
GetDefaultMinimumRequest() int
// SetDefaultMinimumRequest 设置默认实例级熔断最小请求数阈值
SetDefaultMinimumRequest(count int)
}

// Configuration 全量配置对象.
Expand Down
Loading
Loading