go微服务学习一

go-micro学习一

1 . windows下consul安装,直接下载,将exe文件加入到path中,然后执行:
consul agent -dev
go-micro默认使用consul作为服务发现
2 .安装go-micro编译插件

	go get -u github.com/micro/protobuf/proto  
	go get -u github.com/micro/protobuf/protoc-gen-go    

3 .编译

 protoc -I . --go_out=plugins=micro:./ ./proto/consignment/consignment.proto

4.proto 文件

service ShippingService {
    // 托运一批货物
    rpc CreateConsignment (Consignment) returns (Response) {
    }
    // 查看托运货物的信息
    rpc GetConsignments (GetRequest) returns (Response) {
    }
}

5.编写服务端

/这块代码作为服务端真实实现代码来使用
type Repository struct {
	consignments []*pb.Consignment
}

func (repo *Repository) Create(consignment *pb.Consignment) (*pb.Consignment, error) {
	repo.consignments = append(repo.consignments, consignment)
	return consignment, nil
}
type service struct {
    repo Repository
}

// 实现 consignment.pb.go 中的 ShippingServiceHandler 接口
// 托运新的货物
// 
func (s *service) CreateConsignment(ctx context.Context, req *pb.Consignment, resp *pb.Response) error {
    // 接收承运的货物
    consignment, err := s.repo.Create(req)
    if err != nil {
        return err
    }
    resp = &pb.Response{Created: true, Consignment: consignment}
    return nil
}
func main() {
	server := micro.NewService(
		micro.Name(" ShippingService"),
		micro.Version("latest"),
	)

	// 解析命令行参数
	server.Init()
	repo := Repository{}
	pb.RegisterShippingServiceHandler(server.Server(), &service{repo})
	if err := server.Run(); err != nil {
		log.Fatalf("failed to serve: %v", err)
	}
}

6.编写客户端

func main() {
	sercice := micro.NewService(micro.Name(" ShippingService"))
	sercice.Init()

	// 创建微服务的客户端,简化了手动 Dial 连接服务端的步骤
	client := pb.NewShippingServiceClient(" ShippingService", sercice.Client())

	// 在命令行中指定新的货物信息 json 件
	infoFile := DEFAULT_INFO_FILE
	if len(os.Args) > 1 {
		infoFile = os.Args[1]
	}

	// 解析货物信息
	consignment, err := parseFile(infoFile)
	if err != nil {
		log.Fatalf("parse info file error: %v", err)
	}

	// 调用 RPC
	// 将货物存储到我们自己的仓库里
	resp, err := client.CreateConsignment(context.Background(), consignment)
	if err != nil {
		log.Fatalf("create consignment error: %v", err)
	}

	// 新货物是否托运成功
	log.Printf("created: %t", resp.Created)
	log.Printf("resp: %v", resp)

	// 列出目前所有托运的货物
	resp, err = client.GetConsignments(context.Background(), &pb.GetRequest{})
	if err != nil {
		log.Fatalf("failed to list consignments: %v", err)
	}
	for _, c := range resp.Consignments {
		log.Printf("%+v", c)
	}
}

至此初始代码运行成功

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值