- 至此,咱们的项目服务端代码,已经开发完毕,现在来看一下main.go文件中的代码:
package main
import (
micro2 "account/common/micro"
"account/config/logger"
"account/config/mysql"
"account/config/redis"
"account/domain/repository"
"account/domain/service"
"account/handler"
"account/proto/account"
"fmt"
_ "github.com/jinzhu/gorm/dialects/mysql"
"github.com/micro/go-micro/v2"
"github.com/micro/go-micro/v2/registry"
"github.com/micro/go-plugins/registry/consul/v2"
"github.com/micro/go-plugins/wrapper/monitoring/prometheus/v2"
ratelimit "github.com/micro/go-plugins/wrapper/ratelimiter/uber/v2"
opentracing2 "github.com/micro/go-plugins/wrapper/trace/opentracing/v2"
"github.com/opentracing/opentracing-go"
"go.uber.org/zap"
)
func main() {
// 1.配置中心
consulConfig, err := micro2.GetConsulConfig("localhost", 8500, "/micro/config")
if err != nil {
fmt.Printf("Init consulConfig failed, err: %v\n", err)
}
// 2.注册中心
consulRegistry := consul.NewRegistry(func(options *registry.Options) {
options.Addrs = []string{
"127.0.0.1:8500",
}
})
if err := micro2.GetAccountFromConsul(consulConfig, "account"); err != nil {
fmt.Printf("Init consul failed, err: %v\n", err)
}
fmt.Println(micro2.ConsulInfo)
// 3.zap日志初始化
if err := logger.Init(); err != nil {
fmt.Printf("Init logger failed, err: %v\n", err)
return
}
defer zap.L().Sync()
// 4.jaeger 链路追踪
t, io, err := micro2.NewTracer(micro2.ConsulInfo.Jaeger.ServiceName, micro2.ConsulInfo.Jaeger.Addr)
if err != nil {
logger.Error(err)
return
}
defer io.Close()
opentracing.SetGlobalTracer(t)
// 5.初始化数据库
db, err := mysql.MysqlInit(micro2.ConsulInfo.Mysql.User, micro2.ConsulInfo.Mysql.Pwd, micro2.ConsulInfo.Mysql.Database)
if err != nil {
logger.Error(err)
return
}
defer db.Close()
// 创建实例
accountService := service.NewUserService(repository.NewUserRepository(db))
// 6.初始化Redis连接
if err := redis.Init(); err != nil {
logger.Error(err)
return
}
defer redis.Close()
// 7.暴露监控地址
micro2.PrometheusBoot(micro2.ConsulInfo.Prometheus.Host, int(micro2.ConsulInfo.Prometheus.Port))
// 8.注册服务
registryService := micro.NewService(
micro.Name(micro2.ConsulInfo.Micro.Name),
micro.Version(micro2.ConsulInfo.Micro.Version),
//暴露的服务地址
micro.Address(micro2.ConsulInfo.Micro.Address),
//添加consul 注册中心
micro.Registry(consulRegistry),
//添加链路追踪
micro.WrapHandler(opentracing2.NewHandlerWrapper(opentracing.GlobalTracer())),
//添加限流
micro.WrapHandler(ratelimit.NewHandlerWrapper(int(micro2.ConsulInfo.Ratelimit.QPS))),
//添加监控
micro.WrapHandler(prometheus.NewHandlerWrapper()),
)
// 9.初始化服务
registryService.Init()
// 10.注册Handle
account.RegisterAccountHandler(registryService.Server(), &handler.Account{AccountService: accountService})
// 11.启动服务
if err := registryService.Run(); err != nil {
logger.Fatal(err)
}
}
二 客户端代码开发:
- 在client目录下新建一个account.go文件,写入以下代码,完成客户端的建立:
package main
import (
micro2 "account/common/micro"
"account/config/logger"
"account/proto/account"
"context"
"fmt"
"github.com/micro/go-micro/v2"
"github.com/micro/go-micro/v2/registry"
"github.com/micro/go-plugins/registry/consul/v2"
"github.com/micro/go-plugins/wrapper/select/roundrobin/v2"
opentracing2 "github.com/micro/go-plugins/wrapper/trace/opentracing/v2"
"github.com/opentracing/opentracing-go"
"go.uber.org/zap"
)
func main() {
// 1.配置中心
consulConfig, err := micro2.GetConsulConfig("localhost", 8500, "/micro/config")
if err != nil {
fmt.Printf("Init consulConfig failed, err: %v\n", err)
}
// 2.注册中心
newConsul := consul.NewRegistry(func(options *registry.Options) {
options.Addrs = []string{
"127.0.0.1:8500",
}
})
if err := micro2.GetAccountFromConsul(consulConfig, "account"); err != nil {
fmt.Printf("Init consul failed, err: %v\n", err)
}
fmt.Println(micro2.ConsulInfo)
// 3.zap日志初始化
if err := logger.Init(); err != nil {
fmt.Printf("Init logger failed, err: %v\n", err)
return
}
defer zap.L().Sync()
logger.Debug("logger init success...")
// 4.链路追踪
t, io, err := micro2.NewTracer("go.micro.service.account", "localhost:6831")
if err != nil {
logger.Fatal(err)
}
defer io.Close()
opentracing.SetGlobalTracer(t)
// 5.监控
micro2.PrometheusBoot("127.0.0.1", 9292)
// 6.设置服务
service := micro.NewService(
micro.Name("go.micro.service.account.client"),
micro.Version("latest"),
//暴露的服务地址
micro.Address("127.0.0.1:9580"),
//添加注册中心
micro.Registry(newConsul),
//绑定链路追踪
micro.WrapClient(opentracing2.NewClientWrapper(opentracing.GlobalTracer())),
//添加监控
micro.WrapHandler(opentracing2.NewHandlerWrapper(opentracing.GlobalTracer())),
//作为服务端访问时生效
micro.WrapClient(opentracing2.NewClientWrapper(opentracing.GlobalTracer())),
//负载均衡
micro.WrapClient(roundrobin.NewClientWrapper()),
)
// 7.创建服务
accountService := account.NewAccountService("go.micro.service.account", service.Client())
三 客户端测试功能
1.发送注册邮件
// 8.发送注册邮件
registerMail := &account.SendMailRequest{Email: "xxx@qq.com"}
registerMailResponse, err := accountService.SendRegisterMail(context.TODO(), registerMail)
if err != nil {
logger.Error(err)
}
fmt.Println(registerMailResponse)
2.实现注册功能
// 9.实现注册功能
accountAdd := &account.RegisterRequest{
RegisterRequest: &account.UserInfoResponse{
Username: "夏沫の梦",
FirstName: "qi66",
Password: "123456",
Email: "xxx@qq.com",
LastName: "admin",
},
Code: registerMailResponse.Code,
}
registerResponse, err := accountService.Register(context.TODO(), accountAdd)
if err != nil {
logger.Error(err)
}
fmt.Println(registerResponse)
3.查询用户功能
// 10.查询用户功能
getUser := &account.UserIdRequest{UserId: registerResponse.UserId}
userInfoResponse, err := accountService.GetUserInfo(context.TODO(), getUser)
if err != nil {
logger.Error(err)
}
fmt.Println(userInfoResponse)
四 运行项目
-
运行项目之前,要把相关服务启动起来,如consul、jaeger、prometheus、grafana、ELK等等
-
把邮箱改成你自己的哦
-
consul启动之后,记得把配置数据创建一下
-
第一次启动,记得把mysql数据表初始化一下,之后要把初始化语句去掉,否则会报错
-
运行main.go文件
go run main.go
- 运行account.go文件
go run client/account.go
- 如果客户端控制台成功打印出来咱们刚注册的用户信息的话,说明项目已经完成
- 如果出现问题的话,可以自行摆渡解决,无法解决的话,可以私信博主或者加博主的学习交流询问
五 最后
-
至此,go-micro微服务项目客户端开发(使用负载均衡)使用工作就正式完成。
-
接下来就开始项目经验总结了,这是本专栏的最后一篇文章,希望大家关注博主和关注专栏,第一时间获取最新内容,每篇博客都干货满满。