netty作为一个高性能的io框架,是非好用的一个技术框架,

  Netty 是一个基于NIO的客户、服务器端编程框架,使用Netty 可以确保你快速和简单的开发出一个网络应用,例如实现了某种协议的客户、服务端应用。Netty相当于简化和流线化了网络应用的编程开发过程,例如:基于TCP和UDP的socket服务开发。
  “快速”和“简单”并不用产生维护性或性能上的问题。Netty 是一个吸收了多种协议(包括FTP、SMTP、HTTP等各种二进制文本协议)的实现经验,并经过相当精心设计的项目。最终,Netty 成功的找到了一种方式,在保证易于开发的同时还保证了其应用的性能,稳定性和伸缩性
  那么如何和springboot这个比较流行的框架进行整合呢?
  首先整个项目引入pom
  

<?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>
handler类是不会改变的
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下来的

方式一:注解@PostConstruct
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的多种方式的更多相关文章

  1. springboot整合netty,多种启动netty的方式,展现bean得多种启动方法

    首先讲解下,spring中初始化加载问题: 很多时候,我们自己写的线程池,还有bean对象,还有其他的服务类,都可以通过,相关注解进行交给spring去管理,那么我们如何让nettyserver初始化 ...

  2. SpringBoot整合Netty并使用Protobuf进行数据传输(附工程)

    前言 本篇文章主要介绍的是SpringBoot整合Netty以及使用Protobuf进行数据传输的相关内容.Protobuf会简单的介绍下用法,至于Netty在之前的文章中已经简单的介绍过了,这里就不 ...

  3. springboot整合netty(二)

    目录 前言 正文 代码 1. 新建一个springboot项目,在pom文件中添加netty依赖: 2.新建netty服务 3.netty调用所需的服务类 4 springboot启动类 5.测试 我 ...

  4. SpringBoot整合Netty

    总体来说只需要三个步骤,下面详细介绍 第一步 创建SpringBoot工程snetty 第二步 创建子模块也就是ModuleClient,Server,均为SpringBoot工程 第三步 将服务器端 ...

  5. 第6章 使用springboot整合netty搭建后台

    我们不会去使用自增长的id,在现阶段的互联网开发过程中,自增长的id是已经不适用了.在未来随着系统版本的迭代,用户数量的递增,肯定会做分库分表,去做一些相应的切分.在这个时候我们就需要有一个唯一的id ...

  6. SpringBoot整合Netty实现socket通讯简单demo

    依赖 <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifa ...

  7. springboot整合mybatis之注解方式

    1. 创建maven项目,工程目录如下图 2. 在pom.xml文件中添加mybatis依赖. 3. 创建实体类,并生成construct方法,getter和setter方法.同时在数据库中创建对应的 ...

  8. SpringBoot整合Swagger和Actuator

    前言 本篇文章主要介绍的是SpringBoot整合Swagger(API文档生成框架)和SpringBoot整合Actuator(项目监控)使用教程. SpringBoot整合Swagger 说明:如 ...

  9. SpringBoot整合Redis使用Restful风格实现CRUD功能

    前言 本篇文章主要介绍的是SpringBoot整合Redis,使用Restful风格实现的CRUD功能. Redis 介绍 Redis 是完全开源免费的,遵守BSD协议,是一个高性能的key-valu ...

随机推荐

  1. pycharm的使用(day03复习整理)

    pycharm的使用 file --> settings --> editor -->general --> change font size .... file --> ...

  2. Vue 实现前进刷新,后退不刷新的效果 玩转vue-router里的meta

    Vue 实现前进刷新,后退不刷新的效果 玩转vue-router里的meta. 需求一: 在一个列表页中,第一次进入的时候,请求获取数据. 点击某个列表项,跳到详情页,再从详情页后退回到列表页时,不刷 ...

  3. JVM内存结构、参数调优和内存泄露分析

    1. JVM内存区域和参数配置 1.1 JVM内存结构 Java堆(Heap) Java堆是被所有线程共享的一块内存区域,在虚拟机启动时创建.此内存区域的唯一目的就是存放对象实例,几乎所有的对象实例都 ...

  4. 2019 年容器生态统计报告发布 | 云原生生态周报 Vol. 26

    作者 | 酒祝.天元.元毅.心水.衷源 业界要闻 1.2019 年容器生态统计报告发布  据报告显示,Kubernetes 占据 77% 的容器编排产品份额,Docker 占据 79% 的容器引擎产品 ...

  5. .NET Core 又一杀器! Web Blazor框架横空出世!

    多年来,Javascript(及其子框架)已在浏览器中运行DOM(文档对象模型),并且掌握了脚本知识才能真正操作客户端UI.大约2年前,所有这些都随着Web Assembly的引入而发生了变化-Web ...

  6. [考试反思]1026csp-s模拟测试88:发展

    不用你们说,我自己来:我颓闪存我没脸. 昨天的想法, 今天的回答. 生存, 发展. 总分榜应该稍有回升,但是和上面的差距肯定还是很大. 继续. 为昨天的谬误,承担代价. T2和T3都值得张记性. T2 ...

  7. 赤壁情:dp

    首先这道题用到的3个新关键字大概讲一下: (我刚学会仅仅会瞎搞做题,欢迎大神补充) static:声明一个变量并清空.(不知道用不用时间,求解答) 具体用法:static 变量类型 变量名.如:sta ...

  8. Docker实战总结

    >>> 目录 <<< Docker简介 Docker优势 Docker基本概念 Docker安装使用 Docker常用命令 Docker镜像构建 Docker本地仓 ...

  9. python模块——psutil

    import psutil 内存 mem = psutil.virtual_memory() print(mem) >>> svmem(total=17048064000, avai ...

  10. K8S入门系列之集群二进制部署-->node篇(三)

    node节点组件 docker kubelet kube-proxy kubernetes-server-linux-amd64.tar.gz(相关的这里都能找到二进制文件!) falnnel 1. ...