Java io.netty.handler.logging.LoggingHandler 代码实例

・20 分钟阅读

以下是展示如何使用io.netty.handler.logging.LoggingHandler的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


public void bind() throws Exception {
    // ??????NIO???
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, 100)
            .handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch)
                        throws IOException {
                    ch.pipeline().addLast(
                            new NettyMessageDecoder(1024 * 1024, 4, 4));
                    ch.pipeline().addLast(new NettyMessageEncoder());
                    ch.pipeline().addLast("readTimeoutHandler",
                            new ReadTimeoutHandler(50));
                    ch.pipeline().addLast(new LoginAuthRespHandler());
                    ch.pipeline().addLast("HeartBeatHandler",
                            new HeartBeatRespHandler());
                }
            });
    // ???????????
    b.bind(NettyConstant.REMOTEIP, NettyConstant.PORT).sync();
    System.out.println("Netty server start ok : "
            + (NettyConstant.REMOTEIP + " : " + NettyConstant.PORT));
}
 

实例 2


public static void newClientBootstrap(String host, int port, ChannelInitializer<SocketChannel> initializer){
        EventLoopGroup group = new NioEventLoopGroup();
       try {
           Bootstrap b = new Bootstrap();
           ChannelFuture f = b.group(group)
                        .channel(NioSocketChannel.class)
                        .option(ChannelOption.SO_KEEPALIVE, true)
                        .handler(new LoggingHandler(LogLevel.INFO))
                        .handler(initializer)
                        .connect(host, port).sync();            
           f.channel().closeFuture().sync();            
       } catch (Exception e){   
           e.printStackTrace();
       } finally {              
           group.shutdownGracefully();
       }
}
 

实例 3


public static void start(int port) throws Exception {
    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup)//
            .channel(NioServerSocketChannel.class)//
            .handler(new LoggingHandler(LogLevel.INFO))//
            .childHandler(new HttpStaticFileServerInitializer());
    b.bind(port).sync().channel();
    LOGGER.info("Open your web browser and navigate to " + ("http") + "://127.0.0.1:" + port + '/');
}
 

实例 4


@Override
public void initChannel(SocketChannel ch) throws Exception {
    // Create a default pipeline implementation.
    ChannelPipeline p = ch.pipeline();
    p.addLast("log", new LoggingHandler(LogLevel.INFO));
    //        if (ssl) {
    //            SSLContext sslcontext = SSLContext.getInstance("TLS");
    //
    //            sslcontext.init(null, null, null);
    //
    //            SSLEngine engine = sslcontext.createSSLEngine();
    //            engine.setUseClientMode(true);
    //
    //            p.addLast("ssl", new SslHandler(engine));
    //        }
    p.addLast("codec", new HttpClientCodec());
    // Remove the following line if you don't want automatic content decompression.
    p.addLast("inflater", new HttpContentDecompressor());
    p.addLast("handler", new TestHttpClientHandler());
}
 

实例 5


public void start() throws Exception {
    File cert = Paths.get(getClass().getResource("/ssl/server.pem").toURI()).toFile();
    File keyStore = Paths.get(getClass().getResource("/ssl/server.key").toURI()).toFile();
    SslContext sslCtx = SslContext.newServerContext(cert, keyStore);
    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup();
    server = new ServerBootstrap();
    server.group(bossGroup, workerGroup)
          .channel(NioServerSocketChannel.class)
          .option(ChannelOption.SO_BACKLOG, 100)
          .handler(new LoggingHandler(LogLevel.INFO))
          .childHandler(new BasicSSLServerInitializer(sslCtx));
    server.bind(port).sync().channel().closeFuture();
}
 

实例 6


public ChannelFuture start() throws Exception {
  ServerBootstrap b = new ServerBootstrap();
  b.option(ChannelOption.SO_BACKLOG, 1024);
  b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
      .handler(new LoggingHandler(LogLevel.INFO))
      .childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
          ChannelPipeline pipeline = ch.pipeline();
          pipeline.addLast("httpRequestDecoder", new HttpRequestDecoder());
          pipeline.addLast("httpResponseEncoder", new HttpResponseEncoder());
          pipeline.addLast("httpChunkAggregator", new HttpObjectAggregator(MAX_CONTENT_LENGTH));
          pipeline.addLast("httpRequestHandler", new Http1RequestHandler());
        }
      });
  Channel ch = b.bind(PORT).sync().channel();
  return ch.closeFuture();
}
 

