0
点赞
收藏
分享

微信扫一扫

spring boot 启动netty 俩套方案  @PostConstruct注解 和 继承 CommandLineRunner


目录

​​介绍​​

​​基础环境​​

​​pom.xml​​

​​EchoServerHandler类​​

​​NettyServer 类​​

​​启动方案一  @PostConstruct  实现​​

​​NettyStart 类​​

​​启动方案二  继承 CommandLineRunner   从写 run 方法 启动执行​​

​​@SpringBootApplication 注解的 启动类​​

​​日志效果​​

介绍

1.基础还环境要有 pom.xml 映入基础的依赖 netty

2.Handler

3.nettyserver类型

4.然后就是俩种启动方式

喜欢用那种就用那种

 

基础环境

pom.xml

 <dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId> <!-- Use 'netty-all' for 4.0 or above -->
<version>4.1.32.Final</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>

 

EchoServerHandler类

package com.superman.netty.newim;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

public class EchoServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg){
ByteBuf in = (ByteBuf) msg;
System.out.println("Server received: " + in.toString(CharsetUtil.UTF_8));
ctx.write(in);
}

@Override
public void channelReadComplete(ChannelHandlerContext ctx){
ctx.writeAndFlush(ChannelFutureListener.CLOSE);
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){
cause.printStackTrace();
ctx.close();
}

}

 

NettyServer 类

package com.superman.netty.newim;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
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 java.net.InetSocketAddress;

public class NettyServer {

private int port = 8080;

public NettyServer(int port) {
this.port = port;
}

public void start() {
System.out.println("-----------------启动加载netty Server Start--------------------");
EventLoopGroup boss = new NioEventLoopGroup();
EventLoopGroup work = new NioEventLoopGroup();
ServerBootstrap b = new ServerBootstrap();
try {
b.group(boss, work).channel(NioServerSocketChannel.class)
.localAddress(new InetSocketAddress(port))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
ch.pipeline().addLast(new EchoServerHandler());
}
});
System.out.println("----------------启动加载netty Server in-----------------");

ChannelFuture channelFuturef = b.bind().sync();
if (channelFuturef.isSuccess()) {
System.out.println("---------------启动加载netty Server success----------------");

}
} catch (InterruptedException e) {
e.printStackTrace();
}

}

}

 

 

启动方案一  @PostConstruct  实现

NettyStart 类

