為初學(xué)者而來~手工最簡MQ(二)Broker

本文僅展示核心代碼濒憋,全部代碼,請移步:git-soomq

1陶夜,服務(wù)端

服務(wù)端的設(shè)計就非常簡單了凛驮,最核心的就是消息的存取,以及響應(yīng)生產(chǎn)者和消費者的網(wǎng)絡(luò)請求
分為2部分:

1.1 消息文件

消息的存儲我們參考kafka条辟,并簡化其邏輯黔夭,因為是最簡單的mq,我們只考慮單機的情況的就行捂贿,每個topic存儲2個文件

topicname.index
topicname.data

.index 文件存儲格式為:
消息順序號:消息截止位置
.data 文件按照順序存儲具體的消息

文件操作:

package com.esoo.mq.server.message;

import com.alibaba.fastjson.JSON;
import com.esoo.mq.common.ProcessorCommand;

import java.io.RandomAccessFile;

/**
 * 為每個topic創(chuàng)建一個對象進行管理
 */
public class MessageFile {
    private String topic;
    private Long offset;
    //索引文件
    private RandomAccessFile indexFile = null ;
    //數(shù)據(jù)文件
    private RandomAccessFile dataFile = null ;

    //追加消息(生產(chǎn)者進行調(diào)用)
    public ProcessorCommand appendMsg(ProcessorCommand in){

        try {
            //加鎖纠修,避免競爭胳嘲,文件亂碼
            synchronized (in.getResult().getTopic()) {

                //讀取index文件最后一行
                String lastLine = readLastLine(indexFile, null);
                int lastOffset = 1;
                //消息體追加到data文件中厂僧,并返回文件末尾位置,作為本條消息的offset
                long lastindex =  writeEndLine(dataFile, in.getResult().getBody());
                if (lastLine != null && !lastLine.equals("")) {
                    String index[] = lastLine.split(":");
                    lastOffset = Integer.valueOf(index[0]);
                    lastOffset = lastOffset + 1;
                }
                //組裝本條消息index 序列號:消息體末尾位置
                String insertMsgIndex = lastOffset + ":" + lastindex + "\t\n";
                writeEndLine(indexFile, insertMsgIndex.getBytes());
                in.setSuccess(true);
            }
        }catch (Exception e){
            e.printStackTrace();

            in.setSuccess(false);
            in.setExmsg(e.getMessage());
        }
        return in;

    }

    //讀取消息了牛,消費者進行調(diào)用
    public ProcessorCommand readMsg(ProcessorCommand in){


        try {
            synchronized (in.getResult().getTopic()) {
                // 消息定位位置
                int seekIn = 0;
                // 消息體大小
                int bodySize = 0;
                //先定位到開始
                indexFile.seek(0);
                String indesMap=null;
                //遍歷index文件颜屠,找到上一個消息 offset 與本消息offset 進行相減就是消息體大小
                while ((indesMap = indexFile.readLine())!=null){
                    String index[] = indesMap.split(":");
                    int inNum = Integer.valueOf(String.valueOf(index[0]).trim());
                    int off = Integer.valueOf(String.valueOf(index[1]).trim());
                    if (inNum == in.getResult().getOffset()) {
                        seekIn = off;
                    }
                    if (inNum == (in.getResult().getOffset() + 1)) {
                        bodySize = off - seekIn;
                    }
                }
                if (bodySize == 0) {
                    in.setSuccess(false);
                    in.setExmsg("offset is end");
                    return in;
                }
                //定位到具體位置
                dataFile.seek(seekIn);

                //進行消息讀取
                byte[] b = new byte[bodySize];
                dataFile.read(b);
                in.getResult().setBody(b);

                in.setSuccess(true);
                System.out.println(" READ MSG IS: "+JSON.toJSONString(in));
            }
        }catch (Exception e){
            e.printStackTrace();
            in.setSuccess(false);
            in.setExmsg(e.getMessage());
        }
        return in;

    }

    //寫消息到最后一行
    public static long writeEndLine(RandomAccessFile file, byte[] msg)
            throws Exception {
        // 文件長度,字節(jié)數(shù)
        long fileLength = file.length();
        // 將寫文件指針移到文件尾鹰祸。
        file.seek(fileLength);
        file.write(msg);
        return file.getFilePointer();

    }

