Micro (1)

Source: Internet
Author: User
Tags install go
This is a creation in Article, where the information may have evolved or changed.

Simple Introduction

Micro is a framework for simplifying the development of microservices, providing the following features:

    1. Go Micro-Golang-based plug-in RPC framework that provides service discovery, client load Balancing, encoding, synchronous and asynchronous communication capabilities.
    2. API-API Gateway (API Gateway), which is used to provide processing of HTTP requests. Can act as an HTTP reverse proxy or translate related HTTP requests to the RPC service.
    3. Sidecar-Used to access applications written in other languages into the micro.
    4. Web-Provides a web dashboard, and can provide a reverse proxy for micro applications.
    5. CLI-a command-line tool used to interact with a micro service.
    6. Bot-With it we can communicate with Slack, Hipchat, XMPP in our service.

      The schema looks like this:
      Micro Frame composition

Installation

    1. Because the Micro service discovery does not implement itself, simply provide plugin to access the third-party service discovery (consul, ETCD), the default is to use Consule
      Installation Reference: Consul installation doc
    2. Installing PROTOBUF
go get github.com/micro/protobuf/{proto,protoc-gen-go}
    1. Install Go-micro, refer to GitHub Go-micro
go get github.com/micro/go-micro
    1. Install micro, refer to GitHub Micro
go get github.com/micro/micro

Next we'll simply use micro to build a Hello World app.

    1. To create a proto file, proto syntax please refer to Google Protobuf
# hello_world.protosyntax = "proto3";service HelloWorld {    rpc Hello(HelloRequest) returns (HelloResponse) {}}message HelloRequest {    string name = 1;}message HelloResponse {    string greeting = 2;}
    1. Usually we need to compile the above Hello_world.proto file to output the code implementation file of the relevant language.
protoc --go_out=plugins=micro:. hello_world.proto

Generate File Hello_world.pb.go

Code generated by Protoc-gen-go. Do not edit.//Source:hello_world.proto/*package Hello_world are a generated protocol buffer package. It is generated from these files:hello_world.protoIt have these top-level messages:helloworldrequest Helloworldr Esponse*/package hello_worldimport Proto "Github.com/golang/protobuf/proto" Import FMT "FMT" Import math "math" import (c Lient "github.com/micro/go-micro/client" Server "github.com/micro/go-micro/server" context "Golang.org/x/net/contex T ")//Reference imports to suppress errors if they is not otherwise used.var _ = Proto. Marshalvar _ = fmt. Errorfvar _ = Math. inf//This was a compile-time assertion to ensure that this generated file//was compatible with the proto package it is Bei Ng compiled against.//A compilation error At the This line likely means your copy of the//proto package needs to be updated. Const _ = Proto. ProtoPackageIsVersion2//Please upgrade the proto PackageType helloworldrequest struct {Name string ' ProtobUF: "Bytes,1,opt,name=name" JSON: "Name,omitempty" '}func (M *helloworldrequest) Reset () {*m = HelloWorld request{}}func (M *helloworldrequest) string () string {return Proto. Compacttextstring (M)}func (*helloworldrequest) protomessage () {}func (*helloworldrequest) Descriptor () ([]b Yte, []int) {return fileDescriptor0, []int{0}}func (M *helloworldrequest) GetName () string {if M! = Nil {ret Urn M.name} return ""}type helloworldresponse struct {greeting string ' protobuf: "bytes,2,opt,name=greeting" JSO N: "Greeting,omitempty" '}func (M *helloworldresponse) Reset () {*m = helloworldresponse{}}func (M *hell Oworldresponse) string () string {return Proto. Compacttextstring (M)}func (*helloworldresponse) protomessage () {}func (*helloworldresponse) Descriptor () ([        ]byte, []int) {return fileDescriptor0, []int{1}}func (M *helloworldresponse) getgreeting () string {if M! = Nil { RetUrn m.greeting} return ""}func init () {proto. Registertype ((*helloworldrequest) (nil), "Helloworldrequest") Proto. Registertype ((*helloworldresponse) (nil), "Helloworldresponse")}//Reference imports to suppress errors if they is not ot Herwise Used.var _ context. Contextvar _ Client. Optionvar _ server. option//Client API for HelloWorld servicetype helloworldclient interface {Hello (CTX context. Context, in *helloworldrequest, opts ... client. Calloption) (*helloworldresponse, error)}type helloworldclient struct {c client. Client ServiceName string}func newhelloworldclient (serviceName string, C client. Client) Helloworldclient {if c = = Nil {c = client.        Newclient ()} If Len (serviceName) = = 0 {serviceName = "HelloWorld"} return &helloworldclient{ C:c, Servicename:servicename,}}func (c *helloworldclient) Hello (CTX context. Context, in *helloworldrequest, opts ... client. Calloption) (*helloworldresponse, error) {req: = C.c.newrequest (C.servicename, "Helloworld.hello", in) Out: = new (Helloworldresponse) Err: = C.C .    Call (CTX, req, out, opts ...) If err! = Nil {return nil, err} return out, nil}//Server API for HelloWorld servicetype HelloWorldHandler interface {Hello (context. Context, *helloworldrequest, *helloworldresponse) error}func Registerhelloworldhandler (s server). Server, HDLR HelloWorldHandler, opts ... server. handleroption) {S.handle (S.newhandler (&HELLOWORLD{HDLR}, opts ...)} Type HelloWorld struct {helloworldhandler}func (H *helloworld) Hello (CTX context. Context, in *helloworldrequest, out *helloworldresponse) error {return H.helloworldhandler.hello (CTX, in, out)}func in It () {proto. Registerfile ("Hello_world.proto", fileDescriptor0)}var fileDescriptor0 = []byte{//136 bytes of a gzipped Filedescrip  Torproto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xFF, 0xe2, 0x12, 0XCC, 0x48, 0xCD, 0xc9, 0xc9, 0x8f, 0x2f, 0XCF, 0x2f, 0xca, 0x49, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x57, 0x52, 0xe7, 0x12, 0xf4, 0x00, 0x09, 0x86, 0x83, 0xc4, 0x82 , 0x52, 0x0b, 0x4b, 0x53, 0x8b, 0x4b, 0x84, 0x84, 0xb8, 0x58, 0xf2, 0x12, 0x73, 0x53, 0x25, 0x18, 0x15, 0x18, 0x35, 0x3 8, 0x83, 0xc0, 0x6c, 0x25, 0x03, 0x2e, 0x21, 0x64, 0x85, 0xc5, 0x05, 0xf9, 0x79, 0xc5, 0xa9, 0x42, 0x52, 0x5c, 0x1c, 0x E9, 0x45, 0xa9, 0xa9, 0x25, 0x99, 0x79, 0xe9, 0x12, 0x4c, 0x60, 0xd5, 0x70, 0xBE, 0x91, 0x03, 0x17, 0x17, 0x42, 0x87 , 0x90, 0x11, 0x17, 0x2b, 0x98, 0x27, 0x24, 0xa4, 0x87, 0x61, 0xa1, 0x94, 0xb0, 0x1e, 0xa6, 0xd9, 0x4a, 0x0c, 0x49, 0x6 C, 0x60, 0x37, 0x1a, 0x03, 0x02, 0x00, 0x00, 0xFF, 0xFF, 0x80, 0x8c, 0xf7, 0x9b, 0xb8, 0x00, 0x00, 0x00,}

