背景:需要在服务端下发了消息后,等待这个消息回复,再执行下一步。
如何实现?
基本的实现方法就是,使用Netty的Attribute,发送数据后,设置一个超时时间,在这个超时时间里获取相对应的数据后返回。具体如何实现,待我整理下代码公布下。
20200807
有朋友对这个感兴趣,所以再把思路写一写,把部分代码贴上来:
思路:
1、写一个发送数据后同步等待的方法(因为目前对Netty的了解是,大部分的是异步发送的功能,等再深入了解Netty后看还有没有其他现成的方法可以调用):
public class ChannelSyncUtil {
public static MessageFrame writeMsgSync(MessageFrame msg, Channel channel, AttributeKey<MessageFrame> attrKey, int timeout) throws Exception{
if(channel.isActive()){
synchronized(channel){
Attribute<MessageFrame> attr = channel.attr(attrKey);
synchronized(attr){
System.out.println("发消息:");
channel.writeAndFlush(msg);
attr.wait(timeout * 1000);
MessageFrame ret