// Function is a one time executing Service
type Function interface {
// Inherits Service interface
Service
// Done signals to complete execution
Done() error
// Handle registers an RPC handler
Handle(v interface{}) error
// Subscribe registers a subscriber
Subscribe(topic string, v interface{}) error
}
1.初始化
一个函数就像使用micro.NewFunction一样创建。
import "github.com/micro/go-micro"
function := micro.NewFunction()
选项可以在创建过程中传入。
function := micro.NewFunction(
micro.Name("greeter"),
micro.Version("latest"),
)
Go Micro还提供了使用micro.Flags设置命令行标志的方法。
import (
"github.com/micro/cli"
"github.com/micro/go-micro"
)
function := micro.NewFunction(
micro.Flags(
cli.StringFlag{
Name: "environment",
Usage: "The environment",
},
)
)
解析标志使用function.Init。另外访问标志使用micro.Action选项。
function.Init(
micro.Action(func(c *cli.Context) {
env := c.StringFlag("environment")
if len(env) > 0 {
fmt.Println("Environment set to", env)
}
}),
)
// create the greeter client using the service name and client
greeter := proto.NewGreeterClient("greeter", function.Client())
// request the Hello method on the Greeter handler
rsp, err := greeter.Hello(context.TODO(), &proto.HelloRequest{
Name: "John",
})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(rsp.Greeter)
proto.NewGreeterClient接受函数名称和用于发出请求的客户端。
所有可用的选项可以在找到。
Go Micro提供了预定义的标志,如果调用了function.Init,它将被设置和解析。看到的所有标志。