設(shè)計一個消息中間件的前置(二)| Netty 4 + protobuf 3

我也是在做完前置設(shè)計后才開始學(xué)習(xí)Netty框架的,不得不說,相比直接使用Socket,Netty真是封裝得太到位了。另外強(qiáng)烈推薦《Netty實戰(zhàn)》這本書,花了兩天時間讀完,基本就可以對Netty的架構(gòu)有個直觀的了解。后續(xù)看時間再去看看Netty的源碼吧。

選擇Protobuf主要是因為客戶端與服務(wù)端之間的傳輸需要進(jìn)行編解碼,而Protobuf可以實現(xiàn)極高效的序列化和反序列化,且Netty還直接支持Protobuf。讓我覺得不用都不好意思了。

前置最優(yōu)先的功能其實就是用戶校驗和返回路由信息及校驗結(jié)果。由于配套使用了Redis,等后續(xù)的文章我再更新我的數(shù)據(jù)結(jié)構(gòu)設(shè)計。這篇先專注在Netty和Protobuf吧。

我想這系列的文章也只會描述基本功能,介紹個框架吧。

Protobuf數(shù)據(jù)格式

如果在一個用戶粒度分的極細(xì)的場景下,我們可以直接通過用戶+密碼的方式來得到用戶的權(quán)限信息,比如該用戶應(yīng)該連接到哪個MQ集群,是否用戶名密碼匹配等等。所以對客戶端來說,需要告知前置的就是用戶名、密碼這兩個信息。而服務(wù)端需要返回的是校驗碼,校驗信息和MQ集群地址,也是三個String就能解決的事。數(shù)據(jù)很好設(shè)計:

syntax = "proto3";
message usrinfo {
    string usrname = 1;
    string pwd = 2;
}
message authresponse {
    string retcode = 1;
    string address = 2;
}

然后需要做的就是

  1. 編譯proto文件,生成java文件
  2. 把java文件放到你的工程里
  3. 在工程中引入protobuf-java-3.5.1.jar依賴包
    用maven會比較方便,我這里eclipse一直有問題,就下了protobuf的包自己編譯出protobuf-java-3.5.1.jar。

Netty服務(wù)端

在Netty框架下,主要需要設(shè)計的就是ChannalInboundHandler。服務(wù)端用于在獲取客戶端的數(shù)據(jù)后,訪問Redis得到結(jié)果并返回給客戶端。直接上代碼吧:

package front.server;

import java.net.InetSocketAddress;

import front.client.Msg;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
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.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;

public class FrontServer {
    private final int port;
    public FrontServer(int port) {
        this.port=port;
    }
    public static void main(String[] args) throws InterruptedException{
        int port = 9621;
        new FrontServer(port).start();
    }

    public void start() throws InterruptedException{
        EventLoopGroup g = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(g).channel(NioServerSocketChannel.class)
            .localAddress(new InetSocketAddress(port))
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    // TODO Auto-generated method stub
                    ch.pipeline().addLast("frameDecoder", new ProtobufVarint32FrameDecoder());// 用于decode前解決半包和粘包問題(利用包頭中的包含數(shù)組長度來識別半包粘包)  
                    //配置Protobuf解碼處理器,消息接收到了就會自動解碼,ProtobufDecoder是netty自帶的,Message是自己定義的Protobuf類  
                    ch.pipeline().addLast("protobufDecoder",new ProtobufDecoder(Msg.usrinfo.getDefaultInstance()));  
                    // 用于在序列化的字節(jié)數(shù)組前加上一個簡單的包頭,只包含序列化的字節(jié)長度。  
                    ch.pipeline().addLast("frameEncoder",  
                            new ProtobufVarint32LengthFieldPrepender());  
                    //配置Protobuf編碼器,發(fā)送的消息會先經(jīng)過編碼  
                    ch.pipeline().addLast("protobufEncoder", new ProtobufEncoder());  
                    // ----Protobuf處理器END----  
                    ch.pipeline().addLast(new FrontServerhandler());
                }
            });
            ChannelFuture f = b.bind().sync();
            f.channel().closeFuture().sync();
        } finally {
            g.shutdownGracefully().sync();
        }
    }
}
package front.server;

import front.client.Msg;
import front.client.Msg.usrinfo;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelHandler.*;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

