github.com/qiniu/go-sdk/v7@v7.27.0/examples/sandbox_idempotency_retry/main.go (about)

     1  package main
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"log"
     7  	"os"
     8  	"time"
     9  
    10  	"github.com/qiniu/go-sdk/v7/sandbox"
    11  )
    12  
    13  func main() {
    14  	if err := run(); err != nil {
    15  		log.Fatal(err)
    16  	}
    17  }
    18  
    19  func run() error {
    20  	apiKey := os.Getenv("QINIU_API_KEY")
    21  	if apiKey == "" {
    22  		return fmt.Errorf("请设置 QINIU_API_KEY 环境变量")
    23  	}
    24  
    25  	apiURL := os.Getenv("QINIU_SANDBOX_API_URL")
    26  
    27  	c, err := sandbox.NewClient(&sandbox.Config{
    28  		APIKey:   apiKey,
    29  		Endpoint: apiURL,
    30  	})
    31  	if err != nil {
    32  		return fmt.Errorf("创建客户端失败: %w", err)
    33  	}
    34  
    35  	ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second)
    36  	defer cancel()
    37  
    38  	timeout := int32(300)
    39  
    40  	// 指定相同的幂等键连续创建两次,第二次应返回同一沙箱
    41  	idempotencyKey := fmt.Sprintf("sdk-example-%d", time.Now().Unix())
    42  	fmt.Printf("幂等键: %s\n\n", idempotencyKey)
    43  
    44  	// 第一次创建
    45  	sb1, err := c.Create(ctx, sandbox.CreateParams{
    46  		TemplateID:     "base",
    47  		Timeout:        &timeout,
    48  		IdempotencyKey: idempotencyKey,
    49  	})
    50  	if err != nil {
    51  		return fmt.Errorf("第一次创建失败: %w", err)
    52  	}
    53  	defer cleanupSandbox(sb1)
    54  	fmt.Printf("第一次创建: %s\n", sb1.ID())
    55  
    56  	// 第二次创建 — 同一幂等键,应返回同一沙箱
    57  	sb2, err := c.Create(ctx, sandbox.CreateParams{
    58  		TemplateID:     "base",
    59  		Timeout:        &timeout,
    60  		IdempotencyKey: idempotencyKey,
    61  	})
    62  	if err != nil {
    63  		return fmt.Errorf("第二次创建失败: %w", err)
    64  	}
    65  	if sb2.ID() != sb1.ID() {
    66  		defer cleanupSandbox(sb2)
    67  	}
    68  	fmt.Printf("第二次创建: %s\n", sb2.ID())
    69  
    70  	if sb1.ID() == sb2.ID() {
    71  		fmt.Println("\n幂等重试验证通过:两次创建返回同一沙箱")
    72  	} else {
    73  		return fmt.Errorf("幂等重试验证失败:两次创建返回不同沙箱: %s vs %s", sb1.ID(), sb2.ID())
    74  	}
    75  
    76  	return nil
    77  }
    78  
    79  func cleanupSandbox(sb *sandbox.Sandbox) {
    80  	killCtx, killCancel := context.WithTimeout(context.Background(), 10*time.Second)
    81  	defer killCancel()
    82  	if err := sb.Kill(killCtx); err != nil {
    83  		log.Printf("清理沙箱 %s 失败: %v", sb.ID(), err)
    84  		return
    85  	}
    86  	log.Printf("沙箱 %s 已清理", sb.ID())
    87  }