Netty4.1入門(二)客戶端
阿新 • • 發佈:2021-12-12
在前一篇中,實現了一個簡單的Http Server,這次來實現一個Http客戶端。
為了方便進行測試,這次把這個Http客戶端整合到SpringBoot裡邊,呼叫流程是:PostMan -> SpringBoot Controller -> Http客戶端 -> Http Server
簡單Http連線
每次請求:客戶端建立到服務端的連線,發請求,收相應,然後關閉連線。
SimpleNettyHttpClient:
@Slf4j @Component public class SimpleNettyHttpClient { private static final int _1M = 1024 * 1024; private EventLoopGroup workerGroup; @PostConstruct public void init() { workerGroup = new NioEventLoopGroup(); } public String sendRequest(String url, String requestBody) throws Exception { Bootstrap boot = new Bootstrap(); boot.group(workerGroup); boot.channel(NioSocketChannel.class); boot.remoteAddress("127.0.0.1", 8080); SynResponse<String> synResponse = new SynResponse<>(); boot.handler(new ChannelInitializer<NioSocketChannel>() { @Override protected void initChannel(NioSocketChannel ch) throws Exception { ch.pipeline().addLast(new StringEncoder()); ch.pipeline().addLast(new HttpClientCodec()); ch.pipeline().addLast(new HttpObjectAggregator(_1M)); ch.pipeline().addLast(new TestHandler(synResponse)); } }); ChannelFuture f = boot.connect().sync(); log.info("已連線"); URI uri = new URI(url); DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.toASCIIString(), Unpooled.wrappedBuffer(requestBody.getBytes("UTF-8"))); request.headers().set(HttpHeaderNames.CONTENT_LENGTH, request.content().readableBytes()); log.info("組裝Request"); Channel channel = f.channel(); channel.writeAndFlush(request); log.info("寫Request"); channel.closeFuture().sync(); log.info("關閉Channel"); //workerGroup.shutdownGracefully(); log.info("同步阻塞獲取Response Content"); return synResponse.getResponseContent(); } public static class TestHandler extends ChannelInboundHandlerAdapter { private SynResponse<String> synResponse; public TestHandler(SynResponse<String> synResponse) { this.synResponse = synResponse; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { FullHttpResponse response = (FullHttpResponse) msg; String content = response.content().toString(CharsetUtil.UTF_8); log.info("收到服務端response:{}", content); synResponse.setResponseContent(content); log.info("Response content放入result"); } } }
Controller:
@Autowired private SimpleNettyHttpClient simpleNettyClient; @RequestMapping(value = "/postStringSimple", method = RequestMethod.POST) public String postStringSimple(@RequestBody String data) throws Exception { String res = simpleNettyClient.sendRequest("http://127.0.0.1:8080/test", data); logger.info("Controller返回:{}", res); return res; }