1.go环境配置
[guest@localhost test]$ vi /etc/profile
...
export GOROOT=/usr/local/go
export GOBIN=/root/go/bin
export GOPATH=/root/go
export PATH=$PATH:$GOBIN
export PATH=$PATH:$GOROOT/bin
[guest@localhost test]$ source /etc/profile
2.micro框架安装
[guest@localhost test]$ go get -u github.com/micro/micro
[guest@localhost test]$ go get -u github.com/golang/protobuf/protoc-gen-go
[guest@localhost test]$ go get github.com/micro/protobuf/proto
[guest@localhost test]$ go get github.com/micro/protoc-gen-micro
3.启动consul
[guest@localhost]$ docker run -itd -p 8300:8300 -p 8301:8301 -p 8301:8301/udp -p 8302:8302/udp -p 8302:8302 -p 8400:8400 -p 8500:8500 -p 53:53/udp --name consul consul
4.编写main.go
package main
import (
"fmt"
"strconv"
"github.com/gin-gonic/gin"
"github.com/micro/go-micro/v2/registry"
"github.com/micro/go-micro/v2/web"
"github.com/micro/go-plugins/registry/consul/v2"
)
var reg registry.Registry
func init() {
reg = consul.NewRegistry(registry.Addrs("127.0.0.1:8500")) // consul.NewRegistry(registry.Addrs("127.0.0.1:8500"))
}
func initWeb() *gin.Engine {
r := gin.Default()
r.GET("/math/add", func(c *gin.Context) {
x, _ := strconv.Atoi(c.Query("x"))
y, _ := strconv.Atoi(c.Query("y"))
z := x + y
c.String(200, fmt.Sprintf("z=%d", z))
})
return r
}
func main() {
service := web.NewService(
web.Name("math_service"),
web.Address(":50000"),
web.Handler(initWeb()),
web.Registry(reg),
)
_ = service.Run()
}
5.运行测试
[guest@localhost test]$ go mod init && go mod tidy
[guest@localhost test]$ go run main.go
[guest@localhost test]$ curl http://localhost:50000/math/add?x=5&y=6
z=11
可以在浏览器访问:8500查看当前注册的服务