使用Gin + go-micro + consul 实现一个简单的微服务项目,实现服务注册与发现功能
一、引入依赖
gin框架: go get -u github.com/gin-gonic/gin
go-micro: go get -u -v github.com/micro/micro go get -u -v github.com/micro/go-micro
consul:windows版本:www.consul.io/downloads.html 下载后解压并添加系统变量
二、编写user微服务
1. 项目目录:
2. router.go:
import"github.com/gin-gonic/gin"funcInitRouters()*gin.Engine{ginRouter:=gin.Default()ginRouter.POST("/users/",func(context*gin.Context){context.String(200,"getuserInfo")})returnginRouter}
3. main.go
import("gin_micro/userserver/routers""github.com/micro/go-micro/registry""github.com/micro/go-micro/web""github.com/micro/go-plugins/registry/consul")varconsulRegregistry.Registryfuncinit(){consulReg=consul.NewRegistry(registry.Addrs("127.0.0.1:8500"),)}funcmain(){ginRouter:=routers.InitRouters()microService:=web.NewService(web.Name("userServer"),//web.RegisterTTL(30*time.Second),//设置注册服务的过期时间//web.RegisterInterval(20*time.Second),//设置间隔多久再次注册服务web.Address(":18001"),web.Handler(ginRouter),web.Registry(consulReg))microService.Run()}
三、编写order微服务
1. 项目目录:
2. router.go:
import"github.com/gin-gonic/gin"funcInitRouters()*gin.Engine{ginRouter:=gin.Default()ginRouter.POST("/orders/",func(ctx*gin.Context){ctx.String(200,"getorderInfo")})returnginRouter}
3. main.go
import("bytes""fmt""gin_micro/orderserver/routers""github.com/micro/go-micro/client/selector""github.com/micro/go-micro/registry""github.com/micro/go-micro/web""github.com/micro/go-plugins/registry/consul""net/http""time")varconsulRegregistry.Registryfuncinit(){consulReg=consul.NewRegistry(registry.Addrs("127.0.0.1:8500"))}funcmain(){//初始化路由ginRouter:=routers.InitRouters()//注册服务microService:=web.NewService(web.Name("orderServer"),//web.RegisterTTL(time.Second*30),//设置注册服务的过期时间//web.RegisterInterval(time.Second*20),//设置间隔多久再次注册服务web.Address(":18002"),web.Handler(ginRouter),web.Registry(consulReg),)//服务发现:获取服务地址hostAddress:=GetServiceAddr("userServer")iflen(hostAddress)<=0{fmt.Println("hostAddressisnull")}else{url:="http://"+hostAddress+"/users"response,_:=http.Post(url,"application/json;charset=utf-8",bytes.NewBuffer([]byte("")))fmt.Printf("发现服务,response=%v\n",response)}microService.Run()}//服务发现funcGetServiceAddr(serverNamestring)(addressstring){varretryTimesintfor{servers,err:=consulReg.GetService(serverName)fmt.Println(servers)iferr!=nil{fmt.Println(err.Error())}varservices[]*registry.Servicefor_,value:=rangeservers{fmt.Println(value.Name,":",value.Version)services=append(services,value)}//获取其中一个服务的信息next:=selector.RoundRobin(services)ifnode,err:=next();err==nil{address=node.Address}iflen(address)>0{return}//重试次数++retryTimes++time.Sleep(1*time.Second)//重试5次返回空ifretryTimes>=5{return}}}
四、启动项目
1. 启动consul: consul agent -dev -node hhh
2. 服务注册
分别启动 userserver/main.go 和 orderserver/main.go
将 userServer 和 orderServer 发布到consul上
浏览器输入 localhost:8500\ui 进入consul界面,查看已发布的微服务:
3. 服务发现
orderserver/main.go 中调用 userServer 微服务,并打印返回信息到控制台