作者 crossoverJie

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

正在显示 16 个修改的文件 包含 352 行增加29 行删除
  1 +<?xml version="1.0" encoding="UTF-8"?>
  2 +<project xmlns="http://maven.apache.org/POM/4.0.0"
  3 + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5 + <parent>
  6 + <artifactId>netty-action</artifactId>
  7 + <groupId>com.crossoverjie.netty</groupId>
  8 + <version>1.0.0-SNAPSHOT</version>
  9 + </parent>
  10 + <modelVersion>4.0.0</modelVersion>
  11 +
  12 + <artifactId>netty-action-common</artifactId>
  13 +
  14 +
  15 +</project>
  1 +<?xml version="1.0" encoding="UTF-8"?>
  2 +<project xmlns="http://maven.apache.org/POM/4.0.0"
  3 + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5 + <modelVersion>4.0.0</modelVersion>
  6 + <parent>
  7 + <groupId>com.crossoverjie.netty</groupId>
  8 + <artifactId>netty-action</artifactId>
  9 + <version>1.0.0-SNAPSHOT</version>
  10 + </parent>
  11 + <artifactId>netty-action-heartbeat-client</artifactId>
  12 + <packaging>jar</packaging>
  13 +
  14 + <properties>
  15 + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  16 + <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  17 + <java.version>1.8</java.version>
  18 + </properties>
  19 +
  20 +
  21 + <dependencies>
  22 +
  23 + <dependency>
  24 + <groupId>com.crossoverjie.netty</groupId>
  25 + <artifactId>netty-action-common</artifactId>
  26 + </dependency>
  27 +
  28 + <dependency>
  29 + <groupId>org.springframework.boot</groupId>
  30 + <artifactId>spring-boot-starter-web</artifactId>
  31 + </dependency>
  32 + <dependency>
  33 + <groupId>org.springframework.boot</groupId>
  34 + <artifactId>spring-boot-starter-test</artifactId>
  35 + <scope>test</scope>
  36 + </dependency>
  37 +
  38 + <dependency>
  39 + <groupId>org.springframework.boot</groupId>
  40 + <artifactId>spring-boot-configuration-processor</artifactId>
  41 + <optional>true</optional>
  42 + </dependency>
  43 +
  44 + <dependency>
  45 + <groupId>io.netty</groupId>
  46 + <artifactId>netty-all</artifactId>
  47 + <version>${netty.version}</version>
  48 + </dependency>
  49 +
  50 + <dependency>
  51 + <groupId>junit</groupId>
  52 + <artifactId>junit</artifactId>
  53 + </dependency>
  54 +
  55 + <dependency>
  56 + <groupId>com.alibaba</groupId>
  57 + <artifactId>fastjson</artifactId>
  58 + </dependency>
  59 +
  60 + <dependency>
  61 + <groupId>com.google.guava</groupId>
  62 + <artifactId>guava</artifactId>
  63 + </dependency>
  64 +
  65 + </dependencies>
  66 +
  67 + <build>
  68 + <plugins>
  69 + <!-- spring-boot-maven-plugin (提供了直接运行项目的插件:如果是通过parent方式继承spring-boot-starter-parent则不用此插件) -->
  70 + <plugin>
  71 + <groupId>org.springframework.boot</groupId>
  72 + <artifactId>spring-boot-maven-plugin</artifactId>
  73 + <executions>
  74 + <execution>
  75 + <goals>
  76 + <goal>repackage</goal>
  77 + </goals>
  78 + </execution>
  79 + </executions>
  80 + </plugin>
  81 + </plugins>
  82 + </build>
  83 +
  84 +</project>
  1 +package com.crossoverjie.netty.action.client;
  2 +
  3 +import com.crossoverjie.netty.action.client.init.CustomerHandleInitializer;
  4 +import com.crossoverjie.netty.action.common.pojo.CustomProtocol;
  5 +import io.netty.bootstrap.Bootstrap;
  6 +import io.netty.channel.ChannelFuture;
  7 +import io.netty.channel.EventLoopGroup;
  8 +import io.netty.channel.nio.NioEventLoopGroup;
  9 +import io.netty.channel.socket.SocketChannel;
  10 +import io.netty.channel.socket.nio.NioSocketChannel;
  11 +import org.slf4j.Logger;
  12 +import org.slf4j.LoggerFactory;
  13 +import org.springframework.beans.factory.annotation.Value;
  14 +import org.springframework.stereotype.Component;
  15 +
  16 +import javax.annotation.PostConstruct;
  17 +
  18 +/**
  19 + * Function:
  20 + *
  21 + * @author crossoverJie
  22 + * Date: 22/05/2018 14:19
  23 + * @since JDK 1.8
  24 + */
  25 +@Component
  26 +public class HeartbeatClient {
  27 +
  28 + private final static Logger LOGGER = LoggerFactory.getLogger(HeartbeatClient.class);
  29 +
  30 + private EventLoopGroup group = new NioEventLoopGroup();
  31 +
  32 +
  33 + @Value("${netty.server.port}")
  34 + private int nettyPort;
  35 +
  36 + @Value("${netty.server.host}")
  37 + private String host;
  38 +
  39 + private SocketChannel channel ;
  40 +
  41 + @PostConstruct
  42 + public void start() throws InterruptedException {
  43 + Bootstrap bootstrap = new Bootstrap();
  44 + bootstrap.group(group)
  45 + .channel(NioSocketChannel.class)
  46 + .handler(new CustomerHandleInitializer())
  47 + ;
  48 +
  49 + ChannelFuture future = bootstrap.connect(host, nettyPort).sync();
  50 + if (future.isSuccess()) {
  51 + LOGGER.info("启动 Netty 成功");
  52 + }
  53 + channel = (SocketChannel) future.channel();
  54 + }
  55 +
  56 + /**
  57 + * 发送消息
  58 + * @param customProtocol
  59 + */
  60 + public void sendMsg(CustomProtocol customProtocol){
  61 + channel.writeAndFlush(customProtocol) ;
  62 + }
  63 +}
  1 +package com.crossoverjie.netty.action.client;
  2 +
  3 +import com.crossoverjie.netty.action.common.pojo.CustomProtocol;
  4 +import org.slf4j.Logger;
  5 +import org.slf4j.LoggerFactory;
  6 +import org.springframework.beans.factory.annotation.Autowired;
  7 +import org.springframework.boot.CommandLineRunner;
  8 +import org.springframework.boot.SpringApplication;
  9 +import org.springframework.boot.autoconfigure.SpringBootApplication;
  10 +
  11 +/**
  12 + * @author crossoverJie
  13 + */
  14 +@SpringBootApplication
  15 +public class HeartbeatClientApplication implements CommandLineRunner{
  16 +
  17 + private final static Logger LOGGER = LoggerFactory.getLogger(HeartbeatClientApplication.class);
  18 +
  19 +
  20 + @Autowired
  21 + private HeartbeatClient heartbeatClient ;
  22 +
  23 + public static void main(String[] args) {
  24 + SpringApplication.run(HeartbeatClientApplication.class, args);
  25 + LOGGER.info("启动 Client 成功");
  26 + }
  27 +
  28 + @Override
  29 + public void run(String... args) throws Exception {
  30 + heartbeatClient.sendMsg(new CustomProtocol(999999L,"ping"));
  31 + }
  32 +}
  1 +package com.crossoverjie.netty.action.client.encode;
  2 +
  3 +import com.crossoverjie.netty.action.common.pojo.CustomProtocol;
  4 +import io.netty.buffer.ByteBuf;
  5 +import io.netty.channel.ChannelHandlerContext;
  6 +import io.netty.handler.codec.MessageToByteEncoder;
  7 +
  8 +/**
  9 + * Function:编码
  10 + *
  11 + * @author crossoverJie
  12 + * Date: 17/05/2018 19:07
  13 + * @since JDK 1.8
  14 + */
  15 +public class HeartbeatEncode extends MessageToByteEncoder<CustomProtocol> {
  16 + @Override
  17 + protected void encode(ChannelHandlerContext ctx, CustomProtocol msg, ByteBuf out) throws Exception {
  18 +
  19 + out.writeLong(msg.getHeader()) ;
  20 + out.writeBytes(msg.getContent().getBytes()) ;
  21 +
  22 + }
  23 +}
  1 +package com.crossoverjie.netty.action.client.handle;
  2 +
  3 +import com.crossoverjie.netty.action.common.pojo.CustomProtocol;
  4 +import io.netty.buffer.ByteBuf;
  5 +import io.netty.buffer.Unpooled;
  6 +import io.netty.channel.ChannelHandlerContext;
  7 +import io.netty.channel.SimpleChannelInboundHandler;
  8 +import io.netty.handler.timeout.IdleState;
  9 +import io.netty.handler.timeout.IdleStateEvent;
  10 +import io.netty.util.CharsetUtil;
  11 +import org.slf4j.Logger;
  12 +import org.slf4j.LoggerFactory;
  13 +
  14 +/**
  15 + * Function:
  16 + *
  17 + * @author crossoverJie
  18 + * Date: 16/02/2018 18:09
  19 + * @since JDK 1.8
  20 + */
  21 +public class EchoClientHandle extends SimpleChannelInboundHandler<ByteBuf> {
  22 +
  23 + private final static Logger LOGGER = LoggerFactory.getLogger(EchoClientHandle.class);
  24 +
  25 +
  26 + @Override
  27 + public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
  28 +
  29 + if (evt instanceof IdleStateEvent){
  30 + IdleStateEvent idleStateEvent = (IdleStateEvent) evt ;
  31 +
  32 + if (idleStateEvent.state() == IdleState.WRITER_IDLE){
  33 + LOGGER.info("已经 10 秒没有发送信息!");
  34 + //向客户端发送消息
  35 + CustomProtocol customProtocol = new CustomProtocol(45678L,"ping") ;
  36 + ctx.writeAndFlush(Unpooled.copiedBuffer(customProtocol.toString(), CharsetUtil.UTF_8)) ;
  37 + }
  38 +
  39 +
  40 + }
  41 +
  42 + super.userEventTriggered(ctx, evt);
  43 + }
  44 +
  45 + @Override
  46 + public void channelActive(ChannelHandlerContext ctx) throws Exception {
  47 +
  48 + //客户端和服务端建立连接时调用
  49 + LOGGER.info("已经建立了联系。。");
  50 + }
  51 +
  52 + @Override
  53 + protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf in) throws Exception {
  54 +
  55 + //从服务端收到消息时被调用
  56 + LOGGER.info("客户端收到消息={}",in.toString(CharsetUtil.UTF_8)) ;
  57 +
  58 + }
  59 +
  60 + @Override
  61 + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  62 + //异常时断开连接
  63 + cause.printStackTrace() ;
  64 + ctx.close() ;
  65 + }
  66 +}
  1 +package com.crossoverjie.netty.action.client.init;
  2 +
  3 +import com.crossoverjie.netty.action.client.encode.HeartbeatEncode;
  4 +import com.crossoverjie.netty.action.client.handle.EchoClientHandle;
  5 +import io.netty.channel.Channel;
  6 +import io.netty.channel.ChannelInitializer;
  7 +import io.netty.handler.timeout.IdleStateHandler;
  8 +
  9 +/**
  10 + * Function:
  11 + *
  12 + * @author crossoverJie
  13 + * Date: 23/02/2018 22:47
  14 + * @since JDK 1.8
  15 + */
  16 +public class CustomerHandleInitializer extends ChannelInitializer<Channel> {
  17 + @Override
  18 + protected void initChannel(Channel ch) throws Exception {
  19 + ch.pipeline()
  20 + //10 秒没发送消息
  21 + .addLast(new IdleStateHandler(0, 10, 0))
  22 + .addLast(new HeartbeatEncode())
  23 + .addLast(new EchoClientHandle())
  24 + ;
  25 + }
  26 +}
  1 +# web port
  2 +server.port=8082
  3 +
  4 +netty.server.host=127.0.0.1
  5 +netty.server.port=11211
  6 +
  7 +logging.level.root=debug
