The Food RPC create
CD to FoodGuides directory. Creating an RPC folder
mkdir -p foodmanage/rpc/food && cd foodmanage/rpc/food
Copy the code
Write the food.proto file in the RPC /food directory
goctl rpc template -o food.proto
Copy the code
Write the food.proto file
syntax = "proto3";
package food;
message SearchRequest {
string key = 1;
}
message AddFoodRequest {
string userid = 1;
string foodid = 2;
}
message DeleteFoodRequest {
string id = 1;
}
message FoodListRequest {
string userid = 1;
}
message SearchResponse {
string protein = 1;
string fat = 2;
string carbohydrate = 3;
string calorie = 4;
string minerals = 5;
string calcium = 6;
string phosphorus = 7;
string iron = 8;
string purine = 9;
string id = 10;
string name = 11;
}
message StatusResponse {
int32 success = 1;
}
message FoodListResponse {
}
service Food {
rpc Search(SearchRequest) returns(SearchResponse);
rpc AddFood(AddFoodRequest) returns(StatusResponse);
rpc DeleteFood(DeleteFoodRequest) returns(StatusResponse);
rpc FoodList(FoodListRequest) returns(FoodListResponse);
}
Copy the code
We defined three interfaces: Search AddFood DeleteFood FoodList generates the food-RPC service
goctl rpc proto -src food.proto -dir .
Copy the code
Check out the RPC /food directory
➜ food git tree. (master) ✗ ├ ─ ─ etc │ └ ─ ─ the food. The yaml ├ ─ ─ the food │ └ ─ ─ the food. The pb.go├ ─ ─ the food.go├─ food. Proto ├─ food.go└── ├─ ├─go├─ Logic │ ├─ AddFoodLogic.go│ ├ ─ ─ deletefoodlogic.go│ ├ ─ ─ foodlistlogic.go│ └ ─ ─ searchlogic.go├── ├─ ├─go└ ─ ─ SVC └ ─ ─ servicecontext.go
8 directories, 12Files ➜ food git:(master) qualifyCopy the code
API Gateway
Code callsfood rpc
service
Edit the food-api.yaml file in API /etc to add the food. RPC configuration
Name: food-api
Host: 0.0. 0. 0
Port: 8889
Food:
Etcd:
Hosts:
- localhost:2379
Key: food.rpc
Copy the code
Edit config.go file under API /internal/config to add Food variable
type Config struct {
rest.RestConf
Food foodclient.Food
Auth struct {
AccessSecret string
AccessExpire int64}}Copy the code
Edit the servicecontext.go file under API /internal/ SVC, add the Food variable, add the instantiation code.
type ServiceContext struct {
Config config.Config
Food foodclient.Food
}
func NewServiceContext(c config.Config) *ServiceContext {
return &ServiceContext{
Config: c,
Food: foodclient.NewFood(zrpc.MustNewClient(c.Food)),
}
}
Copy the code
Edit the searchlogic.go file under API /internal/logic and add the search method of calling food RPC
func (l *SearchLogic) Search(req types.SearchRequest) (*types.SearchResponse, error) {
resp,err := l.svcCtx.Food.Search(l.ctx,&food.SearchRequest{
Key: req.Key,
})
iferr ! =nil {
return nil, err
}
return &types.SearchResponse{
FoodReply: types.FoodReply{
Id: resp.Id,
Name: resp.Name,
Protein: resp.Protein,
Fat: resp.Fat,
Carbohydrate: resp.Carbohydrate,
Calorie: resp.Calorie,
Minerals: resp.Minerals,
Calcium: resp.Calcium,
Phosphorus: resp.Phosphorus,
Iron: resp.Iron,
Purine: resp.Purine,
},
}, nil
}
Copy the code
Define the database table structure and generate CRUD+cache code
Create the Model folder under FoodManage.
mkdir -p model & cd model
Copy the code
Create a new food. SQL file under Model and write the following.
CREATE TABLE 'food' (' id 'bigint NOT NULL AUTO_INCREMENT COMMENT' food ', 'name' varchar(255) CHARACTER SET utf8MB4 COLLATE UTf8MB4_general_ci NOT NULL DEFAULT COMMENT ', 'protein' vARCHar (255) CHARACTER SET UTf8MB4 COLLATE UTf8MB4_general_ci NOT NULL DEFAULT ', 'fat' varchar(255) CHARACTER SET utf8MB4 COLLATE UTf8MB4_general_ci NOT NULL DEFAULT COMMENT 'fat ', 'Rumen' VARCHar (255) CHARACTER SET UTF8MB4 COLLATE UTF8MB4_general_CI NOT NULL DEFAULT COMMENT 'Food carbohydrate content ', 'Calorie' varchar(255) CHARACTER SET UTf8MB4 COLLATE UTf8MB4_general_ci NOT NULL DEFAULT COMMENT 'Calorie ', 'Minerals' VARCHar (255) CHARACTER SET UTf8MB4 COLLATE UTf8MB4_general_ci NOT NULL DEFAULT COMMENT' Food mineral content ', 'calcium' vARCHar (255) CHARACTER SET UTf8MB4 COLLATE UTf8MB4_general_ci NOT NULL DEFAULT COMMENT 'Dietary calcium content ', 'Phosphorus' varchar(255) CHARACTER SET UTf8MB4 COLLATE UTf8MB4_general_ci NOT NULL DEFAULT' COMMENT 'Food phosphorus content ', 'iron' varchar(255) CHARACTER SET utf8MB4 COLLATE UTf8MB4_general_ci NOT NULL DEFAULT ', 'purine' varchar(255) CHARACTER SET utf8MB4 COLLATE UTf8MB4_general_ci NOT NULL DEFAULT COMMENT ', `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP, `update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`), UNIQUE KEY `name_index` (`name`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;Copy the code
Run the following command in the model directory to generate the CRUD+cache code: -c indicates redis cache
goctl model mysql ddl -c -src food.sql -dir .
Copy the code
Look at the Model directory structure
➜ model git:(master) go onto those who qualify. ├── go // go // go // go // go // go // go // go // go // go // go // go // go / 3 files ➜ model git:(master) qualifyCopy the code
Create the Foodguides database in local mysql and create the food table.
Add a piece of data
INSERT INTO `foodguides`.`food`(`id`, `name`, `protein`, `fat`, `carbohydrate`, `calorie`, `minerals`, `calcium`, ` phosphorus `, ` iron `, ` purine `, ` create_time `, ` update_time `) VALUES (1, 'squid', '60.0', 4.6 ' ', '7.8', '1323', '100', '87', '392', '4.1', '100', '2021-01-26 23:30:43', '2021-01-26 23:33:38');Copy the code
rpc
Code callscrud+cache
code
Edit the food.yaml file in RPC /food/etc and add the following content.
Note that mysql is using the docker container for the ningxi-compose run.
Name: food. RPC ListenOn: 127.0.0.1:8089 Etcd: Hosts: -127.0.0.1:2379 Key: food. RPC DataSource: root:2e70F5E6@(localhost:13306)/foodguides? parseTime=true Table: food Cache: - Host: localhost:16379Copy the code
Edit the config.go file in RPC /food/internal/config to add the DataSource Cache variable
type Config struct {
zrpc.RpcServerConf
DataSource string
Cache cache.CacheConf
}
Copy the code
Edit the servicecontext. go file under RPC /food/internal/ SVC, add the Model variable, add the instantiation code.
type ServiceContext struct {
Config config.Config
Model model.FoodModel
}
func NewServiceContext(c config.Config) *ServiceContext {
return &ServiceContext{
Config: c,
Model: model.NewFoodModel(sqlx.NewMysql(c.DataSource),c.Cache),
}
}
Copy the code
Edit the searchlogic.go file in RPC /food/internal/logic and add the following codes
func (l *SearchLogic) Search(in *food.SearchRequest) (*food.SearchResponse, error) {
res, err := l.svcCtx.Model.FindOneByName(in.Key)
if err == nil {
newid :=strconv.FormatInt(res.Id,10)
return &food.SearchResponse{
Id: newid,
Name: res.Name,
Protein: res.Protein,
Fat: res.Fat,
Carbohydrate: res.Carbohydrate,
Calorie: res.Calorie,
Minerals: res.Minerals,
Calcium: res.Calcium,
Phosphorus: res.Phosphorus,
Iron: res.Iron,
Purine: res.Purine,
}, nil
} else {
return nil,err
}
}
Copy the code
Start the service
Start the service. Note that before starting the service, you need to make sure that the ningxi-compose used in the previous article is up and running.
Start the food RPC service. After the service runs successfully, the food RPC runs on port 8089 of the machine
➜ FoodGuides git: (master) ✗ go run foodmanage/RPC/food/food. Go - f foodmanage/RPC/food/etc/food. The yaml Starting the RPC server The at 127.0.0.1:8089...Copy the code
Start the Food API service. After successful operation, the food API will run on port 8889 of the machine
➜ FoodGuides git:(master) qualify go run foodmanage/ API /food.go -f foodmanage/ API /etc/ food. yaml Starting server at 0.0.0.0:8889...Copy the code
If the API test results are as follows, the service is running properly
➜ ~ curl http://localhost:8889/food/search - POST - d X '{" key ":" squid "}' -- header "content-type: application/json" {" code ": 1, the" message ":" search success ", "result" : {" id ":" 1 ", "name" : "squid", "protein" : "60.0", "fat" : "4.6", "carbohydrate" : "7.8", "calorie" : "1 323 ", "minerals" : "100", "calcium" : "87", "phosphorus" : "392", "iron" : "4.1", "purine" : "100"}} % ➜ ~Copy the code
This completes Food RPC-Search development.
Previous post: Go-Zero Tutorial — Food API Gateway
The next go-Zero Tutorial — Food Rpc-AddFood