1 Star 0 Fork 0

GoLang/microservice_study

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
main.go 2.18 KB
一键复制 编辑 原始数据 按行查看 历史
GoLang 提交于 2022-11-21 17:19 . order up
package main
import (
"context"
"fmt"
go_micro_service_cart "gitee.com/qwert/microservice_study/cart/proto/cart"
"gitee.com/qwert/microservice_study/cartApi/handler"
pb "gitee.com/qwert/microservice_study/cartApi/proto"
"github.com/afex/hystrix-go/hystrix"
consul2 "github.com/go-micro/plugins/v4/registry/consul"
"github.com/go-micro/plugins/v4/wrapper/select/roundrobin"
opentracing2 "github.com/go-micro/plugins/v4/wrapper/trace/opentracing"
"github.com/opentracing/opentracing-go"
"go-micro.dev/v4"
"go-micro.dev/v4/client"
"go-micro.dev/v4/logger"
"go-micro.dev/v4/registry"
)
var (
service = "cartApi"
version = "latest"
)
func main() {
//注册中心
consul := consul2.NewRegistry(func(options *registry.Options) {
options.Addrs = []string{
"192.168.1.89:8500",
}
})
// Create service
srv := micro.NewService()
srv.Init(
micro.Name(service),
micro.Version(version),
micro.Address("0.0.0.0:8086"),
//添加 consul 注册中心
micro.Registry(consul),
//添加链路追踪
micro.WrapClient(opentracing2.NewClientWrapper(opentracing.GlobalTracer())),
//添加熔断
micro.WrapClient(NewClientHystrixWrapper()),
//添加负载均衡
micro.WrapClient(roundrobin.NewClientWrapper()),
)
cartService := go_micro_service_cart.NewCartService("cart", srv.Client())
cartService.AddCart(context.TODO(), &go_micro_service_cart.CartInfo{
UserId: 3,
ProductId: 4,
SizeId: 5,
Num: 5,
})
// Register handler
if err := pb.RegisterCartApiHandler(srv.Server(), &handler.CartApi{CartService: cartService}); err != nil {
logger.Fatal(err)
}
// Run service
if err := srv.Run(); err != nil {
logger.Fatal(err)
}
}
type clientWrapper struct {
client.Client
}
func (c *clientWrapper) Call(ctx context.Context, req client.Request, rsp interface{}, opts ...client.CallOption) error {
return hystrix.Do(req.Service()+"."+req.Endpoint(), func() error {
//run 正常执行
fmt.Println(req.Service() + "." + req.Endpoint())
return c.Client.Call(ctx, req, rsp, opts...)
}, func(err error) error {
fmt.Println(err)
return err
})
}
func NewClientHystrixWrapper() client.Wrapper {
return func(i client.Client) client.Client {
return &clientWrapper{i}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/qwert/microservice_study.git
git@gitee.com:qwert/microservice_study.git
qwert
microservice_study
microservice_study
a16dd36d265e

搜索帮助