public class FrontServerhandler extends SimpleChannelInboundHandler<Msg.usrinfo>{
    
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, usrinfo msg) throws Exception {
    
        Msg.authresponse.Builder res = Msg.authresponse.newBuilder();
        //訪問Redis進(jìn)行權(quán)限校驗并填充res
        ……………………
        ctx.writeAndFlush(res.build())
    System.out.println("receive: "+msg.toString());

    }
}

Netty客戶端

客戶端的功能是訪問前置,在ChannelActive的時候發(fā)送自己的用戶信息,獲取權(quán)限信息后嘗試連接MQ。這里只給出與前置連接的部分代碼。
當(dāng)然,這里不是最終代碼,僅給出一個框架而已。

package front.client;

import java.net.InetSocketAddress;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.util.CharsetUtil;

public class FrontClient {
    private final String host;
    private final int port;
    public FrontClient(){
        //作為開發(fā),配的是本機(jī)地址
        this.host="127.0.0.1";
        this.port=9621;
    }
    public void start() throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        try{
            Bootstrap b = new Bootstrap();
            b.group(group)
            .channel(NioSocketChannel.class)
            .remoteAddress(new InetSocketAddress(host,port))
            .handler(new ChannelInitializer<SocketChannel>(){

                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    // TODO Auto-generated method stub
                    ch.pipeline().addLast("frameDecoder", new ProtobufVarint32FrameDecoder());
                    ch.pipeline().addLast("protobufDecoder",new ProtobufDecoder(Msg.usrinfo.getDefaultInstance())); 
                    ch.pipeline().addLast("frameEncoder",  
                            new ProtobufVarint32LengthFieldPrepender());  
                    ch.pipeline().addLast("protobufEncoder", new ProtobufEncoder());  
                    ch.pipeline().addLast(new FrontClientHandler());
                }   
            });
            ChannelFuture f = b.connect().sync();
            f.channel().closeFuture().sync();
        }finally {
            group.shutdownGracefully().sync();
        }
    }
    public static void main(String[] args) throws InterruptedException{
        new FrontClient().start();
    }
}
package front.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelHandler.*;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
public class FrontClientHandler extends SimpleChannelInboundHandler<Msg.authresponse> {
     //channelActive的時候發(fā)送用戶信息
    public void channelActive(ChannelHandlerContext ctx) {
        Msg.usrinfo.Builder usrinfo = Msg.usrinfo.newBuilder();
        usrinfo.setPwd("1234");
        usrinfo.setUsrname("client");
        usrinfo.build();
        ctx.writeAndFlush(usrinfo);
    }
    @Override
    protected void channelRead0(ChannelHandlerContext arg0, Msg.authresponse in) throws Exception {
        System.out.println(in.toString());
        //找個單例對象存儲校驗結(jié)果后續(xù)再處理。
        ……………………  
    }
    
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,461評論 6 532
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,538評論 3 417
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,423評論 0 375
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,991評論 1 312
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,761評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,207評論 1 324
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,268評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,419評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,959評論 1 335
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,782評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 42,983評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,528評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,222評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,653評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,901評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,678評論 3 392
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 47,978評論 2 374

推薦閱讀更多精彩內(nèi)容

  • 之前提過,我目前在做一個企業(yè)級的消息中間件平臺應(yīng)用,將各個消息中間件整合入這個平臺,實現(xiàn)所有消息中間件的集中監(jiān)控,...
    MisterCH閱讀 2,193評論 14 2
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,785評論 18 139
  • 放學(xué)排隊的時候,班長看見了我和我的同桌表現(xiàn)得非常好。走路的時候也很好,所以我得了兩個小紅花。而我同桌只得了一個小紅...
    平凡一生123閱讀 497評論 0 0
  • 馬大約是排在犬之后人類的第二個忠誠朋友。法國18世紀(jì)自然科學(xué)家、散文家布封說:人類所能做到的最高貴的征服,就是征...
    湖邊人老劉閱讀 1,612評論 0 0
  • 【寫在前面的話:想起某件事要問自己現(xiàn)在能不能馬上做,改掉“待會兒再說”的壞毛病】 我一向做事情沒什么長性,總是計劃...
    盡力了嗎閱讀 405評論 1 3