• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

go-micro v2版本 微服务框架 实战1

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

go version  1.14.3

 最终代码地址:github地址

etcd 请先自行安装或者下载win版本的直接可以启动

etcd下载

安装 go get github.com/micro/go-micro/v2

安装工具protobuf相关工具

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

自己的生成工具

go get github.com/micro/protoc-gen-micro/v2

 

proto文件

syntax = "proto3";
package  Users;

service UserService {
    rpc Test(UserRequest) returns (UserResponse) {}
}
message UserRequest {
    string id = 1;
}
message UserResponse {
    string ret = 2;
}

 

type UserService struct{}

func (g *UserService) Test(ctx context.Context, req *Users.UserRequest, rsp *Users.UserResponse) error {
    rsp.Ret="users"
    return nil
}

 

生成

protoc --proto_path=src/protos   --micro_out=src/Users --go_out=src/Users   Users.proto

运行 

service := micro.NewService(
        micro.Name("UserService"),
    )
     
    service.Init()

 
    Users.RegisterUserServiceHandler(service.Server(), new(UserService))
 
    if err := service.Run(); err != nil {
        fmt.Println(err)
    }

 

package main

import (
    "context"
    "github.com/micro/go-micro/v2"
    "jtthink/src/Users"
    "log"
)

type UserService struct{}
func (g *UserService) Test(ctx context.Context, req *Users.UserRequest, rsp *Users.UserResponse) error {
    rsp.Ret="users"
    return nil
}
func NewUserService() *UserService  {
    return &UserService{}
}
func main()  {

    service:=micro.NewService(
        micro.Name("UserService"))

    service.Init()

    err:=Users.RegisterUserServiceHandler(service.Server(),NewUserService())
    if err!=nil{
        log.Fatal(err)
    }
    if err = service.Run(); err != nil {
        log.Println(err)
    }



}
src\cmd\server.go

 

syntax = "proto3";
package  Users;

service UserService {
    rpc Test(UserRequest) returns (UserResponse) {}
}
message UserRequest {
    string id = 1;
}
message UserResponse {
    string ret = 2;
}
src\protos\Users.proto

 

module jtthink

go 1.14

require (
    github.com/golang/protobuf v1.3.5
    github.com/micro/go-micro/v2 v2.4.0
    github.com/micro/protoc-gen-micro/v2 v2.0.0 // indirect
)
go.mod

 

go run src/cmd/server.go

 2,使用etcd注册服务、web管理界面、api网关

 

 

 

安装Micro工具

go get github.com/micro/micro/v2

serc/cmd/server.go

package main

import (
    "context"
    "github.com/micro/go-micro/v2"
    "jtthink/src/Users"
    "log"
)

type UserService struct{}
func (g *UserService) Test(ctx context.Context, req *Users.UserRequest, rsp *Users.UserResponse) error {
    rsp.Ret="users"+req.Id
    return nil
}
func NewUserService() *UserService  {
    return &UserService{}
}
func main()  {
//api.jtthink.com --- prefix
    service:=micro.NewService(
        micro.Name("api.jtthink.com.user"))
    service.Init()

    err:=Users.RegisterUserServiceHandler(service.Server(),NewUserService())
    if err!=nil{
        log.Fatal(err)
    }
    if err = service.Run(); err != nil {
        log.Println(err)
    }



}
package main

import (
    "context"
    "github.com/micro/go-micro/v2"
    "jtthink/src/Users"
    "log"
)

type UserService struct{}
func (g *UserService) Test(ctx context.Context, req *Users.UserRequest, rsp *Users.UserResponse) error {
    rsp.Ret="users"+req.Id
    return nil
}
func NewUserService() *UserService  {
    return &UserService{}
}
func main()  {
//api.jtthink.com --- prefix
    service:=micro.NewService(
        micro.Name("api.jtthink.com.user"))
    service.Init()

    err:=Users.RegisterUserServiceHandler(service.Server(),NewUserService())
    if err!=nil{
        log.Fatal(err)
    }
    if err = service.Run(); err != nil {
        log.Println(err)
    }



}
src/protos/Users.proto

生成文件:

protoc --proto_path=src/protos   --micro_out=src/Users --go_out=src/Users   Users.proto

 

 

 

启动我们的服务

set MICRO_REGISTRY=etcd

set MICRO_REGISTRY_ADDRESS=localhost:2379

go run src/cmd/server.go

 

web管理界面

set MICRO_REGISTRY=etcd
set MICRO_REGISTRY_ADDRESS=localhost:2379
micro web
默认是 localhost:8082   就可以看到我们的服务

启动网关

set MICRO_REGISTRY=etcd
set MICRO_REGISTRY_ADDRESS=127.0.0.1:2379
set MICRO_CLIENT=grpc
set MICRO_SERVER=grpc
set MICRO_API_NAMESPACE=api.jtthink.com
micro api

 

请求:

POST http://localhost:8080/user/userService/test

 

3,快速创建第二个服务:课程服务

 

 

syntax = "proto3";
package  Course;

service CourseService {
    rpc ListForTop(ListRequest) returns (ListResponse) {}
}
message CourseModel{
    int32 course_id=1;
    string course_name=2;

}
message ListRequest {
    int32 size = 1;
}
message ListResponse {
    repeated CourseModel result = 1;
}
D:\gocode1.14.3\gocode\gjj\src\protos\Course.proto
package main

import (
    "github.com/micro/go-micro/v2"
    "jtthink/src/Course"

    "log"
)


func main()  {
    service:=micro.NewService(
        micro.Name("api.jtthink.com.course"))
    service.Init()

    err:=Course.RegisterCourseServiceHandler(service.Server(),Course.NewCourseServiceImpl())
    if err!=nil{
        log.Fatal(err)
    }
    if err = service.Run(); err != nil {
        log.Println(err)
    }
}
D:\gocode1.14.3\gocode\gjj\src\cmd\course_server.go
package Course