    //讀取最后一行的消息
    public static String readLastLine(RandomAccessFile file, String charset) throws Exception {

        long len = file.length();
        if (len == 0L) {
            return "";
        } else {
            long pos = len - 1;
            while (pos > 0) {
                pos--;
                file.seek(pos);
                if (file.readByte() == '\n') {
                    break;
                }
            }
            if (pos == 0) {
                file.seek(0);
            }
            byte[] bytes = new byte[(int) (len - pos)];
            file.read(bytes);
            if (charset == null) {
                return new String(bytes);
            } else {
                return new String(bytes, charset);
            }
        }

    }

    public static String readByOffset(RandomAccessFile file, String charset) throws Exception {

        return null;
    }



    public String getTopic() {
        return topic;
    }

    public void setTopic(String topic) {
        this.topic = topic;
    }

    public Long getOffset() {
        return offset;
    }

    public void setOffset(Long offset) {
        this.offset = offset;
    }

    public RandomAccessFile getIndexFile() {
        return indexFile;
    }

    public void setIndexFile(RandomAccessFile indexFile) {
        this.indexFile = indexFile;
    }

    public RandomAccessFile getDataFile() {
        return dataFile;
    }

    public void setDataFile(RandomAccessFile dataFile) {
        this.dataFile = dataFile;
    }
}

1.2 網(wǎng)絡(luò)編程

利用netty 開放端口甫窟,響應(yīng)生產(chǎn)者與消費者,每個消息包裝成一個commod蛙婴,commod類型

  • 消息類型(消費/生產(chǎn))
  • 消息topic
  • 消息體(生產(chǎn)時用)
  • 消息順序號(消費時用)
  • 處理結(jié)果(成功/失敶志)
  • 處理消息(失敗時添加原因)

網(wǎng)絡(luò)啟動

package com.esoo.mq.server;

import com.esoo.mq.server.netty.handler.NettySooMqServerHandler;
import com.esoo.mq.server.netty.handler.NettySooMqServerOutHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

public class SooMQServer {
    private static Integer serverPort=9870;
    ServerBootstrap b = new ServerBootstrap();

    public void start(){
        //創(chuàng)建reactor 線程組
        EventLoopGroup bossLoopGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerLoopGroup = new NioEventLoopGroup();

        try {
            //1 設(shè)置reactor 線程組
            b.group(bossLoopGroup, workerLoopGroup);
            //2 設(shè)置nio類型的channel
            b.channel(NioServerSocketChannel.class);
            //3 設(shè)置監(jiān)聽端口
            b.localAddress(serverPort);
            //4 設(shè)置通道的參數(shù)
            b.option(ChannelOption.SO_KEEPALIVE, true);
            b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

            //5 裝配子通道流水線
            b.childHandler(new ChannelInitializer<SocketChannel>() {
                //有連接到達(dá)時會創(chuàng)建一個channel
                protected void initChannel(SocketChannel ch) throws Exception {
                    // pipeline管理子通道channel中的Handler
                    // 向子channel流水線添加一個handler處理器
                    ch.pipeline().addLast(new ObjectEncoder());
                    ch.pipeline().addLast(new ObjectDecoder(Integer.MAX_VALUE,
                            ClassResolvers.cacheDisabled(null)));
                    ch.pipeline().addLast(new NettySooMqServerOutHandler());
                    ch.pipeline().addLast(new NettySooMqServerHandler());
                }
            });
            // 6 開始綁定server
            // 通過調(diào)用sync同步方法阻塞直到綁定成功
            ChannelFuture channelFuture = b.bind().sync();
            System.out.println(" 服務(wù)器啟動成功,監(jiān)聽端口: " +
                    channelFuture.channel().localAddress());

            // 7 等待通道關(guān)閉的異步任務(wù)結(jié)束
            // 服務(wù)監(jiān)聽通道會一直等待通道關(guān)閉的異步任務(wù)結(jié)束
            ChannelFuture closeFuture = channelFuture.channel().closeFuture();
            closeFuture.sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 8 優(yōu)雅關(guān)閉EventLoopGroup,
            // 釋放掉所有資源包括創(chuàng)建的線程
            workerLoopGroup.shutdownGracefully();
            bossLoopGroup.shutdownGracefully();
        }
    }

}

網(wǎng)絡(luò)邏輯分發(fā)

注意:回寫給客戶端的消息體類型必須與入?yún)⒈3忠恢陆匠模駝tnetty無法解析


netty
package com.esoo.mq.server.netty.handler;


import com.alibaba.fastjson.JSON;
import com.esoo.mq.common.ProcessorCommand;
import com.esoo.mq.server.processor.Processor;
import com.esoo.mq.server.processor.ProcessorFactory;
import io.netty.channel.*;

