Golang

关注公众号 jb51net

关闭
首页 > 脚本专栏 > Golang > goZero微服务

goZero微服务开发小结

作者:水痕01

本文主要介绍了使用go-zero搭建微服务环境的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

一、go-zero微服务环境安装

1、go-zero脚手架的安装

go install github.com/zeromicro/go-zero/tools/goctl@latest

2、etcd的安装根据自己电脑操作系统下载对应的版本,具体的使用自己查阅文章

二、创建一个user-rpc服务

1、定义user.proto文件

syntax = "proto3";

package user;
option go_package="./user";


service User {
  rpc FindById(FindByIdReq) returns (FindByIdResp);
}

message FindByIdReq{
  int64 id = 1;
}

message FindByIdResp {
  int64 id = 1;
  string username = 2;
}

2、使用命令生成对应的项目文件

goctl rpc protoc ./user.proto --go_out=. --go-grpc_out=. --zrpc_out=./
goctl rpc protoc ./user.proto --go_out=./types --go-grpc_out=./types --zrpc_out=. --style goZero -m

3、安装对应的依赖包

go mod tidy

4、运行user服务

go run user.go

5、在etcd中查看服务是否已经注册成功

etcdctl get --prefix user.rpc

6、模拟业务代码返回数据

func (l *FindByIdLogic) FindById(in *user.FindByIdReq) (*user.FindByIdResp, error) {
	return &user.FindByIdResp{
		Id:       in.Id,
		Username: "哈哈哈",
	}, nil
}

7、使用apifox可以直接调用rpc的服务,引入文件

三、在提供restful api接口端调用rpc服务返回数据给前端

1、创建一个user-api的项目

2、创建描述文件

syntax = "v1"

type GetUserReq {
    Id int64 `path:"id"` // 主键id
}

type GetUserResp {
    Id int64 `json:"id"`              // 用户id
    Username string `json:"username"` // 用户名
}
@server(
    prefix: api/v1/user
    group: user
)
service user-api {
    @doc "根据用户id获取用户新"
    @handler GetUserByIdApi
    get /:id (GetUserReq) returns (GetUserResp)
}

3、使用脚本生成对应的项目文件

goctl api go -api *.api -dir . --style=gozero

4、在user-api的配置文件中引入rpc服务的配置

Name: user-api
Host: 0.0.0.0
Port: 8888
UserRpc:
  Etcd:
    Hosts:
      - 127.0.0.1:2379
    Key: user.rpc

5、在apps/user-api/internal/config/config.go创建服务的配置

type Config struct {
	rest.RestConf
	UserRpc zrpc.RpcClientConf
}

6、在apps/user-api/internal/svc/servicecontext.go依赖注入rpc服务

type ServiceContext struct {
	Config  config.Config
	UserRpc userclient.User
}
func NewServiceContext(c config.Config) *ServiceContext {
	return &ServiceContext{
		Config:  c,
		UserRpc: userclient.NewUser(zrpc.MustNewClient(c.UserRpc)),
	}
}

7、模拟实现业务代码

func (l *GetUserByIdApiLogic) GetUserByIdApi(req *types.GetUserReq) (resp *types.GetUserResp, err error) {
	// 模拟业务开发
	findByIdResp, err := l.svcCtx.UserRpc.FindById(l.ctx, &user.FindByIdReq{
		Id: req.Id,
	})
	if err != nil {
		return &types.GetUserResp{}, errors.New("查询失败")
	}
	return &types.GetUserResp{
		Id:       findByIdResp.Id,
		Username: findByIdResp.Username,
	}, nil
}

8、直接浏览模拟请求http://localhost:8888/api/v1/user/1

四、实际项目中可能是多个微服务的引入

1、在go-zero项目的svc文件夹下创建一个rpcClient.go的文件

type RpcClient struct {
	config      config.Config
  // 服务1
	systemRpc   zrpc.Client
	systemMutex sync.Mutex
	// 服务2
	usersMutex sync.Mutex
	usersRpc   zrpc.Client
}
func NewRpcClient(c config.Config) *RpcClient {
	return &RpcClient{
		config: c,
	}
}
func (r *RpcClient) GetSystemRpc() system.ConfigServiceClient {
	r.systemMutex.Lock()
	defer r.systemMutex.Unlock()
	if r.systemRpc == nil {
		systemRpc, err := zrpc.NewClient(r.config.SystemRpc)
		if err != nil {
			logx.Errorf("new system rpc failed: %+v", err)
			return nil
		}
		r.systemRpc = systemRpc
	}
	return system.NewConfigServiceClient(r.systemRpc.Conn())
}
func (r *RpcClient) GetUsersRpc() users.UsersClient {
	r.usersMutex.Lock()
	defer r.usersMutex.Unlock()
	if r.usersRpc == nil {
		usersRpc, err := zrpc.NewClient(r.config.UsersRpc)
		if err != nil {
			logx.Errorf("new user rpc failed: %+v", err)
			return nil
		}
		r.usersRpc = usersRpc
	}
	return users.NewUsersClient(r.usersRpc.Conn())
}

2、在serviceContext.go文件中注入上面的rpcClient.go

type ServiceContext struct {
	Config    config.Config
	RpcClient *RpcClient
}
func NewServiceContext(c config.Config) *ServiceContext {
	rpcClient := NewRpcClient(c)
	if rpcClient == nil {
		logx.Errorf("new rpc client failed")
		panic(0)
	}
	return &ServiceContext{
		Config:    c,
		RpcClient: rpcClient,
	}
}

3、正常使用user服务的方法

到此这篇关于goZero微服务开发小结的文章就介绍到这了,更多相关goZero微服务内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文