Commit 1182ce13 authored by duanruiming's avatar duanruiming

[update] 代码优化

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