BFS+剪枝查找目标转推流节点

需求:在各个国家都有可能部署转推流节点,因此需要高效快捷的查找到离推理地点最近的一个目标转推流节点。

现状:国内以省为单位,国外以国家为单位,虽然当前节点较少,但是为了保障业务拓展之后的效果,因此需要及时进行图优化。

分析:建立中国地图和世界地图,根据ip地址在ip数据库中查找,得到ip所属的国家名称,国家代码,省份名称,省份代码。用国家代码在世界地图中查找最近的国家节点,用省份代码在中国地图中查找最近的省份节点。

搜索:搜索方式为广度优先搜索BFS,用于寻找最近的目标点。

BFS+剪枝实现的中国地图和世界地图中查找目标转推流节点的代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
%%%-------------------------------------------------------------------
%%% @author ChenLiang
%%% @copyright (C) 2018, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 2018/03/20 14:59
%%%-------------------------------------------------------------------
-module(detonate_deliver_site_graph).
-author("ChenLiang").
-behaviour(gen_server).
-include("detonate_server.hrl").
%% API
-export([start_link/0, lookup_deliver_node/2]).
%% gen_server callbacks
-export([init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3]).
-define(SERVER, ?MODULE).
-record(state, {
china_graph = digraph:new() :: digraph:graph(),
china_tid = ets:new(undefined, []) :: ets:tid(),
world_graph = digraph:new() :: digraph:graph(),
world_tid = ets:new(undefined, []) :: ets:tid()
}
).
%%%===================================================================
%%% API
%%%===================================================================
%%--------------------------------------------------------------------
%% @doc
%% Starts the server
%%
%% @end
%%--------------------------------------------------------------------
-spec(start_link() ->
{ok, Pid :: pid()} | ignore | {error, Reason :: term()}).
start_link() ->
gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
lookup_deliver_node(lookup_province, Province) ->
lager:debug("lookup_province: ~p ~n", [Province]),
gen_server:call(?MODULE, {lookup_province, Province});
lookup_deliver_node(lookup_country, CountryCode) ->
lager:debug("lookup_country: ~p ~n", [CountryCode]),
gen_server:call(?MODULE, {lookup_country, CountryCode}).
%%%===================================================================
%%% gen_server callbacks
%%%===================================================================
%%--------------------------------------------------------------------
%% @private
%% @doc
%% Initializes the server
%%
%% @spec init(Args) -> {ok, State} |
%% {ok, State, Timeout} |
%% ignore |
%% {stop, Reason}
%% @end
%%--------------------------------------------------------------------
-spec(init(Args :: term()) ->
{ok, State :: #state{}} | {ok, State :: #state{}, timeout() | hibernate} |
{stop, Reason :: term()} | ignore).
init([]) ->
gen_server:cast(?MODULE, init_china),
gen_server:cast(?MODULE, init_world),
{ok, #state{}}.
%%--------------------------------------------------------------------
%% @private
%% @doc
%% Handling call messages
%%
%% @end
%%--------------------------------------------------------------------
-spec(handle_call(Request :: term(), From :: {pid(), Tag :: term()},
State :: #state{}) ->
{reply, Reply :: term(), NewState :: #state{}} |
{reply, Reply :: term(), NewState :: #state{}, timeout() | hibernate} |
{noreply, NewState :: #state{}} |
{noreply, NewState :: #state{}, timeout() | hibernate} |
{stop, Reason :: term(), Reply :: term(), NewState :: #state{}} |
{stop, Reason :: term(), NewState :: #state{}}).
handle_call({lookup_province, Province}, _From, State=#state{china_graph = ChinaGraph, china_tid = ChinaTid}) ->
Reply = lookup_deliver_node(lookup_province, ChinaGraph, ChinaTid, Province),
{reply, Reply, State};
handle_call({lookup_country, CountryCode}, _From, State=#state{world_graph = WorldGraph, world_tid = WorldTid}) ->
Reply = lookup_deliver_node(lookup_country, WorldGraph, WorldTid, CountryCode),
{reply, Reply, State};
handle_call(_Request, _From, State) ->
{reply, ok, State}.
%%--------------------------------------------------------------------
%% @private
%% @doc
%% Handling cast messages
%%
%% @end
%%--------------------------------------------------------------------
-spec(handle_cast(Request :: term(), State :: #state{}) ->
{noreply, NewState :: #state{}} |
{noreply, NewState :: #state{}, timeout() | hibernate} |
{stop, Reason :: term(), NewState :: #state{}}).
handle_cast(init_china, State=#state{china_graph = ChinaGraph, china_tid = ChinaTid}) ->
ChinaVertexFileName = filename:join(code:lib_dir(detonate_server, priv), "china_province_code.csv"),
ChinaEdgeFileName = filename:join(code:lib_dir(detonate_server, priv), "china_province_border.csv"),
initialize_graph(china, ChinaGraph, ChinaTid, ChinaVertexFileName, ChinaEdgeFileName),
{noreply, State};
handle_cast(init_world, State=#state{world_graph = WorldGraph, world_tid = WorldTid}) ->
WorldVertexFileName = filename:join(code:lib_dir(detonate_server, priv), "world_country_code.csv"),
WorldEdgeFileName = filename:join(code:lib_dir(detonate_server, priv), "world_country_border.csv"),
initialize_graph(world, WorldGraph, WorldTid, WorldVertexFileName, WorldEdgeFileName),
{noreply, State};
handle_cast(_Request, State) ->
{noreply, State}.
%%--------------------------------------------------------------------
%% @private
%% @doc
%% Handling all non call/cast messages
%%
%% @spec handle_info(Info, State) -> {noreply, State} |
%% {noreply, State, Timeout} |
%% {stop, Reason, State}
%% @end
%%--------------------------------------------------------------------
-spec(handle_info(Info :: timeout() | term(), State :: #state{}) ->
{noreply, NewState :: #state{}} |
{noreply, NewState :: #state{}, timeout() | hibernate} |
{stop, Reason :: term(), NewState :: #state{}}).
handle_info(_Info, State) ->
{noreply, State}.
%%--------------------------------------------------------------------
%% @private
%% @doc
%% This function is called by a gen_server when it is about to
%% terminate. It should be the opposite of Module:init/1 and do any
%% necessary cleaning up. When it returns, the gen_server terminates
%% with Reason. The return value is ignored.
%%
%% @spec terminate(Reason, State) -> void()
%% @end
%%--------------------------------------------------------------------
-spec(terminate(Reason :: (normal | shutdown | {shutdown, term()} | term()),
State :: #state{}) -> term()).
terminate(_Reason, _State) ->
ok.
%%--------------------------------------------------------------------
%% @private
%% @doc
%% Convert process state when code is changed
%%
%% @spec code_change(OldVsn, State, Extra) -> {ok, NewState}
%% @end
%%--------------------------------------------------------------------
-spec(code_change(OldVsn :: term() | {down, term()}, State :: #state{},
Extra :: term()) ->
{ok, NewState :: #state{}} | {error, Reason :: term()}).
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%%===================================================================
%%% Internal functions
%%%===================================================================
initialize_graph(china, Graph, Tid, VertexFileName, EdgeFileName)->
{ok, VertexIoDevice} = file:open(VertexFileName, [read, binary]),
add_vertex(china, Graph, Tid, VertexIoDevice),
file:close(VertexIoDevice),
{ok, EdgeIoDevice} = file:open(EdgeFileName, [read, binary]),
add_edge(china, Graph, Tid, EdgeIoDevice),
file:close(EdgeIoDevice);
initialize_graph(world, Graph, Tid, VertexFileName, EdgeFileName)->
{ok, VertexIoDevice} = file:open(VertexFileName, [read, binary]),
add_vertex(world, Graph, Tid, VertexIoDevice),
file:close(VertexIoDevice),
{ok, EdgeIoDevice} = file:open(EdgeFileName, [read, binary]),
add_edge(world, Graph, Tid, EdgeIoDevice),
file:close(EdgeIoDevice).
add_vertex(china, Graph, Tid, VertexIoDevice) ->
case file:read_line(VertexIoDevice) of
{ok, Line} ->
case binary:split(Line, [<<",">>, <<"\n">>], [global]) of
[Province, DeliverSite | _] ->
ets:insert(Tid, {Province, DeliverSite}),
digraph:add_vertex(Graph, DeliverSite),
add_vertex(china, Graph, Tid, VertexIoDevice);
_ ->
ok
end;
eof ->
ok
end;
add_vertex(world, Graph, Tid, VertexIoDevice) ->
case file:read_line(VertexIoDevice) of
{ok, Line} ->
case binary:split(Line, [<<",">>, <<"\n">>], [global]) of
[_Continent,<<>>] ->
add_vertex(world, Graph, Tid, VertexIoDevice);
[CountryCode, CountryChineseName, CountryEnglishName | _] ->
ets:insert(Tid, {CountryCode, CountryChineseName, CountryEnglishName}),
digraph:add_vertex(Graph, CountryCode),
add_vertex(world, Graph, Tid, VertexIoDevice);
_ ->
ok
end;
eof ->
ok
end.
add_edge(china, Graph, Tid, EdgeIoDevice) ->
case file:read_line(EdgeIoDevice) of
{ok, Line} ->
case binary:split(Line, [<<",">>, <<"\n">>], [global]) of
[Province1, Province2 | _] ->
[{_, DeliverSite1}] = ets:lookup(Tid, Province1),
[{_, DeliverSite2}] = ets:lookup(Tid, Province2),
digraph:add_edge(Graph, DeliverSite1, DeliverSite2),
digraph:add_edge(Graph, DeliverSite2, DeliverSite1),
add_edge(china, Graph, Tid, EdgeIoDevice);
_ ->
ok
end;
eof ->
ok
end;
add_edge(world, Graph, Tid, EdgeIoDevice) ->
case file:read_line(EdgeIoDevice) of
{ok, Line} ->
case binary:split(Line, [<<",">>, <<"\n">>], [global]) of
[_Continent,<<>>] ->
add_edge(world, Graph, Tid, EdgeIoDevice);
[_CountryCode1, CountryCode2 | _] when byte_size(CountryCode2) =/= 2 ->
add_edge(world, Graph, Tid, EdgeIoDevice);
[CountryCode1, CountryCode2 | _] ->
digraph:add_edge(Graph, CountryCode1, CountryCode2),
digraph:add_edge(Graph, CountryCode2, CountryCode1),
add_edge(world, Graph, Tid, EdgeIoDevice);
_ ->
ok
end;
eof ->
ok
end.
lookup_deliver_node(lookup_province, ChinaGraph, Tid, Province) ->
[{_, DeliverSite}] = ets:lookup(Tid, Province),
case bfs(lookup_province, ChinaGraph, DeliverSite) of
not_found ->
{ok, ?HANGZHOU};
{ok, RecentDeliverSite} ->
{ok, RecentDeliverSite}
end;
lookup_deliver_node(lookup_country, WorldGraph, _Tid, CountryCode) ->
case bfs(lookup_country, WorldGraph, CountryCode) of
not_found ->
{ok, ?TOKYO};
{ok, RecentDeliverSite} ->
{ok, RecentDeliverSite}
end.
bfs(Graph, Queue, NodeList, VisitedList) ->
case queue:is_empty(Queue) of
true ->
not_found;
_ ->
{{value, Vertex} ,NewQueue} = queue:out(Queue),
NewVisitedList = lists:append(VisitedList, [Vertex]),
case find(Vertex, NodeList) of
not_found ->
VertexList = find_vertex_list(Graph, Vertex),
NotVisitedVertexList = filter(VertexList, NewVisitedList),
NewQueue1 = in_queue(NotVisitedVertexList, NewQueue),
bfs(Graph, NewQueue1, NodeList, NewVisitedList);
{ok, DeliverSite} ->
{ok, DeliverSite}
end
end.
bfs(lookup_province, Graph, Vertex) ->
Queue = queue:new(),
{ok, SupportedNodeList} = application:get_env(china_deliver_sites),
NewQueue = in_queue(Vertex, Queue),
bfs(Graph, NewQueue, SupportedNodeList, []);
bfs(lookup_country, Graph, Vertex) ->
Queue = queue:new(),
{ok, SupportedNodeList} = application:get_env(world_deliver_sites),
NewQueue = in_queue(Vertex, Queue),
bfs(Graph, NewQueue, SupportedNodeList, []).
find(_Element, []) ->
not_found;
find(Element, [{CountryCode, DeliverSite}|Tail]) ->
case string:equal(Element, CountryCode) of
true ->
{ok, DeliverSite};
_ ->
find(Element, Tail)
end;
find(Element, [DeliverSite|Tail]) ->
case string:equal(Element, DeliverSite) of
true ->
{ok, DeliverSite};
_ ->
find(Element, Tail)
end.
is_visited(Element, List) ->
case find(Element, List) of
not_found ->
false;
_ ->
true
end.
filter(VertexList, VisitedList) ->
filter(VertexList, VisitedList, []).
filter([Head|Tail], VisitedList, ResultList) ->
case is_visited(Head, VisitedList) of
false ->
filter(Tail, VisitedList, ResultList ++ [Head]);
_ ->
filter(Tail, VisitedList, ResultList)
end;
filter([], _VisitedList, ResultList) ->
ResultList.
find_vertex_list(Graph, Vertex) ->
Edges = digraph:edges(Graph, Vertex),
find_vertex_list(Graph, Vertex, Edges, []).
find_vertex_list(Graph, Vertex, [Head|Tail], VertexList) ->
{_, V1, V2, _} = digraph:edge(Graph, Head),
case string:equal(V1, Vertex) of
true ->
find_vertex_list(Graph, Vertex, Tail, VertexList ++ [V2]);
_ ->
find_vertex_list(Graph, Vertex, Tail, VertexList)
end;
find_vertex_list(_Graph, _Vertex, [], VertexList) ->
VertexList.
in_queue([], Queue) ->
Queue;
in_queue([Head|Tail], Queue) ->
NewQueue = queue:in(Head, Queue),
in_queue(Tail, NewQueue);
in_queue(Item, Queue) ->
queue:in(Item, Queue).

代码到此为止,关于ip数据库的查询部分可以参见ipip.net


附录:

捐赠:喜欢就请我喝一杯