作者: | 来源:互联网 | 2024-10-13 22:43
注册初始化代码packageutilsimport(fmtgithub.comgoogleuuidconsulapigithub.comhashicorpconsulap
注册初始化代码
package utils
import (
"fmt"
"github.com/google/uuid"
consulapi "github.com/hashicorp/consul/api"
"log"
"strconv"
)
var ConsulClient *consulapi.Client
var ServiceID string
var ServiceName string
var ServicePort int
func init() {
config := consulapi.DefaultConfig()
config.Address = "192.168.3.14:8500"
client, err := consulapi.NewClient(config) //创建客户端
if err != nil {
log.Fatal(err)
}
COnsulClient= client
ServiceID = "userservice" + uuid.New().String() //因为最终这段代码是在不同的机器上跑的,是分布式的,有好几台机器提供相同的server,所以这里存到consul中的id必须是唯一的,否则只有一台服务器可以注册进去,这里使用uuid保证唯一性
}
func SetServiceNameAndPort(name string, port int) {
ServiceName = name
ServicePort = port
}
func RegService() {
reg := consulapi.AgentServiceRegistration{}
reg.ID = ServiceID //设置不同的Id,即使是相同的service name也得有不同的id
reg.Name = ServiceName //注册service的名字
reg.Address = "localhost" //注册service的ip
reg.Port = ServicePort //注册service的端口
fmt.Println(ServicePort)
reg.Tags = []string{"primary"}
check := consulapi.AgentServiceCheck{} //创建consul的检查器
check.Interval = "5s" //设置consul心跳检查时间间隔
check.HTTP = "http://192.168.3.14:" + strconv.Itoa(ServicePort) + "/health" //设置检查使用的url
fmt.Println(check.HTTP)
reg.Check = &check
err := ConsulClient.Agent().ServiceRegister(®)
if err != nil {
log.Fatal(err)
}
}
func UnRegService() {
ConsulClient.Agent().ServiceDeregister("userservice")
}
调用代码
package main
import (
"context"
"fmt"
"github.com/go-kit/kit/endpoint"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/sd"
"github.com/go-kit/kit/sd/consul"
httptransport "github.com/go-kit/kit/transport/http"
consulapi "github.com/hashicorp/consul/api"
"gomicro2/Services"
"io"
"net/url"
"os"
)
func main() {
//第一步创建client
{
config := consulapi.DefaultConfig()
config.Address = "localhost:8500"
api_client, _ := consulapi.NewClient(config)
client:= consul.NewClient(api_client)
var logger log.Logger
{
logger = log.NewLogfmtLogger(os.Stdout)
var Tag = []string{"primary"}
instancer := consul.NewInstancer(client, logger, "userservice", Tag, true) //最后的true表示只有通过健康检查的服务才能被得到
{
factory := func(service_url string) (endpoint.Endpoint, io.Closer, error) { //factory定义了如何获得服务端的endpoint,这里的service_url是从consul中读取到的service的address我这里是192.168.3.14:8000
tart, _ := url.Parse("http://" + service_url) //server ip +8080真实服务的地址
return httptransport.NewClient("GET", tart, Services.GetUserInfo_Request, Services.GetUserInfo_Response).Endpoint(), nil, nil //我在GetUserInfo_Request里面定义了访问哪一个api把url拼接成了http://192.168.3.14:8000/v1/user/{uid}的形式
}
endpointer := sd.NewEndpointer(instancer, factory, logger)
endpoints, _ := endpointer.Endpoints()
fmt.Println("服务有", len(endpoints), "条")
getUserInfo := endpoints[0] //写死获取第一个
ctx := context.Background() //第三步:创建一个context上下文对象
//第四步:执行
res, err := getUserInfo(ctx, Services.UserRequest{Uid: 101})
if err != nil {
fmt.Println(err)
os.Exit(1)
}
//第五步:断言,得到响应值
userinfo := res.(Services.UserResponse)
fmt.Println(userinfo.Result)
}
}
}
}
来自为知笔记(Wiz)