@@ -19,7 +19,12 @@ @@ -19,7 +19,12 @@
19 19
20 20
21 <dependencies> 21 <dependencies>
22 - <!-- spring-boot-starter-web (spring-webmvc + tomcat) --> 22 +
  23 + <dependency>
  24 + <groupId>com.crossoverjie.netty</groupId>
  25 + <artifactId>netty-action-common</artifactId>
  26 + </dependency>
  27 +
23 <dependency> 28 <dependency>
24 <groupId>org.springframework.boot</groupId> 29 <groupId>org.springframework.boot</groupId>
25 <artifactId>spring-boot-starter-web</artifactId> 30 <artifactId>spring-boot-starter-web</artifactId>
1 -package com.crossoverjie.netty.action; 1 +package com.crossoverjie.netty.action.client;
2 2
3 -import com.crossoverjie.netty.action.server.HeartBeatServer;  
4 -import io.netty.channel.ChannelFuture;  
5 import org.slf4j.Logger; 3 import org.slf4j.Logger;
6 import org.slf4j.LoggerFactory; 4 import org.slf4j.LoggerFactory;
7 -import org.springframework.beans.factory.annotation.Autowired;  
8 -import org.springframework.boot.CommandLineRunner;  
9 import org.springframework.boot.SpringApplication; 5 import org.springframework.boot.SpringApplication;
10 import org.springframework.boot.autoconfigure.SpringBootApplication; 6 import org.springframework.boot.autoconfigure.SpringBootApplication;
11 7
@@ -13,13 +9,13 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @@ -13,13 +9,13 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
13 * @author crossoverJie 9 * @author crossoverJie
14 */ 10 */
15 @SpringBootApplication 11 @SpringBootApplication
16 -public class Application{ 12 +public class HeartbeatServerApplication {
17 13
18 - private final static Logger LOGGER = LoggerFactory.getLogger(Application.class); 14 + private final static Logger LOGGER = LoggerFactory.getLogger(HeartbeatServerApplication.class);
19 15
20 public static void main(String[] args) { 16 public static void main(String[] args) {
21 - SpringApplication.run(Application.class, args);  
22 - LOGGER.info("启动成功"); 17 + SpringApplication.run(HeartbeatServerApplication.class, args);
  18 + LOGGER.info("启动 Server 成功");
23 } 19 }
24 20
25 } 21 }
1 -package com.crossoverjie.netty.action.channel.init; 1 +package com.crossoverjie.netty.action.client.channel.init;
2 2
3 -import com.crossoverjie.netty.action.decoder.HeartbeatDecoder;  
4 -import com.crossoverjie.netty.action.handle.HeartBeatSimpleHandle; 3 +import com.crossoverjie.netty.action.client.handle.HeartBeatSimpleHandle;
  4 +import com.crossoverjie.netty.action.client.decoder.HeartbeatDecoder;
