springboot整合netty的多种方式
netty作为一个高性能的io框架,是非好用的一个技术框架,
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.cxy</groupId>
<artifactId>netty</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>netty</name>
<description>Demo project for Spring Boot</description> <properties>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.25.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>
package com.cxy.netty.controller; 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();
} }
这个handler是我从官网上copy下来的
package com.cxy.netty.controller; 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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.stereotype.Component; import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.net.InetSocketAddress;
@Component
public class NettyServer {
/*private int port =8080; public int getPort() {
return port;
} public void setPort(int port) {
this.port = port;
} public NettyServer(int port) {
this.port = port;
}*/
@PostConstruct
public void start() throws Exception {
System.out.println("启动记载netty");
EventLoopGroup boss = new NioEventLoopGroup();
EventLoopGroup work = new NioEventLoopGroup();
ServerBootstrap b = new ServerBootstrap();
b.group(boss,work)
.channel(NioServerSocketChannel.class)
.localAddress(new InetSocketAddress(8082))
.childHandler(new ChannelInitializer<SocketChannel>() { @Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new EchoServerHandler());
}
});
System.out.println("启动加载netty2");
ChannelFuture channelFuturef = b.bind().sync();
if (channelFuturef.isSuccess()){
System.out.println("启动成功");
} } }
点击启动:
看日志:

说明已经启动
那么这个注解为什么这么神奇呢:

大概的意思,大家看下,意思就是这个方法会随着类的加载而加载,初始化加载的意思:
@Documented
@Retention (RUNTIME)
@Target(METHOD)
public @interface PostConstruct {
}
方式二:利用监听器启动:
package com.cxy.netty.controller; import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener; /**
* 系统初始化监听器
* @author Administrator
*
*/
public class InitListener implements ServletContextListener { @Override
public void contextInitialized(ServletContextEvent sce) { NettyServer nettyServer = new NettyServer(8081);
try {
nettyServer.start();
} catch (Exception e) {
e.printStackTrace();
}
} @Override
public void contextDestroyed(ServletContextEvent sce) { } }
启动类:
package com.cxy.netty; import com.cxy.netty.controller.InitListener;
import com.cxy.netty.controller.NettyServer;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean; @SpringBootApplication
public class NettyApplication {
/**
* 注册监听器
* @return
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
@Bean
public ServletListenerRegistrationBean servletListenerRegistrationBean() {
ServletListenerRegistrationBean servletListenerRegistrationBean =
new ServletListenerRegistrationBean();
servletListenerRegistrationBean.setListener(new InitListener());
return servletListenerRegistrationBean;
}
public static void main(String[] args) {
SpringApplication.run(NettyApplication.class, args);
} }
看日志:

三 :利用 ApplicationListener 上下文监听器
package com.cxy.netty.controller; import com.cxy.netty.controller.NettyServer;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component; @Component
public class NettyBooter implements ApplicationListener<ContextRefreshedEvent> { @Override
public void onApplicationEvent(ContextRefreshedEvent event) {
NettyServer nettyServer = new NettyServer(8081);
try {
nettyServer.start();
} catch (Exception e) {
e.printStackTrace();
}
} }
启动类:
package com.cxy.netty; import com.cxy.netty.controller.NettyServer;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean; @SpringBootApplication
public class NettyApplication {
/**
* 注册监听器
* @return
*/
/* @SuppressWarnings({ "rawtypes", "unchecked" })
@Bean
public ServletListenerRegistrationBean servletListenerRegistrationBean() {
ServletListenerRegistrationBean servletListenerRegistrationBean =
new ServletListenerRegistrationBean();
servletListenerRegistrationBean.setListener(new InitListener());
return servletListenerRegistrationBean;
}*/
public static void main(String[] args) {
SpringApplication.run(NettyApplication.class, args);
} }
看启动日志:

四:commiandLinerunner启动
package com.cxy.netty; import com.cxy.netty.controller.NettyServer;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean; /*
@SpringBootApplication
public class NettyApplication {
*/
/**
* 注册监听器
* @return
*//* */
/* @SuppressWarnings({ "rawtypes", "unchecked" })
@Bean
public ServletListenerRegistrationBean servletListenerRegistrationBean() {
ServletListenerRegistrationBean servletListenerRegistrationBean =
new ServletListenerRegistrationBean();
servletListenerRegistrationBean.setListener(new InitListener());
return servletListenerRegistrationBean;
}*//* public static void main(String[] args) {
SpringApplication.run(NettyApplication.class, args);
} }
*/ @SpringBootApplication
public class NettyApplication implements CommandLineRunner { public static void main(String[] args) {
SpringApplication.run(NettyApplication.class, args);
} @Override
public void run(String... args) throws Exception {
NettyServer echoServer = new NettyServer(8083);
echoServer.start();
}
}
看日志:

