跳到主要内容

request/multiple_response

介绍

request/multiple_response,同时请求同类型多个逻辑服,是框架提供的通信模型之一,该模型可以把多个同类型逻辑服的结果收集到一起。

框架支持启动多个相同的逻辑服,比如 LogicServer-B-1、LogicServer-B-2。 有时,我们需要启动多个同类型的逻辑服来帮助我们做负载均衡。


场景举例 - 1

request/multiple_response 通信模型在一些特定业务场景下特别实用,比如有 3 台象棋逻辑服 ChessLogicServer。 分别是 ChessLogicServer-1、ChessLogicServer-2、ChessLogicServer-3,这些 ChessLogicServer 可以分布在不同的进程中。

由于我们可以同时请求同类型逻辑服,那么我们就可以做以下业务

  • 获取房间数最少 ChessLogicServer,目的是想让后续的玩家进入该逻辑服进行游戏。
  • 统计房间的总数。
提示

这里只是举个例子,实际当中可以发挥自己的想象力。

An


场景举例 - 2

上面的场景中,我们介绍了通过 request/multiple_response 可以获取房间数最少 ChessLogicServer。 通过结合动态绑定逻辑服功能,可以让后续的玩家进入该逻辑服进行游戏,也就是后续的请求都由指定的逻辑服来处理。

Examples

下面代码展示了同步与异步回调的使用。

  • code 9: 异步回调请求模型,请求同类型的逻辑服。
  • code 10~11: 获取响应列表并遍历,因为可能会有多个相同的逻辑服,所有响应是列表。
  • code 12: 打印各逻辑服的响应结果。
  • code 17: 同步请求模型,请求同类型的逻辑服。
@ActionController(CallCollectCmd.cmd)
public class CallCollectAction {
@ActionMethod(CallCollectCmd.callCollectInt)
private List<Integer> callInt() {
// The two below are equivalent, one is synchronous and the other is asynchronous.
var cmdInfo = InternalCmd.of(InternalCmd.intAction);
int data = 1;
// Asynchronous callback
communication().callbackCollect(cmdInfo, data, responseCollect -> {
List<Response> responseList = responseCollect.getResponseList();
for (Response response : responseList) {
log.info("{}", response.getInt());
}
});

// Synchronous call
var responseCollect = communication().callCollect(cmdInfo, data);
List<Response> responseList = responseCollect.getResponseList();
return responseList.stream()
.map(Response::getInt)
.toList();
}

private Communication communication() {
return CommunicationKit.getCommunication();
}
}

下面 action 来自 ChessLogicServer,并启动了多个。

@ActionController(InternalCmd.cmd)
public class InternalAction {
AtomicInteger inc = new AtomicInteger(1);

@ActionMethod(InternalCmd.intAction)
private int intAction(int value) {
return value + inc.getAndIncrement();
}
}

More Examples

更多使用示例,请阅读 Examples Communication RequestMultipleResponse

注意事项

注意

request/multiple_response 模型必须要有返回值,被调用端的 action 不能是 void。

小结

可以看出,向同类型逻辑服发起请求是非常简单的事,只需要一个方法就能做到。

var communication = CommunicationKit.getCommunication();
communication.callCollect
communication.callbackCollect
// or
flowContext.callCollect
flowContext.callbackCollect

最后,发挥你的想象力,把这一特性用起来!