java springboot 集成 Netty TCP 长连接

1. 实现 springboot pom.xml 文件


    4.0.0

    com.jjiagou
    bc
    0.0.1-SNAPSHOT
    jar

    bc
    Demo project for Spring Boot

    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.1.RELEASE
         
    

    
        UTF-8
        UTF-8
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        

        
        
            org.springframework.boot
            spring-boot-devtools
            true
            true
        

        
        
            
            
            
        |
        
            com.google.code.gson
            gson
        

        
        
            io.netty
            netty-all
            ${netty.version}
        

        
        
            net.sf.json-lib
            json-lib
            2.4
            jdk15
        

        
        
            org.springframework.boot
            spring-boot-starter-data-redis
        


        
            org.json
            json
            20180130
        


    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
                
                    
                    true
                
            
        
    


 

2. application.properties 文件的配置

# MYSQL
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/plate?serverTimezone=UTC&characterEncoding=utf8&useSSL=true&zeroDateTimeBehavior=convertToNull
spring.datasource.username=root
spring.datasource.password=

# redis
spring.redis.hostName=127.0.0.1
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
#springboot版本为2.0.2RELEASE中的RedisProperties配置文件类,从图中可知pool属性则被封装到了内部静态类Jedis和Lettuce中去了
spring.redis.jedis.pool.max-active=200
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=1000

# 开启 mybatis 驼峰命名
mybatis.configuration.map-underscore-to-camel-case=true

 

3.NettyServer

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;

//@Component
public class NettyServer {

    /**
     * 日志
     */
    private Logger log = LoggerFactory.getLogger(getClass());

    public NettyServer(){
    }

    /**
     * 端口号
     */
    private int port = 8131;

    protected static final int BIZGROUPSIZE = Runtime.getRuntime().availableProcessors()*2; //默认

    protected static final int BIZTHREADSIZE = 4;

    /**
     * 启动服务器方法
     */
    public void run() {
        EventLoopGroup bossGroup = new NioEventLoopGroup(BIZGROUPSIZE);
        EventLoopGroup workerGroup = new NioEventLoopGroup(BIZTHREADSIZE);
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup);
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.option(ChannelOption.SO_BACKLOG, 1024);
            serverBootstrap.handler(new LoggingHandler(LogLevel.INFO));
            serverBootstrap.childOption(ChannelOption.TCP_NODELAY, true);
            serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
            serverBootstrap.childHandler(new NettyServerInitializer());

            // 绑定端口,开始接收进来的连接
            ChannelFuture channelFuture = serverBootstrap.bind("192.168.1.150",port).sync();
            log.info("netty服务启动: [port:" + port + "]");
            // 等待服务器socket关闭
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("netty服务启动异常-" + e.getMessage());
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

 

4.NettyServerInitializer

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;


public class NettyServerInitializer extends ChannelInitializer {

    public  NettyServerInitializer(){

    }
    /**
     * 初始化channel
     */
    @Override
    public void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new NettyServerHandler());
    }
}

 

5. NettyServerHandler

import com.jjiagou.bc.util.ConvertCode;
import com.jjiagou.bc.util.RedisUtil;
import com.jjiagou.bc.util.StringUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.util.CharsetUtil;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.util.Arrays;

public class NettyServerHandler extends SimpleChannelInboundHandler {

    /**
     * 日志
     */
    private Logger log = LoggerFactory.getLogger(getClass());

    public NettyServerHandler(){

    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("------------------开始读取数据------------------");


//        ByteBuf msg1 = (ByteBuf) msg;
//        byte[] bytes = new byte[msg1.readableBytes()];
//        msg1.readBytes(bytes);
//        System.out.println( "---:"  + StringUtils.hexStr2Str(StringUtils.parseByte2HexStr(bytes)));

//        System.out.println(ctx);
//        String data = "020056ff008a005ba000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000da03";
//
//        //回复心跳
//        writeToClient(data, ctx, "测试");

    }

    /**
     * 公用回写数据到客户端的方法
     * @param  //需要回写的字符串
     * @param channel
     * @param mark 用于打印/log的输出
     * 
//channel.writeAndFlush(msg);//不行 *
//channel.writeAndFlush(receiveStr.getBytes());//不行 *
在netty里,进出的都是ByteBuf,楼主应确定服务端是否有对应的编码器,将字符串转化为ByteBuf * * https://blog.csdn.net/yqwang75457/article/details/73913572 */ private void writeToClient(final String receiveStr, ChannelHandlerContext channel, final String mark) { try { ByteBuf bufff = Unpooled.buffer();//netty需要用ByteBuf传输 bufff.writeBytes(ConvertCode.hexString2Bytes(receiveStr));//对接需要16进制 channel.writeAndFlush(bufff).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { StringBuilder sb = new StringBuilder(""); if(mark != null){ sb.append("【").append(mark).append("】"); } if (future.isSuccess()) { System.out.println(sb.toString()+"回写成功"+receiveStr); log.info(sb.toString()+"回写成功"+receiveStr); } else { System.out.println(sb.toString()+"回写失败"+receiveStr); log.error(sb.toString()+"回写失败"+receiveStr); } } }); } catch (Exception e) { e.printStackTrace(); System.out.println("调用通用writeToClient()异常"+e.getMessage()); log.error("调用通用writeToClient()异常:",e); } } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { System.out.println("channel 通道 Read 读取 Complete 完成"); ctx.flush(); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress(); String clientIp = insocket.getAddress().getHostAddress(); log.info("收到客户端[ip:" + clientIp + "]连接"); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // 当出现异常就关闭连接 ctx.close(); } }

 

6.NettyServerListener

import com.jjiagou.bc.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.HashMap;

/**
 * netty服务监听器 . 
* @author hkb */ @WebListener public class NettyServerListener implements ServletContextListener { private Logger log = LoggerFactory.getLogger(getClass()); @Override public void contextInitialized(ServletContextEvent sce) { log.info("开始启动netty服务"); Thread thread = new Thread(new NettyServerThread()); // 启动netty服务 thread.start(); } @Override public void contextDestroyed(ServletContextEvent sce) { } /** * netty服务启动线程 .
* * @author hkb */ private class NettyServerThread implements Runnable { @Override public void run() { NettyServer nettyServer = new NettyServer(); nettyServer.run(); log.info("成功启动netty服务"); } } }

 

 

你可能感兴趣的:(netty,springboot,java,netty,tcp,springboot,长连接)