pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.shinho</groupId>
<artifactId>kylinstore</artifactId>
<packaging>jar</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>kylinstore</name>
<url>http://maven.apache.org</url> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jackson.version>2.5.0</jackson.version>
<!-- log4j日志文件管理包版本 -->
<slf4j.version>1.7.7</slf4j.version>
<log4j.version>1.2.17</log4j.version>
</properties> <dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- 导入java ee jar 包 -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency> <!-- json -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.3</version>
</dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- 日志文件管理包 -->
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<!-- 格式化对象,方便输出日志 --> <dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency> <dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- log end --> <dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.27-incubating</version>
</dependency> <dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>0.2.9</version>
</dependency> <dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1.6</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId> <!-- Use 'netty-all' for 4.0 or above -->
<version>4.1.23.Final</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<finalName>dsp</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

入口文件

package com.shinho.kylinstore;

import javax.xml.ws.spi.http.HttpHandler;

import io.netty.bootstrap.*;
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.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.stream.ChunkedWriteHandler; import com.shinho.kylinstore.http.*; public class HttpServer { public static void main(String[] args) throws Exception {
int port = 8083;
new HttpServer().run(port);
} public void run(final int port) throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch)
throws Exception { // HTTP请求消息解码器
ch.pipeline().addLast("http-decoder", new HttpRequestDecoder()); /*
* HttpObjectAggregator解码器
* 将多个消息转换为单一的FullHttpRequest或FullHttpResponse对象
*/
ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536)); //HTTP响应编码器,对HTTP响应进行编码
ch.pipeline().addLast("http-encoder", new HttpResponseEncoder()); //ChunkedWriteHandler的主要作用是支持异步发送大的码流,但不占用过多的内存,防止JAVA内存溢出
ch.pipeline().addLast("http-chunked",
new ChunkedWriteHandler()); ch.pipeline().addLast("httpServerHandler", new HttpServerHandler());
}
});
ChannelFuture future = b.bind("localhost", port).sync();
System.out.println("HTTP Server startup.");
future.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}

请求处理文件

package com.shinho.kylinstore.http;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.DecoderResult;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.CharsetUtil; public class HttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> { @Override
protected void channelRead0(ChannelHandlerContext context, FullHttpRequest request) throws Exception {
//
if (!request.decoderResult().isSuccess()) {
sendError(context, HttpResponseStatus.BAD_REQUEST);
return;
} //
if (request.method() != HttpMethod.GET) {
sendError(context, HttpResponseStatus.METHOD_NOT_ALLOWED);
return;
} FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
response.content().writeInt(100);
context.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
cause.printStackTrace();
if (ctx.channel().isActive()) {
sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR);
}
} private static void sendError(ChannelHandlerContext ctx,
HttpResponseStatus status) {
DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,status,
Unpooled.copiedBuffer("Failure: " + status.toString()+ "\r\n", CharsetUtil.UTF_8));
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}
}

我的Netty笔记的更多相关文章

  1. Netty笔记

    1 基本介绍 Bootstrap Netty应用程序通过设置 bootstrap(引导)类开始,该类提供了一个用于应用程序网络层配置的容器.Bootstrap有两种类型,一种是用于客户端的Bootst ...

  2. Netty笔记--ByteBuf释放

    参考资料:http://www.maljob.com/pages/newsDetail.html?id=394 参考资料:http://www.blogjava.net/liuguly/archive ...

  3. Netty笔记——技术点汇总

    目录 · Linux网络IO模型 · 文件描述符 · 阻塞IO模型 · 非阻塞IO模型 · IO复用模型 · 信号驱动IO模型 · 异步IO模型 · BIO编程 · 伪异步IO编程 · NIO编程 · ...

  4. Netty 笔记

    1.Netty 是一款异步的事件驱动的网络应用程序框架,支持快速地开发可维护的高性能的面向协议的服务器和客户端. 2.早期Java API 使用的阻塞函数 // 创建一个新的ServerSocket, ...

  5. netty笔记(一)--Demo

    Netty是一个Java开源框架,用于传输数据.由server和client组成,封装了Java nio,支持TCP, UDP等协议.这里写了一Demo EchoClientHandler.java ...

  6. netty笔记-:Channel与ChannelHandlerContext执行write方法的区别

      在netty中有我们一般有两种发送数据的方式,即使用ChannelHandlerContext或者Channel的write方法,这两种方法都能发送数据,那么其有什么区别呢.这儿引用netty文档 ...

  7. netty笔记-:EpollEventLoopGroup:Caused by: java.lang.ExceptionInInitializerError:Caused by: java.lang.IllegalStateException: Only supported on Linux

    今天在翻看netty的源码的时候发现netty对EventLoopGroup的实现有不止常用的NIOEventLoopGroup ,一共有以下几种. EpollEventLoopGroup NioEv ...

  8. Netty学习笔记(一)

    学习圣思园Netty笔记,个人理解 2.netty宏观理解-本节内容: 1.阶段性事件驱动,一个请求分为若干阶段处理,每个阶段根据情况合理分配线程去处理,各阶段间通信采用异步事件驱动方式. 2.net ...

  9. Netty入门4之----如何实现长连接

    ​ 前面三章介绍了Netty的一些基本用法,这一章介绍怎么使用Netty来实现一个简单的长连接demo. 关于长连接的背景知识,可以参考<如何使用Socket实现长连接> ​ 一个简单的长 ...

随机推荐

  1. apache用户认证、域名跳转、Apache访问日志(两种格式)

    1.apache 设置,用户访问时 目录或文件的认证: 对目录的认证: <Directory /var/www/222> //指定认证的目录AllowOverride AuthConfig ...

  2. (2)Django入门

    web框架:把一个请求拆成几部分,每部分做相同的事 python中常用的框架 1.Django:大而全的框架 2.flask:微框架又叫轻量级的框架 3.Tornado:高性能框架 pycharm创建 ...

  3. CTEX(LaTeX) 编译 中文

    CTEX 中文编码&编译问题 #win10 tex 文档为 GBK 编码 https://zhidao.baidu.com/question/93645685.html \documentcl ...

  4. SVN三种合并类型

    https://blog.csdn.net/zht666/article/details/36178117 转自:http://wenku.baidu.com/link?url=pnALYESJnX0 ...

  5. webpack 搭建问题汇总

    总结一下遇到的问题: 1.这样的警告(The 'mode' option has not been set, webpack will fallback to 'production' for thi ...

  6. smb文件共享实现

    samba文件共享 首先安装软件 yum install samba -y 编辑配置文件 /etc/samba/smb.conf ,在文章最后添加以下内容 [smbtest] content = do ...

  7. plsql快速入门

    汉化plsql方法: 本来想直接使用英文版的,但是太多专业名词看不懂,只好先汉化熟悉一下先. 安装好plsq后,百度下载plsql汉化包 执行汉化包里面的安装程序,安装目标路径选择plsql的安装路径 ...

  8. 对spark算子aggregateByKey的理解

    案例 aggregateByKey算子其实相当于是针对不同“key”数据做一个map+reduce规约的操作. 举一个简单的在生产环境中的一段代码 有一些整理好的日志字段,经过处理得到了RDD类型为( ...

  9. Stream Processing 101: From SQL to Streaming SQL in 10 Minutes

    转自:https://wso2.com/library/articles/2018/02/stream-processing-101-from-sql-to-streaming-sql-in-ten- ...

  10. memsql kafka集成

    memsql 可以加载s3,文件系统,kafka.hdfs 系统的数据,测试使用kafka 环境使用 docker-compose 运行,新版本的需要申请license,参考链接: https://w ...