我參考了這個:https://gitee.com/xjmroot/netty-pool
其實(shí)他的思路就是做一個緩存,把發(fā)送的信息做一個key存緩存,接收的信息也有這個key放到對應(yīng)的緩存作為返回.
我是這么寫的:
NettyTools.initReceiveMsg(key);
String result = NettyTools.waitReceiveMsg(key);
在netty的inboundHandler實(shí)現(xiàn)類里,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");
/**
* 響應(yīng)消息緩存
*/
private static Cache<String, BlockingQueue<String>> responseMsgCache = CacheBuilder.newBuilder()
.maximumSize(50000)
.expireAfterWrite(100, TimeUnit.SECONDS)
.build();
/**
* 等待響應(yīng)消息
* @param key 消息唯一標(biāo)識
* @return ReceiveDdcMsgVo
*/
public static String waitReceiveMsg(String key) {
try {
//設(shè)置超時時間
String vo = Objects.requireNonNull(responseMsgCache.getIfPresent(key))
.poll(3000, TimeUnit.MILLISECONDS);
//刪除key
responseMsgCache.invalidate(key);
return vo;
} catch (Exception e) {
log.error("獲取數(shù)據(jù)異常,sn={},msg=null",key);
return null;
}
}
/**
* 初始化響應(yīng)消息的隊(duì)列
* @param key 消息唯一標(biāo)識
*/
public static void initReceiveMsg(String key) {
responseMsgCache.put(key,new LinkedBlockingQueue<String>(1));
}
/**
* 設(shè)置響應(yīng)消息
* @param key 消息唯一標(biāo)識
*/
public static void setReceiveMsg(String key, String msg) {
if(responseMsgCache.getIfPresent(key) != null){
responseMsgCache.getIfPresent(key).add(msg);
return;
}
log.warn("sn {}不存在",key);
}
}