实例 7


@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
    ChannelPipeline p = socketChannel.pipeline();
    p.addLast("log", new LoggingHandler("BYTE_LOGGER", LogLevel.DEBUG));
    p.addLast(new SocksInitResponseDecoder());
    p.addLast(new SocksMessageEncoder());
    p.addLast(new SocksClientHandler());
}
 

实例 8


public void connect(int port, LinkList userLinkList) throws Exception {
        this.userLinkList = userLinkList;
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                        .option(ChannelOption.SO_BACKLOG, 100)
                        .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(this);
        ChannelFuture f = b.bind(port).sync();
        f.channel().closeFuture().sync();
}
 

实例 9


public void start() throws Exception {
        if (started.compareAndSet(false, true)) {
            // Configure the server.
            bossGroup = new NioEventLoopGroup(1);
            workerGroup = new NioEventLoopGroup();
            ServerBootstrap server = new ServerBootstrap();
            server.group(bossGroup, workerGroup);
            server.channel(NioServerSocketChannel.class);
            server.option(ChannelOption.SO_BACKLOG, 100);
            server.handler(new LoggingHandler(LogLevel.INFO));
            server.childHandler(new ChannelInitializer<Channel>() {
                @Override
                public void initChannel(Channel ch) throws Exception {
                    if (options instanceof TransportSslOptions) {
                        TransportSslOptions sslOptions = (TransportSslOptions) options;
                        SSLContext context = TransportSupport.createSslContext(sslOptions);
                        SSLEngine engine = TransportSupport.createSslEngine(context, sslOptions);
                        engine.setUseClientMode(false);
                        engine.setNeedClientAuth(needClientAuth);
                        sslHandler = new SslHandler(engine);
                        ch.pipeline().addLast(sslHandler);
                    }
                    ch.pipeline().addLast(new EchoServerHandler());
                }
            });
            // Start the server.
            serverChannel = server.bind(getServerPort()).sync().channel();
        }
    }
 

实例 10


public static void main(String[] args) {
    ObjectMapper mapper = new ObjectMapper();
    ServerConfig config;
    try {
        config = mapper.readValue(new File(args[0]), ServerConfig.class);
    } catch (IOException e) {
        LOGGER.error("unable to read config file '" + args[0] + "'", e);
        return;
    }
    final Instance instance = new Instance(config.getHomeDir());
    final EventLoopGroup boss = new NioEventLoopGroup(1);
    final EventLoopGroup worker = new NioEventLoopGroup();
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            LOGGER.info("shutting down");
            boss.shutdownGracefully();
            worker.shutdownGracefully();
            instance.shutDown();
        }
    });
    try {
        instance.initialize();
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
        bootstrap.group(boss, worker)
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new HttpApiServerInitializer(instance));
        Channel channel = bootstrap.bind(config.getBindInterface(), config.getPort()).sync().channel();
        channel.closeFuture().sync();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (SchemaConfigurationError e) {
        e.printStackTrace();
    } finally {
        LOGGER.info("shutting down");
        boss.shutdownGracefully();
        worker.shutdownGracefully();
    }
}
 

实例 11


@Override
public void configure(final ChannelPipeline pipeline) {
    if (logger.isDebugEnabled())
        pipeline.addLast(new LoggingHandler("log-io", LogLevel.DEBUG));
    logger.debug("HttpRequestDecoder settings - maxInitialLineLength={}, maxHeaderSize={}, maxChunkSize={}",
            settings.maxInitialLineLength, settings.maxHeaderSize, settings.maxChunkSize);
    pipeline.addLast("http-request-decoder", new HttpRequestDecoder(settings.maxInitialLineLength, settings.maxHeaderSize, settings.maxChunkSize));
    if (logger.isDebugEnabled())
        pipeline.addLast(new LoggingHandler("log-decoder-aggregator", LogLevel.DEBUG));
    logger.debug("HttpObjectAggregator settings - maxContentLength={}, maxAccumulationBufferComponents={}",
            settings.maxContentLength, settings.maxAccumulationBufferComponents);
    final HttpObjectAggregator aggregator = new HttpObjectAggregator(settings.maxContentLength);
    aggregator.setMaxCumulationBufferComponents(settings.maxAccumulationBufferComponents);
    pipeline.addLast("aggregator", aggregator);
    if (logger.isDebugEnabled())
        pipeline.addLast(new LoggingHandler("log-aggregator-encoder", LogLevel.DEBUG));
    pipeline.addLast("http-response-encoder", new HttpResponseEncoder());
    pipeline.addLast("request-handler", new WebSocketServerProtocolHandler("/gremlin", null, false, settings.maxContentLength));
    if (logger.isDebugEnabled())
        pipeline.addLast(new LoggingHandler("log-aggregator-encoder", LogLevel.DEBUG));
    pipeline.addLast("response-encoder", wsGremlinResponseEncoder);
    pipeline.addLast("request-text-decoder", wsGremlinTextRequestDecoder);
    pipeline.addLast("request-binary-decoder", wsGremlinBinaryRequestDecoder);
    pipeline.addLast("request-close-decoder", wsGremlinCloseRequestDecoder);
    if (logger.isDebugEnabled())
        pipeline.addLast(new LoggingHandler("log-aggregator-encoder", LogLevel.DEBUG));
    if (authenticationHandler != null)
        pipeline.addLast(PIPELINE_AUTHENTICATOR, authenticationHandler);
}
 

