最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

關(guān)于Netty--Http請求處理方式

 更新時間:2022年06月06日 10:13:24   作者:BtWangZhi  
這篇文章主要介紹了關(guān)于Netty--Http請求處理方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

Netty--Http請求處理

1.這幾天在看Netty權(quán)威指南,代碼敲了一下,就當做個筆記吧。

/**
 * Http服務(wù)端
 * @author Tang
 * 2018年5月13日
 */
public class HttpServer {
	public void run(String url,Integer port) {
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		ServerBootstrap bootstrap = new ServerBootstrap();
		bootstrap.group(bossGroup, workerGroup);
		bootstrap.channel(NioServerSocketChannel.class);
		bootstrap.childHandler(new ChannelInitializer<Channel>() {
			@Override
			protected void initChannel(Channel ch) throws Exception {
				ch.pipeline().addLast("http-decoder", new HttpRequestDecoder());
				ch.pipeline().addLast("http-aggregator",
						new HttpObjectAggregator(65536));
				ch.pipeline()
						.addLast("http-encoder", new HttpResponseEncoder());
				ch.pipeline()
						.addLast("http-chunked", new ChunkedWriteHandler());
				ch.pipeline().addLast("http-handler", new HttpServerHandler());
			}
		});
		try {
			ChannelFuture channelFuture = bootstrap.bind(url, port).sync();
			channelFuture.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
	public static void main(String[] args) {
		new HttpServer().run("127.0.0.1",8001);
	}
}

業(yè)務(wù)處理邏輯

public class HttpServerHandler extends
		SimpleChannelInboundHandler<FullHttpRequest> {
	@Override
	protected void messageReceived(ChannelHandlerContext ctx,
			FullHttpRequest fullHttpRequest) throws Exception {
		// 構(gòu)造返回數(shù)據(jù)
		JSONObject jsonRootObj = new JSONObject();
		JSONObject jsonUserInfo = new JSONObject();
		jsonUserInfo.put("id", 1);
		jsonUserInfo.put("name", "張三");
		jsonUserInfo.put("password", "123");
		jsonRootObj.put("userInfo", jsonUserInfo);
		// 獲取傳遞的數(shù)據(jù)
		Map<String, Object> params = getParamsFromChannel(ctx, fullHttpRequest);
		jsonRootObj.put("params", params);
		FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK);
		response.headers().set(CONTENT_TYPE, "application/json; charset=UTF-8");
		StringBuilder bufRespose = new StringBuilder();
		bufRespose.append(jsonRootObj.toJSONString());
		ByteBuf buffer = Unpooled.copiedBuffer(bufRespose, CharsetUtil.UTF_8);
		response.content().writeBytes(buffer);
		buffer.release();
		ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
	}
	/**
	 * 獲取傳遞的參數(shù)
	 * 
	 * @param ctx
	 * @param fullHttpRequest
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	private static Map<String, Object> getParamsFromChannel(
			ChannelHandlerContext ctx, FullHttpRequest fullHttpRequest)
			throws UnsupportedEncodingException {
		HttpHeaders headers = fullHttpRequest.headers();
		String strContentType = headers.get("Content-Type").trim();
		System.out.println("ContentType:" + strContentType);
		Map<String, Object> mapReturnData = new HashMap<String, Object>();
		if (fullHttpRequest.getMethod() == HttpMethod.GET) {
			// 處理get請求
			QueryStringDecoder decoder = new QueryStringDecoder(
					fullHttpRequest.getUri());
			Map<String, List<String>> parame = decoder.parameters();
			for (Entry<String, List<String>> entry : parame.entrySet()) {
				mapReturnData.put(entry.getKey(), entry.getValue().get(0));
			}
			System.out.println("GET方式:" + parame.toString());
		} else if (fullHttpRequest.getMethod() == HttpMethod.POST) {
			// 處理POST請求
			if (strContentType.contains("x-www-form-urlencoded")) {
				HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(
						new DefaultHttpDataFactory(false), fullHttpRequest);
				List<InterfaceHttpData> postData = decoder.getBodyHttpDatas();
				for (InterfaceHttpData data : postData) {
					if (data.getHttpDataType() == HttpDataType.Attribute) {
						MemoryAttribute attribute = (MemoryAttribute) data;
						mapReturnData.put(attribute.getName(),
								attribute.getValue());
					}
				}
			} else if (strContentType.contains("application/json")) {
				// 解析json數(shù)據(jù)
				ByteBuf content = fullHttpRequest.content();
				byte[] reqContent = new byte[content.readableBytes()];
				content.readBytes(reqContent);
				String strContent = new String(reqContent, "UTF-8");
				System.out.println("接收到的消息" + strContent);
				JSONObject jsonParamRoot = JSONObject.parseObject(strContent);
				for (String key : jsonParamRoot.keySet()) {
					mapReturnData.put(key, jsonParamRoot.get(key));
				}
			} else {
				FullHttpResponse response = new DefaultFullHttpResponse(
						HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR);
				ctx.writeAndFlush(response).addListener(
						ChannelFutureListener.CLOSE);
			}
			System.out.println("POST方式:" + mapReturnData.toString());
		}
		return mapReturnData;
	}
}

支持Get和PostContentType為application/json、x-www-form-urlencoded的處理。

用Postman親測無問題。

Netty處理簡單Http請求的例子

廢話不多說 上代碼

HttpHelloWorldServerInitializer.java

import io.netty.channel.ChannelInitializer;
  import io.netty.channel.ChannelPipeline;
  import io.netty.channel.socket.SocketChannel;
  import io.netty.handler.codec.http.HttpServerCodec;
  import io.netty.handler.ssl.SslContext;
  public class HttpHelloWorldServerInitializer extends ChannelInitializer<SocketChannel> {
      private final SslContext sslCtx;
      public HttpHelloWorldServerInitializer(SslContext sslCtx) {
         this.sslCtx = sslCtx;
      }
      @Override
      public void initChannel(SocketChannel ch) {
          ChannelPipeline p = ch.pipeline();
          if (sslCtx != null) {
              p.addLast(sslCtx.newHandler(ch.alloc()));
          }
          p.addLast(new HttpServerCodec());
          p.addLast(new HttpHelloWorldServerHandler());
      }
  }

HttpHelloWorldServerHandler.java

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderUtil;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpRequest;
import static io.netty.handler.codec.http.HttpHeaderNames.*;
import static io.netty.handler.codec.http.HttpResponseStatus.*;
import static io.netty.handler.codec.http.HttpVersion.*;
  public class HttpHelloWorldServerHandler extends ChannelHandlerAdapter {
      private static final byte[] CONTENT = { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd' };
      @Override
      public void channelReadComplete(ChannelHandlerContext ctx) {
          ctx.flush();
      }
      @Override
      public void channelRead(ChannelHandlerContext ctx, Object msg) {
          if (msg instanceof HttpRequest) {
              HttpRequest req = (HttpRequest) msg;
              if (HttpHeaderUtil.is100ContinueExpected(req)) {
                  ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
              }
              boolean keepAlive = HttpHeaderUtil.isKeepAlive(req);
              FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT));
              response.headers().set(CONTENT_TYPE, "text/plain");
              response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());
              if (!keepAlive) {
                  ctx.write(response).addListener(ChannelFutureListener.CLOSE);
              } else {
                  response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
                  ctx.write(response);
              }
          }
      }
      @Override
      public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
          cause.printStackTrace();
          ctx.close();
      }
  }

HttpHelloWorldServer.java

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.util.SelfSignedCertificate;
/**
 * An HTTP server that sends back the content of the received HTTP request
 * in a pretty plaintext form.
 */
public final class HttpHelloWorldServer {
      static final boolean SSL = System.getProperty("ssl") != null;
      static final int PORT = Integer.parseInt(System.getProperty("port", SSL? "8443" : "8080"));
      public static void main(String[] args) throws Exception {
          // Configure SSL.
          final SslContext sslCtx;
          if (SSL) {
              SelfSignedCertificate ssc = new SelfSignedCertificate();
              sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
          } else {
              sslCtx = null;
          }
          // Configure the server.
          EventLoopGroup bossGroup = new NioEventLoopGroup(1);
          EventLoopGroup workerGroup = new NioEventLoopGroup();
          try {
              ServerBootstrap b = new ServerBootstrap();
              b.option(ChannelOption.SO_BACKLOG, 1024);
              b.group(bossGroup, workerGroup)
               .channel(NioServerSocketChannel.class)
               .handler(new LoggingHandler(LogLevel.INFO))
               .childHandler(new HttpHelloWorldServerInitializer(sslCtx));
              Channel ch = b.bind(PORT).sync().channel();
              System.err.println("Open your web browser and navigate to " +
                      (SSL? "https" : "http") + "://127.0.0.1:" + PORT + '/');
              ch.closeFuture().sync();
          } finally {
              bossGroup.shutdownGracefully();
              workerGroup.shutdownGracefully();
          }
      }
}

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • 關(guān)于Java中Comparable 和 Comparator的用法

    關(guān)于Java中Comparable 和 Comparator的用法

    這篇文章主要介紹了關(guān)于Java中Comparable 和 Comparator的用法,Comparable 和 Comparator 是關(guān)于排序的兩個接口,用來實現(xiàn) Java 集合中的的排序功能,需要的朋友可以參考下
    2023-04-04
  • Java制作驗證碼的完整實例代碼

    Java制作驗證碼的完整實例代碼

    這篇文章主要給大家介紹了關(guān)于Java制作驗證碼的完整實例代碼,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友們下面隨著小編來一起學(xué)習學(xué)習吧
    2020-11-11
  • java web實現(xiàn)郵箱發(fā)送功能

    java web實現(xiàn)郵箱發(fā)送功能

    這篇文章主要為大家詳細介紹了java web實現(xiàn)郵箱發(fā)送功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-05-05
  • Java將字符串String轉(zhuǎn)換為整型Int的兩種方式

    Java將字符串String轉(zhuǎn)換為整型Int的兩種方式

    這篇文章主要介紹了Java如何將字符串String轉(zhuǎn)換為整型Int,在 Java 中要將 String 類型轉(zhuǎn)化為 int 類型時,需要使用 Integer 類中的 parseInt() 方法或者 valueOf() 方法進行轉(zhuǎn)換,本文通過實例代碼給大家詳細講解,需要的朋友可以參考下
    2023-04-04
  • Java實例講解動態(tài)代理

    Java實例講解動態(tài)代理

    動態(tài)代理指的是,代理類和目標類的關(guān)系在程序運行的時候確定的,客戶通過代理類來調(diào)用目標對象的方法,是在程序運行時根據(jù)需要動態(tài)的創(chuàng)建目標類的代理對象。本文將通過案例詳細講解一下動態(tài)代理,需要的可以參考一下
    2022-06-06
  • Java線程同步實例分析

    Java線程同步實例分析

    這篇文章主要介紹了Java線程同步用法,實例分析了java中線程同步的相關(guān)實現(xiàn)技巧與注意事項,具有一定參考借鑒價值,需要的朋友可以參考下
    2015-07-07
  • IDEA中springboot提示java:找不到符號符號:變量log問題

    IDEA中springboot提示java:找不到符號符號:變量log問題

    這篇文章主要介紹了IDEA中springboot提示java:找不到符號符號:變量log問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-04-04
  • 為何HashSet中使用PRESENT而不是null作為value

    為何HashSet中使用PRESENT而不是null作為value

    這篇文章主要介紹了為何HashSet中使用PRESENT而不是null作為value,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-10-10
  • java如何通過Kerberos認證方式連接hive

    java如何通過Kerberos認證方式連接hive

    該文主要介紹了如何在數(shù)據(jù)源管理功能中適配不同數(shù)據(jù)源(如MySQL、PostgreSQL和Hive),特別是如何在SpringBoot3框架下通過Kerberos認證與Hive進行安全交互,文章詳細描述了Kerberos認證過程,包括配置krb5.conf和keytab文件、處理Hadoop和Hive版本兼容性問題
    2025-02-02
  • Dubbo架構(gòu)整體設(shè)計詳解

    Dubbo架構(gòu)整體設(shè)計詳解

    Dubbo是一款高性能、輕量級的開源Java RPC框架,它提供了三大核心能力:面向接口的遠程方法調(diào)用,智能容錯和負載均衡,以及服務(wù)自動注冊和發(fā)現(xiàn),本文將從 Dubbo 整體架構(gòu)的視角出發(fā),帶你從全局俯瞰 Dubbo 的架構(gòu)設(shè)計,感興趣的同學(xué)可以參考一下
    2023-04-04

最新評論

同心县| 南雄市| 临邑县| 高碑店市| 彰化县| 惠安县| 拉萨市| 宁强县| 美姑县| 乐东| 孝感市| 乐至县| 志丹县| 洪泽县| 长阳| 乌兰浩特市| 垫江县| 蚌埠市| 霍城县| 扶余县| 洪泽县| 武定县| 磐安县| 怀远县| 陇川县| 新巴尔虎右旗| 石景山区| 尚义县| 东乌珠穆沁旗| 聂拉木县| 万安县| 香港| 通河县| 额尔古纳市| 屏山县| 桓台县| 南江县| 千阳县| 定兴县| 永顺县| 平陆县|