The

Below outlines several of these key outputs:

Package Hello_world//message definition PackageType helloworldrequest struct {Name string ' protobuf: ' Bytes,1,opt,name=name ' JSON: "Name,omitempty" '}//Request message class type Helloworldresponse struct {greeting string ' protobuf: "bytes,2,opt,name=greeting" JSON: "Greeting,omitempty" '}//Response message class type Helloworldclient interface {Hello (CTX context. Context, in *helloworldrequest, opts ... client. Calloption) (*helloworldresponse, error)}//Service Request interface, define client callable request method ' Hello ', client programming using Type HelloWorldHandler interface {He Llo (context. Context, *helloworldrequest, *helloworldresponse) Error}//server-side interface, defining the method that the server needs to implement ' Hello ', server-side programming using Func Registerhelloworldhandler (s server). Server, HDLR HelloWorldHandler, opts ... server. handleroption) {S.handle (S.newhandler (&HELLOWORLD{HDLR}, opts ...)}//The server uses this method to register the defined service, and the server-side program uses the type HelloWorld struct {helloworldhandler}func (H *helloworld) Hello (CTX context. Context, in *helloworldrequest, out *helloworldresponse) error {return H.helloworldhandler.hello (CTX, in, out)}//defines the HelloWorld class, which requires the server to implement the handle method ' Hello ', which is used by the server-side programming 

Service-Side implementation

package mainimport (    "fmt"    "./hello_world" // import proto生成的类    "github.com/micro/go-micro"    "golang.org/x/net/context")type HelloWorld struct{}func (g *HelloWorld) Hello(ctx context.Context, req *hello_world.HelloWorldRequest, rsp *hello_world.HelloWorldResponse) error {    rsp.Greeting = "Hello World: " + req.Name    return nil} // 实现hello_world service中Hello方法func main() {    service := micro.NewService(        micro.Name("hello_world"), // 定义service的名称为hello_world        micro.Version("latest"),        micro.Metadata(map[string]string{            "type": "helloworld",        }),    )    service.Init() // 初始化service    hello_world.RegisterHelloWorldHandler(service.Server(), new(HelloWorld)) // 注册服务    if err := service.Run(); err != nil {        fmt.Println(err)    } // 运行服务}

Client implementation

package mainimport (    "fmt"    "./hello_world"    "github.com/micro/go-micro"    "golang.org/x/net/context")func main() {    service := micro.NewService(        micro.Name("hello_world"),        micro.Version("latest"),        micro.Metadata(map[string]string{            "type": "helloworld",        }),    )    service.Init()    greeter := hello_world.NewHelloWorldClient("hello_world", service.Client()) // 创建服务hello_world的client对象, 以便调用其中定义的RPC方法'Hello'    rsp, err := greeter.Hello(context.TODO(), &hello_world.HelloWorldRequest{Name: "Alice"}) // 传入HelloWorldRequest对象作为调用RPC方法的参数'Hello'    if err != nil {        fmt.Println(err)        return    }    fmt.Println(rsp.Greeting)}

Summarize the development process

    1. Public development Module
      • Create a message Protobuf file in which the message is defined
      • Generates an implementation class based on the Protobuf file defined by that language
    2. Service side
      • Implementing RPC methods that are defined in messages
      • Initializes a new service object
      • Registration Services
      • Running the service
    3. Client
      • Initializes a new service object
      • Defining a Request message
      • Incoming Request messages call the service-side definition RPC method
      • Interpreting response messages

Code please refer to Https://github.com/zouqilin/micro_demo/tree/master/hello_world

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.