Copyright © 2022-2025 aizws.net · 网站版本: v1.2.6·内部版本: v1.25.2·
页面加载耗时 0.00 毫秒·物理内存 169.2MB ·虚拟内存 1438.9MB
欢迎来到 AI 中文社区(简称 AI 中文社),这里是学习交流 AI 人工智能技术的中文社区。 为了更好的体验,本站推荐使用 Chrome 浏览器。
Go Micro 是一个插件化的 RPC 开发框架,用于使用 Go 语言快速构建微服务。
测试 Go Micro Web 服务可以使用 curl,比如测试 http://localhost:8081/user:
$ curl -H "Content-Type: application/json" -X POST http://localhost:8081/user
输出结果:
{
"msg": "user api"
}
使用 Go Micro Web API 客户端调用 go.micro.api.user 服务。以下为客户端程序 main.go:
package main
import (
"context"
"github.com/micro/go-micro/client"
"github.com/micro/go-micro/util/log"
"github.com/micro/go-plugins/client/http"
)
func main() {
// 创建 http 客户端
httpClient := http.NewClient(
client.ContentType("application/json"),
)
// 创建 go.micro.api.user 服务的 /user 请求
req := httpClient.NewRequest("go.micro.api.user", "/user", nil)
// 返回结果的结构体
var response struct {
Msg string
}
// 调用 http 请求,返回结果
err := httpClient.Call(context.Background(), req, &response)
if err != nil {
log.Error(err)
return
}
// 打印返回结果
log.Info(response.Msg)
}
注意不要忘记 client.ContentType("application/json")。
输出结果:
user api
客户端增加轮询 RoundRobin 均衡算法调用 go.micro.api.user 服务。以下为客户端程序 main.go:
package main
import (
"context"
"github.com/micro/go-micro/client"
"github.com/micro/go-micro/client/selector"
"github.com/micro/go-micro/util/log"
"github.com/micro/go-plugins/client/http"
)
func main() {
// 创建轮询 RoundRobin 均衡算法
rrSelector := selector.NewSelector(
selector.SetStrategy(selector.RoundRobin),
)
// 创建 http 客户端
httpClient := http.NewClient(
client.Selector(rrSelector),
client.ContentType("application/json"),
)
// 创建 go.micro.api.user 服务的 /user 请求
req := httpClient.NewRequest("go.micro.api.user", "/user", nil)
// 返回结果的结构体
var response struct {
Msg string
}
// 调用 http 请求,返回结果
err := httpClient.Call(context.Background(), req, &response)
if err != nil {
log.Error(err)
return
}
// 打印返回结果
log.Info(response.Msg)
}
输出结果:
user api
在构建微服务时,使用服务注册和发现可以减少配置的复杂性。注册机制提供了一个服务发现机制来将名称解析为地址。它可以由consul,etcd,zookeeper,dns,gossip等提供支持。 ...