package com.jpsoft.smart; import com.jpsoft.smart.lapi.handler.HeartReportHandler; import com.jpsoft.smart.lapi.handler.ParseHttpHandler; import com.jpsoft.smart.lapi.handler.PersonVerificationHandler; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpServerCodec; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import javax.annotation.PreDestroy; @Slf4j //@SpringBootApplication //@EnableTransactionManagement //@MapperScan("com.jpsoft.smart.**.dao") public class LapiApplication implements CommandLineRunner { public static void main(String[] args) { SpringApplication.run(LapiApplication.class, args); } @Autowired private PersonVerificationHandler personVerificationHandler; @Autowired private HeartReportHandler heartReportHandler; @Value("${server.port}") private Integer port; private Channel serverChannel; @Override public void run(String... args) throws Exception { NioEventLoopGroup bossGroup = new NioEventLoopGroup(); NioEventLoopGroup workerGroup = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup,workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer(){ @Override protected void initChannel(Channel channel) throws Exception { // channel.pipeline().addLast(new TextDecodeHandler()); // channel.pipeline().addLast(new HttpRequestDecoder()); channel.pipeline().addLast(new HttpServerCodec()); channel.pipeline().addLast(new HttpObjectAggregator(2048*10000)); channel.pipeline().addLast(new ParseHttpHandler()); channel.pipeline().addLast(heartReportHandler); channel.pipeline().addLast(personVerificationHandler); } }); ChannelFuture channelFuture = b.bind("0.0.0.0",port); serverChannel = channelFuture.channel(); channelFuture.addListener((future)-> { if(future.isSuccess()){ log.warn(String.format("netty 已监听%d端口",port)); } }); } @PreDestroy public void stop(){ if (serverChannel!=null && serverChannel.isOpen()){ serverChannel.close(); } } }