Table Store实时数据通道服务Go SDK快速入门

本文涉及的产品
对象存储 OSS,标准 - 本地冗余存储 20GB 3个月
对象存储 OSS,内容安全 1000 次 1年
对象存储OSS,敏感数据保护2.0 200GB 1年
简介: # Tunnel Service Go SDK ## 安装 * 下载源码包 ```bash go get github.com/aliyun/aliyun-tablestore-go-sdk/tunnel ``` * 安装依赖 * 可以在tunnel目录下使用dep安装依赖 * 安装[dep](https://github.

文档

安装

  • 下载源码包
go get github.com/aliyun/aliyun-tablestore-go-sdk/tunnel
  • 安装依赖

    1. 可以在tunnel目录下使用dep安装依赖
dep ensure -v
  1. 也可以直接使用go get安装依赖包:
go get -u go.uber.org/zap
go get github.com/cenkalti/backoff
go get github.com/golang/protobuf/proto
go get github.com/satori/go.uuid
go get github.com/stretchr/testify/assert
go get github.com/smartystreets/goconvey/convey
go get github.com/golang/mock/gomock
go get gopkg.in/natefinch/lumberjack.v2

快速开始

  • 初始化Tunnel client:
// endpoint是表格存储实例endpoint,如https://instance.cn-hangzhou.ots.aliyun.com
// instance为实例名称
// accessKeyId和accessKeySecret分别为访问表格存储服务的AccessKey的Id和Secret
tunnelClient := tunnel.NewTunnelClient(endpoint, instance,
   accessKeyId, accessKeySecret)
  • 创建新Tunnel:
req := &tunnel.CreateTunnelRequest{
   TableName:  "testTable",
   TunnelName: "testTunnel",
   Type:       tunnel.TunnelTypeBaseStream, //全量加增量类型Tunnel
}
resp, err := tunnelClient.CreateTunnel(req)
if err != nil {
   log.Fatal("create test tunnel failed", err)
}
log.Println("tunnel id is", resp.TunnelId)
  • 获取已有Tunnel信息:
req := &tunnel.DescribeTunnelRequest{
   TableName:  "testTable",
   TunnelName: "testTunnel",
}
resp, err := tunnelClient.DescribeTunnel(req)
if err != nil {
   log.Fatal("create test tunnel failed", err)
}
log.Println("tunnel id is", resp.Tunnel.TunnelId)
  • 注册callback,开始数据消费:
//用户定义消费callback函数
func exampleConsumeFunction(ctx *tunnel.ChannelContext, records []*tunnel.Record) error {
    fmt.Println("user-defined information", ctx.CustomValue)
    for _, rec := range records {
        fmt.Println("tunnel record detail:", rec.String())
    }
    fmt.Println("a round of records consumption finished")
    return nil
}
//配置callback到SimpleProcessFactory,配置消费端TunnelWorkerConfig
workConfig := &tunnel.TunnelWorkerConfig{
   ProcessorFactory: &tunnel.SimpleProcessFactory{
      CustomValue: "user custom interface{} value",
      ProcessFunc: exampleConsumeFunction,
   },
}
//使用TunnelDaemon持续消费指定tunnel
daemon := tunnel.NewTunnelDaemon(tunnelClient, tunnelId, workConfig)
log.Fatal(daemon.Run())
  • 删除Tunnel
req := &tunnel.DeleteTunnelRequest {
   TableName: "testTable",
   TunnelName: "testTunnel",
}
_, err := tunnelClient.DeleteTunnel(req)
if err != nil {
   log.Fatal("delete test tunnel failed", err)
}

配置项

  • tunnel client配置
    初始化tunnel client时可以通过NewTunnelClientWithConfig接口自定义客户端配置,使用不指定config初始化接口或者config为nil时会使用DefaultTunnelConfig:
var DefaultTunnelConfig = &TunnelConfig{
      //最大指数退避重试时间
      MaxRetryElapsedTime: 45 * time.Second,
      //HTTP请求超时时间
      RequestTimeout:      30 * time.Second,
      //http.DefaultTransport
      Transport:           http.DefaultTransport,
}
  • 数据消费worker配置
    TunnelWorkerConfig中包含了数据消费worker需要的配置,其中ProcessorFactory为必填项,其余字段不填将使用默认值,通常使用默认值即可:
type TunnelWorkerConfig struct {
   //worker同Tunnel服务的心跳超时时间,通常使用默认值即可
   HeartbeatTimeout  time.Duration
   //worker发送心跳的频率,通常使用默认值即可
   HeartbeatInterval time.Duration
   //tunnel下消费连接建立接口,通常使用默认值即可
   ChannelDialer     ChannelDialer

   //消费连接上具体处理器产生接口,通常使用callback函数初始化SimpleProcessFactory即可
   ProcessorFactory ChannelProcessorFactory

   //zap日志配置,默认值为DefaultLogConfig
   LogConfig      *zap.Config
   //zap日志轮转配置,默认值为DefaultSyncer
   LogWriteSyncer zapcore.WriteSyncer
}

其中的ProcessorFactory为用户注册消费callback函数以及其他信息的接口,建议使用SDK中自带SimpleProcessorFactory实现:

