天天看點

go-micro 自定義熔斷時間與服務降級

package main

import (
	"context"
	"fmt"
	"github.com/afex/hystrix-go/hystrix"
	"github.com/micro/go-micro"
	"github.com/micro/go-micro/client"
	"github.com/micro/go-micro/registry"
	etcd2 "github.com/micro/go-micro/registry/etcd"
	"github.com/micro/go-micro/transport/grpc"
	proto "micro.study.zozoo.net/proto"
)
func main() {
	etcd := etcd2.NewRegistry(func(options *registry.Options) {
		options.Addrs = []string{"127.0.0.1:2379"}
	})
	// Create a new service. Oponally include some options here.
	hystrix.DefaultTimeout = 2000//設定熔斷時間

	service := micro.NewService(
		micro.Name("hello.client"),
		micro.Registry(etcd),
		micro.Transport(grpc.NewTransport()),
		micro.WrapClient(NewMyClientWrapper()),//用戶端熔斷
		)
	service.Init()
	// Create new greeter client
	greeter := proto.NewHelloService("hello", service.Client())
	// Call the greeter,通過protobuf生成的函數進行調用其它微服務

	for i:=0;i<10;i++ {
		rsp, err := greeter.Info(context.TODO(), &proto.Request{Name: "gangan"})
		if err != nil {
			fmt.Println(err)
		}else {
			fmt.Println(rsp.Name)
		}
	}
}

//重新實作熔斷方法
type myWrapper struct {
	client.Client
}

func (c *myWrapper) Call(ctx context.Context, req client.Request, rsp interface{}, opts ...client.CallOption) error {
	return hystrix.Do(req.Service()+"."+req.Endpoint(), func() error {
		return c.Client.Call(ctx, req, rsp, opts...)
	}, func(e error) error {
		//這裡是處理服務降級的地方
		fmt.Println("進入服務降級")
		return nil
	})
}

// NewClientWrapper returns a hystrix client Wrapper.
func NewMyClientWrapper() client.Wrapper {
	return func(c client.Client) client.Client {
		return &myWrapper{c}
	}
}