package com.superman.netty.newim;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
* 启动netty 服务
*
* @author jianghy
*
* @version 1.0
*/
@Component
public class NettyStart {

/**
* netty 端口
* 配置在 application.yml 文件中
*/
@Value("${netty.port}")
private String nettPort;
/**
* 通过 PostConstruct 实现 在类被spring boot 加载的时候 进行启动 下边的netty 服务
*
* 启动 netty
*
*/
@PostConstruct
public void start(){
NettyServer ns = new NettyServer(Integer.valueOf(nettPort));
try {
ns.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}

 

 

启动方案二  继承 CommandLineRunner   从写 run 方法 启动执行

@SpringBootApplication 注解的 启动类

package com.superman;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.BasicConfigurator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;

import com.superman.conf.filter.XssAndSqlFilter;
import com.superman.netty.newim.NettyServer;
import com.superman.tonifi.InitInfo;

/**
* 项目启动类
* 集成 CommandLineRunner 是为了 从写 run 方法 ,在启动springboot 的时候马上启动netty 服务
*
* @author jianghy
*
*/
@SpringBootApplication
public class Provider_App implements CommandLineRunner {

/**
* 项目启动入口
*
* @param args
*/
public static void main(String[] args) {

SpringApplication.run(Provider_App.class, args);



}




/**
* netty 端口
* 配置在 application.yml 文件中
*/
@Value("${netty.port}")
private String nettPort;


@Override
public void run(String... args) throws Exception {
//启动netty
NettyServer ns = new NettyServer(Integer.valueOf(nettPort));
try {
ns.start();
} catch (Exception e) {
e.printStackTrace();
}
}


}

 

日志效果

The Class-Path manifest attribute in D:\apache-maven-3.5.3\apache-maven-3.5.3\maven_repository\com\drewnoakes\metadata-extractor\2.14.0\metadata-extractor-2.14.0.jar referenced one or more files that do not exist: file:/D:/apache-maven-3.5.3/apache-maven-3.5.3/maven_repository/com/drewnoakes/metadata-extractor/2.14.0/xmpcore-6.0.6.jar
The Class-Path manifest attribute in D:\apache-maven-3.5.3\apache-maven-3.5.3\maven_repository\org\htmlparser\htmlparser\2.1\htmlparser-2.1.jar referenced one or more files that do not exist: file:/D:/apache-maven-3.5.3/apache-maven-3.5.3/maven_repository/org/htmlparser/htmlparser/2.1/sax-2.0.1.jar,file:/D:/apache-maven-3.5.3/apache-maven-3.5.3/maven_repository/org/htmlparser/htmlparser/2.1/htmllexer-2.1.jar
The Class-Path manifest attribute in D:\apache-maven-3.5.3\apache-maven-3.5.3\maven_repository\com\sun\xml\bind\jaxb-impl\2.1\jaxb-impl-2.1.jar referenced one or more files that do not exist: file:/D:/apache-maven-3.5.3/apache-maven-3.5.3/maven_repository/com/sun/xml/bind/jaxb-impl/2.1/jaxb-api.jar,file:/D:/apache-maven-3.5.3/apache-maven-3.5.3/maven_repository/com/sun/xml/bind/jaxb-impl/2.1/activation.jar,file:/D:/apache-maven-3.5.3/apache-maven-3.5.3/maven_repository/com/sun/xml/bind/jaxb-impl/2.1/jsr173_1.0_api.jar,file:/D:/apache-maven-3.5.3/apache-maven-3.5.3/maven_repository/com/sun/xml/bind/jaxb-impl/2.1/jaxb1-impl.jar

. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.7.RELEASE)

2020-11-20 15:55:40.656 INFO com.superman.Provider_App - Starting Provider_App on UJ8XUW5KCNHO65F with PID 21640 (D:\eclipseworks_2020\superporject\super_netty-im\target\classes started by Administrator in D:\eclipseworks_2020\superporject\super_netty-im)
2020-11-20 15:55:40.660 INFO com.superman.Provider_App - No active profile set, falling back to default profiles: default
2020-11-20 15:55:40.722 INFO org.springframework.boot.devtools.env.DevToolsPropertyDefaultsPostProcessor - Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2020-11-20 15:55:40.722 INFO org.springframework.boot.devtools.env.DevToolsPropertyDefaultsPostProcessor - For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2020-11-20 15:55:43.002 INFO org.springframework.context.support.PostProcessorRegistrationDelegate$BeanPostProcessorChecker - Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$b7716f65] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-11-20 15:55:44.993 INFO org.springframework.boot.web.embedded.tomcat.TomcatWebServer - Tomcat initialized with port(s): 9018 (https)
2020-11-20 15:55:45.015 INFO org.apache.coyote.http11.Http11NioProtocol - Initializing ProtocolHandler ["https-jsse-nio-9018"]
2020-11-20 15:55:45.029 INFO org.apache.catalina.core.StandardService - Starting service [Tomcat]
2020-11-20 15:55:45.029 INFO org.apache.catalina.core.StandardEngine - Starting Servlet engine: [Apache Tomcat/9.0.22]
2020-11-20 15:55:45.203 INFO org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/] - Initializing Spring embedded WebApplicationContext
2020-11-20 15:55:45.203 INFO org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 4481 ms
2020-11-20 15:55:46.483 INFO org.springframework.boot.devtools.autoconfigure.OptionalLiveReloadServer - LiveReload server is running on port 35729
2020-11-20 15:55:46.566 INFO springfox.documentation.spring.web.PropertySourcedRequestMappingHandlerMapping - Mapped URL path [/v2/api-docs] onto method [public org.springframework.http.ResponseEntity<springfox.documentation.spring.web.json.Json> springfox.documentation.swagger2.web.Swagger2Controller.getDocumentation(java.lang.String,javax.servlet.http.HttpServletRequest)]
2020-11-20 15:55:46.589 INFO org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor - Initializing ExecutorService
2020-11-20 15:55:46.591 INFO org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor - Initializing ExecutorService 'getExecutor'
2020-11-20 15:55:46.594 INFO org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor - Initializing ExecutorService
2020-11-20 15:55:46.595 INFO org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor - Initializing ExecutorService 'getAgentExecutor'
2020-11-20 15:55:46.932 INFO org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler - Initializing ExecutorService 'taskScheduler'
2020-11-20 15:55:47.127 INFO springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper - Context refreshed
2020-11-20 15:55:47.145 INFO springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper - Found 1 custom documentation plugin(s)
2020-11-20 15:55:47.193 INFO springfox.documentation.spring.web.scanners.ApiListingReferenceScanner - Scanning for api listing references
2020-11-20 15:55:47.225 INFO org.apache.coyote.http11.Http11NioProtocol - Starting ProtocolHandler ["https-jsse-nio-9018"]
2020-11-20 15:55:47.535 INFO org.springframework.boot.web.embedded.tomcat.TomcatWebServer - Tomcat started on port(s): 9018 (https) with context path ''
2020-11-20 15:55:47.538 INFO com.superman.Provider_App - Started Provider_App in 7.75 seconds (JVM running for 8.392)
-----------------启动加载netty Server Start--------------------
----------------启动加载netty Server in-----------------
---------------启动加载netty Server success----------------

 

 

ok

 

 

持续更新


举报

相关推荐

0 条评论