1. 实现 springboot pom.xml 文件
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.jjiagou</groupId>
<artifactId>bc</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>bc</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 热启动devtools -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
<scope>true</scope>
</dependency>
<!-- alibaba fastjson -->
<!--<dependency>-->
<!--<groupId>com.alibaba</groupId>-->
<!--<artifactId>fastjson</artifactId>-->
<!--<version>1.2.15</version>-->
<!--</dependency>-->|
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<!-- netty -->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>${netty.version}</version>
</dependency>
<!-- JSONObject 依赖 -->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<!-- redis 引入 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180130</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<!-- 没有该配置,devtools不生效 -->
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build>
</project>
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<SocketChannel> {
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<Object> {
/**
* 日志
*/
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的输出
* <br>//channel.writeAndFlush(msg);//不行
* <br>//channel.writeAndFlush(receiveStr.getBytes());//不行
* <br>在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服务监听器 . <br>
* @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服务启动线程 . <br>
*
* @author hkb
*/
private class NettyServerThread implements Runnable {
@Override
public void run() {
NettyServer nettyServer = new NettyServer();
nettyServer.run();
log.info("成功启动netty服务");
}
}
}