golang微服务框架go-micro使用 (二) Ultimate Guide For Bootstrap

本文介绍了Go Micro框架的使用,包括启动程序的四个部分:依赖、创建与初始化服务、注册业务处理程序和启动服务。重点讲解了NewService方法的多种选项,如服务名称、版本、地址、注册超时时间等,以及如何注册处理程序和启动服务。最后,文章提到了如何检查服务的运行状态,并通过访问HTTP端口查看服务信息。
摘要由CSDN通过智能技术生成

启动程序说明

package main

import (
	"github.com/micro/go-micro/v2"
	log "github.com/micro/go-micro/v2/logger"
	"micro-hello/handler"
	hello "micro-hello/proto/hello"
	"micro-hello/subscriber"
)

func main() {
   
	// New Service
	service := micro.NewService(
		micro.Name("com.foo.service.micro"),
		micro.Version("latest"),
	)

	// Initialise service
	service.Init()

	// Register Handler
	hello.RegisterMicroHandler(service.Server(), new(handler.Micro))

	// Register Struct as Subscriber
	micro.RegisterSubscriber("go.micro.service.micro", service.Server(), new(subscriber.Micro))

	// Run service
	if err := service.Run(); err != nil {
   
		log.Fatal(err)
	}
}

代码可分为4部分:

依赖

特别注意这行代码

	hello "micro-hello/proto/hello"

我们给micro-hello/proto/hello 起了别名hello, 这也是micro的惯例:给所有接口包设置别名。

创建与初始化服务
	// New Service
	service := micro.NewService(
		micro.Name("com.foo.service.micro"),
		micro.Version("latest"),
	)

我们使用func NewService(opts …Option) Service {}方法去创建爱你一个服务,这个方法可以接收多个micro.Option作为参数。共有29个参数来控制服务。

  • 1 micro.Name,指定服务名称。默认是go.micro.server。
// Name of the service
func Name(n string) Option {
   
	return func(o *Options) {
   
		o.Server.Init(server.Name(n))
	}
}
  • 2 micro.Version指定服务版本,默认是启动时间的格式化字符串。使用正确的版本号,结合正确的选择器,我们可以实现优雅的轮换升级,灰度测试,A/B测试及其他操作
// Version of the service
func Version(v string) Option {
   
	return func(o *Options) {
   
		o.Server.Init(server.Version(v))
	}
}
  • 3 micro.Address 指定grpc地址,默认是本地并且随机端口。因为使用Registry进行服务发现,所以随机端口并不影响。然而,实践中通常会固定一个端口,有利于管控与安全
func Address(addr string) Option {
   
	return func(o *Options) {
   
		o.Server.Init(server.Address(addr))
	}
}
  • 4 micro.RegisterTTL 指定服务注册超时时间,默认1分钟
// RegisterTTL specifies the TTL to use when registering the service
func RegisterTTL(t time.Duration) Option {
   
	return func(o *Options) {
   
		o.Server.Init(server.RegisterTTL(t))
	}
}
  • 5 micro.RegisterInterval 指定服务向registry报告状态的时间间隔。避免服务停机时注册信息出现错误
// RegisterInterval specifies the interval on which to re-register
func RegisterInterval(t time.Duration) Option {
   
	return func(o *Options) {
   
		o.Server.Init(server.RegisterInterval(t))
	}
}
  • 6 WrapHandler 从概念上讲与中间件类似,集中控制方法的行为。可以有多层,执行顺序从外向内
// WrapHandler adds a handler Wrapper to a list of options passed into the server
func WrapHandler(w ...server.HandlerWrapper) Option {
   
	return func(o *Options) {
   
		var wrappers []server.Option

		for _, wrap := range w {
   
			wrappers = append(wrappers, server.WrapHandler(wrap))
		}

		// Init once
		o.Server.Init(wrappers...)
	}
}
// HandlerWrapper wraps the HandlerFunc and returns the equivalent
type HandlerWrapper func(HandlerFunc) HandlerFunc

// HandlerFunc represents a single method of a handler. It's used primarily
// for the wrappers. What's handed to the actual method is the concrete
// request and response types.
type HandlerFunc func(ctx context.Context, req Request, rsp interface{
   }) error
  • 7 micro.WrapSubscriber 与 WrapHandler 类似,除了它是用于异步消息传递
// WrapSubscriber adds a subscriber Wrapper to a list of options passed into the server
func WrapSubscriber(w ...server.SubscriberWrapper) Option {
   
	return func(o *Options) {
   
		var wrappers []server.Option

		for _, wrap := range w {
   
			wrappers = append(wrappers, server.WrapSubscriber(wrap))
		}

		// Init once
		o.Server.Init(wrappers...)
	}
}
// SubscriberWrapper wraps the SubscriberFunc and returns the equivalent
type SubscriberWrapper func(SubscriberFunc) SubscriberFunc

// SubscriberFunc represents a single method of a subscriber. It's used primarily
// for the wrappers. What's handed to the actual method is the concrete
// publication message.
type SubscriberFunc func(ctx context.Context, msg Message) error

// Message is an async message interface
type Message interface {
   
	// Topic of the message
	Topic() string
	// The decoded payload value
	Payload() interface{
   }
	// The content type of the payload
	ContentType() string
	// The raw headers of the message
	Header() map[string]string
	// The raw body of the message
	Body() []byte
	// Codec used to decode the message
	Codec() codec.Reader
}
  • 8 micro.WrapCall 包装来自客户端的每个方法调用
// WrapCall is a convenience method for wrapping a Client CallFunc
func WrapCall(w ...client.CallWrapper) Option {
   
	return func(o *Options) {
   
		o.Client.Init(client.WrapCall(w...))
	}
}
// CallFunc represents the individual call func
type CallFunc func(ctx context.Context, node *registry.Node, req Request, rsp interface{
   }, opts CallOptions) error

// CallWrapper is a low level wrapper for the CallFunc
type CallWrapper func(CallFunc) CallFunc
  • 9 micro.WrapClient 包装服务链接,可以应用于多个层次,执行顺序由内到外
// WrapClient is a convenience method for wrapping a Client with
// some middleware component. A list of wrappers can be provided.
// Wrappers are applied in reverse order so the last is executed first.
func WrapClient(w ...client.Wrapper) Option {
   
	return func(o *Options) {
   
		// apply in reverse
		for i := len(w); i > 0; i-- {
   
			o.Client = w[i-1](o.Client)
		}
	}
}
// Wrapper wraps a client and returns a client
type Wrapper func(Client) Client

// Client is the interface used to make requests to services.
// It supports Request/Response via Transport and Publishing via the Broker.
// It also supports bidirectional streaming of requests.
type Client interface {
   
	Init(...Option) error
	Options() Options
	NewMessage(topic string, msg interface{
   }, opts ...MessageOption) Message
	NewRequest(service, endpoint string, req interface{
   }, reqOpts ...RequestOption) Request
	Call(ctx context.Context, req Request, rsp interface{
   }, opts ...CallOption) error
	Stream(ctx context.Context
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值