Compare commits

...

2 Commits

Author SHA1 Message Date
0bedcf366e 优化:1、rpc调用优先调用本地订阅
2、本地模式返回结果与目标类型不一致的转换
2024-04-09 02:06:23 +08:00
af44804282 新增:IType(SHORT、LONG、DOUBLE) 2024-04-08 22:35:55 +08:00
9 changed files with 336 additions and 305 deletions

View File

@ -6,7 +6,7 @@
<groupId>net.tccn</groupId> <groupId>net.tccn</groupId>
<artifactId>zhub-client-spring</artifactId> <artifactId>zhub-client-spring</artifactId>
<version>0.1.3.dev</version> <version>17.0.0409.dev</version>
<parent> <parent>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>

View File

@ -8,6 +8,7 @@ import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer; import java.util.function.Consumer;
/** /**
@ -18,7 +19,7 @@ public abstract class AbstractConsumer implements IConsumer {
public Gson gson = Rpc.gson; public Gson gson = Rpc.gson;
private Map<String, EventType> eventMap = new HashMap<>(); protected Map<String, EventType<?>> eventMap = new ConcurrentHashMap<>();
protected abstract String getGroupid(); protected abstract String getGroupid();
@ -36,6 +37,7 @@ public abstract class AbstractConsumer implements IConsumer {
return set; return set;
} }
// topic 消息消费前处理
protected void accept(String topic, String value) { protected void accept(String topic, String value) {
EventType eventType = eventMap.get(topic); EventType eventType = eventMap.get(topic);
@ -49,6 +51,19 @@ public abstract class AbstractConsumer implements IConsumer {
eventType.accept(data); eventType.accept(data);
} }
// rpc 被调用端
protected <T> void rpcAccept(String topic, T value) {
EventType eventType = eventMap.get(topic);
/*// eventType T 的类型比较
if (!eventType.typeToken.getType().getTypeName().equals(value.getClass().getTypeName())) {
eventType.accept(toStr(value));
} else {
eventType.accept(value);
}*/
eventType.accept(value);
}
protected final void removeEventType(String topic) { protected final void removeEventType(String topic) {
eventMap.remove(topic); eventMap.remove(topic);
} }
@ -76,4 +91,13 @@ public abstract class AbstractConsumer implements IConsumer {
} }
} }
protected String toStr(Object v) {
if (v instanceof String) {
return (String) v;
} else if (v == null) {
return null;
}
return gson.toJson(v);
}
} }

View File

@ -15,9 +15,8 @@ public class Event<V> {
this.value = value; this.value = value;
} }
public static <V> Event of(String topic, V value) { public static <V> Event<V> of(String topic, V value) {
return new Event<V>(topic, value); return new Event<>(topic, value);
} }
} }

View File