@ChannelHandler.Sharable
public class NettySooMqServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        try {
            ProcessorCommand command = (ProcessorCommand) msg;
            System.out.println("["+ctx.channel().remoteAddress()+"] msg:"+JSON.toJSONString(msg));
            Processor processor = ProcessorFactory.getProcessorInstantiate(command.getType());
            msg = processor.handle(command);
            ChannelFuture f = ctx.writeAndFlush(msg);
            f.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    System.out.println("msg ctx send");
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println(cause.getMessage());
        ctx.close();
    }



}

生產(chǎn)者

package com.esoo.mq.server.processor;

import com.esoo.mq.common.Message;
import com.esoo.mq.common.ProcessorCommand;
import com.esoo.mq.server.message.MessageFile;
import com.esoo.mq.server.message.MessageFileFactory;

public class SendMessageProcessor implements Processor<Message,Message> {

    @Override
    public ProcessorCommand handle(ProcessorCommand task) {
        MessageFile file = MessageFileFactory.getTopicFile(task.getResult().getTopic());
        task = file.appendMsg(task);
        return task;
    }


}

消費者

package com.esoo.mq.server.processor;

import com.esoo.mq.common.Message;
import com.esoo.mq.common.ProcessorCommand;
import com.esoo.mq.server.message.MessageFile;
import com.esoo.mq.server.message.MessageFileFactory;

public class ReadMessageProcessor implements Processor<Message,Message> {

    @Override
    public ProcessorCommand handle(ProcessorCommand task) {
        Message msg = task.getResult();
        MessageFile file = MessageFileFactory.getTopicFile(msg.getTopic());
        task = file.readMsg(task);
        return task;
    }


}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末懒构,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子耘擂,更是在濱河造成了極大的恐慌胆剧,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,490評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件醉冤,死亡現(xiàn)場離奇詭異秩霍,居然都是意外死亡,警方通過查閱死者的電腦和手機蚁阳,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,581評論 3 395
  • 文/潘曉璐 我一進店門铃绒,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人韵吨,你說我怎么就攤上這事匿垄。” “怎么了归粉?”我有些...
    開封第一講書人閱讀 165,830評論 0 356
  • 文/不壞的土叔 我叫張陵椿疗,是天一觀的道長。 經(jīng)常有香客問我糠悼,道長届榄,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,957評論 1 295
  • 正文 為了忘掉前任倔喂,我火速辦了婚禮铝条,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘席噩。我一直安慰自己班缰,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,974評論 6 393
  • 文/花漫 我一把揭開白布悼枢。 她就那樣靜靜地躺著埠忘,像睡著了一般。 火紅的嫁衣襯著肌膚如雪馒索。 梳的紋絲不亂的頭發(fā)上莹妒,一...
    開封第一講書人閱讀 51,754評論 1 307
  • 那天,我揣著相機與錄音绰上,去河邊找鬼旨怠。 笑死,一個胖子當(dāng)著我的面吹牛蜈块,可吹牛的內(nèi)容都是我干的鉴腻。 我是一名探鬼主播迷扇,決...
    沈念sama閱讀 40,464評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼爽哎!你這毒婦竟也來了谋梭?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,357評論 0 276
  • 序言:老撾萬榮一對情侶失蹤倦青,失蹤者是張志新(化名)和其女友劉穎瓮床,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體产镐,經(jīng)...
    沈念sama閱讀 45,847評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡隘庄,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,995評論 3 338
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了癣亚。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片丑掺。...
    茶點故事閱讀 40,137評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖述雾,靈堂內(nèi)的尸體忽然破棺而出街州,到底是詐尸還是另有隱情,我是刑警寧澤玻孟,帶...
    沈念sama閱讀 35,819評論 5 346
  • 正文 年R本政府宣布唆缴,位于F島的核電站,受9級特大地震影響黍翎,放射性物質(zhì)發(fā)生泄漏面徽。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,482評論 3 331
  • 文/蒙蒙 一匣掸、第九天 我趴在偏房一處隱蔽的房頂上張望趟紊。 院中可真熱鬧,春花似錦碰酝、人聲如沸霎匈。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,023評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽铛嘱。三九已至,卻和暖如春碱璃,著一層夾襖步出監(jiān)牢的瞬間弄痹,已是汗流浹背饭入。 一陣腳步聲響...
    開封第一講書人閱讀 33,149評論 1 272
  • 我被黑心中介騙來泰國打工嵌器, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人谐丢。 一個月前我還...
    沈念sama閱讀 48,409評論 3 373
  • 正文 我出身青樓爽航,卻偏偏與公主長得像蚓让,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子讥珍,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,086評論 2 355