<> One preface

springboot
How to integrate netty realization mapper Call not for null Many readers have had a headache , The knowledge seeker has given a little time to make a basic introduction to the integration application, which points out the right integration way for the readers , I Believe , As long as you have netty Introduction application knowledge and spring Framework Basics , This article will benefit you for life . Like it. Thank you , If it's the loyal fans of knowledge seekers, share it .

<> Two pom.xml

Let's see what dependencies knowledge seekers introduce

* netty-all All netty Related packages , Non release version for knowledge seekers , Readers can replace themselves
* postgresql Driving dependency , It doesn't matter what database you use , Readers can exchange mysql drive
* mybatis-spring-boot-starte integrate mybatis Starter required
* druid-spring-boot-starte Current mainstream connection pools with better performance , This article is not used
* spring-boot-starter-test Test class , This article should not be tested
* lombok Develop artifact , Save code development <!-- springboot start Superclass --> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version> </parent> <!-- web start to configure --> <dependencies>
<dependency> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency>
<groupId>io.netty</groupId> <artifactId>netty-all</artifactId>
<version>5.0.0.Alpha1</version> </dependency> <dependency>
<groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId>
<scope>runtime</scope> </dependency> <dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version>
</dependency> <dependency> <groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId> <version>1.1.10</version>
</dependency> <dependency> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId> <scope>test</scope>
</dependency> <dependency> <groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId> <version>1.16.18</version>
<scope>provided</scope> </dependency> </dependencies>
<> Three NettyServer

* First of all, the fixed listening port we use here 8080
* Configure two thread groups parentGroup, childGroup
* injection childChannelHandler See section 4 for details
*
Null parameter defined init Method of , Annotate @PostConstruct, We need to give a detailed introduction to this annotation here ; After initialization of dependency injection , If a method has this annotation, it will be executed ; When is it going to be implemented ? In class entry service before , The method marked by the annotation will be executed , And only once ; Another point to note when using this annotation is that all classes must support dependency injection , Otherwise, an error will be reported , In general, only null parameters are supported ;
* init In this way netty Secondary start of , Configuration processing class , Perform synchronous blocking operation ;
*
Last look destory() method , The method is annotated @PreDestroy;@PreDestroy Represents a callback information notification mechanism , Notice will be given when the instance is removed from the container ; We usually use it to close the resource handle ;
/** * @Author lsc * <p>netty server end </p> */ @Component public class
NettyServer { private Integer port = 8080; // Configure thread groups The essence is reactor Thread group
NioEventLoopGroup parentGroup = new NioEventLoopGroup(); // Configure thread groups
NioEventLoopGroup childGroup = new NioEventLoopGroup(); @Autowired
ChildChannelHandler childChannelHandler; @PostConstruct public void init()
throws Exception{ // start-up NIO ServerBootstrap serverBootstrap = new
ServerBootstrap(); // serverBootstrap.group(parentGroup,childGroup)
.channel(NioServerSocketChannel.class)// amount to ServerSocketChannel
.option(ChannelOption.SO_BACKLOG,1024)//TCP parameter 1024 Queues
.childHandler(childChannelHandler);// Handling events // Bind port Synchronization blocking waiting for synchronization to succeed channelFuture
Asynchronous operation notification callback ChannelFuture channelFuture = serverBootstrap.bind(port).sync(); //
Synchronous blocking waiting for service listening port to close channelFuture.channel().closeFuture().sync(); } @PreDestroy
public void destory() throws InterruptedException { // close resource
parentGroup.shutdownGracefully().sync();
childGroup.shutdownGracefully().sync(); } }
<> Four ChildChannelHandler