import "context"

func NewCourseModel(id int32,name string) *CourseModel  {
    return &CourseModel{CourseId:id,CourseName:name}
}
type CourseServiceImpl struct{}
func(this *CourseServiceImpl) ListForTop(ctx context.Context, req *ListRequest, rsp *ListResponse) error{
   ret:=make([]*CourseModel,0)
   ret=append(ret,NewCourseModel(101,"java课程"),NewCourseModel(102,"PHP课程"))
   rsp.Result=ret
   return nil
}
func NewCourseServiceImpl() *CourseServiceImpl  {
  return &CourseServiceImpl{}
}
D:\gocode1.14.3\gocode\gjj\src\Course\helper.go

 

生成文件:

protoc --proto_path=src/protos   --micro_out=src/Users --go_out=src/Users   Users.proto
protoc --proto_path=src/protos   --micro_out=src/Course --go_out=src/Course   Course.proto

 

启动服务

课程服务:

set MICRO_REGISTRY=etcd
set MICRO_REGISTRY_ADDRESS=localhost:2379
go run src/cmd/course_server.go --server_address :9091

 

用户服务

set MICRO_REGISTRY=etcd
set MICRO_REGISTRY_ADDRESS=localhost:2379
go run src/cmd/user_server.go --server_address :9090

 

web管理界面

set MICRO_REGISTRY=etcd
set MICRO_REGISTRY_ADDRESS=localhost:2379
micro web

 

启动micro网关

set MICRO_REGISTRY=etcd
set MICRO_REGISTRY_ADDRESS=localhost:2379
set MICRO_API_NAMESPACE=api.jtthink.com
set MICRO_CLIENT=grpc
set MICRO_SERVER=grpc
micro api --handler=rpc

 

如果不出问题:

 

 

 

通过网关访问课程服务

 

 

通过网关访问用户服务

 

 

使用micro管理工具:

micro get service  api.jtthink.com.course
 micro get service  api.jtthink.com.course
service  api.jtthink.com.course

version latest

ID      Address Metadata
api.jtthink.com.course-9da60d36-d727-4891-b88f-74cecf90b80d     192.168.1.101:9091      transport=grpc,broker=http,protocol=grpc,registry=etcd,server=grpc

Endpoint: CourseService.ListForTop

Request: {
        message_state MessageState {
                no_unkeyed_literals NoUnkeyedLiterals
                do_not_compare DoNotCompare
                do_not_copy DoNotCopy
                message_info MessageInfo
        }
        int32 int32
        unknown_fields []uint8
        size int32
}

Response: {
        message_state MessageState {
                no_unkeyed_literals NoUnkeyedLiterals
                do_not_compare DoNotCompare
                do_not_copy DoNotCopy
                message_info MessageInfo
        }
        int32 int32
        unknown_fields []uint8
        result []CourseModel
}

 

micro call  api.jtthink.com.course  CourseService.ListForTop "{\"size\":10}"
$ micro call  api.jtthink.com.course  CourseService.ListForTop "{\"size\":10}"
{
        "result": [
                {
                        "course_id": 101,
                        "course_name": "java课程"
                },
                {
                        "course_id": 102,
                        "course_name": "PHP课程"
                }
        ]
}

4,创建”单纯”的http api、调用grpc服务

package main

import (
    "context"
    "github.com/micro/go-micro/v2/client/grpc"
    "github.com/micro/go-micro/v2/web"
    "jtthink/src/Course"
    "log"
    "net/http"
)

func main()  {
    service:=web.NewService(
        web.Name("api.jtthink.com.http.course"))
    c:=grpc.NewClient()

    service.HandleFunc("/test", func(writer http.ResponseWriter, request *http.Request) {
        c:=Course.NewCourseService("api.jtthink.com.course",c)
        course_rsp,_:=c.ListForTop(context.Background(),&Course.ListRequest{Size:10})
        log.Println(course_rsp.Result)
        writer.Write([]byte("http api test"))
    })
    service.Init()
    if err:= service.Run(); err != nil {
        log.Println(err)
    }
}
D:\gocode1.14.3\gocode\gjj\src\cmd\course_http_server.go

 

启动http服务

set MICRO_REGISTRY=etcd
set MICRO_REGISTRY_ADDRESS=localhost:2379
go run src/cmd/course_http_server.go --server_address :9000

 

 

 

 

 

 

5,go-micro快速集成gin开发http api

package main

import (
	"context"
	"github.com/gin-gonic/gin"
	"github.com/micro/go-micro/v2/client/grpc"
	"github.com/micro/go-micro/v2/web"
	"jtthink/src/Course"
	"log"
)

func main()  {
	c:=grpc.NewClient()
	r:=gin.New()
	r.Handle("GET","/test", func(ctx *gin.Context) {
	    c:=Course.NewCourseService("api.jtthink.com.course",c)
	    course_rsp,_:=c.ListForTop(context.Background(),&Course.ListRequest{Size:10})
		ctx.JSON(200,gin.H{"Result":course_rsp.Result})
	})
	service:=web.NewService(
		web.Name("api.jtthink.com.http.course"),
		web.Handler(r),
	 )

	service.Init()
	if err:= service.Run(); err != nil {
		log.Println(err)
	}

}

  

运行:

set MICRO_REGISTRY=etcd
set MICRO_REGISTRY_ADDRESS=localhost:2379
go run src/cmd/course_http_server.go --server_address :9000

 

 

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Eclipse配置Go语言开发环境(GoEclipse)发布时间:2022-07-10
下一篇:
go 格式化输出发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap