优化netty通信的部分代码

This commit is contained in:
seagull 2020-02-26 16:12:43 +08:00
parent a8afbe91bb
commit 55f4fb0489
8 changed files with 93 additions and 80 deletions

23
pom.xml
View File

@ -131,7 +131,7 @@
<artifactId>commons-fileupload</artifactId> <artifactId>commons-fileupload</artifactId>
<version>${commons.fileupload.version}</version> <version>${commons.fileupload.version}</version>
</dependency> </dependency>
<!-- hutool工具包 --> <!-- hutool工具包 -->
<dependency> <dependency>
<groupId>cn.hutool</groupId> <groupId>cn.hutool</groupId>
@ -281,14 +281,23 @@
<groupId>org.flywaydb</groupId> <groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId> <artifactId>flyway-core</artifactId>
</dependency> </dependency>
<!--netty--> <!--netty -->
<dependency> <dependency>
<groupId>io.netty</groupId> <groupId>io.netty</groupId>
<artifactId>netty-all</artifactId> <artifactId>netty-all</artifactId>
<version>5.0.0.Alpha2</version>
</dependency> </dependency>
</dependencies> </dependencies>
<!--排除版本管理警告-->
<dependencyManagement>
<dependencies>
<!--netty-->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>5.0.0.Alpha2</version>
</dependency>
</dependencies>
</dependencyManagement>
<build> <build>
<finalName>${project.artifactId}</finalName> <finalName>${project.artifactId}</finalName>
@ -302,9 +311,9 @@
</plugin> </plugin>
<!-- 数据库版本控制插件 --> <!-- 数据库版本控制插件 -->
<plugin> <plugin>
<groupId>org.flywaydb</groupId> <groupId>org.flywaydb</groupId>
<artifactId>flyway-maven-plugin</artifactId> <artifactId>flyway-maven-plugin</artifactId>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>

View File

@ -1,9 +1,8 @@
package com.luckyframe; package com.luckyframe;
import com.luckyframe.common.netty.NettyServer; import java.net.InetSocketAddress;
import org.mybatis.spring.annotation.MapperScan; import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner; import org.springframework.boot.CommandLineRunner;
@ -12,7 +11,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration; import org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import java.net.InetSocketAddress; import com.luckyframe.common.netty.NettyServer;
/** /**
* 启动LuckyFrameWeb程序 * 启动LuckyFrameWeb程序
@ -37,8 +36,13 @@ public class LuckyFrameWebApplication implements CommandLineRunner
@Autowired @Autowired
private NettyServer server; private NettyServer server;
private static final Logger log = LoggerFactory.getLogger(LuckyFrameWebApplication.class); @Override
public void run(String... args) throws Exception {
InetSocketAddress address = new InetSocketAddress(url,port);
System.out.println("服务端启动成功:"+url+":"+port);
server.start(address);
}
public static void main(String[] args) public static void main(String[] args)
{ {
System.setProperty("spring.devtools.restart.enabled", "false"); System.setProperty("spring.devtools.restart.enabled", "false");
@ -46,13 +50,4 @@ public class LuckyFrameWebApplication implements CommandLineRunner
System.out.println("LuckyFrameWeb启动成功......"); System.out.println("LuckyFrameWeb启动成功......");
} }
@Override
public void run(String... args) throws Exception {
InetSocketAddress address = new InetSocketAddress(url,port);
System.out.println("服务端启动成功:"+url+":"+port);
server.start(address);
}
} }

View File

@ -35,7 +35,7 @@ public class NettyChannelMap {
} }
public void remove(SocketChannel socketChannel){ public void remove(SocketChannel socketChannel){
for (Map.Entry entry:map.entrySet()){ for (@SuppressWarnings("rawtypes") Map.Entry entry:map.entrySet()){
if (entry.getValue()==socketChannel){ if (entry.getValue()==socketChannel){
log.info("#############客户端下线##############"); log.info("#############客户端下线##############");
log.info("下线主机名为:"+entry.getKey()); log.info("下线主机名为:"+entry.getKey());

View File

@ -1,5 +1,16 @@
package com.luckyframe.common.netty; package com.luckyframe.common.netty;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import io.netty.bootstrap.ServerBootstrap; import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel; import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFuture;
@ -7,17 +18,6 @@ import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup; import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.*;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
@Component @Component
public class NettyServer { public class NettyServer {

View File

@ -4,7 +4,12 @@ import java.io.Serializable;
public class Result implements Serializable { public class Result implements Serializable {
private int code; /**
*
*/
private static final long serialVersionUID = 1L;
private int code;
private Object message; private Object message;
private String uniId; private String uniId;