* ChildChannelHandler Class inheritance ChannelInitializer
* injection NettyServerHandler, See section 5 for details
* realization initChannel Method and obtain in method pipeline injection nettyServerHandler; /** * @Author lsc *
<p> </p> */ @Component public class ChildChannelHandler extends
ChannelInitializer<SocketChannel> { @Autowired NettyServerHandler
nettyServerHandler; @Override protected void initChannel(SocketChannel
socketChannel) throws Exception { ChannelPipeline pipeline =
socketChannel.pipeline(); // pipeline.addLast(nettyServerHandler); } }
<> Five NettyServerHandler

* NettyServerHandler inherit ChannelHandlerAdapter
* Separate implementation channelRead,channelReadComplete, exceptionCaught method
* injection NettyMapper , Customized mapper
* Focus on channelRead in Read listening 8080 Data sent by client , Then write zszxz-66666 Build response
* If mapper Empty Can print can you believe that the mapper is null
* Execute callback processing finally ; /** * @Author lsc * <p> Processing class </p> */ @Slf4j @Component public
class NettyServerHandler extends ChannelHandlerAdapter { @Autowired NettyMapper
mapper; @Override public void channelRead(ChannelHandlerContext ctx, Object
msg) throws Exception { System.out.println("-----handler-------"); // Convert to byte buffer
ByteBuf buf = (ByteBuf)msg; // Byte array byte[] bytes = new
byte[buf.readableBytes()]; // Buffer data read into byte array buf.readBytes(bytes); // Code to string
String body = (new String(bytes, "UTF-8")); System.out.println(" get the data
from client : " + body); // Construct response data String responseData = "zszxz-66666"; //
Data write buffer ByteBuf resp = Unpooled.copiedBuffer(responseData.getBytes()); //
Write data response ChannelFuture channelFuture = ctx.writeAndFlush(resp); if
(mapper==null){ System.out.println("can you believe that the mapper is null");
} List<Map> user = mapper.getUser(); System.out.println(user); // Callback processing
channelFuture.addListener(new ChannelFutureListener() { @Override public void
operationComplete(ChannelFuture channelFuture) throws Exception { if
(channelFuture.isSuccess()){ log.info("success"); }else { log.error("error"); }
} }); } @Override public void channelReadComplete(ChannelHandlerContext ctx)
throws Exception { // write in seocketChannel ctx.flush(); } @Override public void
exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// Closing resource handle abnormally ctx.close(); } }
<> Six mapper

<>6.1 mapper Interface

mapper A query method is defined in the interface , Get users ;
@Mapper @Repository public interface NettyMapper { List<Map> getUser(); }
<>6.2 mapper Mapper

Query all students
<mapper namespace="com.zszxz.netty.mapper.NettyMapper"> <select id="getUser"
resultType="map"> select * from "student" </select> </mapper>
<> Seven application.yml
spring: datasource: druid: # local url:
jdbc:postgresql://localhost:5432/springboot username: postgres password: 123456
driver-class-name: org.postgresql.Driver mybatis: mapper-locations:
classpath:mapper/*.xml configuration: mapUnderscoreToCamelCase: true
<> Eight Startup class
/** * @Author lsc * <p> Knowledge seeker netty series </p> */ @SpringBootApplication public
class App { public static void main(String[] args) {
SpringApplication.run(App.class,args); } }
<> Nine results of enforcement

* Sent a great staff for knowledge seekers
* response zszxz-66666

<> Ten epilogue

Finally, I wish readers a happy New Year , Prevention of influenza virus , Go out with a mask , Don't go to places with high traffic , Eating cooked meat , wash hands more often ; Rational treatment of new influenza virus on the Internet , Cheer for China , Cheer for Wuhan ; Don't forget to study in the new year , Knowledge seekers should carry out the policy of learning every day , Unswervingly follow the steps of readers ;

Technology
©2019-2020 Toolsou All rights reserved,
First knowledge python Skills summary GDOI2019 travels c Linguistic 5 Three common sorting methods Python Basic knowledge and notes " Cephalosporin wine Say go and go "? DANGER ! Don't drink alcohol when taking these drugs Thorough explanation from Zhongtai vue The component page height is adaptive according to the screen size Classical algorithm - recursion ( The case of raw rabbit ) Big data tells you , How tired are Chinese women about keras use fit_generator Encountered in StopIteration