Commit 81366567 by 叶立庆
2 parents 46365e7a ff393b86
...@@ -29,7 +29,7 @@ public class TimeSettingRspHandler implements TcpHandler<TimeSettingRsp, TimeSet ...@@ -29,7 +29,7 @@ public class TimeSettingRspHandler implements TcpHandler<TimeSettingRsp, TimeSet
.parseCp56Time2aStr(data.getTime()) /* DateUtils.datetimeToStr(ByteUtils.parseCp56Time2a(timeSettingRsp.getData().getTime())) */); .parseCp56Time2aStr(data.getTime()) /* DateUtils.datetimeToStr(ByteUtils.parseCp56Time2a(timeSettingRsp.getData().getTime())) */);
// TODO // TODO
String key = channel.attr(ProxyHelper.PILE_ID_KEY).get() + "+" + rsp.getSeq(); String key = ProxyHelper.getCallbackKey(rsp, channel);
TcpCallback<TcpRsp> callback = ProxyHelper.getCallback(key); TcpCallback<TcpRsp> callback = ProxyHelper.getCallback(key);
callback.callback(rsp); callback.callback(rsp);
......
package cn.com.glsx.charging.modules.gbt.ocpp16.tcp.server; package cn.com.glsx.charging.modules.gbt.ocpp16.tcp.server;
import cn.com.glsx.charging.modules.gbt.ocpp16.tcp.base.TcpBase;
import cn.com.glsx.charging.modules.gbt.ocpp16.tcp.base.TcpCallback; import cn.com.glsx.charging.modules.gbt.ocpp16.tcp.base.TcpCallback;
import cn.com.glsx.charging.modules.gbt.ocpp16.tcp.base.TcpRsp; import cn.com.glsx.charging.modules.gbt.ocpp16.tcp.base.TcpRsp;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
...@@ -174,4 +175,11 @@ public class ProxyHelper { ...@@ -174,4 +175,11 @@ public class ProxyHelper {
public static TcpCallback<TcpRsp> getCallback(String key) { public static TcpCallback<TcpRsp> getCallback(String key) {
return callbackMap.get(key); return callbackMap.get(key);
} }
public static <T extends TcpBase> String getCallbackKey(T data, Channel channel) {
if (channel == null) {
throw new RuntimeException("channel为null!!!");
}
return channel.attr(ProxyHelper.PILE_ID_KEY).get() + "+" + data.getSeq();
}
} }
...@@ -32,185 +32,191 @@ import lombok.extern.slf4j.Slf4j; ...@@ -32,185 +32,191 @@ import lombok.extern.slf4j.Slf4j;
@Setter @Setter
public class TcpServer { public class TcpServer {
public static Integer PROTOCOL_MAX_LENGTH = 200; public static Integer PROTOCOL_MAX_LENGTH = 200;
/** 用于分配处理业务线程的线程组个数 */ /**
protected static final int BIZGROUPSIZE = Runtime.getRuntime().availableProcessors(); // 默认 * 用于分配处理业务线程的线程组个数
/** 业务线程大小 */ */
protected static final int BIZTHREADSIZE = Math.max(Runtime.getRuntime().availableProcessors() * 2, 16); protected static final int BIZGROUPSIZE = Runtime.getRuntime().availableProcessors(); // 默认
/**
private final String host; * 业务线程大小
private final int port; */
protected static final int BIZTHREADSIZE = Math.max(
private final EventLoopGroup bossGroup = new NioEventLoopGroup(BIZGROUPSIZE); Runtime.getRuntime().availableProcessors() * 2, 16);
private final EventLoopGroup workerGroup = new NioEventLoopGroup(BIZTHREADSIZE);
private final String host;
private ServerBootstrap b; private final int port;
private ChannelFuture future;
private ScheduledFuture<?> startFuture; private final EventLoopGroup bossGroup = new NioEventLoopGroup(BIZGROUPSIZE);
private final EventLoopGroup workerGroup = new NioEventLoopGroup(BIZTHREADSIZE);
public TcpServer(String host, int port) {
this.host = host; private ServerBootstrap b;
this.port = port; private ChannelFuture future;
private ScheduledFuture<?> startFuture;
b = new ServerBootstrap();
b.group(bossGroup, workerGroup); public TcpServer(String host, int port) {
b.channel(NioServerSocketChannel.class); this.host = host;
b.childHandler(new ChannelInitializer<SocketChannel>() { this.port = port;
@Override
public void initChannel(SocketChannel ch) throws Exception { b = new ServerBootstrap();
ChannelPipeline pipeline = ch.pipeline(); b.group(bossGroup, workerGroup);
b.channel(NioServerSocketChannel.class);
pipeline.addLast("lengthDecoder", new LengthFieldBasedFrameDecoder(PROTOCOL_MAX_LENGTH, 1, 1, 2, 0)); b.childHandler(new ChannelInitializer<SocketChannel>() {
pipeline.addLast("decoder", new ByteArrayDecoder()); @Override
pipeline.addLast("encoder", new ByteArrayEncoder()); public void initChannel(SocketChannel ch) throws Exception {
pipeline.addLast("handler", new TcpServerHandler()); ChannelPipeline pipeline = ch.pipeline();
}
}); pipeline.addLast("lengthDecoder",
} new LengthFieldBasedFrameDecoder(PROTOCOL_MAX_LENGTH, 1, 1, 2, 0));
pipeline.addLast("decoder", new ByteArrayDecoder());
public boolean isActive() { pipeline.addLast("encoder", new ByteArrayEncoder());
return future != null && future.channel() != null && future.channel().isActive(); pipeline.addLast("handler", new TcpServerHandler());
} }
});
public void start() { }
startFuture = TaskExecutor.addTask(new Task() {
@Override public boolean isActive() {
public void execute() throws Exception { return future != null && future.channel() != null && future.channel().isActive();
try { }
if (isActive()) {
return; public void start() {
} startFuture = TaskExecutor.addTask(new Task() {
@Override
Thread.sleep(3000); public void execute() throws Exception {
if (future == null) { try {
log.info("【{}】开始启动TCP服务器......", port); if (isActive()) {
} else { return;
log.info("【{}】重启TCP服务器......", port); }
}
future = b.bind(port).sync(); Thread.sleep(3000);
log.info("【{}】成功启动TCP服务器......", port); if (future == null) {
} catch (Exception e) { log.info("【{}】开始启动TCP服务器......", port);
log.info("{}:{}", host, port, e); } else {
} log.info("【{}】重启TCP服务器......", port);
} }
}, 3 * 1000, 20 * 1000); future = b.bind(port).sync();
} log.info("【{}】成功启动TCP服务器......", port);
} catch (Exception e) {
public void shutdown() throws Exception { log.info("{}:{}", host, port, e);
if (startFuture != null) { }
startFuture.cancel(true); }
} }, 3 * 1000, 20 * 1000);
}
workerGroup.shutdownGracefully().sync();
bossGroup.shutdownGracefully().sync(); public void shutdown() throws Exception {
if (startFuture != null) {
if (future != null) { startFuture.cancel(true);
future.channel().parent().close().sync(); }
}
log.info("【{}】关闭TCP服务器!!!!!!", port); workerGroup.shutdownGracefully().sync();
} bossGroup.shutdownGracefully().sync();
@SuppressWarnings({ "rawtypes" }) if (future != null) {
public <T extends TcpBase> TcpCallback<TcpRsp> sendSync(T data) { future.channel().parent().close().sync();
ProxyInfo proxyInfo = ProxyHelper.getProxyInfo(data.getData().getPileIdStr()); }
String ip=proxyInfo.getIp(); log.info("【{}】关闭TCP服务器!!!!!!", port);
// seq字段处理 }
String seqKey = ip;
if (data.getData() != null) { @SuppressWarnings({"rawtypes"})
seqKey = data.getData().getPileIdStr(); public <T extends TcpBase> TcpCallback<TcpRsp> sendSync(T data) {
} ProxyInfo proxyInfo = ProxyHelper.getProxyInfo(data.getData().getPileIdStr());
data.setSeq(Ocpp16Helper.generateSeq(seqKey)); String ip = proxyInfo.getIp();
// seq字段处理
byte[] bs = Ocpp16Helper.build(data); String seqKey = ip;
log.info("【{}】读取proxyInfo:{}", data.getData().getPileIdStr(), proxyInfo); if (data.getData() != null) {
String key = proxyInfo.getChannel().attr(ProxyHelper.PILE_ID_KEY).get() + "+" + data.getSeq(); seqKey = data.getData().getPileIdStr();
TcpCallback<TcpRsp> callback = new TcpCallback<>(TcpRsp.class); }
ProxyHelper.addCallback(key, callback); data.setSeq(Ocpp16Helper.generateSeq(seqKey));
sendSync(bs, proxyInfo.getChannel()); byte[] bs = Ocpp16Helper.build(data);
log.info("【{}】读取proxyInfo:{}", data.getData().getPileIdStr(), proxyInfo);
log.info("【{}】【{}】send1: {} ", ip, data.getClass().getSimpleName(), ByteUtils.toHex(bs)); String key = ProxyHelper.getCallbackKey(data, proxyInfo.getChannel());
log.info("【{}】【{}】send2: {} ", ip, data.getClass().getSimpleName(), data); TcpCallback<TcpRsp> callback = new TcpCallback<>(TcpRsp.class);
ProxyHelper.addCallback(key, callback);
return callback;
} sendSync(bs, proxyInfo.getChannel());
private void sendSync(byte[] bs, Channel channel) { log.info("【{}】【{}】send1: {} ", ip, data.getClass().getSimpleName(), ByteUtils.toHex(bs));
try { log.info("【{}】【{}】send2: {} ", ip, data.getClass().getSimpleName(), data);
if (channel == null ) {
log.info("channel null ..."); return callback;
return; }
}
channel.writeAndFlush(bs); private void sendSync(byte[] bs, Channel channel) {
} catch (Exception e) { try {
log.error("" + bs, e); if (channel == null) {
} log.info("channel null ...");
} return;
}
private void sendSync(byte[] bytes) { channel.writeAndFlush(bs);
try { } catch (Exception e) {
if (future == null || future.channel() == null) { log.error("" + bs, e);
log.info("future null ..."); }
return; }
}
future.channel().writeAndFlush(bytes); private void sendSync(byte[] bytes) {
} catch (Exception e) { try {
log.error("" + bytes, e); if (future == null || future.channel() == null) {
} log.info("future null ...");
} return;
}
@Override future.channel().writeAndFlush(bytes);
protected void finalize() throws Throwable { } catch (Exception e) {
super.finalize(); log.error("" + bytes, e);
shutdown(); }
} }
public static String getIp(ChannelHandlerContext ctx) { @Override
return getIp(ctx.channel()); protected void finalize() throws Throwable {
} super.finalize();
shutdown();
public static String getIp(Channel channel) { }
String ip = ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress();
return ip; public static String getIp(ChannelHandlerContext ctx) {
} return getIp(ctx.channel());
}
// public static Queue<TcpNotify> notifys = new LinkedBlockingQueue<>(1000);
// private static boolean notifyLock = false; public static String getIp(Channel channel) {
// String ip = ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress();
// public static void startNotify() { return ip;
// if (notifyLock) { }
// return;
// } // public static Queue<TcpNotify> notifys = new LinkedBlockingQueue<>(1000);
// org.glsx.wxwork.task.TaskExecutor.addTask(new Task() { // private static boolean notifyLock = false;
// //
// @Override // public static void startNotify() {
// public void execute() throws Exception { // if (notifyLock) {
// notifyLock = true; // return;
// // }
// try { // org.glsx.wxwork.task.TaskExecutor.addTask(new Task() {
// KafkaTemplate<String, String> kafkaTemplate = ApplicationContextHolder.popBean(KafkaTemplate.class); //
// if (kafkaTemplate == null) { // @Override
// return; // public void execute() throws Exception {
// } // notifyLock = true;
// //
// while (!notifys.isEmpty() && ClientMain.getInstance().isActive()) { // try {
// try { // KafkaTemplate<String, String> kafkaTemplate = ApplicationContextHolder.popBean(KafkaTemplate.class);
// TcpNotify notify = notifys.poll(); // if (kafkaTemplate == null) {
// log.info("【{}】{} doNotify remain:{}", notify.getClass().getSimpleName(), notify.getData().getClass().getSimpleName(), // return;
// notifys.size()); // }
// //
// if (notify != null && notify.getNotifyKey() != null) { // while (!notifys.isEmpty() && ClientMain.getInstance().isActive()) {
// kafkaTemplate.send(notify.getNotifyKey(), JacksonUtils.toJson(notify)); // try {
// } // TcpNotify notify = notifys.poll();
// } catch (Exception e) { // log.info("【{}】{} doNotify remain:{}", notify.getClass().getSimpleName(), notify.getData().getClass().getSimpleName(),
// e.printStackTrace(); // notifys.size());
// } //
// } // if (notify != null && notify.getNotifyKey() != null) {
// } finally { // kafkaTemplate.send(notify.getNotifyKey(), JacksonUtils.toJson(notify));
// notifyLock = false; // }
// } // } catch (Exception e) {
// } // e.printStackTrace();
// }, 3 * 1000); // }
// } // }
// } finally {
// notifyLock = false;
// }
// }
// }, 3 * 1000);
// }
} }
...@@ -54,11 +54,11 @@ public class TimeSettingTest { ...@@ -54,11 +54,11 @@ public class TimeSettingTest {
req.setData(data); req.setData(data);
Thread.sleep(30000); Thread.sleep(20000);
TcpCallback<TcpRsp> callback = tcpServer.sendSync(req); TcpCallback<TcpRsp> callback = tcpServer.sendSync(req);
Thread.sleep(30000); Thread.sleep(10000);
TcpRsp rsp = callback.get(); TcpRsp rsp = callback.get();
log.info("callback{}",req); log.info("callback{}",req);
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!