View File

@ -1,5 +1,16 @@
package com.luckyframe.common.netty; package com.luckyframe.common.netty;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.ReentrantLock;
import javax.annotation.Resource;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.luckyframe.common.constant.JobConstants; import com.luckyframe.common.constant.JobConstants;
@ -7,26 +18,17 @@ import com.luckyframe.common.constant.ScheduleConstants;
import com.luckyframe.framework.config.LuckyFrameConfig; import com.luckyframe.framework.config.LuckyFrameConfig;
import com.luckyframe.project.monitor.job.domain.Job; import com.luckyframe.project.monitor.job.domain.Job;
import com.luckyframe.project.monitor.job.mapper.JobMapper; import com.luckyframe.project.monitor.job.mapper.JobMapper;
import com.luckyframe.project.monitor.job.service.IJobService;
import com.luckyframe.project.monitor.job.util.ScheduleUtils; import com.luckyframe.project.monitor.job.util.ScheduleUtils;
import com.luckyframe.project.system.client.domain.Client; import com.luckyframe.project.system.client.domain.Client;
import com.luckyframe.project.system.client.mapper.ClientMapper; import com.luckyframe.project.system.client.mapper.ClientMapper;
import com.luckyframe.project.system.client.service.IClientService; import com.luckyframe.project.system.client.service.IClientService;
import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleState; import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent; import io.netty.handler.timeout.IdleStateEvent;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.ReentrantLock;
@Component("ServerHandler") @Component("ServerHandler")
@ChannelHandler.Sharable @ChannelHandler.Sharable

View File

