{"id":28836237,"url":"https://github.com/weaxs/microservice_go_kubernetes","last_synced_at":"2026-04-24T11:38:26.234Z","repository":{"id":180850316,"uuid":"658747104","full_name":"Weaxs/microservice_go_kubernetes","owner":"Weaxs","description":"Go版本Kubernetes微服务实现，需求参考《凤凰架构》Kubernetes微服务。","archived":false,"fork":false,"pushed_at":"2023-07-20T04:19:08.000Z","size":168,"stargazers_count":1,"open_issues_count":0,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-06-19T11:02:02.811Z","etag":null,"topics":["configmaps","golang","hertz","kitex","kubernetes","microservice","skaffold"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Weaxs.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2023-06-26T12:09:53.000Z","updated_at":"2025-01-05T07:50:10.000Z","dependencies_parsed_at":"2025-06-19T11:02:16.748Z","dependency_job_id":null,"html_url":"https://github.com/Weaxs/microservice_go_kubernetes","commit_stats":null,"previous_names":["weaxs/microservice_go_kubernetes"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/Weaxs/microservice_go_kubernetes","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Weaxs%2Fmicroservice_go_kubernetes","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Weaxs%2Fmicroservice_go_kubernetes/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Weaxs%2Fmicroservice_go_kubernetes/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Weaxs%2Fmicroservice_go_kubernetes/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Weaxs","download_url":"https://codeload.github.com/Weaxs/microservice_go_kubernetes/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Weaxs%2Fmicroservice_go_kubernetes/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":260738881,"owners_count":23055065,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["configmaps","golang","hertz","kitex","kubernetes","microservice","skaffold"],"created_at":"2025-06-19T11:01:40.157Z","updated_at":"2025-10-23T02:28:24.922Z","avatar_url":"https://github.com/Weaxs.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# 搭建Go版本Kubernetes微服务示例\n\n# 前言\n\n此项目示例主要是参考[Java版Kubernets微服务示例](https://icyfenix.cn/exploration/projects/microservice_arch_kubernetes.html)，在业务需求相同的情况下，搭建一个Golang版本的Kubernetes项目\n\n项目代码：[Go微服务架构 Kubernetes](https://github.com/Weaxs/microservice_go_kubernetes)\n\n# 架构图\n\n本项目和Java版本的示例类似架构，也是采用的DDD领域驱动设计，故架构图如下：\n\n![Untitled](https://raw.githubusercontent.com/fenixsoft/awesome-fenix/master/.vuepress/public/images/kubernetes-ms.png)\n\n# 模块\n\n本项目分别采用了字节的kitex和hertz框架构建的微服务，具体的内容包括：\n\n- 框架方面，domain领域模块(account/payment/warehouse)采用的[**Kitex框架**](https://www.cloudwego.io/docs/kitex/)；gateway网关采用的**[Hertz框架](https://www.cloudwego.io/docs/hertz/)**，网关目前只做了简单的转发验签\n- 配置方面，使用https://github.com/spf13/viper读取 toml 文件，同时兼容了environment环境变量\n- 通信和序列化协议方面，account领域提供了RPC+Thrift协议进行内部服务间调用；payment和warehouse模块提供了RPC+Protobuf协议进行内部服务间调用；gateway模块提供了RESTful接口供外部前端模块使用\n\n\u003e Kitex框架中序列化的代码生成，具体参考[代码生成工具](https://www.cloudwego.io/zh/docs/kitex/tutorials/code-gen/code_generation/)\n\u003e\n\n# 技术组件\n\n采用基于Kubernetes的微服务架构，其中的技术组件包括\n\n- **配置中心**：采用的 Kubernetes 的 ConfigMap 来管理配置文件。在Kubernetes的 Deployment 中，将 ConfigMap 中的配置文件映射到Pod容器内，使用 viper 读取容器中配置文件并实现动态更新。\n- **服务发现**：采用 Kubernetes 的Service 来管理，通过 Kubernetes 的 NameSpace 名称空间，使用 Service name 自动将 RPC 访问中的服务路由到对应容器。\n- **服务网关**：仅用hertz框架搭建了一个简易的网关，只是进行简单的 restful 到 RPC 的请求转发，并使用Oauth中间键做权限校验。\n- **认证授权**：采用[Google OAuth2](https://github.com/golang/oauth2)\n\n# 镜像构建\n\nDockerFile 中的镜像生成，将镜像构建和镜像运行分为了两步：\n\n- 使用golang:1.20镜像作为builder，编译构建微服务，产出二进制文件\n- 使用alpine镜像运行 builder 中产生的二进制文件\n\n以gateway模块为例，具体的操作如下：\n\n```docker\nFROM golang:1.20 as builder\n\nRUN mkdir /app\nWORKDIR /app\n\nENV GO111MODULE=on \\\n    GOPROXY=https://goproxy.cn,direct \\\n    PORT=8888\n\nCOPY *.go ./\nCOPY go.mod go.sum ./\nRUN go mod tidy\nRUN CGO_ENABLED=0 go build -o bookstore-platform-gateway *.go\n\n###################################################################\n# Run container\nFROM alpine:latest\n\nRUN apk --no-cache add ca-certificates\n\nRUN mkdir /app\nWORKDIR /app\nCOPY conf/*.toml conf/\nCOPY --from=builder /app/bookstore-platform-gateway .\n\nEXPOSE $PORT\n\n# Run\nCMD [ \"./bookstore-platform-gateway\" ]\n```\n\n# 运行程序\n\n相比于《凤凰架构》中的原工程，这里仅支持 [Skaffold](https://skaffold.dev/) 的方式运行。\n\nSkaffold 是根据`skaffold.yml`中的配置来进行的，开发时 skaffold 通过`dev`指令来执行这些配置。\n\n# 拓展\n\n## Kitex Protobuf 中使用 google.timestamp 的序列化问题\n\nkitex 框架中 fastpb 部分对于 google.timestamp 的序列化暂无支持，具体 issue 可以追溯到 https://github.com/cloudwego/kitex/issues/835，这里通过 string 类型兼容了这一处理，具体操作如下：\n\n```protobuf\nimport \"google/protobuf/timestamp.proto\";\n\nmessage Payment {\n  google.protobuf.Timestamp createTime = 1;\n  string payId = 2;\n  double totalPrice = 3;\n  int64 expires = 4;\n  string paymentLink = 5;\n}\n```\n\n```go\ntype Payment struct {\n\tstate         protoimpl.MessageState\n\tsizeCache     protoimpl.SizeCache\n\tunknownFields protoimpl.UnknownFields\n\n\tCreateTime  *timestamppb.Timestamp `protobuf:\"bytes,1,opt,name=createTime,proto3\" json:\"createTime,omitempty\"`\n\tPayId       string                 `protobuf:\"bytes,2,opt,name=payId,proto3\" json:\"payId,omitempty\"`\n\tTotalPrice  float64                `protobuf:\"fixed64,3,opt,name=totalPrice,proto3\" json:\"totalPrice,omitempty\"`\n\tExpires     int64                  `protobuf:\"varint,4,opt,name=expires,proto3\" json:\"expires,omitempty\"`\n\tPaymentLink string                 `protobuf:\"bytes,5,opt,name=paymentLink,proto3\" json:\"paymentLink,omitempty\"`\n}\n\nfunc (x *Payment) fastReadField1(buf []byte, _type int8) (offset int, err error) {\n\tvalue, offset, err := fastpb.ReadString(buf, _type)\n\tif err != nil {\n\t\treturn offset, err\n\t}\n\ttimestamp, _ := time.Parse(time.RFC3339Nano, value)\n\tx.CreateTime = \u0026timestamppb.Timestamp{Seconds: timestamp.Unix(), Nanos: int32(timestamp.Nanosecond())}\n\treturn offset, nil\n}\n\nfunc (x *Payment) fastWriteField1(buf []byte) (offset int) {\n\tif x.CreateTime == nil {\n\t\treturn offset\n\t}\n\ttimestamp := x.GetCreateTime().AsTime()\n\toffset += fastpb.WriteString(buf[offset:], 1, timestamp.Format(time.RFC3339Nano))\n\treturn offset\n}\n\nfunc (x *Payment) sizeField1() (n int) {\n\tif x.CreateTime == nil {\n\t\treturn n\n\t}\n\ttimestamp := x.GetCreateTime().AsTime()\n\tn += fastpb.SizeString(1, timestamp.Format(time.RFC3339Nano))\n\treturn n\n}\n```\n\n## Viper 读取 ConfigMap 配置\n\n采用 Kubernetes ConfigMap 定义`config.toml` 配置文件，在使用 Kubernetes Deployment 构建过程中，将 ConfigMap 映射到 volumes ，并在 volumes 映射到 container 对应的配置文件目录。具体的操作示例如下：\n\n```yaml\n# ConfigMap 定义配置配置文件config.toml\nkind: ConfigMap\napiVersion: v1\nmetadata:\n  name: gateway\n  namespace: bookstore-microservices\ndata:\n  config.toml: |-\n    [account.client]\n    connnum = 1\n    hostport = [\"account:8810\"]\n\n    [payment.client]\n    connnum = 1\n    hostport = [\"payment:8812\"]\n\n    [warehouse.client]\n    connnum = 1\n    hostport = [\"warehouse:8811\"]\n\n---\nkind: Deployment\napiVersion: apps/v1\nmetadata:\n  name: bookstore-platform-gateway\n  namespace: bookstore-microservices\n  labels:\n    app: gateway\nspec:\n  replicas: 1\n  selector:\n    matchLabels:\n      app: gateway\n  template:\n    metadata:\n      labels:\n        app: gateway\n    spec:\n      serviceAccountName: book-admin\n      containers:\n        - name: gateway\n          image: icyfenix/bookstore-platform-gateway\n          ports:\n            - name: http-server\n              containerPort: 8888\n          env:\n            - name: CONFIG_PATH\n              value: /app/conf/config.toml\n          # volumes 映射到 container 中的配置文件目录\n          volumeMounts:\n            - name: config-volume\n              mountPath: /app/conf\n      # 映射 configmap 到 volumes\n      volumes:\n        - name: config-volume\n          configMap:\n            name: gateway\n```\n\n微服务层面，使用 viper 读取对应的配置文件，具体操作如下：\n\n```go\nfunc NewConfig() (v *viper.Viper) {\n\tv = viper.New()\n\tv.SetDefault(configPathKey, defaultConfigPath)\n\tdefaultClientConfig(v)\n\tv.AutomaticEnv()\n\t// 通过ENV获取\n\tv.SetEnvKeyReplacer(strings.NewReplacer(\".\", \"_\"))\n\tv.SetTypeByDefaultValue(true)\n\tv.SetConfigFile(v.GetString(configPathKey))\n\terr := v.ReadInConfig()\n\tif err != nil {\n\t\tklog.CtxErrorf(context.Background(), err.Error())\n\t}\n\tv.WatchConfig()\n\tv.OnConfigChange(func(in fsnotify.Event) {\n\t\tklog.CtxErrorf(context.Background(), \"Config file changed: %s\", in.Name)\n\t})\n\treturn\n}\n```\n\n# 框架\n\n[https://github.com/cloudwego/kitex](https://github.com/cloudwego/kitex)\n\n[https://github.com/cloudwego/hertz](https://github.com/cloudwego/hertz)\n\n[https://github.com/spf13/viper](https://github.com/spf13/viper)\n\n[https://github.com/golang/oauth2](https://github.com/golang/oauth2)\n\n# 参考\n\n[go微服务示例——shippy](https://github.com/EwanValentine/shippy)\n\n[《凤凰架构》——Java基于Kubernetes的微服务架构实例](https://github.com/fenixsoft/microservice_arch_kubernetes)\n\n[kitex-examples 示例工程](https://github.com/cloudwego/kitex-examples)\n\n[hertz-examples 示例工程](https://github.com/cloudwego/hertz-examples)\n\n[viper 读取 ConfigMap 配置](https://medium.com/@xcoulon/kubernetes-configmap-hot-reload-in-action-with-viper-d413128a1c9a)\n\n[Kubernetes Deployment 添加 ConfigMap 和 Secret 配置映射](https://medium.com/@xcoulon/managing-pod-configuration-using-configmaps-and-secrets-in-kubernetes-93a2de9449be)","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fweaxs%2Fmicroservice_go_kubernetes","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fweaxs%2Fmicroservice_go_kubernetes","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fweaxs%2Fmicroservice_go_kubernetes/lists"}