5 import io.netty.channel.Channel; 5 import io.netty.channel.Channel;
6 import io.netty.channel.ChannelInitializer; 6 import io.netty.channel.ChannelInitializer;
7 import io.netty.handler.timeout.IdleStateHandler; 7 import io.netty.handler.timeout.IdleStateHandler;
1 -package com.crossoverjie.netty.action.decoder; 1 +package com.crossoverjie.netty.action.client.decoder;
2 2
3 -import com.crossoverjie.netty.action.pojo.CustomProtocol; 3 +import com.crossoverjie.netty.action.common.pojo.CustomProtocol;
4 import io.netty.buffer.ByteBuf; 4 import io.netty.buffer.ByteBuf;
5 import io.netty.channel.ChannelHandlerContext; 5 import io.netty.channel.ChannelHandlerContext;
6 import io.netty.handler.codec.ByteToMessageDecoder; 6 import io.netty.handler.codec.ByteToMessageDecoder;
1 -package com.crossoverjie.netty.action.handle; 1 +package com.crossoverjie.netty.action.client.handle;
2 2
3 -import com.crossoverjie.netty.action.pojo.CustomProtocol; 3 +import com.crossoverjie.netty.action.common.pojo.CustomProtocol;
4 import io.netty.buffer.Unpooled; 4 import io.netty.buffer.Unpooled;
5 import io.netty.channel.ChannelFutureListener; 5 import io.netty.channel.ChannelFutureListener;
6 import io.netty.channel.ChannelHandlerContext; 6 import io.netty.channel.ChannelHandlerContext;
1 -package com.crossoverjie.netty.action.server; 1 +package com.crossoverjie.netty.action.client.server;
2 2
3 -import com.crossoverjie.netty.action.Application;  
4 -import com.crossoverjie.netty.action.channel.init.HeartbeatInitializer; 3 +import com.crossoverjie.netty.action.client.channel.init.HeartbeatInitializer;
5 import io.netty.bootstrap.ServerBootstrap; 4 import io.netty.bootstrap.ServerBootstrap;
6 import io.netty.channel.*; 5 import io.netty.channel.*;
7 import io.netty.channel.nio.NioEventLoopGroup; 6 import io.netty.channel.nio.NioEventLoopGroup;
8 import io.netty.channel.socket.nio.NioServerSocketChannel; 7 import io.netty.channel.socket.nio.NioServerSocketChannel;
9 -import io.netty.handler.timeout.IdleStateHandler;  
10 import org.slf4j.Logger; 8 import org.slf4j.Logger;
11 import org.slf4j.LoggerFactory; 9 import org.slf4j.LoggerFactory;
12 -import org.springframework.beans.factory.annotation.Configurable;  
13 -import org.springframework.context.annotation.Bean;  
14 -import org.springframework.context.annotation.Configuration; 10 +import org.springframework.beans.factory.annotation.Value;
15 import org.springframework.stereotype.Component; 11 import org.springframework.stereotype.Component;
16 12
17 import javax.annotation.PostConstruct; 13 import javax.annotation.PostConstruct;
@@ -34,18 +30,21 @@ public class HeartBeatServer { @@ -34,18 +30,21 @@ public class HeartBeatServer {
34 private EventLoopGroup work = new NioEventLoopGroup(); 30 private EventLoopGroup work = new NioEventLoopGroup();
35 31
36 32
  33 + @Value("${netty.server.port}")
  34 + private int nettyPort ;
  35 +
37 /** 36 /**
38 * 启动 Netty 37 * 启动 Netty
39 * @return 38 * @return
40 * @throws InterruptedException 39 * @throws InterruptedException
41 */ 40 */
42 @PostConstruct 41 @PostConstruct
43 - public ChannelFuture start() throws InterruptedException { 42 + public void start() throws InterruptedException {
44 43
45 ServerBootstrap bootstrap = new ServerBootstrap() 44 ServerBootstrap bootstrap = new ServerBootstrap()
46 .group(boss, work) 45 .group(boss, work)
47 .channel(NioServerSocketChannel.class) 46 .channel(NioServerSocketChannel.class)
48 - .localAddress(new InetSocketAddress(11211)) 47 + .localAddress(new InetSocketAddress(nettyPort))
49 //保持长连接 48 //保持长连接
50 .childOption(ChannelOption.SO_KEEPALIVE,true) 49 .childOption(ChannelOption.SO_KEEPALIVE,true)
51 .childHandler(new HeartbeatInitializer()); 50 .childHandler(new HeartbeatInitializer());
@@ -54,8 +53,6 @@ public class HeartBeatServer { @@ -54,8 +53,6 @@ public class HeartBeatServer {
54 if (future.isSuccess()){ 53 if (future.isSuccess()){
55 LOGGER.info("启动 Netty 成功"); 54 LOGGER.info("启动 Netty 成功");
56 } 55 }
57 -  
58 - return future;  
59 } 56 }
60 57
61 58
@@ -27,11 +27,20 @@ @@ -27,11 +27,20 @@
27 27
28 <modules> 28 <modules>
29 <module>netty-action-heartbeat</module> 29 <module>netty-action-heartbeat</module>
  30 + <module>netty-action-heartbeat-client</module>
  31 + <module>netty-action-common</module>
30 </modules> 32 </modules>
31 33
32 34
33 <dependencyManagement> 35 <dependencyManagement>
34 <dependencies> 36 <dependencies>
  37 +
  38 + <dependency>
  39 + <groupId>com.crossoverjie.netty</groupId>
  40 + <artifactId>netty-action-common</artifactId>
  41 + <version>1.0.0-SNAPSHOT</version>
  42 + </dependency>
  43 +
35 <dependency> 44 <dependency>
36 <groupId>io.netty</groupId> 45 <groupId>io.netty</groupId>
37 <artifactId>netty-all</artifactId> 46 <artifactId>netty-all</artifactId>