最近在做物联网项目,通过netty与设备进行通讯。
服务端用的是spring boot框架,用户在调用接口查询设备当前状态,比如设备是否开启。我这时候就会发送一条查询的指令到设备,然后设备再把相关发送到服务端。
在自定义的handler中,在channelRead方法读取了设备给服务端的数据,但是怎么把数据传给前端呢?
/**
* 查看设备的状态
* @param equipNo 设备编号
*
* @return 设备的状态
*/
@RequestMapping(value = "/data/relay", method = RequestMethod.GET)
public ServerResponse relayData(int equipNo) {
ContextManager contextManager = ContextManager.instance();
//发送请求
contextManager.dataGet(equipNo);
//这里我想的是返回设备的当前状态
return ServerResponse.createBySuccess("指令已发送");
}
@Sharable
public class DataReceivedHandler extends ChannelDuplexHandler {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
//在这里处理数据,并且返回将处理好的数据给controller
}
}
问题就是该怎么把channelRead方法中处理好的数据,再给controller中
前端同步调用你的后端接口(controller)查询设备的信息,此时后端与设备间通过netty通讯,对吧?
当设备将数据返回给后端时(即channelRead方法),此时需要想办法将数据返回到用户的业务线程中,大概是这个逻辑是吧---
方案1:
channelRead中处理好数据后,将数据写入MQ中 ,业务线程轮询消费结果,防止超时,可以设个超时时间;
方案2:
业务线程中用future方式异步调用netty通信类通信,用future.get阻塞等待返回结果。
希望可以帮助你。