微服务引擎 CSE-托管Kitex应用:代码接入

时间:2024-08-30 16:28:52

代码接入

  • Provider端:
    import (
    	"context"
    	"log"
    	"net"
    	"github.com/cloudwego/kitex-examples/hello/kitex_gen/api"
    	"github.com/cloudwego/kitex-examples/hello/kitex_gen/api/hello"
    	"github.com/cloudwego/kitex/pkg/rpcinfo"
    	"github.com/cloudwego/kitex/server"
    	"github.com/kitex-contrib/registry-servicecomb/registry"
    )
    type HelloImpl struct{}
    func (h *HelloImpl) Echo(_ context.Context, req *api.Request) (resp *api.Response, err error) {
    	resp = &api.Response{
    		Message: req.Message,
    	}
    	return
    }
    func main() {
    	// **初始化ServiceComb注册中心,默认从环境变量读取配置**
    	r, err := registry.NewDefaultSCRegistry()
    	if err != nil {
    		panic(err)
    	}
    	svr := hello.NewServer(
    		new(HelloImpl),
    		server.WithRegistry(r),
    		server.WithServerBasicInfo(&rpcinfo.EndpointBasicInfo{ServiceName: "Hello"}),
    		server.WithServiceAddr(&net.TCPAddr{IP: net.IPv4(0, 0, 0, 0), Port: 8080}),
    	)
    	if err := svr.Run(); err != nil {
    		log.Println("server stopped with error:", err)
    	} else {
    		log.Println("server stopped")
    	}
    }
  • Consumer端:
    import (
    	"context"
    	"log"
    	"time"
    	"github.com/cloudwego/kitex-examples/hello/kitex_gen/api"
    	"github.com/cloudwego/kitex-examples/hello/kitex_gen/api/hello"
    	"github.com/cloudwego/kitex/client"
    	"github.com/kitex-contrib/registry-servicecomb/resolver"
    )
    
    func main() {
    	// **初始化ServiceComb注册中心,默认从环境变量读取配置**
    	r, err := resolver.NewDefaultSCResolver()
    	if err != nil {
    		panic(err)
    	}
    	newClient := hello.MustNewClient(
    		"Hello",
    		client.WithResolver(r),
    		client.WithRPCTimeout(time.Second*3),
    	)
    	for {
    		resp, err := newClient.Echo(context.Background(), &api.Request{Message: "Hello"})
    		if err != nil {
    			log.Fatal(err)
    		}
    		log.Println(resp)
    		time.Sleep(time.Second)
    	}
    }
support.huaweicloud.com/bestpractice-cse/cse_05_0029.html