0

Micro v3 入门教程

 3 years ago
source link: https://www.fdevops.com/2020/12/31/micro-19519
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Micro v3 入门教程

兰玉磊 • 2020年12月31日 15:23 • Golang • 阅读 2625

本文翻译自官网

本文将通过全球入门实例 Hello World 的方式,来带领大家入门Micro v3。

Micro 是通过 protoc-gen-micro 来进行代码生成的,因此我们需要安装上对应的依赖库。

# 下载最新的 proto 稳定版
# https://github.com/protocolbuffers/protobuf/releases
go get github.com/golang/protobuf/protoc-gen-go
go get github.com/micro/micro/v3/cmd/protoc-gen-micro

使用 Go 进行安装

go get github.com/micro/micro/v3

二进制方式安装

# MacOS
curl -fsSL https://raw.githubusercontent.com/micro/micro/master/scripts/install.sh | /bin/bash
# Linux
wget -q  https://raw.githubusercontent.com/micro/micro/master/scripts/install.sh -O - | /bin/bash
# Windows
powershell -Command "iwr -useb https://raw.githubusercontent.com/micro/micro/master/scripts/install.ps1 | iex"

Docker镜像

docker pull micro/micro

Helm Chart

helm repo add micro https://micro.github.io/helm
helm install micro micro/micro

在开始服务程序之前,我们先运营一个现有的服务。

首先我们必须先执行 micro server,启动服务:

micro server

micro server 启动的服务进行交互之前,我们需要先进行登陆,账号是 admin,密码是 micro

$ micro login
Enter email address: admin
Enter Password:
Successfully logged in.

为了验证是否运行成功,执行 micro services 是否运行了以下服务:

$ micro services
broker
config
events
network
proxy
registry
runtime
server
store

github.com/micro/services 下面我们会看到有许多 Micro 作者写的各种服务,其中我们今天演示的例子 Hello World 就在这个下面。

接下来我们就来运行我们的 Hello World 了。

我们会使用 micro run 来运行我们的 Hello World

$ micro run github.com/micro/services/helloworld

查看运行服务的状态:

$ micro status
NAME        VERSION    SOURCE                    STATUS    BUILD    UPDATED    METADATA
helloworld    latest    github.com/micro/services/helloworld    running    n/a    4s ago    owner=admin, group=micro

查看指定服务的运行日志:

$ micro logs helloworld
2020-10-06 17:52:21  file=service/service.go:195 level=info Starting [service] helloworld
2020-10-06 17:52:21  file=grpc/grpc.go:902 level=info Server [grpc] Listening on [::]:33975
2020-10-06 17:52:21  file=grpc/grpc.go:732 level=info Registry [service] Registering node: helloworld-67627b23-3336-4b92-a032-09d8d13ecf95

到这里你的服务都是正常输出了这些信息,执行也没有问题的话,那么下面我们就要尝试调用这个服务了。

CLI 命令行工具

Micro会以以下格式自动为您的服务生成CLI命令:micro [service] [method],默认方法是 “Call”。

我们可以使用以下命令调用服务:

$ micro helloworld --name=Jane
    "msg": "Hello Jane"

查看命令行管理服务的帮助信息:

$ micro helloworld --help
NAME:
    micro helloworld
VERSION:
    latest
USAGE:
    micro helloworld [command]
COMMANDS:

查看命令行管理服务 方法 的帮助信息:

$ micro helloworld call --help
NAME:
    micro helloworld call
USAGE:
    micro helloworld call [flags]
FLAGS:
    --name string

API 接口

Micro在端口8080上公开了http API,因此可以直接通过8080访问对应的服务。

curl "http://localhost:8080/helloworld?name=John"

我们写一个小的客户端,来调用helloworld服务。

