Qi
go-kit三层架构

搭建基本的三层架构

作者: Qi 发表时间: 2023-12-16 130

目标:搭建一个最简单的微服务架构

简介 GO kit是构建微服务的工具包,它能帮助我们解决分布式系统和应用程序体系结构中的常见问题,让我们能够更加专注于业务逻辑本身。 下载地址 Go-kit地址:github.com/go-kit/kit 提交点:搭建go-kit 最基本三层框架 GO-Kit 三层架构

Transport 主要负责与http, grpc, thrift等相关的逻辑
Endpoint 定义Request和Response格式,以及各种中间件
Service 业务类,接口

1.1 准备go.mod文件 go复制代码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)
}
go-kit

本文作者: Qi

版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!

我也是有底线的哦!

联系我呀

技术支持

学习网站

博主寄诗

学习是一辈子的事情,保持好奇心和学习的态度。

面对生活的挑战,要保持乐观的心态和勇气,相信自己能够克服困难。