poolboy在checkout工作者进程的时候,每次都取第一个进程,导致就算是用cast异步处理耗时操作,也会被阻塞,换成随机取进程
老代码
handle_call({checkout, Block}, {FromPid, _} = From, State) -> #state{supervisor = Sup, workers = Workers, monitors = Monitors, overflow = Overflow, max_overflow = MaxOverflow} = State, case Workers of [Pid | Left] -> Ref = erlang:monitor(process, FromPid), true = ets:insert(Monitors, {Pid, Ref}), {reply, Pid, State#state{workers = Left}}; [] when MaxOverflow > 0, Overflow < MaxOverflow -> {Pid, Ref} = new_worker(Sup, FromPid), true = ets:insert(Monitors, {Pid, Ref}), {reply, Pid, State#state{overflow = Overflow + 1}}; [] when Block =:= false -> {reply, full, State}; [] -> Ref = erlang:monitor(process, FromPid), Waiting = queue:in({From, Ref}, State#state.waiting), {noreply, State#state{waiting = Waiting}} end;
换成
handle_call({checkout, Block}, {FromPid, _} = From, State) -> #state{supervisor = Sup, workers = Workers, monitors = Monitors, overflow = Overflow, max_overflow = MaxOverflow} = State, case length(Workers) of 0 when MaxOverflow > 0, Overflow < MaxOverflow -> {Pid, Ref} = new_worker(Sup, FromPid), true = ets:insert(Monitors, {Pid, Ref}), {reply, Pid, State#state{overflow = Overflow + 1}}; 0 when Block =:= false -> {reply, full, State}; 0 -> Ref = erlang:monitor(process, FromPid), Waiting = queue:in({From, Ref}, State#state.waiting), {noreply, State#state{waiting = Waiting}}; _ when length(Workers) > 0 -> RadomIndex = random:uniform(999999999999) rem length(Workers), Pid = lists:nth(RadomIndex,Workers), Left = lists:delete(Pid,Workers), Ref = erlang:monitor(process, FromPid), true = ets:insert(Monitors, {Pid, Ref}), {reply, Pid, State#state{workers = Left}} end;
时间: 2024-10-26 09:23:41