Netty适合做HTTP服务docker 重启容器服务吗

Netty作为服务框架,还必要把项目部署到Web容器里吗? - 知乎31被浏览<strong class="NumberBoard-itemValue" title="1分享邀请回答1添加评论分享收藏感谢收起  Netty 是一个基于 JAVA NIO 类库的异步通信框架,它的架构特点是:异步非阻塞、基于事件驱动、高性能、高可靠性和高可定制性。换句话说,Netty是一个NIO框架,使用它可以简单快速地开发网络应用程序,比如客户端和服务端的协议。Netty大大简化了网络程序的开发过程比如TCP和UDP的 Socket的开发。Netty 已逐渐成为 Java NIO 编程的首选框架,Netty中,通讯的双方建立连接后,会把数据按照ByteBuf的方式进行传输,因此我们在构建Http服务器的时候就是通过HttpRequestDecoder对ByteBuf数据流进行处理,转换成http的对象。代码如下:
&dependency&
&groupId&io.netty&/groupId&
&artifactId&netty-all&/artifactId&
&version&4.1.0.Final&/version&
&/dependency&
HttpServer类
package com.example.demo.
import io.netty.bootstrap.ServerB
import io.netty.channel.ChannelF
import io.netty.channel.ChannelI
import io.netty.channel.ChannelP
import io.netty.channel.EventLoopG
import io.netty.channel.nio.NioEventLoopG
import io.netty.channel.socket.SocketC
import io.netty.channel.socket.nio.NioServerSocketC
import io.netty.handler.codec.http.HttpServerC
public class HttpServer {
public static void main(String[] args) throws InterruptedException {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer&SocketChannel&() {
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new HttpServerHandler());
ChannelFuture f = b.bind(8080).sync();
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
HttpServerHandler类
package com.example.demo.
import java.io.UnsupportedEncodingE
import io.netty.buffer.U
import io.netty.channel.ChannelHandlerC
import io.netty.channel.ChannelInboundHandlerA
import io.netty.handler.codec.http.DefaultFullHttpR
import io.netty.handler.codec.http.FullHttpR
import io.netty.handler.codec.http.HttpR
import io.netty.handler.codec.http.HttpResponseS
import io.netty.handler.codec.http.HttpV
import io.netty.handler.codec.http.QueryStringD
class HttpServerHandler extends ChannelInboundHandlerAdapter {
public void channelRead(ChannelHandlerContext ctx, Object msg) throws UnsupportedEncodingException {
if (msg instanceof HttpRequest) {
// 请求,解码器将请求转换成HttpRequest对象
HttpRequest request = (HttpRequest)
// 获取请求参数
QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri());
String name = "netty";
if(queryStringDecoder.parameters().get("name") != null) {
name = queryStringDecoder.parameters().get("name").get(0);
// 响应HTML
String responseHtml = "&html&&body&Hello, " + name + "&/body&&/html&";
byte[] responseBytes = responseHtml.getBytes("UTF-8");
int contentLength = responseBytes.
// 构造FullHttpResponse对象,FullHttpResponse包含message body
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(responseBytes));
response.headers().set("Content-Type", "text/ charset=utf-8");
response.headers().set("Content-Length", Integer.toString(contentLength));
ctx.writeAndFlush(response);
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
运行HttpServer中main方法,启动httpServer,打开浏览器输入http://localhost:8080?name=zhangsan&,结果如下:
阅读(...) 评论()没有更多推荐了,
不良信息举报
举报内容:
使用netty构建http服务器
举报原因:
原文地址:
原因补充:
最多只允许输入30个字
加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!netty 基本使用- 作为http服务器 - 简书
netty 基本使用- 作为http服务器
netty 概念
netty 是一个基于NIO的客户端服务器框架,它可以快速并且很容易的开发网络应用程序,
如客户端服务器协议。netty 大大简化了网络编程,如TCP和UDP socket服务。
netty 使用场景
1,可以作为rpc的通信的框架远程过程的调用。
2,netty可以作为长连接的服务器基于websoket,实现客户端与服务器端长连接。
3,netty 可以作为http服务器,类似jetty,tomcat。
netty 作为http 服务器 hello world
netty 学习曲线很陡峭,看官方的例子一头雾水。
gradle 引入jar。
compile 'io.netty:netty-all:4.1.13.Final'
** 实现hello world 具体代码 **
HelloServer.java
HelloServerlInitializer.java
事件 channel
HelloServerHandler.java 具体处理类
public class HelloServer {
public static void main(String... arg) throws Exception {
//负责接收客户端连接
EventLoopGroup boosGroup = new NioEventLoopGroup();
//处理连接
EventLoopGroup workerGroup = new NioEventLoopGroup();
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(boosGroup,workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new HelloServerlInitializer());
//绑定端口号
ChannelFuture channelFuture = bootstrap.bind(9999).sync();
channelFuture.channel().closeFuture().sync();
} finally {
boosGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
public class HelloServerlInitializer extends ChannelInitializer&SocketChannel& {
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline channelPipeline = ch.pipeline();
//负载http 请求编码解码
channelPipeline.addLast(new HttpServerCodec());
//实际处理请求
channelPipeline.addLast(new HelloServerHandler());
public class HelloServerHandler extends SimpleChannelInboundHandler&HttpObject& {
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
System.out.println("接收到请求:
if(msg instanceof HttpRequest) {
HttpRequest msgs = (HttpRequest)
System.out.println("接收到请求:
"+msgs.method());
//设置返回内容
ByteBuf content = Unpooled.copiedBuffer("Hello World\n", CharsetUtil.UTF_8);
//创建响应
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK,content);
response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
response.headers().set(HttpHeaderNames.CONTENT_LENGTH,content.readableBytes());
ctx.writeAndFlush(response);
curl -X POST '
或者在浏览器中请求
no one will believe in you unless you
Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智能路由,微代理,控制总线)。分布式系统的协调导致了样板模式, 使用Spring Cloud开发人员可以快速地支持实现这些模式的服务和应用程序。他们将在任何分布式...
Java 基础思维导图,让 Java 不再难懂 - 工具资源 - 掘金思维导图的好处 最近看了一些文章的思维导图,发现思维导图真是个强大的工具。了解了思维导图的作用之后,觉得把它运用到java上应该是个不错的想法,这样回顾知识点的时候一目了然,快速知道自己的短板。 思维导图...
百战程序员_ Java1573题 QQ群:034603 掌握80%年薪20万掌握50%年薪10万 全程项目穿插, 从易到难,含17个项目视频和资料持续更新,请关注www.itbaizhan.com 国内最牛七星级团队马士兵、高淇等11位十年开发经验专...
Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgbook/spring-boot-reference-guide-zh/details带目录浏览地址:http://www.maoyupeng.com/sprin...
我叫谢言笑,我有一个好朋友叫潘美硕,她长得十分漂亮。 她有着一头 乌黑亮丽自然卷头发,戴着粉红色蝴蝶结的发卡,长着的像香蕉似的弯眉毛,葡萄似的大眼睛,苹果一样粉嫩的脸庞和樱桃般的小嘴。
她喜欢吃香蕉、苹果和西瓜......
她调皮可爱、聪明...
网页内容:
学校广播站,第一个音符响起的时候,真真是心跳漏了一拍,环顾四周,却只有一张张茫然的脸庞。没什么,只是觉得,知音原来如此可遇不可求。从考完研,已经连着五天十二点的时候在学校里溜达了。空无一人的学校,昏黄的灯光,地上的影子,没有风,没有人陪着,我自己。喝点酒,慢慢走。还有半年毕...
了解了纳什均衡以及囚徒困境后,你会发现,囚徒困境是基于纳什均衡的逻辑之上的,从本源上来看,都离不开制度设计以及三种心的影响:功利心、风险厌恶心、求稳心。 在纳什均衡下,博弈方会更倾向于在心理稳定区做决策,它可能会导致好的纳什均衡,也可能会导致坏的纳什均衡。在囚徒困境下,由于...
黑暗中的一缕光 一个赤身裸体的女人 在这缕光中摇摆 一个稚嫩的少年站在近处 看着眼前这美丽的胴体 大脑发热,身体颤抖 似乎有一股最原始的力量在驱使着他 像一头野兽一样 他扑倒了那个女人 肌肤接触的一刹那 他感受到从未感受到的炽热 他用尽力气 把内心的火焰从下体倾泻而出 翻云...用Netty实现的简单HTTP服务器
用Netty实现的一个简单的HTTP服务器,可以处理静态文件,例子中的注释也比较全。主要是对HTTP的理解,接下来的文章中我也会更新一些HTTP相关的文章以及对例子的进一步完善,由浅到深,记录一些我的学习过程!
public&class&HttpServer&{
&public&static&void&main(String[]&args)&{
&ServerBootstrap&bootstrap&=newServerBootstrap(newNioServerSocketChannelFactory(
&Executors.newCachedThreadPool(),&Executors.newCachedThreadPool()));
&bootstrap.setPipelineFactory(newHttpServerPipelineFactory());
&&bootstrap.bind(newInetSocketAddress(8080));
&System.out.println("服务器已经启动,请访问http://127.0.0.1:8080/index.html进行测试!\n\n");
2.Pipeline
public&class&HttpServerPipelineFactory&implements&ChannelPipelineFactory&{
&public&ChannelPipeline&getPipeline()&throws&Exception&{
&//&Create&a&default&pipeline&implementation.
&ChannelPipeline&pipeline&=&pipeline();
&pipeline.addLast("decoder",newHttpRequestDecoder());
&//&Uncomment&the&following&line&if&you&don't&want&to&handle&HttpChunks.
&pipeline.addLast("encoder",newHttpResponseEncoder());
&pipeline.addLast("chunkedWriter",newChunkedWriteHandler());
&pipeline.addLast("deflater",newHttpContentCompressor());
&pipeline.addLast("handler",newHttpRequestHandler());
3.handler类
&public&class&HttpRequestHandler&extends&SimpleChannelUpstreamHandler&{
&private&HttpRequest&
&private&boolean&readingC
&@Override
&public&void&messageReceived(ChannelHandlerContext&ctx,&MessageEvent&e)&throws&Exception&{
&if(!readingChunks)&{
&HttpRequest&request&=this.request&=&(HttpRequest)&e.getMessage();
&String&uri&=&request.getUri();
&System.out.println("-----------------------------------------------------------------");
&System.out.println("uri:"+uri);
&System.out.println("-----------------------------------------------------------------");
&if(is100ContinueExpected(request))&{
&send100Continue(e);
&//&解析http头部
&for(Map.Entry&h&:&request.getHeaders())&{
&System.out.println("HEADER:&"+&h.getKey()&+"&=&"+&h.getValue()&+"\r\n");
&//&解析请求参数
&QueryStringDecoder&queryStringDecoder&=newQueryStringDecoder(request.getUri());
&Map&&params&=&queryStringDecoder.getParameters();
&if(!params.isEmpty())&{
&for(Entry&&p&:&params.entrySet())&{
&String&key&=&p.getKey();
&List&vals&=&p.getValue();
&for(String&val&:&vals)&{
&System.out.println("PARAM:&"+&key&+"&=&"+&val&+"\r\n");
&if(request.isChunked())&{
&readingChunks&=true;
&ChannelBuffer&content&=&request.getContent();
&if(content.readable())&{
&System.out.println(content.toString(CharsetUtil.UTF_8));
&writeResponse(e,&uri);
&}else{//&为分块编码时
&HttpChunk&chunk&=&(HttpChunk)&e.getMessage();
&if(chunk.isLast())&{
&readingChunks&=false;
&//&END&OF&CONTENT\r\n"
&HttpChunkTrailer&trailer&=&(HttpChunkTrailer)&
&if(!trailer.getHeaderNames().isEmpty())&{
&for(String&name&:&trailer.getHeaderNames())&{
&for(String&value&:&trailer.getHeaders(name))&{
&//System.out.println("TRAILING&HEADER:&"&+&name&+&"&=&"&+&value);
&//writeResponse(e,&"/");
&//System.out.println("CHUNK:&"&+&chunk.getContent().toString(CharsetUtil.UTF_8));
&private&void&writeResponse(MessageEvent&e,&String&uri)&{
&//&解析Connection首部,判断是否为持久连接
&boolean&keepAlive&=&isKeepAlive(request);
&//&Build&the&response&object.
&HttpResponse&response&=newDefaultHttpResponse(HTTP_1_1,&OK);
&response.setStatus(HttpResponseStatus.OK);
&//&服务端可以通过location首部将客户端导向某个资源的地址。
&//&response.addHeader("Location",&uri);
&if(keepAlive)&{
&//&Add&'Content-Length'&header&only&for&a&keep-alive&connection.
&response.setHeader(CONTENT_LENGTH,&response.getContent().readableBytes());
&//&得到客户端的cookie信息,并再次写到客户端
&String&cookieString&=&request.getHeader(COOKIE);
&if(cookieString&!=null)&{
&CookieDecoder&cookieDecoder&=newCookieDecoder();
&Set&cookies&=&cookieDecoder.decode(cookieString);
&if(!cookies.isEmpty())&{
&CookieEncoder&cookieEncoder&=newCookieEncoder(true);
&for(Cookie&cookie&:&cookies)&{
&cookieEncoder.addCookie(cookie);
&response.addHeader(SET_COOKIE,&cookieEncoder.encode());
&final&String&path&=&Config.getRealPath(uri);
&File&localFile&=newFile(path);
&//&如果文件隐藏或者不存在
&if(localFile.isHidden()&||&!localFile.exists())&{
&//&逻辑处理
&//&如果请求路径为目录
&if(localFile.isDirectory())&{
&//&逻辑处理
&RandomAccessFile&raf&=null;
&raf&=newRandomAccessFile(localFile,&"r");
&long&fileLength&=&raf.length();
&response.setHeader(HttpHeaders.Names.CONTENT_LENGTH,&String.valueOf(fileLength));
&Channel&ch&=&e.getChannel();
&ch.write(response);
&//&这里又要重新温习下http的方法,head方法与get方法类似,但是服务器在响应中只返回首部,不会返回实体的主体部分
&if(!request.getMethod().equals(HttpMethod.HEAD))&{
&ch.write(newChunkedFile(raf,&0,&fileLength,&8192));
&}&}catch(Exception&e2)&{
&e2.printStackTrace();
&}&finally&{
&if(keepAlive)&{
&response.setHeader(CONTENT_LENGTH,&response.getContent().readableBytes());
&if(!keepAlive)&{
&e.getFuture().addListener(ChannelFutureListener.CLOSE);
private&void&send100Continue(MessageEvent&e)&{
&HttpResponse&response&=newDefaultHttpResponse(HTTP_1_1,&CONTINUE);
&e.getChannel().write(response);
&public&void&exceptionCaught(ChannelHandlerContext&ctx,&ExceptionEvent&e)&throws&Exception&{
&e.getCause().printStackTrace();
&e.getChannel().close();
public&class&Config&{
&public&static&String&getRealPath(String&uri)&{
&StringBuilder&sb=newStringBuilder("/home/guolei/workspace/Test/web");
&sb.append(uri);
&if(!uri.endsWith("/"))&{
&sb.append('/');
&returnsb.toString();
在项目中新建一个文件夹,名称为web(可以在配置中配置),在文件夹中放入静态页面index.html。
6.启动服务器,测试
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。

我要回帖

更多关于 英伟达遥测容器服务 的文章

 

随机推荐