go-kit
https://github.com/go-kit/kit
https://gokit.io/
go-kit 本身不是一个框架,而是一套微服务工具集,是框架的底层,可以用Go-kit 做适应自己平台的框架。
go-kit 采用三层架构方式,自上而下分别为:Transport、Endpoint、Service。
Transport层主要负责请求协议的实现和路由转发,例如HTTP、gRPC、Thrift等;
Endpoint层主要负责功能逻辑转发,这一层会调用Service具体方法,是go-kit的核心,提供了对日志、限流、熔断、链路追踪、服务监控等方面的扩展能力;
Service层则专注于业务逻辑。
为了帮助开发者构建微服务,go-kit提供了对consul、etcd、zookeeper、eureka等注册中心的支持。
缺点:框架繁琐、代码冗余
demo
使用Go-kit 代码生成工具 truss, 通过truss你可以快速编写Go-kit中繁杂的代码, 并生成支持http和grpc两种调用方式的服务
- 定义接口
(1)安装truss: https://github.com/tuneinc/truss#install
(2)编写.proto文件来定义服务
syntax = "proto3";
// 定义你的包名
package echo;
import "https://github.com/tuneinc/truss/deftree/googlethirdparty/annotations.proto";
// 定义你的服务名
service Echo {
// 定义一个方法Echo,输入 EchoRequest ,输出 EchoResponse
// EchoRequest 和EchoResponse 在下面的代码中定义
rpc Echo (EchoRequest) returns (EchoResponse) {
option (google.api.http) = {
// http接口使用GET方法路由至/echo, 所有的字段都会放到query string中
get: "/echo"
};
}
// 定义一个方法Louder,输入 LouderRequest ,输出 EchoResponse
rpc Louder (LouderRequest) returns (EchoResponse) {
option (google.api.http) = {
// http接口使用POST方法路由至/louder/{Loudness}
post: "/louder/{Loudness}"
// 所有字段都会被从Body中以http/json方式获取
body: "*"
};
}
}
message EchoRequest {
string In = 1;
}
message LouderRequest {
string In = 1;
int32 Loudness = 2;
}
message EchoResponse {
string Out = 1;
}
(3)执行truss *.proto , 生成你的服务
(4)在handlers中注入你所需要的中间件, 如日志, 服务发现, 负载均衡, Metrics, 限流器, 断路器等
(5)在handlers/handlers.go文件中实现服务的业务逻辑
(6)运行
运行成功后打印 Http Server start at port:9000
http请求:http://localhost:9000/xxxx/xxx
restful demo
https://github.com/Kevin005/gokit-simple-restful-golang
目录:
编译、运行
go build ./
请求
get: http://localhost:8080/calculate/result -v
post: http://localhost:8080/calculate/Add/1/1 -X POST -v