本文仅展示核心代码,全部代码,请移步:git-soomq
为初学者而来~手工最简MQ(一)设计篇
为初学者而来~手工最简MQ(二)Broker
为初学者而来~手工最简MQ(三)Client
2,client
2.1 连接管理
通过netty与mq服务器进行连接,并相应生产者与消费者的请求,通过netty自带的序列化工具,将消息序列化未byte字节进行传输
2.1.1 服务启动,连接broker
package com.esoo.mq.client.connection;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.Map;
public class ConnectionManager {
private static HashMap<String,Channel> channelMap=new HashMap<>();
public static Channel get(String ip,Integer port){
Channel channel=null;
String url = ip+":"+port;
synchronized (url) {
if (!channelMap.containsKey(url)) {
channel=createChannel(ip,port);
channelMap.put(url,channel);
}else{
channel= channelMap.get(url);
}
}
return channel;
}
private static Channel createChannel(String ip,Integer port){
Bootstrap b = new Bootstrap();
//创建reactor 线程组
EventLoopGroup workerLoopGroup = new NioEventLoopGroup();
Channel channel=null;
try {
//1 设置reactor 线程组
b.group(workerLoopGroup);
//2 设置nio类型的channel
b.channel(