@ -20,8 +20,7 @@ import com.luckyframe.project.system.client.domain.Client;
import com.luckyframe.project.system.client.service.IClientService; import com.luckyframe.project.system.client.service.IClientService;
/** /**
* 客户端心跳监听 * 客户端心跳监听 =================================================================
* =================================================================
* 这是一个受限制的自由软件您不能在任何未经允许的前提下对程序代码进行修改和用于商业用途也不允许对程序代码修改后以任何形式任何目的的再发布 * 这是一个受限制的自由软件您不能在任何未经允许的前提下对程序代码进行修改和用于商业用途也不允许对程序代码修改后以任何形式任何目的的再发布
* 为了尊重作者的劳动成果LuckyFrame关键版权信息严禁篡改 有任何疑问欢迎联系作者讨论 QQ:1573584944 Seagull * 为了尊重作者的劳动成果LuckyFrame关键版权信息严禁篡改 有任何疑问欢迎联系作者讨论 QQ:1573584944 Seagull
* ================================================================= * =================================================================
@ -33,9 +32,9 @@ import com.luckyframe.project.system.client.service.IClientService;
public class ClientHeart { public class ClientHeart {
@Autowired @Autowired
private IClientService clientService; private IClientService clientService;
@Autowired @Autowired
private LuckyFrameConfig lfConfig; private LuckyFrameConfig lfConfig;
public static ClientHeart clientHeart; public static ClientHeart clientHeart;
@ -64,42 +63,45 @@ public class ClientHeart {
} }
public void heartTask(String params) { public void heartTask(String params) {
try { try {
String result = HttpRequest.httpClientGet( if (!params.contains("netty")) {
"http://" + params + ":" + ClientConstants.CLIENT_MONITOR_PORT + "/getClientStatus", String result = HttpRequest.httpClientGet(
new HashMap<String, Object>(0),3000); "http://" + params + ":" + ClientConstants.CLIENT_MONITOR_PORT + "/getClientStatus",
JSONObject jsonObject = JSON.parseObject(result); new HashMap<String, Object>(0), 3000);
JSONObject jsonObject = JSON.parseObject(result);
if(null==ClientHeart.getClientStatus(params)){
ClientHeart.setClientStatus(params, 1); if (null == ClientHeart.getClientStatus(params)) {
} ClientHeart.setClientStatus(params, 1);
}
if ("success".equals(jsonObject.get("status"))) {
if (ClientHeart.getClientStatus(params) != 0) { if ("success".equals(jsonObject.get("status"))) {
Client client = new Client(); if (ClientHeart.getClientStatus(params) != 0) {
if(lfConfig.getVersion().equals(jsonObject.get("version"))){ Client client = new Client();
if (lfConfig.getVersion().equals(jsonObject.get("version"))) {
client.setClientIp(params);
client.setRemark("检测客户端状态成功");
client.setStatus(0);
clientService.updateClientStatusByIp(client);
} else {
client.setClientIp(params);
client.setRemark(
"客户端(" + jsonObject.get("version") + ")与服务器(" + lfConfig.getVersion() + ")版本不一致");
client.setStatus(1);
clientService.updateClientStatusByIp(client);
}
}
} else {
if (ClientHeart.getClientStatus(params) != 1) {
Client client = new Client();
client.setClientIp(params); client.setClientIp(params);
client.setRemark("检测客户端状态成功"); client.setRemark("客户端返回状态异常");
client.setStatus(0);
clientService.updateClientStatusByIp(client);
}else{
client.setClientIp(params);
client.setRemark("客户端("+jsonObject.get("version")+")与服务器("+lfConfig.getVersion()+")版本不一致");
client.setStatus(1); client.setStatus(1);
clientService.updateClientStatusByIp(client); clientService.updateClientStatusByIp(client);
} }
} }
} else {
if (ClientHeart.getClientStatus(params) != 1) {
Client client = new Client();
client.setClientIp(params);
client.setRemark("客户端返回状态异常");
client.setStatus(1);
clientService.updateClientStatusByIp(client);
}
} }
} catch (RuntimeException | KeyManagementException | NoSuchAlgorithmException | NoHttpResponseException e) { } catch (RuntimeException | KeyManagementException | NoSuchAlgorithmException | NoHttpResponseException e) {
if (null==ClientHeart.getClientStatus(params) || ClientHeart.getClientStatus(params) != 1) { if (null == ClientHeart.getClientStatus(params) || ClientHeart.getClientStatus(params) != 1) {
Client client = new Client(); Client client = new Client();
client.setClientIp(params); client.setClientIp(params);
client.setRemark("检测客户端远程异常"); client.setRemark("检测客户端远程异常");

View File

@ -191,7 +191,7 @@ public class ClientController extends BaseController
if(oldClient!=null&&oldClient.getClientIp().contains("netty")) if(oldClient!=null&&oldClient.getClientIp().contains("netty"))
{ {
if(!oldClient.getClientIp().equals(client.getClientIp())) if(!oldClient.getClientIp().equals(client.getClientIp()))
return error("修改使用Netty方式的客户端请修改客户端配置!"); return error("Netty通信的客户端如需修改客户端IP请在客户端配置!");
} }
for(Integer projectId:client.getProjectIds()){ for(Integer projectId:client.getProjectIds()){
if(!PermissionUtils.isProjectPermsPassByProjectId(projectId)){ if(!PermissionUtils.isProjectPermsPassByProjectId(projectId)){