package main
import (
    "context"
    "fmt"
    "time"
    "github.com/micro/micro/v3/service"
    proto "github.com/micro/services/helloworld/proto"
func main() {
    // create and initialise a new service
    srv := service.New()
        // create the proto client for helloworld
        client := proto.NewHelloworldService("helloworld", srv.Client())
        // call an endpoint on the service
        rsp, err := client.Call(context.Background(), &proto.Request{
            Name: "John",
        if err != nil {
            fmt.Println("Error calling helloworld: ", err)
            return
        // print the response
        fmt.Println("Response: ", rsp.Msg)
        // let's delay the process for exiting for reasons you'll see below
        time.Sleep(time.Second * 5)

将示例保存在本地。

进入到新建的服务目录里面,然后执行 go mod init example ,并且使用 micro run运行服务。

micro run .

查看运行状态,到这里正常来说,我们应该有两个服务才对呢。

$ micro status
NAME        VERSION    SOURCE                                    STATUS    BUILD    UPDATED        METADATA
example        latest    example.tar.gz                            running    n/a     2s ago        owner=admin, group=micro
helloworld    latest    github.com/micro/services/helloworld    running    n/a        5m59s ago    owner=admin, group=micro

查看我们刚刚写的示例服务的日志,会返回 Hello World 服务的返回值,因为我们是调用的 Hello World

$ micro logs example
# some go build output here
Response:  Hello John

支持多种语言的客户端

不久,我们将发布由多语言grpc生成的客户端,以查询服务并也使用micro。

使用 micro new 来新建服务:

$ micro new helloworld
Creating service helloworld
├── main.go
├── generate.go
├── handler
│   └── helloworld.go
├── proto
│   └── helloworld.proto
├── Dockerfile
├── Makefile
├── README.md
├── .gitignore
└── go.mod
download protoc zip packages (protoc-$VERSION-$PLATFORM.zip) and install:
visit https://github.com/protocolbuffers/protobuf/releases
download protobuf for micro:
go get -u github.com/golang/protobuf/proto
go get -u github.com/golang/protobuf/protoc-gen-go
go get github.com/micro/micro/v3/cmd/protoc-gen-micro
compile the proto file helloworld.proto:
cd helloworld
make proto

从上面的输出可以看出,在构建第一个服务之前,必须安装以下工具,前面如果安装过了,此处可以省略:

安装以上三个库,是因为proto文件转Go语言代码需要用到。

使用以下命令从proto文件生成Go代码:

make proto

除其他有用的内置服务外,Micro还包括用于对数据进行持久化存储的服务。

CLI 命令行工具

首先,让我们看一下更基本的store CLI命令。

要保存一个值,我们使用write命令:

$ micro store write key1 value1

UNIX风格的无输出表示它被愉快地保存了。

读取数据:

$ micro store read key1

可以使用–verbose或-v,来进行更人性化的数据展示。

$ micro store read -v key1
KEY    VALUE   EXPIRY
key1   val1    None

我们可以使用–prefix或-p,搜索键具有某些前缀的数据。

为了验证这一点,我们先保存另一个值:

$ micro store write key2 val2

然后,我们可以列出key1和key2键,因为它们都共享通用前缀:

$ micro store read --prefix --verbose key
KEY    VALUE   EXPIRY
key1   val1    None
key2   val2    None

刚刚我们工作命令的方式从Go Micro服务中非常简单的进行数据的存取。

接下来我们创建一个服务可以读取的条目。 然而这次我们还将为Go Micro存储服务写命令指定表,因为每个服务在存储区中都有自己的表:

micro store write --table=example mykey "Hi there"

让我们修改我们先前编写的示例服务,以便它从存储中读取上述值,而不是调用服务。

package main
import (
    "fmt"
    "time"
    "github.com/micro/micro/v3/service"
    "github.com/micro/micro/v3/service/store"
func main() {
    srv := service.New(service.Name("example"))
    srv.Init()
    records, err := store.Read("mykey")
    if err != nil {
        fmt.Println("Error reading from store: ", err)
    if len(records) == 0 {
        fmt.Println("No records")
    for _, record := range records {
        fmt.Printf("key: %v, value: %v\n", record.Key, string(record.Value))
    time.Sleep(1 * time.Hour)

我们刚刚修改了我们的示例服务,也就是 example 服务。并且这个服务正在运行中,因此我们无法使用 micro run 再次运行这个服务,因此我们需要使用 micro update 来更新服务。

我们可以直接使用update命令进行更新,但是需要注意的是,一定要切换回示例服务的根目录:

micro update .

查看状态:

$ micro status example
NAME    VERSION    SOURCE    STATUS    BUILD    UPDATED    METADATA
example    latest    n/a        running    n/a        7s ago    owner=admin, group=micro

如果因为某些原因导致程序卡死了,可以使用以下方式进行重启:

micro kill example
micro run .

现在我们重新查看日志,如果返回的是存储的数据,那么就说明我们更新成功了。

$ micro logs example
key: mykey, value: Hi there

配置信息和密钥信息是任何生产系统中重要的组成部分,下面我们就来看下Go Micro Config是如何进行工作的。

CLI 命令行工具

简单使用:

$ micro config set key val
$ micro config get key

仅仅这种健值对的形式就已经满足了很多的应用场景。

同时 Go Micro Config 还支持嵌套的方式,如下:

$ micro config set key.subkey val
$ micro config get key.subkey

当我们获取这种嵌套配置的时候,会以Json的方式为我们返回数据。

$ micro config get key
{"subkey":"val"}

新增一组配置,依然是以JSON的数据格式返回。

$ micro config set key.othersubkey val2
$ micro config get key
{"othersubkey":"val2","subkey":"val"}

在其他服务中调用,其实也是类似的。

package main
import (
    "fmt"
    "github.com/micro/micro/v3/service"
    "github.com/micro/micro/v3/service/config"
func main() {
    // setup the service
    srv := service.New(service.Name("example"))
    srv.Init()
    // read config value
    val, _ := config.Get("key.subkey")
    fmt.Println("Value of key.subkey: ", val.String(""))

使用上面的方式更新服务,更新成功后,会输出一下结果。

$ micro logs example
Value of key.subkey:  val

本文为原创文章,未经授权禁止转载本站文章。
原文出处:兰玉磊的个人博客
原文链接:https://www.fdevops.com/2020/12/31/micro-19519
版权:本文采用「署名-非商业性使用-相同方式共享 4.0 国际」知识共享许可协议进行许可。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK