可按Ctrl+D收藏 蚂蚁资源网

蚂蚁资源网

netty 源码分析(netty的异步实现原理)

  • 全部评论(3)
  • 互站网
  • 写在另外的线程里。netty自己的线程应该只被用于处理网络,比如收发消息,网络连接的建立断开,超时...,业务逻辑应该放在业务线程里,使业务逻辑与网络分离。比如你的业务处理很时间,如果放在netty的线程里,可能会导致网络阻塞,甚至挂掉
  • 2021-02-27 16:40:01
  • 201538
  • package test2;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.util.HashMap;import java.util.Map;import java.util.Set;public class JavaCodeAnalyzer {    public static void analyze(File file) throws IOException{        //FileOutputStream fos = new FileOutputStream("F;"+File.separator+"result.txt");        if(!(file.getName().endsWith(".txt")||file.getName().endsWith(".java"))){            System.out.println("输入的分析文件格式不对!");        }        InputStream is= new FileInputStream(file);        BufferedReader br= new BufferedReader(new InputStreamReader(is));        String temp;        int count=0;        int countSpace=0;        int countCode=0;        int countDesc=0;        Map map = getKeyWords();        while((temp=br.readLine())!=null){            countKeys(temp, map);            count++;            if(temp.trim().equals("")){                countSpace++;            }else if(temp.trim().startsWith("/*")||temp.trim().startsWith("//")){                countDesc++;            }else{                countCode++;            }        }        System.out.printf("代码行数:"+countCode+"占总行数的%4.2f\n",(double)countCode/count);        System.out.printf("空行数:"+countSpace+"占总行数的%4.2f\n",(double)countSpace/count);        System.out.printf("注释行数:"+countDesc+"占总行数的%4.2f\n",(double)countDesc/count);        System.out.println("总行数:"+count);        System.out.println("出现最多的5个关键字是:");        System.out.println("");        System.out.println("");        System.out.println("");        System.out.println("");        System.out.println("");    }    public static void main(String[] args) {        getKeyWords();        File file = new File("F://Test.java");        try {            analyze(file);        } catch (IOException e) {            // TODO 自动生成 catch 块            e.printStackTrace();        }    }    public static Map getKeyWords(){        Map map = new HashMap();        String[]keywords = {"abstract","assert","boolean","break","byte","case","catch","char","class","continue","default","do","double","else","enum","extends","final","finally","float","for","if","implements","import","instanceof","int","interface","long","native","new","package","private","protected","public","return","    strictfp","short","static","super","    switch","synchronized","this","throw","throws","transient","try","void","volatile","while","goto","const"};        for(String s:keywords){            map.put(s, 0);        }        return map;    }    public static void countKeys(String s,Map map){        Set keys = map.keySet();        for(String ss:keys){            if(s.indexOf(ss)!=-1){                map.put(ss, map.get(ss)+1);            }        }    }}上班没啥时间了,还有点没写完,你在想想。
  • 2021-02-12 04:12:19
  • visitor
  • 谁能写个netty的简单例子 并解释一下!谢谢!,packagecom.wujintao.netty;importjava.net.InetSocketAddress;importjava.util.concurrent.Executors;importorg.jboss.netty.bootstrap.ClientBootstrap;importorg.jboss.netty.bootstrap.ServerBootstrap;importorg.jboss.netty.channel.ChannelFuture;importorg.jboss.netty.channel.ChannelHandlerContext;importorg.jboss.netty.channel.ChannelPipeline;importorg.jboss.netty.channel.ChannelPipelineFactory;importorg.jboss.netty.channel.ChannelStateEvent;importorg.jboss.netty.channel.Channels;importorg.jboss.netty.channel.ExceptionEvent;importorg.jboss.netty.channel.MessageEvent;importorg.jboss.netty.channel.SimpleChannelHandler;importorg.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;importorg.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;importorg.jboss.netty.handler.codec.string.StringDecoder;importorg.jboss.netty.handler.codec.string.StringEncoder;importorg.junit.Test;classHelloWorldServerHandlerextendsSimpleChannelHandler{publicvoidchannelConnected(ChannelHandlerContextctx,ChannelStateEvente)throwsException{e.getChannel().write("Hello,World");}publicvoidexceptionCaught(ChannelHandlerContextctx,ExceptionEvente){System.out.println("Unexpectedexceptionfromdownstream."+e.getCause());e.getChannel().close();}}classHelloWorldClientHandlerextendsSimpleChannelHandler{publicvoidmessageReceived(ChannelHandlerContextctx,MessageEvente){Stringmessage=(String)e.getMessage();System.out.println(message);e.getChannel().close();}publicvoidexceptionCaught(ChannelHandlerContextctx,ExceptionEvente){System.out.println("Unexpectedexceptionfromdownstream."+e.getCause());e.getChannel().close();}}/***NettyVSMinaNetty基于Pipeline处理,Mina基于Filter过滤*Netty的事件驱动模型具有更好的扩展性和易用性*Https,SSL,PB,RSTP,Text&Binary等协议支持*Netty中UDP传输有更好的支持官方测试Netty比Mina性能更好*@authorAdministrator**/publicclassTestCase{publicvoidtestServer(){//初始化channel的辅助类,为具体子类提供公共数据结构ServerBootstrapbootstrap=newServerBootstrap(newNioServerSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newCachedThreadPool()));bootstrap.setPipelineFactory(newChannelPipelineFactory(){publicChannelPipelinegetPipeline(){ChannelPipelinepipeline=Channels.pipeline();pipeline.addLast("decoder",newStringDecoder());pipeline.addLast("encoder",newStringEncoder());pipeline.addLast("handler",newHelloWorldServerHandler());returnpipeline;}});//创建服务器端channel的辅助类,接收connection请求bootstrap.bind(newInetSocketAddress(8080));}publicvoidtestClient(){//创建客户端channel的辅助类,发起connection请求ClientBootstrapbootstrap=newClientBootstrap(newNioClientSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newCachedThreadPool()));//ItmeansonesameHelloWorldClientHandlerinstanceisgoingtohandlemultipleChannelsandconsequentlythedatawillbecorrupted.//基于上面这个描述,必须用到ChannelPipelineFactory每次创建一个pipelinebootstrap.setPipelineFactory(newChannelPipelineFactory(){publicChannelPipelinegetPipeline(){ChannelPipelinepipeline=Channels.pipeline();pipeline.addLast("decoder",newStringDecoder());pipeline.addLast("encoder",newStringEncoder());pipeline.addLast("handler",newHelloWorldClientHandler());returnpipeline;}});//创建无连接传输channel的辅助类(UDP),包括client和serverChannelFuturefuture=bootstrap.connect(newInetSocketAddress("localhost",8080));future.getChannel().getCloseFuture().awaitUninterruptibly();bootstrap.releaseExternalResources();}@TestpublicvoidtestNetty(){testServer();testClient();}}
  • 2021-02-12 04:12:19
  • 商品推荐