Commit 1182ce13 authored by duanruiming's avatar duanruiming

[update] 代码优化

parent 1acb0431
......@@ -2,14 +2,11 @@ package net.wanji.com;
import net.wanji.com.netty.NettyClient;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
......@@ -22,9 +19,6 @@ import org.springframework.transaction.annotation.EnableTransactionManagement;
@EnableScheduling
@SuppressWarnings("all")
public class Application implements CommandLineRunner {
@Qualifier(value = "threadPoolExecutor")
@Autowired
ThreadPoolTaskExecutor threadPoolExecutor;
@Value("${portParam.localPort}")
int localPort;
@Value("${portParam.remotePort}")
......@@ -36,6 +30,6 @@ public class Application implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
NettyClient.start(localPort, remoteProt, threadPoolExecutor);
NettyClient.start(localPort, remoteProt);
}
}
......@@ -65,7 +65,7 @@ public class StaticInfoController {
@ApiResponse(code = 200, message = "OK", response = SchemePhaseLightsVO.class)
})
public JsonViewObject schemePhaseLights(@RequestBody @Validated SchemePhaseLightsDTO schemePhaseLightsDTO) throws Exception {
// 更新数据库
// 命令调用
staticInfoService.schemePhaseLights(schemePhaseLightsDTO);
// 构造返回值
SchemePhaseLightsVO schemePhaseLightsVO = staticInfoService.buildSchemePhaseLightsResponse(schemePhaseLightsDTO);
......@@ -83,7 +83,7 @@ public class StaticInfoController {
@ApiResponse(code = 200, message = "OK", response = PlanSectionVO.class)
})
public JsonViewObject planSection(@RequestBody @Validated PlanSectionDTO planSectionDTO) throws Exception {
// 更新数据库
// 命令调用
staticInfoService.planSection(planSectionDTO);
// 构造返回值
String crossId = planSectionDTO.getCrossId();
......@@ -110,7 +110,7 @@ public class StaticInfoController {
@ApiResponse(code = 200, message = "OK", response = CrossSchedulesPO.class)
})
public JsonViewObject crossSchedules(@RequestBody @Validated CrossSchedulesDTO crossSchedulesDTO) throws Exception {
// 更新数据库
// 命令调用
staticInfoService.crossSchedules(crossSchedulesDTO);
// 构造返回值
List<String> crossIdList = crossSchedulesDTO.getCrossIdList();
......
......@@ -19,32 +19,30 @@ import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.net.InetSocketAddress;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@Slf4j
@Component
public class NettyClient {
private static final Map<String, ChannelId> IP_PORT_CHANNEL_ID_MAP = new HashMap<>();
private static ChannelFuture udpChannelFuture = null;
@Resource(name = "threadPoolExecutor")
private ThreadPoolTaskExecutor threadPoolExecutor;
/**
* 建立连接
*/
public static void start(int localPort, int remotePort, ThreadPoolTaskExecutor threadPoolExecutor) throws InterruptedException {
public static void start(int localPort, int remotePort) throws InterruptedException {
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioDatagramChannel.class)
.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(65535))
// .localAddress(new InetSocketAddress(5051))
// 绑定端口
.localAddress(new InetSocketAddress(localPort))
.remoteAddress(new InetSocketAddress(remotePort))
.handler(new ChannelInitializer<NioDatagramChannel>() {
@Override
......@@ -55,13 +53,13 @@ public class NettyClient {
.addLast(new NettyServerHandler());
}
});
ChannelFuture channelFuture = bootstrap.bind(localPort).sync();
ChannelFuture channelFuture = bootstrap.bind().sync();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
group.shutdownGracefully();
channelFuture.channel().closeFuture().syncUninterruptibly();
log.warn("server is closed");
log.warn("udp服务关闭!");
}));
log.info("udp application is running. binding port is {}", remotePort);
log.info("udp服务正在运行,端口:{}", remotePort);
NettyClient.udpChannelFuture = channelFuture;
}
......@@ -73,7 +71,7 @@ public class NettyClient {
}
udpChannelFuture.channel()
.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(bytes), new InetSocketAddress(ip, port))).sync();
log.info("send msg {} to {}/{}", msg, ip, port);
log.info("发送信号机:{}/{}命令消息:{}", ip, port, msg);
} catch (InterruptedException e) {
log.error("sendMsg is error", e);
}
......@@ -101,12 +99,12 @@ public class NettyClient {
public void checkWaitTimeout() {
long now = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
NettyMessageCache.NETTY_MESSAGE_RESULT_MAP.forEach((k, v) -> {
// threadPoolExecutor.execute(() -> {
if (now - v.getStartTime() > v.getWaitMillisecond()) {
log.warn("wait {}ms {} timeout", v.getWaitMillisecond(), k);
v.getCountDownLatch().countDown();
}
threadPoolExecutor.execute(() -> {
if (now - v.getStartTime() > v.getWaitMillisecond()) {
log.warn("wait {}ms {} timeout", v.getWaitMillisecond(), k);
v.getCountDownLatch().countDown();
}
});
});
// });
}
}
\ No newline at end of file
......@@ -51,7 +51,7 @@ public class NettyServerHandler extends SimpleChannelInboundHandler<DatagramPack
String data = HexUtil.encodeHexStr(b);
String hexSign = CommandResultSign.getHexSign(data);
if (StringUtils.isEmpty(hexSign)) {
log.error("data unique hex sign error");
log.error("返回命令标识为空hexSign: {}", hexSign);
return;
}
String className = getClassNameByHexSign(hexSign);
......
......@@ -20,7 +20,7 @@ public class HeartBeatService implements CommandResponseService {
return commandPojo.getResponseMsg();
}
@Scheduled(fixedRate = 1000)
@Scheduled(fixedRate = 1000, initialDelay = 10 * 1000)
public void heartbeat() {
// String body = String.format("%02x", Constants.COMMAND_HEARTBEAT.length() / 2).concat(Constants.COMMAND_HEARTBEAT);
// String crc16HexStr = CRC16Utils.getCRC16HexStr(body);
......
package net.wanji.com.service.controller.impl;
import net.wanji.com.netty.NettyClient;
import net.wanji.com.pojo.netty.MessageResultPojo;
import net.wanji.com.service.controller.ControlCommandService;
import net.wanji.common.enums.BaseEnum;
import net.wanji.common.framework.rest.JsonViewObject;
......@@ -20,6 +22,8 @@ public class DTControlCommandServiceImpl implements ControlCommandService {
@Override
public JsonViewObject schemeSend(SchemeSendVO schemeSendVO) throws Exception {
String hex = "";
MessageResultPojo resultPojo = NettyClient.sendMessage("ip", 5050, hex, "aabb", 300);
return null;
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment