作者 crossoverJie

:art: 改进代码的结构/格式

正在显示 16 个修改的文件 包含 352 行增加29 行删除
<?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">
<parent>
<artifactId>netty-action</artifactId>
<groupId>com.crossoverjie.netty</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>netty-action-common</artifactId>
</project>
\ No newline at end of file
... ...
<?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>
<parent>
<groupId>com.crossoverjie.netty</groupId>
<artifactId>netty-action</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>netty-action-heartbeat-client</artifactId>
<packaging>jar</packaging>
<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>com.crossoverjie.netty</groupId>
<artifactId>netty-action-common</artifactId>
</dependency>
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>${netty.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<!-- spring-boot-maven-plugin (提供了直接运行项目的插件:如果是通过parent方式继承spring-boot-starter-parent则不用此插件) -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
... ...
package com.crossoverjie.netty.action.client;
import com.crossoverjie.netty.action.client.init.CustomerHandleInitializer;
import com.crossoverjie.netty.action.common.pojo.CustomProtocol;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
/**
* Function:
*
* @author crossoverJie
* Date: 22/05/2018 14:19
* @since JDK 1.8
*/
@Component
public class HeartbeatClient {
private final static Logger LOGGER = LoggerFactory.getLogger(HeartbeatClient.class);
private EventLoopGroup group = new NioEventLoopGroup();
@Value("${netty.server.port}")
private int nettyPort;
@Value("${netty.server.host}")
private String host;
private SocketChannel channel ;
@PostConstruct
public void start() throws InterruptedException {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioSocketChannel.class)
.handler(new CustomerHandleInitializer())
;
ChannelFuture future = bootstrap.connect(host, nettyPort).sync();
if (future.isSuccess()) {
LOGGER.info("启动 Netty 成功");
}
channel = (SocketChannel) future.channel();
}
/**
* 发送消息
* @param customProtocol
*/
public void sendMsg(CustomProtocol customProtocol){
channel.writeAndFlush(customProtocol) ;
}
}
... ...
package com.crossoverjie.netty.action.client;
import com.crossoverjie.netty.action.common.pojo.CustomProtocol;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author crossoverJie
*/
@SpringBootApplication
public class HeartbeatClientApplication implements CommandLineRunner{
private final static Logger LOGGER = LoggerFactory.getLogger(HeartbeatClientApplication.class);
@Autowired
private HeartbeatClient heartbeatClient ;
public static void main(String[] args) {
SpringApplication.run(HeartbeatClientApplication.class, args);
LOGGER.info("启动 Client 成功");
}
@Override
public void run(String... args) throws Exception {
heartbeatClient.sendMsg(new CustomProtocol(999999L,"ping"));
}
}
\ No newline at end of file
... ...
package com.crossoverjie.netty.action.client.encode;
import com.crossoverjie.netty.action.common.pojo.CustomProtocol;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
/**
* Function:编码
*
* @author crossoverJie
* Date: 17/05/2018 19:07
* @since JDK 1.8
*/
public class HeartbeatEncode extends MessageToByteEncoder<CustomProtocol> {
@Override
protected void encode(ChannelHandlerContext ctx, CustomProtocol msg, ByteBuf out) throws Exception {
out.writeLong(msg.getHeader()) ;
out.writeBytes(msg.getContent().getBytes()) ;
}
}
... ...
package com.crossoverjie.netty.action.client.handle;
import com.crossoverjie.netty.action.common.pojo.CustomProtocol;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Function:
*
* @author crossoverJie
* Date: 16/02/2018 18:09
* @since JDK 1.8
*/
public class EchoClientHandle extends SimpleChannelInboundHandler<ByteBuf> {
private final static Logger LOGGER = LoggerFactory.getLogger(EchoClientHandle.class);
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent){
IdleStateEvent idleStateEvent = (IdleStateEvent) evt ;
if (idleStateEvent.state() == IdleState.WRITER_IDLE){
LOGGER.info("已经 10 秒没有发送信息!");
//向客户端发送消息
CustomProtocol customProtocol = new CustomProtocol(45678L,"ping") ;
ctx.writeAndFlush(Unpooled.copiedBuffer(customProtocol.toString(), CharsetUtil.UTF_8)) ;
}
}
super.userEventTriggered(ctx, evt);
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
//客户端和服务端建立连接时调用
LOGGER.info("已经建立了联系。。");
}
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf in) throws Exception {
//从服务端收到消息时被调用
LOGGER.info("客户端收到消息={}",in.toString(CharsetUtil.UTF_8)) ;
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//异常时断开连接
cause.printStackTrace() ;
ctx.close() ;
}
}
... ...
package com.crossoverjie.netty.action.client.init;
import com.crossoverjie.netty.action.client.encode.HeartbeatEncode;
import com.crossoverjie.netty.action.client.handle.EchoClientHandle;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.handler.timeout.IdleStateHandler;
/**
* Function:
*
* @author crossoverJie
* Date: 23/02/2018 22:47
* @since JDK 1.8
*/
public class CustomerHandleInitializer extends ChannelInitializer<Channel> {
@Override
protected void initChannel(Channel ch) throws Exception {
ch.pipeline()
//10 秒没发送消息
.addLast(new IdleStateHandler(0, 10, 0))
.addLast(new HeartbeatEncode())
.addLast(new EchoClientHandle())
;
}
}
... ...
# web port
server.port=8082
netty.server.host=127.0.0.1
netty.server.port=11211
logging.level.root=debug
\ No newline at end of file
... ...
... ... @@ -19,7 +19,12 @@
<dependencies>
<!-- spring-boot-starter-web (spring-webmvc + tomcat) -->
<dependency>
<groupId>com.crossoverjie.netty</groupId>
<artifactId>netty-action-common</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
... ...
package com.crossoverjie.netty.action;
package com.crossoverjie.netty.action.client;
import com.crossoverjie.netty.action.server.HeartBeatServer;
import io.netty.channel.ChannelFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
... ... @@ -13,13 +9,13 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
* @author crossoverJie
*/
@SpringBootApplication
public class Application{
public class HeartbeatServerApplication {
private final static Logger LOGGER = LoggerFactory.getLogger(Application.class);
private final static Logger LOGGER = LoggerFactory.getLogger(HeartbeatServerApplication.class);
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
LOGGER.info("启动成功");
SpringApplication.run(HeartbeatServerApplication.class, args);
LOGGER.info("启动 Server 成功");
}
}
\ No newline at end of file
... ...
package com.crossoverjie.netty.action.channel.init;
package com.crossoverjie.netty.action.client.channel.init;
import com.crossoverjie.netty.action.decoder.HeartbeatDecoder;
import com.crossoverjie.netty.action.handle.HeartBeatSimpleHandle;
import com.crossoverjie.netty.action.client.handle.HeartBeatSimpleHandle;
import com.crossoverjie.netty.action.client.decoder.HeartbeatDecoder;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.handler.timeout.IdleStateHandler;
... ...
package com.crossoverjie.netty.action.decoder;
package com.crossoverjie.netty.action.client.decoder;
import com.crossoverjie.netty.action.pojo.CustomProtocol;
import com.crossoverjie.netty.action.common.pojo.CustomProtocol;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
... ...
package com.crossoverjie.netty.action.handle;
package com.crossoverjie.netty.action.client.handle;
import com.crossoverjie.netty.action.pojo.CustomProtocol;
import com.crossoverjie.netty.action.common.pojo.CustomProtocol;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
... ...
package com.crossoverjie.netty.action.server;
package com.crossoverjie.netty.action.client.server;
import com.crossoverjie.netty.action.Application;
import com.crossoverjie.netty.action.channel.init.HeartbeatInitializer;
import com.crossoverjie.netty.action.client.channel.init.HeartbeatInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
... ... @@ -34,18 +30,21 @@ public class HeartBeatServer {
private EventLoopGroup work = new NioEventLoopGroup();
@Value("${netty.server.port}")
private int nettyPort ;
/**
* 启动 Netty
* @return
* @throws InterruptedException
*/
@PostConstruct
public ChannelFuture start() throws InterruptedException {
public void start() throws InterruptedException {
ServerBootstrap bootstrap = new ServerBootstrap()
.group(boss, work)
.channel(NioServerSocketChannel.class)
.localAddress(new InetSocketAddress(11211))
.localAddress(new InetSocketAddress(nettyPort))
//保持长连接
.childOption(ChannelOption.SO_KEEPALIVE,true)
.childHandler(new HeartbeatInitializer());
... ... @@ -54,8 +53,6 @@ public class HeartBeatServer {
if (future.isSuccess()){
LOGGER.info("启动 Netty 成功");
}
return future;
}
... ...
... ... @@ -27,11 +27,20 @@
<modules>
<module>netty-action-heartbeat</module>
<module>netty-action-heartbeat-client</module>
<module>netty-action-common</module>
</modules>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.crossoverjie.netty</groupId>
<artifactId>netty-action-common</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
... ...