Maison > Java > javaDidacticiel > le corps du texte

Quels sont les moyens par lesquels Springboot intègre le framework Netty ?

WBOY
Libérer: 2023-05-10 21:55:10
avant
752 Les gens l'ont consulté

netty est un framework io hautes performances et un framework technique très facile à utiliser

Netty est un framework de programmation côté client et serveur basé sur NIO. L'utilisation de Netty peut garantir cela. vous êtes rapide et simple Développez une application réseau, telle qu'une application client ou serveur qui implémente un certain protocole. Netty équivaut à simplifier et rationaliser le processus de programmation et de développement d'applications réseau, telles que : le développement de services de socket basés sur TCP et UDP.
"Rapide" et "simple" ne créent pas de problèmes de maintenance ou de performances. Netty est un projet qui absorbe l'expérience de mise en œuvre de plusieurs protocoles (y compris divers protocoles de texte binaire tels que FTP, SMTP, HTTP, etc.) et est conçu avec beaucoup de soin. En fin de compte, Netty a réussi à trouver un moyen d'assurer un développement facile tout en garantissant les performances, la stabilité et l'évolutivité de son application
Tout d'abord, l'ensemble du projet a introduit la classe 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>
Copier après la connexion

handler. ne change pas

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);
    }
    public void channelReadComplete(ChannelHandlerContext ctx){
        ctx.writeAndFlush(ChannelFutureListener.CLOSE);
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){
        cause.printStackTrace();
        ctx.close();
}
Copier après la connexion

Ce gestionnaire a été copié depuis le site officiel

Méthode 1 : Annoter @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("启动成功");
        }
    }
}
Copier après la connexion

Cliquez pour commencer :

Regardez le journal :

Quels sont les moyens par lesquels Springboot intègre le framework Netty ?

La description a été commencée

Alors pourquoi cette annotation est-elle si magique : # 🎜🎜#

Quels sont les moyens par lesquels Springboot intègre le framework Netty ?

La signification générale, veuillez jeter un œil, cela signifie que cette méthode sera chargée au fur et à mesure du chargement de la classe, et la signification du chargement initial est :

@Documented
@Retention (RUNTIME)
@Target(METHOD)
public @interface PostConstruct {
}
Copier après la connexion

Méthode 2 : Utiliser l'écouteur pour démarrer :

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) {
        
    }
}
Copier après la connexion

Classe de démarrage :

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);
    }
}
Copier après la connexion

Regardez le journal :

#🎜 🎜#

# 🎜🎜#

Méthode 3 : Utiliser l'écouteur de contexte ApplicationListenerQuels sont les moyens par lesquels Springboot intègre le framework Netty ?

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();
        }
    }
}
Copier après la connexion

Classe de démarrage :

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);
    }
}
Copier après la connexion

Regardez le journal de démarrage : #🎜 🎜#

#🎜 🎜#

Méthode 4 : commiandLinerunner démarre

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();
    }
}
Copier après la connexion

Regardez le log : Quels sont les moyens par lesquels Springboot intègre le framework Netty ?

# 🎜🎜#

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Étiquettes associées:
source:yisu.com
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!