Commit 81366567 by 叶立庆
2 parents 46365e7a ff393b86
......@@ -29,7 +29,7 @@ public class TimeSettingRspHandler implements TcpHandler<TimeSettingRsp, TimeSet
.parseCp56Time2aStr(data.getTime()) /* DateUtils.datetimeToStr(ByteUtils.parseCp56Time2a(timeSettingRsp.getData().getTime())) */);
// TODO
String key = channel.attr(ProxyHelper.PILE_ID_KEY).get() + "+" + rsp.getSeq();
String key = ProxyHelper.getCallbackKey(rsp, channel);
TcpCallback<TcpRsp> callback = ProxyHelper.getCallback(key);
callback.callback(rsp);
......
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.TcpRsp;
import java.net.InetSocketAddress;
......@@ -174,4 +175,11 @@ public class ProxyHelper {
public static TcpCallback<TcpRsp> getCallback(String 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;
@Setter
public class TcpServer {
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);
private final String host;
private final int port;
private final EventLoopGroup bossGroup = new NioEventLoopGroup(BIZGROUPSIZE);
private final EventLoopGroup workerGroup = new NioEventLoopGroup(BIZTHREADSIZE);
private ServerBootstrap b;
private ChannelFuture future;
private ScheduledFuture<?> startFuture;
public TcpServer(String host, int port) {
this.host = host;
this.port = port;
b = new ServerBootstrap();
b.group(bossGroup, workerGroup);
b.channel(NioServerSocketChannel.class);
b.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("lengthDecoder", new LengthFieldBasedFrameDecoder(PROTOCOL_MAX_LENGTH, 1, 1, 2, 0));
pipeline.addLast("decoder", new ByteArrayDecoder());
pipeline.addLast("encoder", new ByteArrayEncoder());
pipeline.addLast("handler", new TcpServerHandler());
}
});
}
public boolean isActive() {
return future != null && future.channel() != null && future.channel().isActive();
}
public void start() {
startFuture = TaskExecutor.addTask(new Task() {
@Override
public void execute() throws Exception {
try {
if (isActive()) {
return;
}
Thread.sleep(3000);
if (future == null) {
log.info("【{}】开始启动TCP服务器......", port);
} else {
log.info("【{}】重启TCP服务器......", port);
}
future = b.bind(port).sync();
log.info("【{}】成功启动TCP服务器......", port);
} catch (Exception e) {
log.info("{}:{}", host, port, e);
}
}
}, 3 * 1000, 20 * 1000);
}
public void shutdown() throws Exception {
if (startFuture != null) {
startFuture.cancel(true);
}
workerGroup.shutdownGracefully().sync();
bossGroup.shutdownGracefully().sync();
if (future != null) {
future.channel().parent().close().sync();
}
log.info("【{}】关闭TCP服务器!!!!!!", port);
}
@SuppressWarnings({ "rawtypes" })
public <T extends TcpBase> TcpCallback<TcpRsp> sendSync(T data) {
ProxyInfo proxyInfo = ProxyHelper.getProxyInfo(data.getData().getPileIdStr());
String ip=proxyInfo.getIp();
// seq字段处理
String seqKey = ip;
if (data.getData() != null) {
seqKey = data.getData().getPileIdStr();
}
data.setSeq(Ocpp16Helper.generateSeq(seqKey));
byte[] bs = Ocpp16Helper.build(data);
log.info("【{}】读取proxyInfo:{}", data.getData().getPileIdStr(), proxyInfo);
String key = proxyInfo.getChannel().attr(ProxyHelper.PILE_ID_KEY).get() + "+" + data.getSeq();
TcpCallback<TcpRsp> callback = new TcpCallback<>(TcpRsp.class);
ProxyHelper.addCallback(key, callback);
sendSync(bs, proxyInfo.getChannel());
log.info("【{}】【{}】send1: {} ", ip, data.getClass().getSimpleName(), ByteUtils.toHex(bs));
log.info("【{}】【{}】send2: {} ", ip, data.getClass().getSimpleName(), data);
return callback;
}
private void sendSync(byte[] bs, Channel channel) {
try {
if (channel == null ) {
log.info("channel null ...");
return;
}
channel.writeAndFlush(bs);
} catch (Exception e) {
log.error("" + bs, e);
}
}
private void sendSync(byte[] bytes) {
try {
if (future == null || future.channel() == null) {
log.info("future null ...");
return;
}
future.channel().writeAndFlush(bytes);
} catch (Exception e) {
log.error("" + bytes, e);
}
}
@Override
protected void finalize() throws Throwable {
super.finalize();
shutdown();
}
public static String getIp(ChannelHandlerContext ctx) {
return getIp(ctx.channel());
}
public static String getIp(Channel channel) {
String ip = ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress();
return ip;
}
// public static Queue<TcpNotify> notifys = new LinkedBlockingQueue<>(1000);
// private static boolean notifyLock = false;
//
// public static void startNotify() {
// if (notifyLock) {
// return;
// }
// org.glsx.wxwork.task.TaskExecutor.addTask(new Task() {
//
// @Override
// public void execute() throws Exception {
// notifyLock = true;
//
// try {
// KafkaTemplate<String, String> kafkaTemplate = ApplicationContextHolder.popBean(KafkaTemplate.class);
// if (kafkaTemplate == null) {
// return;
// }
//
// while (!notifys.isEmpty() && ClientMain.getInstance().isActive()) {
// try {
// TcpNotify notify = notifys.poll();
// log.info("【{}】{} doNotify remain:{}", notify.getClass().getSimpleName(), notify.getData().getClass().getSimpleName(),
// notifys.size());
//
// if (notify != null && notify.getNotifyKey() != null) {
// kafkaTemplate.send(notify.getNotifyKey(), JacksonUtils.toJson(notify));
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// } finally {
// notifyLock = false;
// }
// }
// }, 3 * 1000);
// }
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);
private final String host;
private final int port;
private final EventLoopGroup bossGroup = new NioEventLoopGroup(BIZGROUPSIZE);
private final EventLoopGroup workerGroup = new NioEventLoopGroup(BIZTHREADSIZE);
private ServerBootstrap b;
private ChannelFuture future;
private ScheduledFuture<?> startFuture;
public TcpServer(String host, int port) {
this.host = host;
this.port = port;
b = new ServerBootstrap();
b.group(bossGroup, workerGroup);
b.channel(NioServerSocketChannel.class);
b.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("lengthDecoder",
new LengthFieldBasedFrameDecoder(PROTOCOL_MAX_LENGTH, 1, 1, 2, 0));
pipeline.addLast("decoder", new ByteArrayDecoder());
pipeline.addLast("encoder", new ByteArrayEncoder());
pipeline.addLast("handler", new TcpServerHandler());
}
});
}
public boolean isActive() {
return future != null && future.channel() != null && future.channel().isActive();
}
public void start() {
startFuture = TaskExecutor.addTask(new Task() {
@Override
public void execute() throws Exception {
try {
if (isActive()) {
return;
}
Thread.sleep(3000);
if (future == null) {
log.info("【{}】开始启动TCP服务器......", port);
} else {
log.info("【{}】重启TCP服务器......", port);
}
future = b.bind(port).sync();
log.info("【{}】成功启动TCP服务器......", port);
} catch (Exception e) {
log.info("{}:{}", host, port, e);
}
}
}, 3 * 1000, 20 * 1000);
}
public void shutdown() throws Exception {
if (startFuture != null) {
startFuture.cancel(true);
}
workerGroup.shutdownGracefully().sync();
bossGroup.shutdownGracefully().sync();
if (future != null) {
future.channel().parent().close().sync();
}
log.info("【{}】关闭TCP服务器!!!!!!", port);
}
@SuppressWarnings({"rawtypes"})
public <T extends TcpBase> TcpCallback<TcpRsp> sendSync(T data) {
ProxyInfo proxyInfo = ProxyHelper.getProxyInfo(data.getData().getPileIdStr());
String ip = proxyInfo.getIp();
// seq字段处理
String seqKey = ip;
if (data.getData() != null) {
seqKey = data.getData().getPileIdStr();
}
data.setSeq(Ocpp16Helper.generateSeq(seqKey));
byte[] bs = Ocpp16Helper.build(data);
log.info("【{}】读取proxyInfo:{}", data.getData().getPileIdStr(), proxyInfo);
String key = ProxyHelper.getCallbackKey(data, proxyInfo.getChannel());
TcpCallback<TcpRsp> callback = new TcpCallback<>(TcpRsp.class);
ProxyHelper.addCallback(key, callback);
sendSync(bs, proxyInfo.getChannel());
log.info("【{}】【{}】send1: {} ", ip, data.getClass().getSimpleName(), ByteUtils.toHex(bs));
log.info("【{}】【{}】send2: {} ", ip, data.getClass().getSimpleName(), data);
return callback;
}
private void sendSync(byte[] bs, Channel channel) {
try {
if (channel == null) {
log.info("channel null ...");
return;
}
channel.writeAndFlush(bs);
} catch (Exception e) {
log.error("" + bs, e);
}
}
private void sendSync(byte[] bytes) {
try {
if (future == null || future.channel() == null) {
log.info("future null ...");
return;
}
future.channel().writeAndFlush(bytes);
} catch (Exception e) {
log.error("" + bytes, e);
}
}
@Override
protected void finalize() throws Throwable {
super.finalize();
shutdown();
}
public static String getIp(ChannelHandlerContext ctx) {
return getIp(ctx.channel());
}
public static String getIp(Channel channel) {
String ip = ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress();
return ip;
}
// public static Queue<TcpNotify> notifys = new LinkedBlockingQueue<>(1000);
// private static boolean notifyLock = false;
//
// public static void startNotify() {
// if (notifyLock) {
// return;
// }
// org.glsx.wxwork.task.TaskExecutor.addTask(new Task() {
//
// @Override
// public void execute() throws Exception {
// notifyLock = true;
//
// try {
// KafkaTemplate<String, String> kafkaTemplate = ApplicationContextHolder.popBean(KafkaTemplate.class);
// if (kafkaTemplate == null) {
// return;
// }
//
// while (!notifys.isEmpty() && ClientMain.getInstance().isActive()) {
// try {
// TcpNotify notify = notifys.poll();
// log.info("【{}】{} doNotify remain:{}", notify.getClass().getSimpleName(), notify.getData().getClass().getSimpleName(),
// notifys.size());
//
// if (notify != null && notify.getNotifyKey() != null) {
// kafkaTemplate.send(notify.getNotifyKey(), JacksonUtils.toJson(notify));
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// } finally {
// notifyLock = false;
// }
// }
// }, 3 * 1000);
// }
}
......@@ -54,11 +54,11 @@ public class TimeSettingTest {
req.setData(data);
Thread.sleep(30000);
Thread.sleep(20000);
TcpCallback<TcpRsp> callback = tcpServer.sendSync(req);
Thread.sleep(30000);
Thread.sleep(10000);
TcpRsp rsp = callback.get();
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!