關(guān)于netty結(jié)合springboot的一些高級用法


  1. netty和springboot的整合方式,netty采用的是4.0.25版本

            <dependency>
                <groupId>io.netty</groupId>
                <artifactId>netty-all</artifactId>
                <version>4.0.25.Final</version>
            </dependency>
    
  2. 服務(wù)端實(shí)現(xiàn),

    ? 可以選擇讓netty服務(wù)端伴隨著springboot啟動(dòng),即通過注解的形式,讓netty Server變成一個(gè)bean,當(dāng)加載這個(gè)bean時(shí)默認(rèn)啟動(dòng),但這種方式當(dāng)啟動(dòng)nettyServer后會(huì)阻斷springboot的啟動(dòng)郁副,即加載到nettyServer這個(gè)bean之后,后面的bean不能繼續(xù)加載,springboot項(xiàng)目的啟動(dòng)也將阻塞在這父款。第二種方式通過手動(dòng)啟動(dòng),比較友好瞻凤,不會(huì)阻塞springboot的啟動(dòng)憨攒。

    package com.zt.apply.server;
    
    import com.zt.apply.handler.DispacherHandler;
    import io.netty.bootstrap.ServerBootstrap;
    import io.netty.channel.ChannelFuture;
    import io.netty.channel.ChannelInitializer;
    import io.netty.channel.ChannelOption;
    import io.netty.channel.nio.NioEventLoopGroup;
    import io.netty.channel.socket.SocketChannel;
    import io.netty.channel.socket.nio.NioServerSocketChannel;
    import io.netty.handler.codec.LineBasedFrameDecoder;
    import io.netty.handler.codec.string.StringDecoder;
    import io.netty.handler.codec.string.StringEncoder;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    
    import javax.annotation.PostConstruct;
    
    //@Component
    public class Server {
    
    
    //    @PostConstruct
        public static void run() {
    
            NioEventLoopGroup workerGroup = new NioEventLoopGroup();
            NioEventLoopGroup bossGroup = new NioEventLoopGroup();
    
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup);
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.childHandler(new ChanelInit());
            serverBootstrap = serverBootstrap.option(ChannelOption.SO_BACKLOG, 128);
            serverBootstrap = serverBootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    
            /***
             * 綁定端口并啟動(dòng)去接收進(jìn)來的連接
             */
            ChannelFuture f = null;
            try {
                f = serverBootstrap.bind(6910).sync();
    
                System.err.println("啟動(dòng)成功");
                /**
                 * 這里會(huì)一直等待,直到socket被關(guān)閉
                 */
                f.channel().closeFuture().sync();
                System.err.println("Start succss!");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
                System.err.println("關(guān)閉完成!");
            }
        }
    
        static class ChanelInit extends ChannelInitializer<SocketChannel> {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                socketChannel.pipeline().addLast(new StringEncoder());
                socketChannel.pipeline().addLast(new StringDecoder());
                socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024));
                socketChannel.pipeline().addLast(new DispacherHandler());
            }
    
        }
    }
    
    

    手動(dòng)方式啟動(dòng):

    public class NettyApplyApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(NettyApplyApplication.class, args);
            Server.run();
        }
    }
    
  1. netty如何實(shí)現(xiàn)業(yè)務(wù)的分發(fā)

    ? 當(dāng)netty接收到消息后將直接分發(fā)出去阀参,交給業(yè)務(wù)層處理肝集,而不用每次接收到消息都要handler自己去處理

    package com.zt.apply.handler;
    import com.zt.apply.dispacher.TcpDispacher;
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.SimpleChannelInboundHandler;
    
    
    public class DispacherHandler extends SimpleChannelInboundHandler<String> {
    
        private TcpDispacher tcpDispacher = TcpDispacher.getInstance();
    
        @Override
        protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
            tcpDispacher.messageRecived(channelHandlerContext, s);
        }
    
    }
    
    
  1. 業(yè)務(wù)的分發(fā)

    ? 在handler接收到消息后,如何將消息分發(fā)到業(yè)務(wù)層蛛壳,成了最大的問題杏瞻。這也將是本文的精華所在,通過注解的形式實(shí)現(xiàn)業(yè)務(wù)的分發(fā)衙荐,在handler中收到消息后捞挥,調(diào)用TcpDispacher的messageRecived方法去處理,messageRecived方法將從客戶端傳過來的數(shù)據(jù)中解析出messageCode忧吟,根據(jù)messageCode找到這個(gè)code所對應(yīng)的實(shí)體業(yè)務(wù)bean砌函。

    ? 所有的實(shí)體業(yè)務(wù)bean都統(tǒng)一實(shí)現(xiàn)BaseBusinessCourse接口。

    package com.zt.apply.dispacher;
    
    import com.alibaba.fastjson.JSONObject;
    import com.zt.apply.base.BaseBusinessCourse;
    import io.netty.channel.ChannelHandlerContext;
    import org.springframework.stereotype.Component;
    
    import java.util.Map;
    import java.util.concurrent.ConcurrentHashMap;
    
    /**
     * @Author: zt
     * @Date: 2019/1/6 15:50
     */
    @Component
    public class TcpDispacher {
    
        private static TcpDispacher instance = new TcpDispacher();
    
        private TcpDispacher() {
    
        }
    
        public static TcpDispacher getInstance() {
            return instance;
        }
    
    
        private static Map<String, Object> coursesTable = new ConcurrentHashMap<>();
    
        /**
         * 消息流轉(zhuǎn)處理
         *
         * @param channelHandlerContext
         * @param s
         */
        public void messageRecived(ChannelHandlerContext channelHandlerContext, String s) {
            System.err.println("收到的消息:" + s);
            JSONObject jsonObject = JSONObject.parseObject(s);
            String code = jsonObject.getString("messageCode");
            BaseBusinessCourse baseBusinessCourse = (BaseBusinessCourse) coursesTable.get(code);
            baseBusinessCourse.doBiz(channelHandlerContext, s);
        }
    
    
        public void setCourses(Map<String, Object> courseMap) {
            System.err.println("設(shè)置map的值");
            if (courseMap != null && courseMap.size() > 0) {
                for (Map.Entry<String, Object> entry : courseMap.entrySet()) {
                    coursesTable.put(entry.getKey(), entry.getValue());
                }
            }
        }
    
    
    }
    
    
  1. 業(yè)務(wù)bean

    @Component
    @Biz(value = "10003")
    public class LinsenceBizService implements BaseBusinessCourse {
        @Override
        public void doBiz(ChannelHandlerContext context, String message) {
            System.out.println("業(yè)務(wù)層收到的數(shù)據(jù):" + message);
            context.writeAndFlush("{test:\"test\"}\r\n");
        }
    
    }
    
  1. Biz注解

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.TYPE)
    @Documented
    public @interface Biz {
    
        String value();
    
    }
    
  1. TcpDispacher中messageCode和業(yè)務(wù)bean的注入

    ? 這里通過監(jiān)聽ApplicationStartedEvent事件溜族,在項(xiàng)目啟動(dòng)完成后獲取到所有被Biz注解過的bean,并獲取到注解中的value值讹俊,存入map,注入到TcpDispacher中。

    public class ContextRefreshedListener implements ApplicationListener<ApplicationStartedEvent> {
    
        @Override
        public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {
    
            Map<String, Object> map = new HashMap<>();
    
            Map<String, Object> bizMap = applicationStartedEvent.getApplicationContext().getBeansWithAnnotation(Biz.class);
            for (Map.Entry<String, Object> entry : bizMap.entrySet()) {
                Object object = entry.getValue();
                Class c = object.getClass();
                System.err.println(c + "===>");
                Annotation[] annotations = c.getDeclaredAnnotations();
    
                for (Annotation annotation : annotations) {
                    if (annotation.annotationType().equals(Biz.class)) {
                        Biz biz = (Biz) annotation;
                        map.put(biz.value(), object);
                    }
                }
            }
    
    
            TcpDispacher tcpDispacher = (TcpDispacher) applicationStartedEvent.getApplicationContext().getBean("tcpDispacher");
            tcpDispacher.setCourses(map);
    
        }
    }
    
    
  2. 請求體

    public class BaseRequest {
    
        private String messageCode;
    
        private String content;
    
        public String getMessageCode() {
            return messageCode;
        }
    
        public void setMessageCode(String messageCode) {
            this.messageCode = messageCode;
        }
    
        public String getContent() {
            return content;
        }
    
        public void setContent(String content) {
            this.content = content;
        }
    
        public String toJson() {
            return JSON.toJSONString(this) + "\r\n";
        }
    }
    
  1. 客戶端

    ? 下篇再講吧煌抒,同時(shí)交代如何在發(fā)布消息的地方實(shí)時(shí)獲取到服務(wù)端返回的內(nèi)容仍劈,通過回調(diào)實(shí)現(xiàn)。以及channel連接池的設(shè)計(jì)寡壮。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末耳奕,一起剝皮案震驚了整個(gè)濱河市绑青,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌屋群,老刑警劉巖闸婴,帶你破解...
    沈念sama閱讀 216,651評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異芍躏,居然都是意外死亡邪乍,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,468評論 3 392
  • 文/潘曉璐 我一進(jìn)店門对竣,熙熙樓的掌柜王于貴愁眉苦臉地迎上來庇楞,“玉大人,你說我怎么就攤上這事否纬÷郎危” “怎么了?”我有些...
    開封第一講書人閱讀 162,931評論 0 353
  • 文/不壞的土叔 我叫張陵临燃,是天一觀的道長睛驳。 經(jīng)常有香客問我,道長膜廊,這世上最難降的妖魔是什么乏沸? 我笑而不...
    開封第一講書人閱讀 58,218評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮爪瓜,結(jié)果婚禮上蹬跃,老公的妹妹穿的比我還像新娘。我一直安慰自己铆铆,他們只是感情好蝶缀,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,234評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著薄货,像睡著了一般扼劈。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上菲驴,一...
    開封第一講書人閱讀 51,198評論 1 299
  • 那天荐吵,我揣著相機(jī)與錄音,去河邊找鬼赊瞬。 笑死先煎,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的巧涧。 我是一名探鬼主播薯蝎,決...
    沈念sama閱讀 40,084評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼谤绳!你這毒婦竟也來了占锯?” 一聲冷哼從身側(cè)響起袒哥,我...
    開封第一講書人閱讀 38,926評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎消略,沒想到半個(gè)月后堡称,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,341評論 1 311
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡艺演,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,563評論 2 333
  • 正文 我和宋清朗相戀三年却紧,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片胎撤。...
    茶點(diǎn)故事閱讀 39,731評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡晓殊,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出伤提,到底是詐尸還是另有隱情巫俺,我是刑警寧澤,帶...
    沈念sama閱讀 35,430評論 5 343
  • 正文 年R本政府宣布肿男,位于F島的核電站介汹,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏次伶。R本人自食惡果不足惜痴昧,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,036評論 3 326
  • 文/蒙蒙 一稽穆、第九天 我趴在偏房一處隱蔽的房頂上張望冠王。 院中可真熱鬧,春花似錦舌镶、人聲如沸柱彻。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,676評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽哟楷。三九已至,卻和暖如春否灾,著一層夾襖步出監(jiān)牢的瞬間卖擅,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,829評論 1 269
  • 我被黑心中介騙來泰國打工墨技, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留惩阶,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,743評論 2 368
  • 正文 我出身青樓扣汪,卻偏偏與公主長得像断楷,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子崭别,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,629評論 2 354

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