## 5) 獲取Route信息
### 5.1 proto協議定義
? 獲取Route信息,根據之前的架構圖,可以看出來應該是Agent來獲取,這里我們并沒有實現Agent,所以用一個其他簡單的客戶端來完成單元測試。但是無論用什么,總需要一個傳遞數據,需要一定的消息協議,lars-dns也需要設置不同纖細的分發消息路由機制,所以我們需要先定義一些proto協議。
? 在`Lars/base`下創建`proto/`文件夾.
> Lars/base/proto/lars.proto
```protobuf
syntax = "proto3";
package lars;
/* Lars系統的消息ID */
enum MessageId {
ID_UNKNOW = 0; //proto3 enum第一個屬性必須是0,用來占位
ID_GetRouteRequest = 1; //向DNS請求Route對應的關系的消息ID
ID_GetRouteResponse = 2; //DNS回復的Route信息的消息ID
}
//一個管理的主機的信息
message HostInfo {
int32 ip = 1;
int32 port = 2;
}
//請求lars-dns route信息的消息內容
message GetRouteRequest {
int32 modid = 1;
int32 cmdid = 2;
}
//lars-dns 回復的route信息消息內容
message GetRouteResponse {
int32 modid = 1;
int32 cmdid = 2;
repeated HostInfo host = 3;
}
```
? 然后我們將proto文件編譯成對應的C++文件, 我們還是提供一個腳本
> Lars/base/proto/build.sh
```bash
#!/bin/bash
# proto編譯
protoc --cpp_out=. ./*.proto
# 將全部的cc 文件 變成 cpp文件
oldsuffix="cc"
newsuffix="cpp"
dir=$(eval pwd)
for file in $(ls $dir | grep .${oldsuffix})
do
name=$(ls ${file} | cut -d. -f1,2)
mv $file ${name}.${newsuffix}
done
echo "build proto file successd!"
```
? 因為protoc會自動生成cc后綴的文件,為了方便我們Makefile的編譯,所以將cc文件改成cpp的。
### 5.2 proto編譯環境集成
? 現在我們將`lars-dns`的Makefile加入針對proto文件的編譯
> Lars/lars_dns/Makefile
```makefile
TARGET= bin/lars_dns
CXX=g++
CFLAGS=-g -O2 -Wall -Wno-deprecated
BASE=../base
BASE_H=$(BASE)/include
PROTO = $(BASE)/proto
PROTO_H = $(BASE)/proto
LARS_REACTOR=../lars_reactor
LARS_REACTOR_H =$(LARS_REACTOR)/include
LARS_REACTOR_LIB=$(LARS_REACTOR)/lib -llreactor
MYSQL=$(BASE)/mysql-connector-c
MYSQL_H=$(MYSQL)/include
MYSQL_LIB=$(MYSQL)/lib/libmysqlclient.a
OTHER_LIB = -lpthread -ldl -lprotobuf
SRC= ./src
INC= -I./include -I$(BASE_H) -I$(LARS_REACTOR_H) -I$(MYSQL_H) -I$(PROTO_H)
LIB= $(MYSQL_LIB) -L$(LARS_REACTOR_LIB) $(OTHER_LIB)
OBJS = $(addsuffix .o, $(basename $(wildcard $(SRC)/*.cpp)))
OBJS += $(PROTO)/lars.pb.o
$(TARGET): $(OBJS)
mkdir -p bin
$(CXX) $(CFLAGS) -o $(TARGET) $(OBJS) $(INC) $(LIB)
%.o: %.cpp
$(CXX) $(CFLAGS) -c -o $@ $< $(INC)
.PHONY: clean
clean:
-rm -f src/*.o $(TARGET)
```
? 添加了兩個部分一個`OBJS`增添一個`lars.pb.o`的依賴,然后再`OTHER_LIB`增加`-lprotobuf`動態庫的連接。
### 5.3 實現Route獲取
? 接下來我們來實現針對`ID_GetRouteRequest`消息指令的業務處理.
> lars_dns/src/dns_service.cpp
```c
#include "lars_reactor.h"
#include "dns_route.h"
#include "lars.pb.h"
void get_route(const char *data, uint32_t len, int msgid, net_connection *net_conn, void *user_data)
{
//1. 解析proto文件
lars::GetRouteRequest req;
req.ParseFromArray(data, len);
//2. 得到modid 和 cmdid
int modid, cmdid;
modid = req.modid();
cmdid = req.cmdid();
//3. 根據modid/cmdid 獲取 host信息
host_set hosts = Route::instance()->get_hosts(modid, cmdid);
//4. 將數據打包成protobuf
lars::GetRouteResponse rsp;
rsp.set_modid(modid);
rsp.set_cmdid(cmdid);
for (host_set_it it = hosts.begin(); it != hosts.end(); it ++) {
uint64_t ip_port = *it;
lars::HostInfo host;
host.set_ip((uint32_t)(ip_port >> 32));
host.set_port((int)(ip_port));
rsp.add_host()->CopyFrom(host);
}
//5. 發送給客戶端
std::string responseString;
rsp.SerializeToString(&responseString);
net_conn->send_message(responseString.c_str(), responseString.size(), lars::ID_GetRouteResponse) ;
}
int main(int argc, char **argv)
{
event_loop loop;
//加載配置文件
config_file::setPath("conf/lars_dns.conf");
std::string ip = config_file::instance()->GetString("reactor", "ip", "0.0.0.0");
short port = config_file::instance()->GetNumber("reactor", "port", 7778);
//創建tcp服務器
tcp_server *server = new tcp_server(&loop, ip.c_str(), port);
//注冊路由業務
server->add_msg_router(lars::ID_GetRouteRequest, get_route);
//開始事件監聽
printf("lars dns service ....\n");
loop.event_process();
return 0;
}
```
? 需要給`Route`類,實現一個get_host()方法,來針對modid/cmdid取出對應的value
> lars_dns/src/dns_route.cpp
```c
//獲取modid/cmdid對應的host信息
host_set Route::get_hosts(int modid, int cmdid)
{
host_set hosts;
//組裝key
uint64_t key = ((uint64_t)modid << 32) + cmdid;
pthread_rwlock_rdlock(&_map_lock);
route_map_it it = _data_pointer->find(key);
if (it != _data_pointer->end()) {
//找到對應的ip + port對
hosts = it->second;
}
pthread_rwlock_unlock(&_map_lock);
return hosts;
}
```
### 5.3 lars_dns獲取Route信息測試-V0.2
? 下面我們寫一個客戶端檢查測試一下該功能.
> lars_dns/test/lars_dns_test1.cpp
```c
#include <string.h>
#include <unistd.h>
#include <string>
#include "lars_reactor.h"
#include "lars.pb.h"
//命令行參數
struct Option
{
Option():ip(NULL),port(0) {}
char *ip;
short port;
};
Option option;
void Usage() {
printf("Usage: ./lars_dns_test -h ip -p port\n");
}
//解析命令行
void parse_option(int argc, char **argv)
{
for (int i = 0; i < argc; i++) {
if (strcmp(argv[i], "-h") == 0) {
option.ip = argv[i + 1];
}
else if (strcmp(argv[i], "-p") == 0) {
option.port = atoi(argv[i + 1]);
}
}
if ( !option.ip || !option.port ) {
Usage();
exit(1);
}
}
//typedef void (*conn_callback)(net_connection *conn, void *args);
void on_connection(net_connection *conn, void *args)
{
//發送Route信息請求
lars::GetRouteRequest req;
req.set_modid(1);
req.set_cmdid(2);
std::string requestString;
req.SerializeToString(&requestString);
conn->send_message(requestString.c_str(), requestString.size(), lars::ID_GetRouteRequest);
}
void deal_get_route(const char *data, uint32_t len, int msgid, net_connection *net_conn, void *user_data)
{
//解包得到數據
lars::GetRouteResponse rsp;
rsp.ParseFromArray(data, len);
//打印數據
printf("modid = %d\n", rsp.modid());
printf("cmdid = %d\n", rsp.cmdid());
printf("host_size = %d\n", rsp.host_size());
for (int i = 0; i < rsp.host_size(); i++) {
printf("-->ip = %u\n", rsp.host(i).ip());
printf("-->port = %d\n", rsp.host(i).port());
}
//再請求
lars::GetRouteRequest req;
req.set_modid(rsp.modid());
req.set_cmdid(rsp.cmdid());
std::string requestString;
req.SerializeToString(&requestString);
net_conn->send_message(requestString.c_str(), requestString.size(), lars::ID_GetRouteRequest);
}
int main(int argc, char **argv)
{
parse_option(argc, argv);
event_loop loop;
tcp_client *client;
//創建客戶端
client = new tcp_client(&loop, option.ip, option.port, "lars_dns_test");
if (client == NULL) {
fprintf(stderr, "client == NULL\n");
exit(1);
}
//客戶端成功建立連接,首先發送請求包
client->set_conn_start(on_connection);
//設置服務端回應包處理業務
client->add_msg_router(lars::ID_GetRouteResponse, deal_get_route);
loop.event_process();
return 0;
}
```
?
? 同時提供一個`Makefile`對客戶端進行編譯。
> lars_dns/test/Makefile
```makefile
TARGET= lars_dns_test1
CXX=g++
CFLAGS=-g -O2 -Wall -Wno-deprecated
BASE=../../base
BASE_H=$(BASE)/include
PROTO = $(BASE)/proto
PROTO_H = $(BASE)/proto
LARS_REACTOR=../../lars_reactor
LARS_REACTOR_H =$(LARS_REACTOR)/include
LARS_REACTOR_LIB=$(LARS_REACTOR)/lib -llreactor
OTHER_LIB = -lpthread -ldl -lprotobuf
SRC= ./src
INC= -I./include -I$(BASE_H) -I$(LARS_REACTOR_H) -I$(PROTO_H)
LIB= $(MYSQL_LIB) -L$(LARS_REACTOR_LIB) $(OTHER_LIB)
OBJS = lars_dns_test1.o
OBJS += $(PROTO)/lars.pb.o
$(TARGET): $(OBJS)
$(CXX) $(CFLAGS) -o $(TARGET) $(OBJS) $(INC) $(LIB)
%.o: %.cpp
$(CXX) $(CFLAGS) -c -o $@ $< $(INC)
.PHONY: clean
clean:
-rm -f ./*.o $(TARGET)
```
我們分別啟動`bin/lars_dns`進程,和`test/lars_dns_test1`進程
服務端
```bash
$ ./bin/lars_dns
msg_router init...
create 0 thread
create 1 thread
create 2 thread
create 3 thread
create 4 thread
add msg cb msgid = 1
lars dns service ....
begin accept
begin accept
[thread]: get new connection succ!
modID = 1, cmdID = 1, ip = 3232235953, port = 7777
modID = 1, cmdID = 2, ip = 3232235954, port = 7776
modID = 2, cmdID = 1, ip = 3232235955, port = 7778
modID = 2, cmdID = 2, ip = 3232235956, port = 7779
modID = 1, cmdID = 1, ip = 3232235953, port = 7777
modID = 1, cmdID = 2, ip = 3232235954, port = 7776
modID = 2, cmdID = 1, ip = 3232235955, port = 7778
modID = 2, cmdID = 2, ip = 3232235956, port = 7779
read data from socket
```
客戶端
```bash
$ ./lars_dns_test1 -h 127.0.0.1 -p 7778
msg_router init...
do_connect EINPROGRESS
add msg cb msgid = 2
connect 127.0.0.1:7778 succ!
modid = 1
cmdid = 2
host_size = 1
-->ip = 3232235954
-->port = 7776
```
---
### 關于作者:
作者:`Aceld(劉丹冰)`
mail: [danbing.at@gmail.com](mailto:danbing.at@gmail.com)
github: [https://github.com/aceld](https://github.com/aceld)
原創書籍: [http://www.hmoore.net/@aceld](http://www.hmoore.net/@aceld)

>**原創聲明:未經作者允許請勿轉載, 如果轉載請注明出處**
- 一、Lars系統概述
- 第1章-概述
- 第2章-項目目錄構建
- 二、Reactor模型服務器框架
- 第1章-項目結構與V0.1雛形
- 第2章-內存管理與Buffer封裝
- 第3章-事件觸發EventLoop
- 第4章-鏈接與消息封裝
- 第5章-Client客戶端模型
- 第6章-連接管理及限制
- 第7章-消息業務路由分發機制
- 第8章-鏈接創建/銷毀Hook機制
- 第9章-消息任務隊列與線程池
- 第10章-配置文件讀寫功能
- 第11章-udp服務與客戶端
- 第12章-數據傳輸協議protocol buffer
- 第13章-QPS性能測試
- 第14章-異步消息任務機制
- 第15章-鏈接屬性設置功能
- 三、Lars系統之DNSService
- 第1章-Lars-dns簡介
- 第2章-數據庫創建
- 第3章-項目目錄結構及環境構建
- 第4章-Route結構的定義
- 第5章-獲取Route信息
- 第6章-Route訂閱模式
- 第7章-Backend Thread實時監控
- 四、Lars系統之Report Service
- 第1章-項目概述-數據表及proto3協議定義
- 第2章-獲取report上報數據
- 第3章-存儲線程池及消息隊列
- 五、Lars系統之LoadBalance Agent
- 第1章-項目概述及構建
- 第2章-主模塊業務結構搭建
- 第3章-Report與Dns Client設計與實現
- 第4章-負載均衡模塊基礎設計
- 第5章-負載均衡獲取Host主機信息API
- 第6章-負載均衡上報Host主機信息API
- 第7章-過期窗口清理與過載超時(V0.5)
- 第8章-定期拉取最新路由信息(V0.6)
- 第9章-負載均衡獲取Route信息API(0.7)
- 第10章-API初始化接口(V0.8)
- 第11章-Lars Agent性能測試工具
- 第12章- Lars啟動工具腳本