One of the Go Micro Service series

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed. How do I write a micro service? Here is the Go Micro-service framework go micro, the specific situation can be consulted: http://btfak.com/%E5%BE%AE%E6%9C%8D%E5%8A%A1/2016/03/28/go-micro/ Here is the step to develop a microservices (if you want to access the source code directly or through demo learning, you can visit [Ricoder_demo] (Https://gitee.com/xi_fan/ricoder_demo). ): 1, write Proto file, define functions and other specific implementation: "Protobufsyntax =" Proto3 ";p ackage pb;service userservice {//RPC Insertuser (insertuserreq ) returns (Insertuserrep) {}//delete RPC Deletetuser (deletetuserreq) returns (Deletetuserrep) {}//check RPC Selectuser (selectuser REQ) returns (Selectuserrep) {}//change RPC ModifyUser (modifyuserreq) returns (Modifyuserrep) {}}message user{int32 id = 1; stri ng name = 2; string Address = 3; String Phone = 4;} Message Modifyuserreq {Int32 id = 1; string name = 2; string Address = 3; string Phone = 4;} Message Modifyuserrep {}message Selectuserreq {int32 id = 1;} Message Selectuserrep {User users = 1;} Message Deletetuserreq {Int32 id = 1;} Message Deletetuserrep {}message Insertuserreq {int32 id = 1; string name = 2; string Address = 3; string Phone = 4;} MesSage Insertuserrep {Int32 id = 1; string name = 2; string Address = 3; string Phone = 4;} "2, using the Code generation tool to generate the User.pb.go file, build the protocol can see HTTPS://GITHUB.COM/MICRO/GO-MICRO, here I wrote a script file build_proto.sh, automatically generates the appropriate protocol for the proto file under the specified folder, with the following code: "' Bash#!/usr/bin/env bashprotoc--proto_path=./proto--go_out=plugins=micro:./ SRC/SHARE/PB./proto/*.proto "can make custom changes to the code ..... After running the build_proto.sh file, you can see that the corresponding User.pb.go file is generated under the specified folder, as in my case:! [screenshot from 2017-10-11 17-09-09.png] (http://upload-images.jianshu.io/upload_images/3365849-a5ddf7ce5fd38070.png?imageMogr2/auto-orient/strip% 7cimageview2/2/w/1240) 3, Write a handler implementation of the USER.PB.GO definition of the interface implementation: 1) First create a User.go file 2) Define a struct, named Userhandler, implement the User.proto file all defined service, here to pay attention to, even if it is temporarily not achieve good karma The code is as follows: "' Gopackage handlerimport (" MEWE_JOB/GOMICRODEMO/SRC/SHARE/PB "" Golang.org/x/net/context ") type Userhandler struct {}//new one userhandlerfunc Newuserhandler () *userhandler{return &userhandler{}}//add func (c * Userhandler) Insertuser (CTX context. Context, req * pb. InsertuserrEQ,RSP *PB. Insertuserrep) Error {return nil}//delete func (c *userhandler) Deletetuser (CTX context. Context, req * pb. DELETETUSERREQ,RSP *PB. Deletetuserrep) Error {return nil}//check func (c *userhandler) Selectuser (CTX context. Context, req * pb. SELECTUSERREQ,RSP *PB. Selectuserrep) Error {return nil}//modified func (c *userhandler) ModifyUser (CTX context. Context, req * pb. MODIFYUSERREQ,RSP *PB. Modifyuserrep) error {return nil} ' 4, register handler into microservices, this step is implemented in main: ' Gopackage mainimport ("Github.com/micro/cli "" MEWE_JOB/GOMICRODEMO/SRC/SHARE/PB "" Github.com/micro/go-micro/server "" mewe_job/gomicrodemo/src/user-srv/ Handler "" Github.com/micro/go-micro "" Log "" mewe_job/gomicrodemo/src/user-srv/db "" mewe_job/gomicrodemo/src/share/ Config ") func main () {//Create service, and define some parameter service: = Micro. NewService (micro. Name ("Go.micro.srv.user"), Micro. Version ("latest"),//Define Service Action action Service.init (micro. Action (func (c *cli. Context) {log. Println ("Micro. Action test ... ")//register DBDB first. Init (config. MYSQLDSN) PB. Registeruserservicehandler (Service. Server (), handler. Newuserhandler (), server. Internalhandler (True))}), Micro. Afterstop (func () error {log. Println ("Micro. Afterstop test ... ") return nil}), Micro. Afterstart (func () error {log. Println ("Micro. Afterstart test ... ") return nil}), log. Println ("Start user-srv service ...")//Start Serviceif err: = service. Run (); Err! = Nil {log. Panic ("User-srv service failed to start ...")}} "The main points of this code are:-Create service, initialize a microservices called go.micro.srv.user" go/Create service with the following code, and define some parameter service: = Micro. NewService (micro. Name ("Go.micro.srv.user"), Micro. Version ("latest"), ""-register the DB connection and give Go.micro.srv.user this micro-service binding handler, although currently I have not defined the operations of the DB layer in db ' Godb. Init (config. MYSQLDSN) PB. Registeruserservicehandler (service. Server (), handler. Newuserhandler (), server. Internalhandler (True)) '-Start service, open ' goif err: = Service by Run '. Run (); Err! = Nil {log. Panic ("User-srv service failed to start ...")} ' 5, now you can start the service through Go run Main.go--registry=mdns, and carry--registry=mdns Because my local Ubuntu system did not install consul to realize service discovery, so we adopted the GOMICRO official recommended method. [screenshot from 2017-10-11 17-42-03.png] (Http://upload-images.jianshu.io/upload_images/3365849-33f56af2c4e93f67.png?imagemogr2/auto-orient/strip%7cimageview2/2/w/ 1240) 6, to this step the client has not access to the service, need to do some processing, I here is a Web service, and then forward the client's request, the main function is implemented as follows: "' Gofunc main () {/* Scenario one: mux: = http. Newservemux () Mux. Handlefunc ("/", HANDLERPC) log. Println ("Listen on:8082") http. Listenandserve (": 8082", MUX) *//* Scenario two */service: = Web. NewService (web. Name (config. serviceprefix+ ". Web"), service. Handlefunc ("/", HANDLERPC) If err: = Service. Init (); Err! = Nil {log. Fatal (Err)}if err: = service. Run (); Err! = Nil {log. Fatal (Err)}} "" Here the main function is handlerpc this function, because the code is too much, the implementation can see the source. If you use Consul to implement service discovery, you can also implement it through scenario one, so that the port of the Web service is still fixed. 7. Open Web Service "' go$ go Run web.go--registry=mdnslistening on [::]:36859 ' 8, to this step the client can access the user's micro-service via the Web service port and interface and parameters, Access Link: (Here Amway postman, a Google plugin, super easy to use ...) "Gohttp://127.0.0.1:36859/user/selectuser" Tip: The project's source code (including the database of additions and deletions of the demo) can view [source] (https://gitee.com/xi_fan/ Ricoder_demo) 767 reads  ∙  2 likes  
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.