Files
toutoukan/services/user/userLogin/grpc/user-consumer/main.go
2025-09-15 11:09:22 +08:00

70 lines
1.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// client.go
package main
import (
"context"
"log"
"time"
"go-micro.dev/v4"
"go-micro.dev/v4/client"
"go-micro.dev/v4/registry"
"go.etcd.io/etcd/client/v3"
)
type LoginRequest struct {
Username string
Password string
}
type LoginResponse struct {
Token string
}
func main() {
// 1. 创建 etcd 客户端
etcdClient, err := clientv3.New(clientv3.Config{
Endpoints: []string{"127.0.0.1:2379"},
DialTimeout: 5 * time.Second,
})
if err != nil {
log.Fatal(err)
}
defer etcdClient.Close()
// 2. 创建注册中心
reg := registry.NewRegistry(
registry.Addrs("127.0.0.1:2379"),
)
// 3. 创建微服务客户端
service := micro.NewService(
micro.Registry(reg),
)
service.Init()
// 4. 创建 RPC 客户端
userService := micro.NewService(
micro.Name("user.client"),
micro.Registry(reg),
)
userService.Init()
// 5. 调用远程服务
req := client.NewRequest(
"user.service", // 服务名
"UserService.Login", // 方法名
&LoginRequest{ // 请求参数
Username: "admin",
Password: "123456",
},
)
rsp := &LoginResponse{}
if err := userService.Client().Call(context.Background(), req, rsp); err != nil {
log.Fatal("调用失败:", err)
}
log.Printf("登录成功Token: %s", rsp.Token)
}