这是我参与「第三届青训营 -后端场」笔记创作活动的第3篇笔记
为什么用docker部署
分布式的服务有着这样的一些功能:容灾,负载均衡,自动扩容缩容……这些服务都是需要把一个服务部署好几次的,这就需要一些容器编排的功能比如docker-compose,k8s。但无论用哪种容器编排工具都需要一个符合容器协议的容器技术比如podman或者docker,这次实现我选择docker。用docker把程序打包起来便是第一步。
步骤
- 编写并编译好基于kitex框架开发的go程序
- 打包go程序
- 编写Dockerfile
- 打包成镜像
- 运行测试
编写并编译好基于kitex框架开发的go程序
test.thrift
namespace go api
struct MyRequest{
1: string message
}
struct MyResponse{
1: string message
}
service MyTest {
MyResponse echo(1: MyRequest req)
}
handler.go
package main
import (
"context"
"kitex-test/server/kitex_gen/api"
)
// MyTestImpl implements the last service interface defined in the IDL.
type MyTestImpl struct{}
// Echo implements the MyTestImpl interface.
func (s *MyTestImpl) Echo(ctx context.Context, req *api.MyRequest) (resp *api.MyResponse, err error) {
// TODO: Your code here...
resp = &api.MyResponse{}
resp.SetMessage("hello world")
return
}
打包go程序
执行kitex自动生成的build.sh即可
编写Dockerfile
FROM centos
ADD output /ouput
CMD ["sh","/ouput/bootstrap.sh"]
打包成镜像
docker build -t test-kitex:v1 .
编写客户端
其中172.17.0.2为docker容器的ip,在平时使用的集群里面不用特意去指定容器ip,比如使用k8s的话,暴露一个service,用service的ip即可。
package main
import (
"context"
"fmt"
"github.com/cloudwego/kitex/client"
"kitex-test/server/kitex_gen/api"
"kitex-test/server/kitex_gen/api/mytest"
"log"
"time"
)
func main() {
client, err := mytest.NewClient("myTest", client.WithHostPorts("172.17.0.2:8888"))
if err != nil {
fmt.Println("test")
log.Fatal(err)
}
for {
req := &api.MyRequest{Message: "hello!"}
resp, err := client.Echo(context.Background(), req)
if err != nil {
log.Fatal(err)
}
log.Println(resp)
time.Sleep(time.Second)
}
}
运行测试
运行docker容器
docker run test-kitex:v4
运行客户端
[root@nginx client]# go run main.go
2022/06/08 01:02:21 MyResponse({Message:hello world})
2022/06/08 01:02:22 MyResponse({Message:hello world})
2022/06/08 01:02:23 MyResponse({Message:hello world})
2022/06/08 01:02:24 MyResponse({Message:hello world})
2022/06/08 01:02:25 MyResponse({Message:hello world})