62,614
社区成员
发帖
与我相关
我的任务
分享
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
/*
*@Description //TODO 缓存帮助类$
*@Author 吾王剑锋所指 吾等心之所向
*@Date 2019/8/30 11:11
*/
public class CacheHelper{
private static final Logger LOGGER = LoggerFactory.getLogger(EntityCacheHelp.class);
public static Cache<Integer, ChannelHandlerContext> channelIdCache = CacheBuilder
.newBuilder()
.maximumSize(99999)
.expireAfterAccess(120, TimeUnit.SECONDS)
.build();
public static boolean arrayEquals(String[] a,String[] b){
return Arrays.equals(a, b);
}
public static String[] getItemVosByIndicex(List<ItemVO> itemVos){
Set<String> set = new HashSet<>();
/*itemVos.forEach(itemVo -> set.add(itemVo.getItemInfo()));*/
return set.toArray(new String[set.size()]);
}
}
然后, 在netty 服务启动的地方, 例如在 channelActive 方法中使用缓存来保存 ctx
/**
* 客户端主动连接服务端 连接成功时向客户端发送一条信息
*
* */
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
LOGGER.info("RemoteAddress"+ ctx.channel().remoteAddress() + " active !");
LOGGER.info("msg send active !"+ctx.channel().writeAndFlush("123456"));
ctx.writeAndFlush("啦啦啦!");
CacheHelper.channelIdCache.put(56193,ctx);
super.channelActive(ctx);
}
这样, 在建立连接后, 缓存会自动将 ctx 保存起来
如果需要使用 ctx,
就在需要使用的地方
public Boolean firstSendMsg(int clientId, JSONObject jsonObject){
try{
if(jsonObject == null) return false;
System.out.println(jsonObject);
ChannelHandlerContext ctx = CacheHelper.channelIdCache.getIfPresent(clientId);
ctx.writeAndFlush(jsonObject);
}catch (Exception ex){
LOGGER.error(ex.getMessage(), ex);
}
return true;
}
啦啦啦,,就是这么简单, 哇, 我好开心啊