做者:Jackphp
最近發現golang社區裏出了一個新星的微服務框架,來自好將來,光看這個名字,就頗有奔頭,以前,也只是玩過go-micro,其實真正的尚未在項目中運用過,只是以爲 微服務,grpc 這些很高大尚,尚未在項目中,真正的玩過,我看了一下官方提供的工具真的很好用,只須要定義好,溫馨文件jia結構 都生成了,只須要關心業務,加上最近 有個投票的活動,加上最近這幾年中臺也比較火,因此決定玩一下,node
開源地址: https://github.com/jackluo2012/datacentermysql
先聊聊中臺架構思路吧:nginx
中臺的概念大概就是把一個一個的app 統一塊兒來,反正我是這樣理解的。laravel
先聊用戶服務吧,如今一個公司有不少的公衆號,小程序,微信的,支付寶的,還有xxx xxx ,不少的平臺,每次開發的時候,咱們老是須要作用戶登錄的服務,不停的複製代碼,而後咱們就在思考能不能有一套獨立的用戶服務,只須要告訴我你須要傳個你要登錄的平臺(好比微信),微信登錄,須要的是客戶端返回給服務端一個code ,而後服務端拿着這個code去微信獲取用戶信息,反正你們都明白。git
咱們決定,將全部的信息 弄到 配置公共服務中去,裏面在存,微信,支付寶,以及其它平臺的 appid ,appkey,還有支付的appid,appkey,這樣就寫一套。github
最後說說實現吧,整個就一個repo:golang
網關,咱們用的是: go-zero的Api服務web
其它它的是服務,咱們就是用的go-zero的rpc服務redis
看下目錄結構
整個項目完成,我一我的操刀, 寫了1個來星期,我就實現了上面的中臺系統。
先看官方文檔 https://www.yuque.com/tal-tech/go-zero/yaoehb
咱們先把網關搭建起來
➜ blogs mkdir datacenter && cd datacenter ➜ datacenter go mod init datacenter go: creating new go.mod: module datacenter ➜ datacenter
查看book目錄:
➜ datacenter tree . └── go.mod 0 directories, 1 file
➜ datacenter goctl api -o datacenter.api Done. ➜ datacenter tree . ├── datacenter.api └── go.mod
分別包含了上面的 公共服務,用戶服務,投票活動服務
info( title: "中臺系統" desc: "中臺系統" author: "jackluo" email: "net.webjoy@gmail.com" ) // 獲取 應用信息 type Beid struct { Beid int64 `json:"beid"` } type Token struct{ Token string `json:"token"` } type WxTicket struct{ Ticket string `json:"ticket"` } type Application struct { Sname string `json:"Sname"` //名稱 Logo string `json:"logo"` // login Isclose int64 `json:"isclose"` //是否關閉 Fullwebsite string `json:"fullwebsite"` // 全站名稱 } type SnsReq struct{ Beid Ptyid int64 `json:"ptyid"` //對應平臺 BackUrl string `json:"back_url"` //登錄返回的地址 } type SnsResp struct{ Beid Ptyid int64 `json:"ptyid"` //對應平臺 Appid string `json:"appid"` //sns 平臺的id Title string `json:"title"` //名稱 LoginUrl string `json:"login_url"` //微信登錄的地址 } type WxShareResp struct { Appid string `json:"appid"` Timestamp int64 `json:"timestamp"` Noncestr string `json:"noncestr"` Signature string `json:"signature"` } @server( group: common ) service datacenter-api { @doc( summary: "獲取站點的信息" ) @handler votesVerification get /MP_verify_NT04cqknJe0em3mT.txt (SnsReq) returns (SnsResp) @handler appInfo get /common/appinfo (Beid) returns (Application) @doc( summary: "獲取站點的社交屬性信息" ) @handler snsInfo post /common/snsinfo (SnsReq) returns (SnsResp) // 獲取分享的 @handler wxTicket post /common/wx/ticket (SnsReq) returns (WxShareResp) } // 上傳須要登錄 @server( jwt: Auth group: common ) service datacenter-api { @doc( summary: "七牛上傳憑證" ) @handler qiuniuToken post /common/qiuniu/token (Beid) returns (Token) } // 註冊請求 type RegisterReq struct { // TODO: add members here and delete this comment Mobile string `json:"mobile"` // 基本一個手機號碼就完事 Password string `json:"password"` Smscode string `json:"smscode"` // 短信碼 } // 登錄請求 type LoginReq struct{ Mobile string `json:"mobile"` Type int64 `json:"type"` // 1.密碼登錄,2.短信登錄 Password string `json:"password"` } // 微信登錄 type WxLoginReq struct { Beid int64 `json:"beid"` // 應用id Code string `json:"code"` // 微信登錄密鑰 Ptyid int64 `json:"ptyid"` // 對應平臺 } //返回用戶信息 type UserReply struct { Auid int64 `json:"auid"` Uid int64 `json:"uid"` Beid int64 `json:"beid"` // 應用id Ptyid int64 `json:"ptyid"` // 對應平臺 Username string `json:"username"` Mobile string `json:"mobile"` Nickname string `json:"nickname"` Openid string `json:"openid"` Avator string `json:"avator"` JwtToken } // 返回APPUser type AppUser struct{ Uid int64 `json:"uid"` Auid int64 `json:"auid"` Beid int64 `json:"beid"` // 應用id Ptyid int64 `json:"ptyid"` // 對應平臺 Nickname string `json:"nickname"` Openid string `json:"openid"` Avator string `json:"avator"` } type LoginAppUser struct{ Uid int64 `json:"uid"` Auid int64 `json:"auid"` Beid int64 `json:"beid"` // 應用id Ptyid int64 `json:"ptyid"` // 對應平臺 Nickname string `json:"nickname"` Openid string `json:"openid"` Avator string `json:"avator"` JwtToken } type JwtToken struct { AccessToken string `json:"access_token,omitempty"` AccessExpire int64 `json:"access_expire,omitempty"` RefreshAfter int64 `json:"refresh_after,omitempty"` } type UserReq struct{ Auid int64 `json:"auid"` Uid int64 `json:"uid"` Beid int64 `json:"beid"` // 應用id Ptyid int64 `json:"ptyid"` // 對應平臺 } type Request { Name string `path:"name,options=you|me"` } type Response { Message string `json:"message"` } @server( group: user ) service user-api { @handler ping post /user/ping () @handler register post /user/register (RegisterReq) returns (UserReply) @handler login post /user/login (LoginReq) returns (UserReply) @handler wxlogin post /user/wx/login (WxLoginReq) returns (LoginAppUser) @handler code2Session get /user/wx/login () returns (LoginAppUser) } @server( jwt: Auth group: user middleware: Usercheck ) service user-api { @handler userInfo get /user/dc/info (UserReq) returns (UserReply) } // 投票活動api type Actid struct { Actid int64 `json:"actid"` //活動id } type VoteReq struct { Aeid int64 `json:"aeid"` // 做品id Actid } type VoteResp struct { VoteReq Votecount int64 `json:"votecount"` //投票票數 Viewcount int64 `json:"viewcount"` //瀏覽數 } // 活動返回的參數 type ActivityResp struct { Actid int64 `json:"actid"` Title string `json:"title"` //活動名稱 Descr string `json:"descr"` //活動描述 StartDate int64 `json:"start_date"` //活動時間 EnrollDate int64 `json:"enroll_date"` //投票時間 EndDate int64 `json:"end_date"` //活動結束時間 Votecount int64 `json:"votecount"` //當前活動的總票數 Viewcount int64 `json:"viewcount"` //當前活動的總瀏覽數 Type int64 `json:"type"` //投票方式 Num int64 `json:"num"` //投票幾票 } //報名 type EnrollReq struct { Actid Name string `json:"name"` // 名稱 Address string `json:"address"` //地址 Images []string `json:"images"` //做品圖片 Descr string `json:"descr"` // 做品描述 } // 做品返回 type EnrollResp struct { Actid Aeid int64 `json:"aeid"` // 做品id Name string `json:"name"` // 名稱 Address string `json:"address"` //地址 Images []string `json:"images"` //做品圖片 Descr string `json:"descr"` // 做品描述 Votecount int64 `json:"votecount"` //當前活動的總票數 Viewcount int64 `json:"viewcount"` //當前活動的總瀏覽數 } @server( group: votes ) service votes-api { @doc( summary: "獲取活動的信息" ) @handler activityInfo get /votes/activity/info (Actid) returns (ActivityResp) @doc( summary: "活動訪問+1" ) @handler activityIcrView get /votes/activity/view (Actid) returns (ActivityResp) @doc( summary: "獲取報名的投票做品信息" ) @handler enrollInfo get /votes/enroll/info (VoteReq) returns (EnrollResp) @doc( summary: "獲取報名的投票做品列表" ) @handler enrollLists get /votes/enroll/lists (Actid) returns(EnrollResp) } @server( jwt: Auth group: votes middleware: Usercheck ) service votes-api { @doc( summary: "投票" ) @handler vote post /votes/vote (VoteReq) returns (VoteResp) @handler enroll post /votes/enroll (EnrollReq) returns (EnrollResp) }
上面基本上寫就寫的API及文檔的思路
➜ datacenter goctl api go -api datacenter.api -dir . Done. ➜ datacenter tree . ├── datacenter.api ├── etc │ └── datacenter-api.yaml ├── go.mod ├── internal │ ├── config │ │ └── config.go │ ├── handler │ │ ├── common │ │ │ ├── appinfohandler.go │ │ │ ├── qiuniutokenhandler.go │ │ │ ├── snsinfohandler.go │ │ │ ├── votesverificationhandler.go │ │ │ └── wxtickethandler.go │ │ ├── routes.go │ │ ├── user │ │ │ ├── code2sessionhandler.go │ │ │ ├── loginhandler.go │ │ │ ├── pinghandler.go │ │ │ ├── registerhandler.go │ │ │ ├── userinfohandler.go │ │ │ └── wxloginhandler.go │ │ └── votes │ │ ├── activityicrviewhandler.go │ │ ├── activityinfohandler.go │ │ ├── enrollhandler.go │ │ ├── enrollinfohandler.go │ │ ├── enrolllistshandler.go │ │ └── votehandler.go │ ├── logic │ │ ├── common │ │ │ ├── appinfologic.go │ │ │ ├── qiuniutokenlogic.go │ │ │ ├── snsinfologic.go │ │ │ ├── votesverificationlogic.go │ │ │ └── wxticketlogic.go │ │ ├── user │ │ │ ├── code2sessionlogic.go │ │ │ ├── loginlogic.go │ │ │ ├── pinglogic.go │ │ │ ├── registerlogic.go │ │ │ ├── userinfologic.go │ │ │ └── wxloginlogic.go │ │ └── votes │ │ ├── activityicrviewlogic.go │ │ ├── activityinfologic.go │ │ ├── enrollinfologic.go │ │ ├── enrolllistslogic.go │ │ ├── enrolllogic.go │ │ └── votelogic.go │ ├── middleware │ │ └── usercheckmiddleware.go │ ├── svc │ │ └── servicecontext.go │ └── types │ └── types.go └── datacenter.go 14 directories, 43 files
咱們打開 etc/datacenter-api.yaml
把必要的配置信息加上
Name: datacenter-api Log: Mode: console Host: 0.0.0.0 Port: 8857 Auth: AccessSecret: 你的jwtwon Secret AccessExpire: 86400 CacheRedis: - Host: 127.0.0.1:6379 Pass: 密碼 Type: node UserRpc: Etcd: Hosts: - 127.0.0.1:2379 Key: user.rpc CommonRpc: Etcd: Hosts: - 127.0.0.1:2379 Key: common.rpc VotesRpc: Etcd: Hosts: - 127.0.0.1:2379 Key: votes.rpc
上面的 UserRpc
, CommonRpc
,還有 VotesRpc
這些我先寫上,後面再來慢慢加。
咱們先來寫 CommonRpc
服務。
➜ datacenter mkdir -p common/rpc && cd common/rpc
直接就新建在了,datacenter目錄中,由於common 裏面,可能之後會不僅會提供rpc服務,可能還有api的服務,因此又加了rpc目錄
➜ rpc goctl rpc template -o=common.proto ➜ rpc ls common.proto
往裏面填入內容:
➜ rpc cat common.proto syntax = "proto3"; package common; message BaseAppReq{ int64 beid=1; } message BaseAppResp{ int64 beid=1; string logo=2; string sname=3; int64 isclose=4; string fullwebsite=5; } // 請求的api message AppConfigReq { int64 beid=1; int64 ptyid=2; } // 返回的值 message AppConfigResp { int64 id=1; int64 beid=2; int64 ptyid=3; string appid=4; string appsecret=5; string title=6; } service Common { rpc GetAppConfig(AppConfigReq) returns(AppConfigResp); rpc GetBaseApp(BaseAppReq) returns(BaseAppResp); }
➜ rpc goctl rpc proto -src common.proto -dir . protoc -I=/Users/jackluo/works/blogs/datacenter/common/rpc common.proto --go_out=plugins=grpc:/Users/jackluo/works/blogs/datacenter/common/rpc/common Done.
➜ rpc tree . ├── common │ └── common.pb.go ├── common.go ├── common.proto ├── commonclient │ └── common.go ├── etc │ └── common.yaml └── internal ├── config │ └── config.go ├── logic │ ├── getappconfiglogic.go │ └── getbaseapplogic.go ├── server │ └── commonserver.go └── svc └── servicecontext.go 8 directories, 10 files
基本上,就把全部的目錄規範和結構的東西都生成了,就不用糾結項目目錄了,怎麼放了,怎麼組織了。
看一下,配置信息,裏面能夠寫入mysql和其它redis的信息:
Name: common.rpc ListenOn: 127.0.0.1:8081 Mysql: DataSource: root:admin@tcp(127.0.0.1:3306)/datacenter?charset=utf8&parseTime=true&loc=Asia%2FShanghai CacheRedis: - Host: 127.0.0.1:6379 Pass: Type: node Etcd: Hosts: - 127.0.0.1:2379 Key: common.rpc
咱們再來加上數據庫服務:
➜ rpc cd .. ➜ common ls rpc ➜ common pwd /Users/jackluo/works/blogs/datacenter/common ➜ common goctl model mysql datasource -url="root:admin@tcp(127.0.0.1:3306)/datacenter" -table="base_app" -dir ./model -c Done. ➜ common tree . ├── model │ ├── baseappmodel.go │ └── vars.go └── rpc ├── common │ └── common.pb.go ├── common.go ├── common.proto ├── commonclient │ └── common.go ├── etc │ └── common.yaml └── internal ├── config │ └── config.go ├── logic │ ├── getappconfiglogic.go │ └── getbaseapplogic.go ├── server │ └── commonserver.go └── svc └── servicecontext.go 10 directories, 12 files
這樣基本的一個 rpc
就寫完了,而後咱們將rpc 和model 還有api串連起來,這個官方的文檔已經很詳細了,這裏就只是貼一下代碼:
➜ common cat rpc/internal/config/config.go package config import ( "github.com/tal-tech/go-zero/core/stores/cache" "github.com/tal-tech/go-zero/zrpc" ) type Config struct { zrpc.RpcServerConf Mysql struct { DataSource string } CacheRedis cache.ClusterConf }
再在svc中修改:
➜ common cat rpc/internal/svc/servicecontext.go package svc import ( "datacenter/common/model" "datacenter/common/rpc/internal/config" "github.com/tal-tech/go-zero/core/stores/sqlx" ) type ServiceContext struct { c config.Config AppConfigModel model.AppConfigModel BaseAppModel model.BaseAppModel } func NewServiceContext(c config.Config) *ServiceContext { conn := sqlx.NewMysql(c.Mysql.DataSource) apm := model.NewAppConfigModel(conn, c.CacheRedis) bam := model.NewBaseAppModel(conn, c.CacheRedis) return &ServiceContext{ c: c, AppConfigModel: apm, BaseAppModel: bam, } }
上面的代碼已經將 rpc
和 model
數據庫關聯起來了,咱們如今再將 rpc
和 api
關聯起來:
➜ datacenter cat internal/config/config.go package config import ( "github.com/tal-tech/go-zero/core/stores/cache" "github.com/tal-tech/go-zero/rest" "github.com/tal-tech/go-zero/zrpc" ) type Config struct { rest.RestConf Auth struct { AccessSecret string AccessExpire int64 } UserRpc zrpc.RpcClientConf CommonRpc zrpc.RpcClientConf VotesRpc zrpc.RpcClientConf CacheRedis cache.ClusterConf }
加入 svc
服務中:
➜ datacenter cat internal/svc/servicecontext.go package svc import ( "context" "datacenter/common/rpc/commonclient" "datacenter/internal/config" "datacenter/internal/middleware" "datacenter/shared" "datacenter/user/rpc/userclient" "datacenter/votes/rpc/votesclient" "fmt" "net/http" "time" "github.com/tal-tech/go-zero/core/logx" "github.com/tal-tech/go-zero/core/stores/cache" "github.com/tal-tech/go-zero/core/stores/redis" "github.com/tal-tech/go-zero/core/syncx" "github.com/tal-tech/go-zero/rest" "github.com/tal-tech/go-zero/zrpc" "google.golang.org/grpc" ) type ServiceContext struct { Config config.Config GreetMiddleware1 rest.Middleware GreetMiddleware2 rest.Middleware Usercheck rest.Middleware UserRpc userclient.User //用戶 CommonRpc commonclient.Common VotesRpc votesclient.Votes Cache cache.Cache RedisConn *redis.Redis } func timeInterceptor(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { stime := time.Now() err := invoker(ctx, method, req, reply, cc, opts...) if err != nil { return err } fmt.Printf("調用 %s 方法 耗時: %v\n", method, time.Now().Sub(stime)) return nil } func NewServiceContext(c config.Config) *ServiceContext { ur := userclient.NewUser(zrpc.MustNewClient(c.UserRpc, zrpc.WithUnaryClientInterceptor(timeInterceptor))) cr := commonclient.NewCommon(zrpc.MustNewClient(c.CommonRpc, zrpc.WithUnaryClientInterceptor(timeInterceptor))) vr := votesclient.NewVotes(zrpc.MustNewClient(c.VotesRpc, zrpc.WithUnaryClientInterceptor(timeInterceptor))) //緩存 ca := cache.NewCache(c.CacheRedis, syncx.NewSharedCalls(), cache.NewCacheStat("dc"), shared.ErrNotFound) rcon := redis.NewRedis(c.CacheRedis[0].Host, c.CacheRedis[0].Type, c.CacheRedis[0].Pass) return &ServiceContext{ Config: c, GreetMiddleware1: greetMiddleware1, GreetMiddleware2: greetMiddleware2, Usercheck: middleware.NewUserCheckMiddleware().Handle, UserRpc: ur, CommonRpc: cr, VotesRpc: vr, Cache: ca, RedisConn: rcon, } }
這樣基本上,咱們就能夠在 logic
的文件目錄中調用了:
cat internal/logic/common/appinfologic.go package logic import ( "context" "datacenter/internal/svc" "datacenter/internal/types" "datacenter/shared" "datacenter/common/model" "datacenter/common/rpc/common" "github.com/tal-tech/go-zero/core/logx" ) type AppInfoLogic struct { logx.Logger ctx context.Context svcCtx *svc.ServiceContext } func NewAppInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) AppInfoLogic { return AppInfoLogic{ Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx, } } func (l *AppInfoLogic) AppInfo(req types.Beid) (appconfig *common.BaseAppResp, err error) { //檢查 緩存中是否有值 err = l.svcCtx.Cache.GetCache(model.GetcacheBaseAppIdPrefix(req.Beid), appconfig) if err != nil && err == shared.ErrNotFound { appconfig, err = l.svcCtx.CommonRpc.GetBaseApp(l.ctx, &common.BaseAppReq{ Beid: req.Beid, }) if err != nil { return } err = l.svcCtx.Cache.SetCache(model.GetcacheBaseAppIdPrefix(req.Beid), appconfig) } return }
這樣,基本就鏈接起來了,其它基本上就不用改了,UserRPC
, VotesRPC
相似,這裏就不在寫了。
go-zero
的確香,由於它有一個 goctl
的工具,他能夠自動的把代碼結構所有的生成好,咱們就再也不去糾結,目錄結構 ,怎麼組織,沒有個好幾年的架構能力是很差實現的,有什麼規範那些,併發,熔斷,徹底不用,考濾其它的,專心的實現業務就好,像微服務,還要有服務發現,一系列的東西,都不用關心,由於 go-zero
內部已經實現了。
我寫代碼也寫了有10多年了,以前一直用的 php,比較出名的就 laravel,thinkphp,基本上就是模塊化的,像微服那些實現直來真的有成本,可是你用上go-zero,你就像調api接口同樣簡單的開發,其它什麼服務發現,那些根本就不用關注了,只須要關注業務。
一個好的語言,框架,他們的底層思惟,永遠都是效率高,不加班的思想,我相信go-zero會提升你和你團隊或是公司的效率。go-zero的做者說,他們有個團隊專門整理go-zero框架,目的也應該很明顯,那就是提升,他們本身的開發效率,流程化,標準化,是提升工做效率的準則,像咱們平時遇到了問題,或是遇到了bug,我第一個想到的不是怎麼去解決個人bug,而是在想個人流程是否是有問題,個人哪一個流程會致使bug,最後我相信 go-zero
能成爲 微服務開發 的首選框架。
最後說說遇到的坑吧:
grpc
grpc
本人第一次用,而後就遇到了,有些字符爲空時,字段值不顯示的問題:
經過 grpc
官方庫中的 jsonpb
來實現,官方在它的設定中有一個結構體用來實現 protoc buffer
轉換爲JSON結構,並能夠根據字段來配置轉換的要求。
go-zero
中設置了,感受沒有效果,大佬說經過nginx 設置,後面發現仍是不行,最近強行弄到了一個域名下,後面有時間再解決。
sqlx
go-zero
的 sqlx
問題,這個真的費了很長的時間:
time.Time
這個數據結構,數據庫中用的是 timestamp 這個 好比個人字段 是delete_at 默認數庫設置的是null ,結果插入的時候,就報了Incorrect datetime value: '0000-00-00' for column 'deleted_at' at row 1"}
這個錯,查詢的時候報deleted_at\": unsupported Scan, storing driver.Value type \u003cnil\u003e into type *time.Time"
後面果斷去掉了這個字段,字段上面加上
.omitempty
這個標籤,好像也有用,db:".omitempty"
其次就是這個 Conversion from collation utf8_general_ci into utf8mb4_unicode_ci
,這個致使的大概緣由是,如今都喜歡用emj表情了,mysql數據識別不了。
mysql
這邊照樣按照原始的方式,將配置文件修改編碼格式,從新建立數據庫,而且設置數據庫編碼爲utf8mb4,排序規則爲 utf8mb4_unicode_ci
。
這樣的話,全部的表還有string字段都是這個編碼格式,若是不想全部的都是,能夠單獨設置,這個不是重點.由於在navicat上都好設置,手動點一下就好了。
重點來了:golang中使用的是 github.com/go-sql-driver/mysql
驅動,將鏈接 mysql
的 dsn
(由於我這使用的是gorm,因此dsn可能跟原生的格式不太同樣,不過不要緊, 只須要關注 charset
和 collation
就好了)
root:password@/name?parseTime=True&loc=Local&charset=utf8
修改成:
root:password@/name?parseTime=True&loc=Local&charset=utf8mb4&collation=utf8mb4_unicode_ci
https://github.com/tal-tech/go-zero
歡迎點贊👍