@ -7,13 +7,19 @@ import java.util.Map;
public interface IType { public interface IType {
TypeToken<String> STRING = new TypeToken<String>() { TypeToken<String> STRING = new TypeToken<>() {
}; };
TypeToken<Integer> INT = new TypeToken<Integer>() { TypeToken<Short> SHORT = new TypeToken<>() {
};
TypeToken<Integer> INT = new TypeToken<>() {
};
TypeToken<Long> LONG = new TypeToken<>() {
};
TypeToken<Double> DOUBLE = new TypeToken<>() {
}; };
TypeToken<Map<String, String>> MAP = new TypeToken<Map<String, String>>() { TypeToken<Map<String, String>> MAP = new TypeToken<>() {
}; };
TypeToken<List<Map<String, String>>> LMAP = new TypeToken<List<Map<String, String>>>() { TypeToken<List<Map<String, String>>> LMAP = new TypeToken<List<Map<String, String>>>() {

View File

@ -24,7 +24,7 @@ public class TimerExecutor {
for (Task t : task) { for (Task t : task) {
t.setTimerExecutor(this); t.setTimerExecutor(this);
queue.push(t); queue.push(t);
logger.finest("add new task : " + t.getName()); // logger.finest("add new task : " + t.getName());
} }
} }

View File

@ -93,10 +93,10 @@ public class TimerTask implements Task {
if (!isComplete) { if (!isComplete) {
int count = execCount.incrementAndGet(); // 执行次数+1 int count = execCount.incrementAndGet(); // 执行次数+1
long start = System.currentTimeMillis(); // long start = System.currentTimeMillis();
job.execute(this); job.execute(this);
long end = System.currentTimeMillis(); // long end = System.currentTimeMillis();
logger.finest(String.format("task [%s] : not complete -> %s, time: %s ms, exec count: %s.", getName(), isComplete ? "had complete" : "not complete", end - start, count)); // logger.finest(String.format("task [%s] : not complete -> %s, time: %s ms, exec count: %s.", getName(), isComplete ? "had complete" : "not complete", end - start, count));
if (!isComplete) { if (!isComplete) {
timerExecutor.add(this, true); timerExecutor.add(this, true);

View File

@ -2,7 +2,14 @@ package tccn.zhub;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.annotations.Expose; import com.google.gson.annotations.Expose;
import com.google.gson.reflect.TypeToken;
import lombok.Getter;
import lombok.Setter;
import java.util.UUID;
@Getter
@Setter
public class Rpc<T> { public class Rpc<T> {
/*public final static Gson gson = new GsonBuilder() /*public final static Gson gson = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation() .excludeFieldsWithoutExposeAnnotation()
@ -16,48 +23,18 @@ public class Rpc<T> {
@Expose(deserialize = false, serialize = false) @Expose(deserialize = false, serialize = false)
private RpcResult rpcResult; private RpcResult rpcResult;
public Rpc() { @Expose(deserialize = false, serialize = false)
} private TypeToken typeToken;
public Rpc(String appname, String ruk, String topic, Object value) { /*public Rpc() {
this.ruk = appname + "::" + ruk; }*/
protected Rpc(String appname, String topic, T value) {
this.ruk = appname + "::" + UUID.randomUUID().toString().replaceAll("-", "");
this.topic = topic; this.topic = topic;
this.value = (T) gson.toJson(value);
}
public String getRuk() {
return ruk;
}
public void setRuk(String ruk) {
this.ruk = ruk;
}
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value; this.value = value;
} }
public RpcResult getRpcResult() {
return rpcResult;
}
public void setRpcResult(RpcResult rpcResult) {
this.rpcResult = rpcResult;
}
public String getBackTopic() { public String getBackTopic() {
return ruk.split("::")[0]; return ruk.split("::")[0];
} }

View File

@ -34,7 +34,7 @@ public class RpcResult<R> {
return result; return result;
} }
public void setResult(R result) { public void setResult(Object result) {
this.result = result; this.result = (R) result;
} }
} }

View File

@ -5,10 +5,7 @@ import jakarta.annotation.PostConstruct;
import lombok.Setter; import lombok.Setter;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import tccn.AbstractConsumer; import tccn.*;
import tccn.Event;
import tccn.IConsumer;
import tccn.IProducer;
import tccn.timer.Timers; import tccn.timer.Timers;
import java.io.BufferedReader; import java.io.BufferedReader;
@ -18,14 +15,8 @@ import java.io.OutputStream;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.net.Socket; import java.net.Socket;
import java.net.SocketException; import java.net.SocketException;
import java.util.HashMap; import java.util.*;
import java.util.HashSet; import java.util.concurrent.*;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.function.BiConsumer;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.Function; import java.util.function.Function;
import java.util.logging.Level; import java.util.logging.Level;
@ -53,26 +44,20 @@ public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer
init(null); init(null);
} }
private Socket client;
private OutputStream writer; private OutputStream writer;
private BufferedReader reader; private BufferedReader reader;
private final LinkedBlockingQueue<Timer> timerQueue = new LinkedBlockingQueue<>(); private final LinkedBlockingQueue<Timer> timerQueue = new LinkedBlockingQueue<>();
private final LinkedBlockingQueue<Event<String>> topicQueue = new LinkedBlockingQueue<>(); private final LinkedBlockingQueue<Event<String>> topicQueue = new LinkedBlockingQueue<>();
private final LinkedBlockingQueue<Event<String>> rpcBackQueue = new LinkedBlockingQueue<>(); // RPC BACK MSG private final LinkedBlockingQueue<Event<Object>> rpcBackQueue = new LinkedBlockingQueue<>(); // RPC BACK MSG [=> Object]
private final LinkedBlockingQueue<Event<String>> rpcCallQueue = new LinkedBlockingQueue<>(); // RPC CALL MSG private final LinkedBlockingQueue<Event<Object>> rpcCallQueue = new LinkedBlockingQueue<>(); // RPC CALL MSG [=> Object]
private final LinkedBlockingQueue<String> sendMsgQueue = new LinkedBlockingQueue<>(); // SEND MSG private final LinkedBlockingQueue<String> sendMsgQueue = new LinkedBlockingQueue<>(); // SEND MSG
private final BiConsumer<Runnable, Integer> threadBuilder = (r, n) -> { private static Map<String, ZHubClient> mainHub = new HashMap<>(); // 127.0.0.1:1216 - ZHubClient
for (int i = 0; i < n; i++) {
new Thread(() -> r.run()).start();
}
};
/*private static boolean isFirst = true;
private boolean isMain = false;*/
private static final Map<String, ZHubClient> mainHub = new HashMap<>(); // 127.0.0.1:1216 - ZHubClient
public ZHubClient() { public ZHubClient() {
} }
public ZHubClient(String addr, String groupid, String appid, String auth) { public ZHubClient(String addr, String groupid, String appid, String auth) {
@ -96,14 +81,11 @@ public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer
} }
// 设置第一个启动的 实例为主实例 // 设置第一个启动的 实例为主实例
/*if (isFirst) {
isMain = true;
isFirst = false;
}*/
if (!mainHub.containsKey(addr)) { // 确保同步执行此 init 逻辑 if (!mainHub.containsKey(addr)) { // 确保同步执行此 init 逻辑
mainHub.put(addr, this); mainHub.put(addr, this);
} }
CompletableFuture.runAsync(() -> {
if (!initSocket(0)) { if (!initSocket(0)) {
return; return;
} }
@ -116,7 +98,7 @@ public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer
continue; continue;
} }
String type; String type = "";
// +ping // +ping
if ("+ping".equals(readLine)) { if ("+ping".equals(readLine)) {
@ -126,8 +108,7 @@ public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer
// 主题订阅消息 // 主题订阅消息
if ("*3".equals(readLine)) { if ("*3".equals(readLine)) {
reader.readLine(); // $7 len() readLine = reader.readLine(); // $7 len()
type = reader.readLine(); // message type = reader.readLine(); // message
if (!"message".equals(type)) { if (!"message".equals(type)) {
continue; continue;
@ -143,13 +124,14 @@ public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer
String value = ""; String value = "";
do { do {
if (value.length() > 0) { if (!value.isEmpty()) {
value += "\r\n"; value += "\r\n";
} }
String s = reader.readLine(); String s = reader.readLine();
value += s; // value value += s; // value
} while (clen > 0 && clen > strLength(value)); } while (clen > 0 && clen > strLength(value));
logger.finest("topic[" + topic + "]: " + value);
// lock msg // lock msg
if ("lock".equals(topic)) { if ("lock".equals(topic)) {
@ -193,8 +175,7 @@ public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer
// timer 消息 // timer 消息
if ("*2".equals(readLine)) { if ("*2".equals(readLine)) {
reader.readLine(); // $7 len() readLine = reader.readLine(); // $7 len()
type = reader.readLine(); // message type = reader.readLine(); // message
if (!"timer".equals(type)) { if (!"timer".equals(type)) {
continue; continue;
@ -202,6 +183,7 @@ public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer
reader.readLine(); //$n len(key) reader.readLine(); //$n len(key)
String topic = reader.readLine(); // name String topic = reader.readLine(); // name
logger.finest("timer[" + topic + "]: ");
timerQueue.add(timerMap.get(topic)); timerQueue.add(timerMap.get(topic));
continue; continue;
} }
@ -215,90 +197,99 @@ public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer
} }
} }
}).start(); }).start();
}).thenAcceptAsync(x -> {
// 定时调度事件 // 定时调度事件已加入耗时监控
threadBuilder.accept(() -> { new Thread(() -> {
ExecutorService pool = Executors.newFixedThreadPool(1);
while (true) { while (true) {
Timer timer = null; Timer timer = null;
try { try {
if ((timer = timerQueue.take()) == null) { timer = timerQueue.take();
return;
}
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
timer.runnable.run(); pool.submit(timer.runnable).get(5, TimeUnit.SECONDS);
long end = System.currentTimeMillis(); long end = System.currentTimeMillis();
logger.finest(String.format("timer [%s] : elapsed time %s ms", timer.name, end - start)); logger.finest(String.format("timer [%s] : elapsed time %s ms", timer.name, end - start));
} catch (InterruptedException e) { } catch (InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
} catch (TimeoutException e) {
logger.log(Level.SEVERE, "timer [" + timer.name + "] time out: " + 5 + " S", e);
pool = Executors.newFixedThreadPool(1);
} catch (Exception e) { } catch (Exception e) {
logger.log(Level.WARNING, "timer [" + timer.name + "]", e); logger.log(Level.WARNING, "timer [" + timer.name + "]", e);
} }
} }
}, 1); }).start();
// topic msg // topic msg已加入耗时监控
threadBuilder.accept(() -> { new Thread(() -> {
ExecutorService pool = Executors.newFixedThreadPool(1);
while (true) { while (true) {
Event<String> event = null; Event<String> event = null;
try { try {
if ((event = topicQueue.take()) == null) { event = topicQueue.take();
continue;
} String topic = event.topic;
logger.log(Level.FINE, "topic[" + event.topic + "] :" + event.value); String value = event.value;
accept(event.topic, event.value); pool.submit(() -> accept(topic, value)).get(5, TimeUnit.SECONDS);
} catch (InterruptedException e) { } catch (InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
} catch (TimeoutException e) {
logger.log(Level.SEVERE, "topic[" + event.topic + "] event deal time out: " + 5 + " S, value: " + toStr(event.value), e);
pool = Executors.newFixedThreadPool(1);
} catch (Exception e) { } catch (Exception e) {
logger.log(Level.WARNING, "topic[" + event.topic + "] event accept error :" + event.value, e); logger.log(Level.WARNING, "topic[" + event.topic + "] event accept error :" + toStr(event.value), e);
} }
} }
}, 1); }).start();
// rpc back // rpc back ,仅做数据解析暂无耗时监控
threadBuilder.accept(() -> { new Thread(() -> {
while (true) { while (true) {
Event<String> event = null; Event<Object> event = null;
try { try {
if ((event = rpcBackQueue.take()) == null) { event = rpcBackQueue.take();
continue;
}
//if (event) //if (event)
logger.info(String.format("rpc-back:[%s]: %s", event.topic, event.value)); logger.finest(String.format("rpc-back:[%s]: %s", event.topic, toStr(event.value)));
rpcAccept(event.value); rpcAccept(event.value);
} catch (InterruptedException e) { } catch (InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
} catch (Exception e) { } catch (Exception e) {
logger.log(Level.WARNING, "rpc-back[" + event.topic + "] event accept error :" + event.value, e); logger.log(Level.WARNING, "rpc-back[" + event.topic + "] event accept error :" + toStr(event.value), e);
} }
} }
}, 1); }).start();
// rpc call // rpc call已加入耗时监控
threadBuilder.accept(() -> { new Thread(() -> {
ExecutorService pool = Executors.newFixedThreadPool(1);
while (true) { while (true) {
Event<String> event = null; Event<Object> event = null;
try { try {
if ((event = rpcCallQueue.take()) == null) { event = rpcCallQueue.take();
continue;
} logger.finest(String.format("rpc-call:[%s] %s", event.topic, toStr(event.value)));
logger.info(String.format("rpc-call:[%s] %s", event.topic, event.value)); String topic = event.topic;
accept(event.topic, event.value); Object value = event.value;
pool.submit(() -> rpcAccept(topic, value)).get(5, TimeUnit.SECONDS);
} catch (InterruptedException e) { } catch (InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
} catch (TimeoutException e) {
logger.log(Level.SEVERE, "topic[" + event.topic + "] event deal time out: " + 5 + " S, value: " + toStr(event.value), e);
pool = Executors.newFixedThreadPool(1);
} catch (Exception e) { } catch (Exception e) {
logger.log(Level.WARNING, "rpc-call[" + event.topic + "] event accept error :" + event.value, e); logger.log(Level.WARNING, "rpc-call[" + event.topic + "] event accept error :" + toStr(event.value), e);
} }
} }
}, 1); }).start();
// send msg // send msg
threadBuilder.accept(() -> { new Thread(() -> {
while (true) { while (true) {
String msg = null; String msg = null;
try { try {
if ((msg = sendMsgQueue.take()) == null) { msg = sendMsgQueue.take();
continue;
}
// logger.log(Level.FINEST, "send-msg: [" + msg + "]"); // logger.log(Level.FINEST, "send-msg: [" + msg + "]");
writer.write(msg.getBytes()); writer.write(msg.getBytes());
writer.flush(); writer.flush();
@ -308,8 +299,8 @@ public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer
logger.log(Level.WARNING, "send-msg[" + msg + "] event accept error :", e); logger.log(Level.WARNING, "send-msg[" + msg + "] event accept error :", e);
} }
} }
}, 1); }).start();
});
} }
// --------------------- // ---------------------
@ -356,16 +347,6 @@ public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer
return str.length(); return str.length();
} }
private String toStr(Object v) {
if (v instanceof String) {
return (String) v;
} else if (v == null) {
return null;
}
return gson.toJson(v);
}
protected boolean initSocket(int retry) { protected boolean initSocket(int retry) {
for (int i = 0; i <= retry; i++) { for (int i = 0; i <= retry; i++) {
try { try {
@ -373,8 +354,7 @@ public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer
String host = hostPort[0]; String host = hostPort[0];
int port = Integer.parseInt(hostPort[1]); int port = Integer.parseInt(hostPort[1]);
//private ReentrantLock lock = new ReentrantLock(); client = new Socket();
Socket client = new Socket();
client.connect(new InetSocketAddress(host, port)); client.connect(new InetSocketAddress(host, port));
client.setKeepAlive(true); client.setKeepAlive(true);
@ -388,9 +368,7 @@ public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer
send("auth", auth); send("auth", auth);
send("groupid " + groupid); send("groupid " + groupid);
StringBuffer buf = new StringBuffer("subscribe lock trylock"); StringBuilder buf = new StringBuilder("subscribe lock trylock");
/*if (isMain) {
}*/
if (mainHub.containsValue(this)) { if (mainHub.containsValue(this)) {
buf.append(" ").append(appid); buf.append(" ").append(appid);
} }
@ -402,13 +380,13 @@ public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer
// 重连 timer 订阅 // 重连 timer 订阅
timerMap.forEach((name, timer) -> send("timer", name)); timerMap.forEach((name, timer) -> send("timer", name));
if (retry > 0) { if (retry > 0) {
logger.warning(String.format("ZHubClient[%s][%s] %s Succeed", getGroupid(), i + 1, retry > 0 ? "reconnection" : "init")); logger.warning(String.format("ZHubClient[%s][%s] %s Succeed", getGroupid(), i + 1, "reconnection"));
} else { } else {
logger.fine(String.format("ZHubClient[%s] %s Succeed", getGroupid(), retry > 0 ? "reconnection" : "init")); logger.fine(String.format("ZHubClient[%s] %s Succeed", getGroupid(), "init"));
} }
return true; return true;
} catch (Exception e) { } catch (Exception e) {
if (retry == 0 || i == 0) { if (i == 0) {
logger.log(Level.WARNING, String.format("ZHubClient[%s] %s Failed 初始化失败!", getGroupid(), retry == 0 ? "init" : "reconnection"), e); logger.log(Level.WARNING, String.format("ZHubClient[%s] %s Failed 初始化失败!", getGroupid(), retry == 0 ? "init" : "reconnection"), e);
try { try {
Thread.sleep(1000); Thread.sleep(1000);
@ -435,11 +413,15 @@ public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer
} }
public boolean publish(String topic, Object v) { public boolean publish(String topic, Object v) {
/*if (eventMap.containsKey(topic)) { // 本地调用
topicQueue.add(Event.of(topic, v));
return true;
}*/
return send("publish", topic, toStr(v)); return send("publish", topic, toStr(v));
} }
public void broadcast(String topic, Object v) { public void broadcast(String topic, Object v) {
send("broadcast", topic, toStr(v)); send("broadcast", topic, toStr(v)); // 广播必须走远端模式
} }
// 发送 publish 主题消息若多次发送的 topic + "-" + value 相同将会做延时重置 // 发送 publish 主题消息若多次发送的 topic + "-" + value 相同将会做延时重置
@ -465,22 +447,16 @@ public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer
} }
} }
switch (endchar) { if ("M".equals(endchar)) {
case "M":
delay *= (1000 * 60 * 60 * 24 * 30); delay *= (1000 * 60 * 60 * 24 * 30);
break; } else if ("d".equals(endchar)) {
case "d":
delay *= (1000 * 60 * 60 * 24); delay *= (1000 * 60 * 60 * 24);
break; } else if ("H".equals(endchar)) {
case "H":
delay *= (1000 * 60 * 60); delay *= (1000 * 60 * 60);
break; } else if ("m".equals(endchar)) {
case "m":
delay *= (1000 * 60); delay *= (1000 * 60);
break; } else if ("s".equals(endchar)) {
case "s":
delay *= 1000; delay *= 1000;
break;
} }
delay(topic, v, delay); delay(topic, v, delay);
@ -497,7 +473,7 @@ public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer
} }
// ================================================== lock ================================================== // ================================================== lock ==================================================
private final Map<String, Lock> lockTag = new ConcurrentHashMap<>(); private Map<String, Lock> lockTag = new ConcurrentHashMap<>();
/** /**
* 尝试加锁立即返回 * 尝试加锁立即返回
@ -538,7 +514,7 @@ public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer
} }
// ================================================== timer ================================================== // ================================================== timer ==================================================
private final ConcurrentHashMap<String, Timer> timerMap = new ConcurrentHashMap(); private ConcurrentHashMap<String, Timer> timerMap = new ConcurrentHashMap();
class Timer { class Timer {
String name; String name;
@ -566,6 +542,7 @@ public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer
send("timer", name); send("timer", name);
} }
@Deprecated
public void reloadTimer() { public void reloadTimer() {
send("cmd", "reload-timer"); send("cmd", "reload-timer");
} }
@ -573,7 +550,7 @@ public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer
// ================================================== rpc ================================================== // ================================================== rpc ==================================================
// -- 调用端 -- // -- 调用端 --
private static final Map<String, Rpc> rpcMap = new ConcurrentHashMap<>(); private static final Map<String, Rpc> rpcMap = new ConcurrentHashMap<>();
private static final Map<String, TypeToken> rpcRetType = new ConcurrentHashMap<>(); // private static final Map<String, TypeToken> rpcRetType = new ConcurrentHashMap<>();
// rpc call // rpc call
public RpcResult<Void> rpc(String topic, Object v) { public RpcResult<Void> rpc(String topic, Object v) {
@ -587,14 +564,18 @@ public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer
// rpc call // rpc call
public <T, R> RpcResult<R> rpc(String topic, T v, TypeToken<R> typeToken, long timeout) { public <T, R> RpcResult<R> rpc(String topic, T v, TypeToken<R> typeToken, long timeout) {
Rpc rpc = new Rpc<>(appid, UUID.randomUUID().toString().replaceAll("-", ""), topic, v); Rpc rpc = new Rpc<>(appid, topic, v);
rpc.setTypeToken(typeToken);
String ruk = rpc.getRuk(); String ruk = rpc.getRuk();
rpcMap.put(ruk, rpc); rpcMap.put(ruk, rpc);
if (typeToken != null) {
rpcRetType.put(ruk, typeToken);
}
try { try {
if (eventMap.containsKey(topic)) { // 本地调用
rpcCallQueue.add(Event.of(topic, rpc));
} else {
rpc.setValue(toStr(rpc.getValue()));
publish(topic, rpc); // send("rpc", topic, toStr(rpc)); publish(topic, rpc); // send("rpc", topic, toStr(rpc));
}
synchronized (rpc) { synchronized (rpc) {
if (timeout <= 0) { if (timeout <= 0) {
timeout = 1000 * 15; timeout = 1000 * 15;
@ -644,8 +625,30 @@ public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer
// RpcResult: {ruk:xxx-xxxx, retcode:0} // RpcResult: {ruk:xxx-xxxx, retcode:0}
// rpc call back consumer // rpc call back consumer
private void rpcAccept(String value) { private <T> void rpcAccept(T value) {
RpcResult resp = gson.fromJson(value, new TypeToken<RpcResult<String>>() { // 接收到 本地调用返回的 RpcResult
if (value instanceof RpcResult) {
String ruk = ((RpcResult) value).getRuk();
Rpc rpc = rpcMap.remove(ruk);
if (rpc == null) {
return;
}
// TODO, 本地模式下返回的数据对象类型需要和处理端一致不然会出现类型转换异常 - 解决办法当出现不一致的情况取数据做转换
TypeToken typeToken = rpc.getTypeToken();
if (typeToken.getType() != ((RpcResult<?>) value).getResult().getClass()) {
Object result = gson.fromJson(toStr(((RpcResult<?>) value).getResult()), typeToken.getType());
((RpcResult<?>) value).setResult(result);
}
rpc.setRpcResult((RpcResult) value);
synchronized (rpc) {
rpc.notify();
}
return;
}
RpcResult resp = gson.fromJson((String) value, new TypeToken<RpcResult<String>>() {
}.getType()); }.getType());
String ruk = resp.getRuk(); String ruk = resp.getRuk();
@ -653,10 +656,10 @@ public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer
if (rpc == null) { if (rpc == null) {
return; return;
} }
TypeToken typeToken = rpcRetType.get(ruk); TypeToken typeToken = rpc.getTypeToken();
Object result = resp.getResult(); Object result = resp.getResult();
if (result != null && typeToken != null && !"java.lang.String".equals(typeToken.getType().getTypeName())) { if (result != null && typeToken != null && !"java.lang.String".equals(typeToken.getType().getTypeName()) && !"java.lang.Void".equals(typeToken.getType().getTypeName())) {
result = gson.fromJson((String) resp.getResult(), typeToken.getType()); result = gson.fromJson((String) resp.getResult(), typeToken.getType());
} }
@ -668,22 +671,38 @@ public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer
} }
// -- 订阅端 -- // -- 订阅端 --
private final HashSet rpcTopics = new HashSet(); private Set<String> rpcTopics = new HashSet();
// rpc call consumer
public <R> void rpcSubscribe(String topic, Function<Rpc<String>, RpcResult<R>> fun) {
rpcSubscribe(topic, IType.STRING, fun);
}
// rpc call consumer // rpc call consumer
public <T, R> void rpcSubscribe(String topic, TypeToken<T> typeToken, Function<Rpc<T>, RpcResult<R>> fun) { public <T, R> void rpcSubscribe(String topic, TypeToken<T> typeToken, Function<Rpc<T>, RpcResult<R>> fun) {
Consumer<String> consumer = v -> { Consumer<T> consumer = v -> {
Rpc<T> rpc = null; Rpc<T> rpc = null;
try { try {
rpc = gson.fromJson(v, new TypeToken<Rpc<String>>() { if (v instanceof String) {
rpc = gson.fromJson((String) v, new TypeToken<Rpc<String>>() {
}.getType()); }.getType());
} else {
rpc = (Rpc<T>) v;
}
// 参数转换 // 参数转换
if (rpc.getValue() instanceof String && !"java.lang.String".equals(typeToken.getType().getTypeName())) {
T paras = gson.fromJson((String) rpc.getValue(), typeToken.getType()); T paras = gson.fromJson((String) rpc.getValue(), typeToken.getType());
rpc.setValue(paras); rpc.setValue(paras);
}
RpcResult result = fun.apply(rpc); RpcResult result = fun.apply(rpc);
result.setResult(toStr(result.getResult())); if (appid.equals(rpc.getBackTopic())) {
rpcBackQueue.add(Event.of(topic, result));
} else {
result.setResult(toStr(result.getResult())); // 远程模式 结果转换
publish(rpc.getBackTopic(), result); publish(rpc.getBackTopic(), result);
}
} catch (Exception e) { } catch (Exception e) {
logger.log(Level.WARNING, "rpc call consumer error: " + v, e); logger.log(Level.WARNING, "rpc call consumer error: " + v, e);
publish(rpc.getBackTopic(), rpc.retError("服务调用失败!")); publish(rpc.getBackTopic(), rpc.retError("服务调用失败!"));
@ -692,6 +711,12 @@ public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer
}; };
rpcTopics.add(topic); rpcTopics.add(topic);
subscribe(topic, consumer); subscribe(topic, typeToken, consumer);
}
public static void main(String[] args) {
System.out.println(IType.INT.getType());
Integer a = 1;
System.out.println(a.getClass());
} }
} }