API Gateway
代码调用 food rpc
服务
编辑 api/internal/handler
下的 addfoodhandler.go
文件,新增如下代码
func AddFoodHandler(ctx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.AddFoodRequest
if err := httpx.Parse(r, &req); err != nil {
httpx.OkJson(w, ningxi.FailureResponse(nil,err.Error(),1000))
return
}
userId:=r.Header.Get("x-user-id")
l := logic.NewAddFoodLogic(r.Context(), ctx)
resp, err := l.AddFood(req,userId)
if err != nil {
httpx.OkJson(w, ningxi.FailureResponse(nil,err.Error(),1000))
} else {
httpx.OkJson(w, ningxi.SuccessResponse(resp,"新增成功"))
}
}
}
可以看到,我们这代码中增加了获取 x-user-id
,原因是 addfood
是需要鉴权的,同时我们再header 中带了 x-user-id
同时 addfoodlogic.go
我们也增加了一个参数 userid
。原先模板生成的代码并没有 userid
这个参数。但是在接下去的业务逻辑又是需要 userid
的,因此我们稍作了修改。
编辑 api/internal/logic
下的 addfoodlogic.go
文件,新增 调用 food rpc
的 addfood 方法
func (l *AddFoodLogic) AddFood(req types.AddFoodRequest,userid string) (*types.FoodResponse, error) {
// todo: add your logic here and delete this line
_,err := l.svcCtx.Food.AddFood(l.ctx,&food.AddFoodRequest{
Userid: userid,
Foodid: req.Id,
})
if err != nil{
return &types.FoodResponse{}, nil
} else {
return nil, err
}
}
定义数据库表结构,并生成CRUD+cache
代码
编辑 model
下 food.sql
文件并新增如下内容。
CREATE TABLE `user_food` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT 'id',
`userid` bigint COMMENT '用户Id',
`foodid` bigint COMMENT '食物Id',
`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `userid_index` (`userid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
在 model
目录下执行如下命令生成 CRUD+cache
代码,-c
表示使用 redis cache
goctl model mysql ddl -c -src food.sql -dir .
rpc
代码调用 crud+cache
代码
编辑 rpc/food/internal/svc
下的 serviceContext.go
文件,新增 UserFoodModel
变量 ,新增实例化代码。
type ServiceContext struct {
Config config.Config
Model model.FoodModel
UserFoodModel model.UserFoodModel
}
func NewServiceContext(c config.Config) *ServiceContext {
return &ServiceContext{
Config: c,
Model: model.NewFoodModel(sqlx.NewMysql(c.DataSource),c.Cache),
UserFoodModel: model.NewUserFoodModel(sqlx.NewMysql(c.DataSource),c.Cache),
}
}
编辑 rpc/food/internal/logic
下的 addfoodlogic.go
文件, 新增如下代码
func (l *AddFoodLogic) AddFood(in *food.AddFoodRequest) (*food.StatusResponse, error) {
newid,_ := strconv.ParseInt(in.Userid,10,64)
newfoodid,_ := strconv.ParseInt(in.Foodid,10,64)
_, err := l.svcCtx.UserFoodModel.Insert(model.UserFood{
Userid: newid,
Foodid: newfoodid,
})
if err != nil {
return nil,err
}
return &food.StatusResponse{
Success: 1,
}, nil
}
启动服务
启动服务,注意 在启动服务前,需要确保 上一篇文章用到的 ningxi-compose
正常运行起来。
启动 food rpc
服务, 运行成功后,food rpc
则运行在本机的 8089
端口
➜ FoodGuides git:(master) ✗ go run foodmanage/rpc/food/food.go -f foodmanage/rpc/food/etc/food.yaml
Starting rpc server at 127.0.0.1:8089...
启动 food api
服务, 运行成功后,food api
则运行在本机的 8889
端口
➜ FoodGuides git:(master) ✗
Starting server at 0.0.0.0:8889...
api
测试 得到如下数据则说明 服务运行正常
➜ FoodGuides git:(master) ✗ curl --location --request POST 'http://localhost:8889/food/addfood' \
--header 'Authorization: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MTE5MzI3MDMsImlhdCI6MTYxMTg0NjMwMywidXNlcklkIjoxfQ.bdJzc4h2NaXmYwi3MrStKJaDb84GzVYgyerLVeWilpo' \
--header 'x-user-id: 1' \
--header 'Content-Type: application/json' \
--data-raw '{
"foodId": "1"
}'
{"code":1,"message":"新增成功","result":{}}%
➜ FoodGuides git:(master) ✗
这样 Food rpc - AddFood
就开发完成了。