1.概述
本文涉及类图如下:
2.ExchangeHandler
在 DubboProtocol 中,实现了 ExchangeHandler ,代码如下:
private ExchangeHandler requestHandler = new ExchangeHandlerAdapter() {
@Override
public Object reply(ExchangeChannel channel, Object message) throws RemotingException {
// ... 省略具体实现
}
@Override
public void received(Channel channel, Object message) throws RemotingException {
// ... 省略具体实现
}
@Override
public void connected(Channel channel) throws RemotingException {
this.invoke(channel, Constants.ON_CONNECT_KEY);
}
@Override
public void disconnected(Channel channel) throws RemotingException {
// ... 省略具体实现
}
private void invoke(Channel channel, String methodKey) {
// ... 省略具体实现
}
};
3. Codec
实现 Codec2 接口,支持多消息的编解码器。
3.1 DubboCountCodec
/**
* 支持多消息的编解码器
*/
public final class DubboCountCodec implements Codec2 {
/**
* 编解码器
*/
private DubboCodec codec = new DubboCodec();
@Override
public void encode(Channel channel, ChannelBuffer buffer, Object msg) throws IOException {
codec.encode(channel, buffer, msg);
}
@Override
public Object decode(Channel channel, ChannelBuffer buffer) throws IOException {
// 记录当前读位置
int save = buffer.readerIndex();
// 创建 MultiMessage 对象
MultiMessage result = MultiMessage.create();
do {
// 解码
Object obj = codec.decode(channel, buffer);
// 输入不够,重置读进度
if (Codec2.DecodeResult.NEED_MORE_INPUT == obj) {
buffer.readerIndex(save);
break;
// 解析到消息
} else {
// 添加结果消息
result.addMessage(obj);
// 记录消息长度到隐式参数集合,用于 MonitorFilter 监控
logMessageLength(obj, buffer.readerIndex() - save);
// 记录当前读位置
save = buffer.readerIndex();
}
} while (true);
// 需要更多的输入
if (result.isEmpty()) {
return Codec2