目标
- 搭建一个最简单的微服务架构
简介
GO kit是构建微服务的工具包,它能帮助我们解决分布式系统和应用程序体系结构中的常见问题,让我们能够更加专注于业务逻辑本身。
下载地址
Go-kit地址:github.com/go-kit/kit 本文中的程序代码:github.com/CalvinQiang… 提交点:搭建go-kit 最基本三层框架
GO-Kit 三层架构
-
Transport 主要负责与http, grpc, thrift等相关的逻辑
-
Endpoint 定义Request和Response格式,以及各种中间件
-
Service 业务类,接口
准备对应的结构
1.1 准备go.mod文件
module com.calvin.service
require github.com/go-kit/kit v0.10.0
go 1.14
1.2 完成server层 - 业务逻辑
- 这里我们主要定义了一个UserService的服务,并定义了一个GetName的方法(根据传入的userId,获取用户的名字)
package service
type IUserService interface {
GetName(userId int) string
}
type UserService struct {
}
func (s UserService) GetName(userId int) string {
if userId == 101 {
return "calvin"
}
return "guest"
}
1.3 完成Endpoint层 - 封装请求和相应
- 这里的
endpoint.Endpoint
实际上返回的是一个函数类型。 - Endpoint代表单个PRC方法,他是服务端和客户端的桥梁。
- 在这个RPC方法中,我们封装了用户的请求,以及对应的返回结构
package endpoint
import (
"com.calvin.service/service"
"context"
"github.com/go-kit/kit/endpoint"
)
type UserRequest struct {
Uid int `json:"uid"`
}
type UserResponse struct {
Result string `json:"result"`
}
func GetUserEndPoint(userService service.IUserService) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
r := request.(UserRequest)
result := userService.GetName(r.Uid)
return UserResponse{Result: result}, nil
}
}
1.3 完成Transport层 - 负责与http, grpc, thrift等相关的逻辑
- 这里我们定义数据的交互方式,可以是json/xml/二进制格式
- DecodeUserRequest方法用来解析用户发送来的数据
- EncodeUserResponse方法用来编码给客户发送的数据
package transport
import (
"com.calvin.service/endpoint"
"context"
"encoding/json"
"errors"
"net/http"
"strconv"
)
func DecodeUserRequest(ctx context.Context, r *http.Request) (interface{}, error) {
// 限定参数来源,我们直接从url的params中获取用户id
// 请求格式类似于:http://127.0.0.1?uid=101
if r.URL.Query().Get("uid") != "" {
uid, _ := strconv.Atoi(r.URL.Query().Get("uid"))
return endpoint.UserRequest{Uid: uid}, nil
}
return nil, errors.New("参数错误")
}
func EncodeUserResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error {
// 将返回体body置为json格式
w.Header().Set("Content-type", "application/json")
return json.NewEncoder(w).Encode(response)
}
1.4 编写主程序
package main
import (
"com.calvin.service/endpoint"
"com.calvin.service/service"
"com.calvin.service/transport"
httpTransport "github.com/go-kit/kit/transport/http"
"net/http"
)
func main() {
user := service.UserService{}
endPoint := endpoint.GetUserEndPoint(user)
// 构造服务,实现http.handler并包装endpoint层
serverHandler := httpTransport.NewServer(endPoint, transport.DecodeUserRequest, transport.EncodeUserResponse)
// 监听端口,并且使用serverHandler处理随之而来的请求
_ = http.ListenAndServe(":8080", serverHandler)
}
1.5 运行程序
-
请求http://127.0.0.1:8080, 我们会发现请求在解析过程中发生错误,还未进入server层
结尾
欢迎关注我的公众号【奇点之心】我会定期我的学习笔记,大家一起加油,一起努力