type SimpleProcessFactory struct {
   //用户自定义信息,会传递到ProcessFunc和ShutdownFunc中的ChannelContext参数中
   CustomValue interface{}

   //Worker记录checkpoint的间隔,CpInterval<=0时会使用DefaultCheckpointInterval
   CpInterval time.Duration

   //worker数据处理的同步调用callback,ProcessFunc返回error时worker会用本批数据退避重试ProcessFunc
   ProcessFunc  func(channelCtx *ChannelContext, records []*Record) error
   //worker退出时的同步调用callback
   ShutdownFunc func(channelCtx *ChannelContext)

   //日志配置,Logger为nil时会使用DefaultLogConfig初始化logger
   Logger *zap.Logger
}
  • 日志配置
    默认日志配置:
//DefaultLogConfig是TunnelWorkerConfig和SimpleProcessFactory使用的默认日志配置
var DefaultLogConfig = zap.Config{
   Level:       zap.NewAtomicLevelAt(zap.InfoLevel),
   Development: false,
   Sampling: &zap.SamplingConfig{
      Initial:    100,
      Thereafter: 100,
   },
   Encoding: "json",
   EncoderConfig: zapcore.EncoderConfig{
      TimeKey:        "ts",
      LevelKey:       "level",
      NameKey:        "logger",
      CallerKey:      "caller",
      MessageKey:     "msg",
      StacktraceKey:  "stacktrace",
      LineEnding:     zapcore.DefaultLineEnding,
      EncodeLevel:    zapcore.LowercaseLevelEncoder,
      EncodeTime:     zapcore.ISO8601TimeEncoder,
      EncodeDuration: zapcore.SecondsDurationEncoder,
      EncodeCaller:   zapcore.ShortCallerEncoder,
   },
}

日志轮转配置:

//DefaultSyncer是TunnelWorkerConfig和SimpleProcessFactory使用的默认日志轮转配置
var DefaultSyncer = zapcore.AddSync(&lumberjack.Logger{
   //日志文件路径
   Filename:   "tunnelClient.log",
   //最大日志文件大小
   MaxSize:    512, //MB
   //压缩轮转的日志文件数
   MaxBackups: 5,
   //轮转日志文件保留的最大天数
   MaxAge:     30, //days
   //是否压缩轮转日志文件
   Compress:   true,
})
相关实践学习
阿里云表格存储使用教程
表格存储(Table Store)是构建在阿里云飞天分布式系统之上的分布式NoSQL数据存储服务,根据99.99%的高可用以及11个9的数据可靠性的标准设计。表格存储通过数据分片和负载均衡技术,实现数据规模与访问并发上的无缝扩展,提供海量结构化数据的存储和实时访问。 产品详情:https://www.aliyun.com/product/ots
目录
相关文章
|
5月前
|
Go 开发者
Go 并发编程基础:无缓冲与有缓冲通道
本章深入探讨Go语言中通道(Channel)的两种类型:无缓冲通道与有缓冲通道。无缓冲通道要求发送和接收必须同步配对,适用于精确同步和信号通知;有缓冲通道通过内部队列实现异步通信,适合高吞吐量和生产者-消费者模型。文章通过示例对比两者的行为差异,并分析死锁风险及使用原则,帮助开发者根据场景选择合适的通道类型以实现高效并发编程。
|
7月前
|
SQL 监控 Go
新一代 Cron-Job分布式调度平台,v1.0.8版本发布,支持Go执行器SDK!
现代化的Cron-Job分布式任务调度平台,支持Go语言执行器SDK,多项核心优势优于其他调度平台。
116 8
|
12月前
|
存储 Go 开发者
Go语言中的并发编程与通道(Channel)的深度探索
本文旨在深入探讨Go语言中并发编程的核心概念和实践,特别是通道(Channel)的使用。通过分析Goroutines和Channels的基本工作原理,我们将了解如何在Go语言中高效地实现并行任务处理。本文不仅介绍了基础语法和用法,还深入讨论了高级特性如缓冲通道、选择性接收以及超时控制等,旨在为读者提供一个全面的并发编程视角。
250 50
|
12月前
|
安全 Java Go
Go语言中的并发编程:掌握goroutine与通道的艺术####
本文深入探讨了Go语言中的核心特性——并发编程,通过实例解析goroutine和通道的高效使用技巧,旨在帮助开发者提升多线程程序的性能与可靠性。 ####
|
安全 Go 调度
探索Go语言的并发模式:协程与通道的协同作用
Go语言以其并发能力闻名于世,而协程(goroutine)和通道(channel)是实现并发的两大利器。本文将深入了解Go语言中协程的轻量级特性,探讨如何利用通道进行协程间的安全通信,并通过实际案例演示如何将这两者结合起来,构建高效且可靠的并发系统。
|
Kubernetes API 开发工具
【Azure Developer】通过SDK(for python)获取Azure服务生命周期信息
需要通过Python SDK获取Azure服务的一些通知信息,如:K8S版本需要更新到指定的版本,Azure服务的维护通知,服务处于不健康状态时的通知,及相关的操作建议等内容。
149 18
|
算法 数据挖掘 数据库
表格存储低成本向量检索服务助力 AI 检索
本文阐述了阿里云表格存储(Tablestore)如何通过其向量检索服务应对大规模数据检索的需求,尤其是在成本、规模和召回率这三个关键挑战方面。
345 13
|
API 开发工具 网络架构
【Azure Developer】使用Python SDK去Azure Container Instance服务的Execute命令的疑问解释
【Azure Developer】使用Python SDK去Azure Container Instance服务的Execute命令的疑问解释
103 0
【Azure Developer】使用Python SDK去Azure Container Instance服务的Execute命令的疑问解释
|
存储 安全 Go
Go 并发编程精粹:掌握通道(channels)的艺术
Go 并发编程精粹:掌握通道(channels)的艺术