代表这四种都可以启动成功,下章接再分析后面三种为什么可以启动成功
springboot整合netty的多种方式的更多相关文章
- springboot整合netty,多种启动netty的方式,展现bean得多种启动方法
首先讲解下,spring中初始化加载问题: 很多时候,我们自己写的线程池,还有bean对象,还有其他的服务类,都可以通过,相关注解进行交给spring去管理,那么我们如何让nettyserver初始化 ...
- SpringBoot整合Netty并使用Protobuf进行数据传输(附工程)
前言 本篇文章主要介绍的是SpringBoot整合Netty以及使用Protobuf进行数据传输的相关内容.Protobuf会简单的介绍下用法,至于Netty在之前的文章中已经简单的介绍过了,这里就不 ...
- springboot整合netty(二)
目录 前言 正文 代码 1. 新建一个springboot项目,在pom文件中添加netty依赖: 2.新建netty服务 3.netty调用所需的服务类 4 springboot启动类 5.测试 我 ...
- SpringBoot整合Netty
总体来说只需要三个步骤,下面详细介绍 第一步 创建SpringBoot工程snetty 第二步 创建子模块也就是ModuleClient,Server,均为SpringBoot工程 第三步 将服务器端 ...
- 第6章 使用springboot整合netty搭建后台
我们不会去使用自增长的id,在现阶段的互联网开发过程中,自增长的id是已经不适用了.在未来随着系统版本的迭代,用户数量的递增,肯定会做分库分表,去做一些相应的切分.在这个时候我们就需要有一个唯一的id ...
- SpringBoot整合Netty实现socket通讯简单demo
依赖 <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifa ...
- springboot整合mybatis之注解方式
1. 创建maven项目,工程目录如下图 2. 在pom.xml文件中添加mybatis依赖. 3. 创建实体类,并生成construct方法,getter和setter方法.同时在数据库中创建对应的 ...
- SpringBoot整合Swagger和Actuator
前言 本篇文章主要介绍的是SpringBoot整合Swagger(API文档生成框架)和SpringBoot整合Actuator(项目监控)使用教程. SpringBoot整合Swagger 说明:如 ...
- SpringBoot整合Redis使用Restful风格实现CRUD功能
前言 本篇文章主要介绍的是SpringBoot整合Redis,使用Restful风格实现的CRUD功能. Redis 介绍 Redis 是完全开源免费的,遵守BSD协议,是一个高性能的key-valu ...
随机推荐
- codeforce -14A A. Letter
A. Letter time limit per test 1 second memory limit per test 64 megabytes input standard input outpu ...
- MySql悲观锁与乐观锁区别及使用场景
一.概念上的区别 乐观锁( Optimistic Locking):顾名思义,对加锁持有一种乐观的态度,即先进行业务操作,不到最后一步不进行加锁,"乐观"的认为加锁一定会成功的,在 ...
- C#3种常见的定时器(多线程)
总结以下三种方法,实现c#每隔一段时间执行代码: 方法一:调用线程执行方法,在方法中实现死循环,每个循环Sleep设定时间: 方法二:使用System.Timers.Timer类: 方法三:使用Sys ...
- Android应用程序权限说明
1.声明运行该应用本身所需要的权限 <!-- 声明该应用本身需要打电话的权限 --> <users-permission androd:name="android:perm ...
- vue cli 4.0.5 的使用
vue cli 4.0.5 的使用 现在的 vue 脚手架已经升级到4.0的版本了,前两日vue 刚发布了3.0版本,我看了一下cli 4 和cli 3 没什么区别,既然这样,就只总结一下vue cl ...
- git 命令归纳版
1.克隆: 单纯的克隆名字: git clone [url] 自定义新建项目名称: git clone [url] [项目名字] 2.跟踪文件: git add [文件名] 3.添加忽略文件 ...
- AutoCad 二次开发 .net 之相同块的自动编号
主要步骤: 一.获取一个块的id: 其中oId就是了. 二.通过次oId获取块引用blkRef: 三.通过它获取所有相同的块引用的id集合: 四.通过步骤三的集合得到所有的块引用得到集合listBr: ...
- docker安装mysql,tomcat,并且在tomcat可以访问到mysql
1.uname -an 查看当前系统版本 2.yum -y install docker 下载安装docker 3.service docker start 启动docker服务 4.docker ...
- CentOS安装图解(在VMware 8上安装)
近期准备学习一下CentOS,打算先在VMware上装一个用于初步了解. 整体步骤如下: 一.获取CentOS安装镜像.可以从以下几个地方获取,顺便提一句,我是从163下载的. 1.CentOS的官方 ...
- 为什么 HTTPS 比 HTTP 安全
HTTP(超文本传输协议)是目前互联网应用最广泛的协议,伴随着人们网络安全意识的加强,HTTPS 被越来越多地采纳.不论是访问一些购物网站,或是登录一些博客.论坛等,我们都被 HTTPS 保护着,甚至 ...