我参考了这个:https://gitee.com/xjmroot/netty-pool
其实他的思路就是做一个缓存,把发送的信息做一个key存缓存,接收的信息也有这个key放到对应的缓存作为返回.
我是这么写的:
NettyTools.initReceiveMsg(key);
String result = NettyTools.waitReceiveMsg(key);
在netty的inboundHandler实现类里,channelRead方法下
...
NettyTools.setReceiveMsg(key, "1");
具体工具类:
package com.app.netty;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.log;
import java.util.Objects;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class NettyTools {
// private static final Logger log = LoggerFactory.getLogger("netty-demo");
/**
* 响应消息缓存
*/
private static Cache<String, BlockingQueue<String>> responseMsgCache = CacheBuilder.newBuilder()
.maximumSize(50000)
.expireAfterWrite(100, TimeUnit.SECONDS)
.build();
/**
* 等待响应消息
* @param key 消息唯一标识
* @return ReceiveDdcMsgVo
*/
public static String waitReceiveMsg(String key) {
try {
//设置超时时间
String vo = Objects.requireNonNull(responseMsgCache.getIfPresent(key))
.poll(3000, TimeUnit.MILLISECONDS);
//删除key
responseMsgCache.invalidate(key);
return vo;
} catch (Exception e) {
log.error("获取数据异常,sn={},msg=null",key);
return null;
}
}
/**
* 初始化响应消息的队列
* @param key 消息唯一标识
*/
public static void initReceiveMsg(String key) {
responseMsgCache.put(key,new LinkedBlockingQueue<String>(1));
}
/**
* 设置响应消息
* @param key 消息唯一标识
*/
public static void setReceiveMsg(String key, String msg) {
if(responseMsgCache.getIfPresent(key) != null){
responseMsgCache.getIfPresent(key).add(msg);
return;
}
log.warn("sn {}不存在",key);
}
}
网友评论