实例 12


public void start(int port) {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        ethereumChannelInitializer = ctx.getBean(EthereumChannelInitializer.class, "");
        worldManger.getListener().trace("Listening on port " + port);
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup);
            b.channel(NioServerSocketChannel.class);
            b.option(ChannelOption.SO_KEEPALIVE, true);
            b.option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, DefaultMessageSizeEstimator.DEFAULT);
            b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONFIG.peerConnectionTimeout());
            b.handler(new LoggingHandler());
            b.childHandler(ethereumChannelInitializer);
            // Start the client.
            logger.info("Listening for incoming connections, port: [{}] ", port);
            ECKey myKey = ECKey.fromPrivate(CONFIG.privateKey().getBytes()).decompress();
            byte[] nodeIdWithFormat = myKey.getPubKey();
            byte[] nodeId = new byte[nodeIdWithFormat.length - 1];
            System.arraycopy(nodeIdWithFormat, 1, nodeId, 0, nodeId.length);
            logger.info("NodeId: [{}] ", Hex.toHexString(nodeId));
            ChannelFuture f = b.bind(port).sync();
            // Wait until the connection is closed.
            f.channel().closeFuture().sync();
            logger.debug("Connection is closed");
        } catch (Exception e) {
            logger.debug("Exception: {} ({})", e.getMessage(), e.getClass().getName());
            throw new Error("Server Disconnected");
        } finally {
            workerGroup.shutdownGracefully();
        }
    }
 

实例 13


public void start() {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap
            .group(bossGroup, workerGroup)
            .channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, 100)
            .childOption(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.TCP_NODELAY, true)
            .handler(new LoggingHandler(LogLevel.TRACE))
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline()
                            .addLast(new PacketDecoder())
                            .addLast(new PacketEncoder())
                            .addLast(new MessageDecoder())
                            .addLast(new MessageEncoder())
                            .addLast(new MessageDispatcher());
                }
            });
    try {
        future = bootstrap.bind(socket).sync();
        logger.info("Starting listening for clients on {}...", socket);
        channel = future.channel();
        // Wait until server socket is closed.
        // channel.closeFuture().sync();
    } catch (InterruptedException e) {
        e.printStackTrace();
        throw new RuntimeException("Can't start server: ", e);
    }
}
 

实例 14


@Override
public void init() throws Exception {
        if (isStarted.get()) {
                throw new IllegalStateException("Netty server bootstrap already started!");
        }
        configure();
        if (channelInitializer == null) {
                throw new IllegalStateException("ChannelInitializer is null, unset in configure() ?");
        }
        if (!bossGroupSetted) {
                bossGroup = EventLoopGroupFactory.newNioLoopGroup(bossGroupSize);
        }
        if (!workGroupSetted) {
                workGroup = EventLoopGroupFactory.newNioLoopGroup(workGroupSize);
        }
        bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workGroup)
                        .channel(NioServerSocketChannel.class)
                        .handler(new LoggingHandler(nettyLogLevel))
                        .childHandler(channelInitializer);
        options(bootstrap);
        isStarted.set(true);
        isShutdown.set(false);
}
 

实例 15


public void start() throws IOException, InterruptedException {
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ClientInitializer(server));
    channel = b.bind(server.getConfig().server.port).sync().channel();
    OgarServer.log.info("Server started on port " + server.getConfig().server.port + ".");
}
 
讨论
淘淘あ西西 profile image