更新时间:2024-08-30 GMT+08:00
分享

托管Kratos应用

概述

Kratos是轻量级Go微服务框架,包含大量微服务相关功能及工具,更多Kratos框架相关信息详见Kratos官方文档

前提条件

创建ServiceComb引擎,请参考创建ServiceComb引擎

代码接入

  • Provider端:
    package main
    
    import (
            "crypto/tls"
            "log"
            "net/url"
            "github.com/go-chassis/sc-client"
            "github.com/go-kratos/kratos/contrib/registry/servicecomb/v2"
            "github.com/go-kratos/kratos/v2"
    )
    func main() {
    	c, err := sc.NewClient(sc.Options{
                    // EndPoints填写servicecomb中service center的地址
    		Endpoints: []string{"127.0.0.1:30100"},
                    EnableSSL: true,
                    TLSConfig: &tls.Config{   
                        InsecureSkipVerify: true, 
                    },
    	})
    	if err != nil {
    		log.Panic(err)
    	}
    	r := servicecomb.NewRegistry(c)
    	app := kratos.New(
                    //需要传入注册实例的endpoint
                    kratos.Endpoint(&url.URL{Scheme: "{endpoint}"}),
                    //服务名
    		kratos.Name("helloServicecomb"),
                    //接入servicecomb注册中心service center
    		kratos.Registrar(r),
    	)
    	if err := app.Run(); err != nil {
    		log.Fatal(err)
    	}
    }
  • Consumer端:
    package main
    
    import (
            "context"
            "crypto/tls"
            "log"
            "github.com/go-chassis/sc-client"
            "github.com/go-kratos/kratos/contrib/registry/servicecomb/v2"
             "github.com/go-kratos/kratos/v2/transport/grpc"
    )
    func main() {
    	c, err := sc.NewClient(sc.Options{
                    EnableSSL: true,
                    TLSConfig:  &tls.Config{  
                        InsecureSkipVerify: true,
                    },
                    // EndPoints填写servicecomb中service center的地址
    		Endpoints: []string{"127.0.0.1:30100"},
    	})
    	if err != nil {
    		log.Panic(err)
    	}
    	r := servicecomb.NewRegistry(c)
    	ctx := context.Background()
    	conn, err := grpc.DialInsecure(
    		ctx,
                    //Endpoint格式:<schema>://[namespace]/<service-name>
    		grpc.WithEndpoint("discovery:///helloServicecomb"),
    		grpc.WithDiscovery(r),
    	)
    	if err != nil {
    		return
    	}
    	defer conn.Close()
    }

应用部署

参考快速体验ServiceStage选择合适的方式部署应用。

相关文档