Compare commits
71 Commits
dev/spring
...
dev/redkal
Author | SHA1 | Date | |
---|---|---|---|
79402950be | |||
0ab33845f0 | |||
11ed5d2018 | |||
71ccfc919b | |||
385bffac8f | |||
b9eb54a405 | |||
2e0d9af014 | |||
747b165e77 | |||
e1581f8cff | |||
ee7f9b882a | |||
9c112b1a50 | |||
bdeb961002 | |||
318a8ff299 | |||
c0a1c60cb6 | |||
4986fafdd2 | |||
d40d4e6e5d | |||
54369c08dc | |||
bca3ac6590 | |||
96adba4e48 | |||
7e0351cfc6 | |||
4a7b6c33e4 | |||
8316fce151 | |||
2ef7ce67cc | |||
558c29912d | |||
a8788b419d | |||
6c49e7c3f6 | |||
4a7db13ce3 | |||
076e8283bf | |||
6f1d1fc98a | |||
aeba8fa635 | |||
44c1cf9f0d | |||
1171304a04 | |||
dd0521a983 | |||
3d4186ca65 | |||
6e8e367b18 | |||
92c769c708 | |||
0079bb2b27 | |||
c6a24098ff | |||
f1e1974aa2 | |||
5201cb6088 | |||
074e5a0685 | |||
9be0721de0 | |||
d7058907d6 | |||
1f23dbf3cd | |||
eaa3e913f8 | |||
241a507ebc | |||
3760f01b51 | |||
6a4a6bbf7e | |||
b9c6360241 | |||
cb5d701e8c | |||
d711bfa9cf | |||
71a2043da8 | |||
bf410c13f3 | |||
873d86fd60 | |||
b08469963d | |||
0cd83f1a19 | |||
f4ed1b05d0 | |||
3e91d785e3 | |||
48db458f5e | |||
cc67bd2b60 | |||
b458186ed8 | |||
d49bc65538 | |||
687dd924c2 | |||
1d6ae86cbd | |||
d2e13df56e | |||
f12679c5a9 | |||
d201cd3917 | |||
ddebb8c7d6 | |||
f06af4e31f | |||
1ce4ccdbc7 | |||
3c084723ed |
13
conf/application.properties
Normal file
13
conf/application.properties
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
redkale.name=zhub-dev
|
||||||
|
redkale.port=6560
|
||||||
|
redkale.server[0].protocol=HTTP
|
||||||
|
redkale.server[0].host=127.0.0.1
|
||||||
|
redkale.server[0].port=80
|
||||||
|
# redkale.server[0].root = root
|
||||||
|
redkale.server[0].rest.autoload=true
|
||||||
|
redkale.server[0].rest.path=
|
||||||
|
redkale.server[0].services[0].autoload=true
|
||||||
|
# zhub
|
||||||
|
redkale.cluster.zhub[hub].addr=47.111.150.118:6066
|
||||||
|
redkale.cluster.zhub[hub].auth=zchd@123456
|
||||||
|
redkale.cluster.zhub[hub].groupid=venue-zhub
|
14
conf/config.properties
Normal file
14
conf/config.properties
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
# redis
|
||||||
|
redis.host=47.111.150.118
|
||||||
|
redis.password=*Zhong9307!
|
||||||
|
redis.port=6064
|
||||||
|
|
||||||
|
# pulsar
|
||||||
|
pulsar.serviceurl=pulsar://47.113.228.247:6650
|
||||||
|
|
||||||
|
# zdb
|
||||||
|
# zdb.host = 127.0.0.1
|
||||||
|
# zdb.port = 1216
|
||||||
|
|
||||||
|
zhub.host = 127.0.0.1
|
||||||
|
zhub.port = 1216
|
18
conf/logging.properties
Normal file
18
conf/logging.properties
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
handlers=java.util.logging.ConsoleHandler
|
||||||
|
# handlers = java.util.logging.FileHandler
|
||||||
|
############################################################
|
||||||
|
.level=FINEST
|
||||||
|
java.level=INFO
|
||||||
|
javax.level=INFO
|
||||||
|
com.sun.level=INFO
|
||||||
|
sun.level=INFO
|
||||||
|
jdk.level=INFO
|
||||||
|
java.util.logging.FileHandler.level=FINER
|
||||||
|
#10M
|
||||||
|
java.util.logging.FileHandler.limit=10M
|
||||||
|
java.util.logging.FileHandler.count=20
|
||||||
|
java.util.logging.FileHandler.encoding=UTF-8
|
||||||
|
java.util.logging.FileHandler.pattern=${APP_HOME}/logs-%tY%tm/log-%tY%tm%td.log
|
||||||
|
java.util.logging.FileHandler.unusual=${APP_HOME}/logs-%tY%tm/log-warnerr-%tY%tm%td.log
|
||||||
|
java.util.logging.FileHandler.append=true
|
||||||
|
java.util.logging.ConsoleHandler.level=FINEST
|
5
conf/source.properties
Normal file
5
conf/source.properties
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
############ ClusterSource @Resource(name="hub") ############
|
||||||
|
# redkale.cluster.zhub[hub].addr = 47.111.150.118:6066
|
||||||
|
# redkale.cluster.zhub[hub].auth = zchd@123456
|
||||||
|
# redkale.cluster.zhub[hub].groupid = venue-zhub
|
||||||
|
|
53
pom.xml
53
pom.xml
@@ -4,54 +4,41 @@
|
|||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
<groupId>dev.zhub</groupId>
|
<groupId>net.tccn</groupId>
|
||||||
<artifactId>zhub-client-spring</artifactId>
|
<artifactId>zhub-client-redkale</artifactId>
|
||||||
<version>8.0.0424.dev</version>
|
<version>x.22.0</version> <!-- 支持 redkale-2.2 版本 -->
|
||||||
|
|
||||||
<parent>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-starter-parent</artifactId>
|
|
||||||
<version>2.5.4</version>
|
|
||||||
<relativePath/> <!-- lookup parent from repository -->
|
|
||||||
</parent>
|
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<maven.compiler.source>1.8</maven.compiler.source>
|
<maven.compiler.source>17</maven.compiler.source>
|
||||||
<maven.compiler.target>1.8</maven.compiler.target>
|
<maven.compiler.target>17</maven.compiler.target>
|
||||||
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.redkale</groupId>
|
||||||
<artifactId>spring-boot-starter-web</artifactId>
|
<artifactId>redkale</artifactId>
|
||||||
<scope>provided</scope>
|
<version>2.2.0</version>
|
||||||
</dependency>
|
<scope>compile</scope>
|
||||||
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.google.code.gson</groupId>
|
|
||||||
<artifactId>gson</artifactId>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>junit</groupId>
|
<groupId>junit</groupId>
|
||||||
<artifactId>junit</artifactId>
|
<artifactId>junit</artifactId>
|
||||||
<!--<version>4.13.1</version>-->
|
<version>4.13.1</version>
|
||||||
<scope>test</scope>
|
<scope>compile</scope>
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.projectlombok</groupId>
|
|
||||||
<artifactId>lombok</artifactId>
|
|
||||||
<!--<version>1.18.30</version>-->
|
|
||||||
<scope>provided</scope>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
|
|
||||||
<repositories>
|
<repositories>
|
||||||
<repository>
|
<repository>
|
||||||
<id>maven-release</id>
|
<id>maven-nexus</id>
|
||||||
<name>maven-nexus</name>
|
<name>maven-nexus</name>
|
||||||
<url>https://nexus.1216.top/repository/maven-public/</url>
|
<url>https://nexus.1216.top/repository/maven-public/</url>
|
||||||
</repository>
|
</repository>
|
||||||
</repositories>
|
</repositories>
|
||||||
|
|
||||||
|
|
||||||
<distributionManagement>
|
<distributionManagement>
|
||||||
<repository>
|
<repository>
|
||||||
<id>mvn-release</id>
|
<id>mvn-release</id>
|
||||||
@@ -59,12 +46,4 @@
|
|||||||
<url>https://nexus.1216.top/repository/maven-releases/</url>
|
<url>https://nexus.1216.top/repository/maven-releases/</url>
|
||||||
</repository>
|
</repository>
|
||||||
</distributionManagement>
|
</distributionManagement>
|
||||||
<!--<distributionManagement>
|
|
||||||
<repository>
|
|
||||||
<id>mvn-recloud</id>
|
|
||||||
<name>mvn-release</name>
|
|
||||||
<url>http://nexus.recloud.cn/repository/maven-releases/</url>
|
|
||||||
</repository>
|
|
||||||
</distributionManagement>-->
|
|
||||||
|
|
||||||
</project>
|
</project>
|
@@ -1,70 +0,0 @@
|
|||||||
package dev.zhub.client;
|
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
|
||||||
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 final static Gson gson = new GsonBuilder()
|
|
||||||
.excludeFieldsWithoutExposeAnnotation()
|
|
||||||
.create();*/
|
|
||||||
public final static Gson gson = new Gson();
|
|
||||||
|
|
||||||
private String ruk; // request unique key:
|
|
||||||
private String topic; // call topic
|
|
||||||
private T value; // call paras
|
|
||||||
|
|
||||||
@Expose(deserialize = false, serialize = false)
|
|
||||||
private RpcResult rpcResult;
|
|
||||||
|
|
||||||
@Expose(deserialize = false, serialize = false)
|
|
||||||
private TypeToken typeToken;
|
|
||||||
|
|
||||||
/*public Rpc() {
|
|
||||||
}*/
|
|
||||||
|
|
||||||
protected Rpc(String appname, String topic, T value) {
|
|
||||||
this.ruk = appname + "::" + UUID.randomUUID().toString().replaceAll("-", "");
|
|
||||||
this.topic = topic;
|
|
||||||
this.value = value;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getBackTopic() {
|
|
||||||
return ruk.split("::")[0];
|
|
||||||
}
|
|
||||||
|
|
||||||
public <R> RpcResult<R> render() {
|
|
||||||
RpcResult<R> response = new RpcResult<>();
|
|
||||||
response.setRuk(ruk);
|
|
||||||
return response;
|
|
||||||
}
|
|
||||||
|
|
||||||
public <R> RpcResult<R> render(R result) {
|
|
||||||
RpcResult<R> response = new RpcResult<>();
|
|
||||||
response.setRuk(ruk);
|
|
||||||
response.setResult(result);
|
|
||||||
return response;
|
|
||||||
}
|
|
||||||
|
|
||||||
public <R> RpcResult<R> retError(String retinfo) {
|
|
||||||
RpcResult<R> response = new RpcResult<>();
|
|
||||||
response.setRuk(ruk);
|
|
||||||
response.setRetcode(100);
|
|
||||||
response.setRetinfo(retinfo);
|
|
||||||
return response;
|
|
||||||
}
|
|
||||||
|
|
||||||
public <R> RpcResult<R> retError(int retcode, String retinfo) {
|
|
||||||
RpcResult<R> response = new RpcResult<>();
|
|
||||||
response.setRuk(ruk);
|
|
||||||
response.setRetcode(retcode);
|
|
||||||
response.setRetinfo(retinfo);
|
|
||||||
return response;
|
|
||||||
}
|
|
||||||
}
|
|
@@ -1,10 +1,9 @@
|
|||||||
package dev.zhub;
|
package net.tccn;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import org.redkale.convert.json.JsonConvert;
|
||||||
import com.google.gson.reflect.TypeToken;
|
import org.redkale.util.TypeToken;
|
||||||
import dev.zhub.client.Rpc;
|
|
||||||
|
|
||||||
import java.util.HashSet;
|
import javax.annotation.Resource;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
@@ -16,27 +15,23 @@ import java.util.function.Consumer;
|
|||||||
*/
|
*/
|
||||||
public abstract class AbstractConsumer implements IConsumer {
|
public abstract class AbstractConsumer implements IConsumer {
|
||||||
|
|
||||||
public Gson gson = Rpc.gson;
|
protected JsonConvert convert = JsonConvert.root();
|
||||||
|
|
||||||
protected Map<String, EventType<?>> eventMap = new ConcurrentHashMap<>();
|
@Resource(name = "APP_NAME")
|
||||||
|
protected String APP_NAME = "";
|
||||||
|
|
||||||
|
private Map<String, EventType> eventMap = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
protected abstract String getGroupid();
|
protected abstract String getGroupid();
|
||||||
|
|
||||||
protected boolean preInit() {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected final Set<String> getTopics() {
|
protected final Set<String> getTopics() {
|
||||||
if (!eventMap.isEmpty()) {
|
if (!eventMap.isEmpty()) {
|
||||||
return eventMap.keySet();
|
return eventMap.keySet();
|
||||||
}
|
}
|
||||||
HashSet<String> set = new HashSet<>();
|
|
||||||
set.add("-");
|
|
||||||
|
|
||||||
return set;
|
return Set.of("-");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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);
|
||||||
|
|
||||||
@@ -44,25 +39,12 @@ public abstract class AbstractConsumer implements IConsumer {
|
|||||||
if ("java.lang.String".equals(eventType.typeToken.getType().getTypeName())) {
|
if ("java.lang.String".equals(eventType.typeToken.getType().getTypeName())) {
|
||||||
data = value;
|
data = value;
|
||||||
} else {
|
} else {
|
||||||
data = gson.fromJson(value, eventType.typeToken.getType());
|
data = convert.convertFrom(eventType.typeToken.getType(), value);
|
||||||
}
|
}
|
||||||
|
|
||||||
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);
|
||||||
}
|
}
|
||||||
@@ -75,7 +57,7 @@ public abstract class AbstractConsumer implements IConsumer {
|
|||||||
protected abstract void subscribe(String topic);
|
protected abstract void subscribe(String topic);
|
||||||
|
|
||||||
public void subscribe(String topic, Consumer<String> consumer) {
|
public void subscribe(String topic, Consumer<String> consumer) {
|
||||||
subscribe(topic, TYPE_TOKEN_STRING, consumer);
|
subscribe(topic, IType.STRING, consumer);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -90,13 +72,5 @@ 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);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
@@ -1,4 +1,4 @@
|
|||||||
package dev.zhub;
|
package net.tccn;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 发布订阅 事件
|
* 发布订阅 事件
|
||||||
@@ -19,4 +19,5 @@ public class Event<V> {
|
|||||||
return new Event<>(topic, value);
|
return new Event<>(topic, value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
@@ -1,7 +1,6 @@
|
|||||||
package dev.zhub;
|
package net.tccn;
|
||||||
|
|
||||||
|
import org.redkale.util.TypeToken;
|
||||||
import com.google.gson.reflect.TypeToken;
|
|
||||||
|
|
||||||
import java.util.function.Consumer;
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
@@ -10,7 +9,7 @@ public class EventType<T> {
|
|||||||
public final TypeToken<T> typeToken;
|
public final TypeToken<T> typeToken;
|
||||||
private final Consumer<T> consumer;
|
private final Consumer<T> consumer;
|
||||||
|
|
||||||
private final static TypeToken<String> stringToken = new TypeToken<String>() {
|
private final static TypeToken<String> stringToken = new TypeToken<>() {
|
||||||
};
|
};
|
||||||
|
|
||||||
private EventType(String topic, TypeToken<T> typeToken, Consumer<T> consumer) {
|
private EventType(String topic, TypeToken<T> typeToken, Consumer<T> consumer) {
|
@@ -1,14 +1,10 @@
|
|||||||
package dev.zhub;
|
package net.tccn;
|
||||||
|
|
||||||
import com.google.gson.reflect.TypeToken;
|
import org.redkale.util.TypeToken;
|
||||||
|
|
||||||
import java.util.function.Consumer;
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
public interface IConsumer {
|
public interface IConsumer {
|
||||||
TypeToken<String> TYPE_TOKEN_STRING = new TypeToken<String>() {
|
|
||||||
};
|
|
||||||
TypeToken<Integer> TYPE_TOKEN_INT = new TypeToken<Integer>() {
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 取消订阅
|
* 取消订阅
|
@@ -1,4 +1,4 @@
|
|||||||
package dev.zhub;
|
package net.tccn;
|
||||||
|
|
||||||
import java.util.logging.Logger;
|
import java.util.logging.Logger;
|
||||||
|
|
@@ -1,6 +1,6 @@
|
|||||||
package dev.zhub;
|
package net.tccn;
|
||||||
|
|
||||||
import com.google.gson.reflect.TypeToken;
|
import org.redkale.util.TypeToken;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
@@ -10,13 +10,13 @@ public interface IType {
|
|||||||
TypeToken<String> STRING = new TypeToken<String>() {
|
TypeToken<String> STRING = new TypeToken<String>() {
|
||||||
};
|
};
|
||||||
|
|
||||||
TypeToken<Short> SHORT = new TypeToken<Short>() {
|
|
||||||
};
|
|
||||||
TypeToken<Integer> INT = new TypeToken<Integer>() {
|
TypeToken<Integer> INT = new TypeToken<Integer>() {
|
||||||
};
|
};
|
||||||
TypeToken<Long> LONG = new TypeToken<Long>() {
|
|
||||||
|
TypeToken<Short> SHORT = new TypeToken<Short>() {
|
||||||
};
|
};
|
||||||
TypeToken<Double> DOUBLE = new TypeToken<Double>() {
|
|
||||||
|
TypeToken<Long> LONG = new TypeToken<Long>() {
|
||||||
};
|
};
|
||||||
|
|
||||||
TypeToken<Map<String, String>> MAP = new TypeToken<Map<String, String>>() {
|
TypeToken<Map<String, String>> MAP = new TypeToken<Map<String, String>>() {
|
||||||
@@ -24,4 +24,10 @@ public interface IType {
|
|||||||
|
|
||||||
TypeToken<List<Map<String, String>>> LMAP = new TypeToken<List<Map<String, String>>>() {
|
TypeToken<List<Map<String, String>>> LMAP = new TypeToken<List<Map<String, String>>>() {
|
||||||
};
|
};
|
||||||
|
|
||||||
|
TypeToken<List<String>> LSTRING = new TypeToken<List<String>>() {
|
||||||
|
};
|
||||||
|
|
||||||
|
TypeToken<List<Integer>> LINT = new TypeToken<List<Integer>>() {
|
||||||
|
};
|
||||||
}
|
}
|
50
src/main/java/net/tccn/ZhubListener.java
Normal file
50
src/main/java/net/tccn/ZhubListener.java
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
package net.tccn;
|
||||||
|
|
||||||
|
import net.tccn.zhub.ZHubClient;
|
||||||
|
import org.redkale.boot.Application;
|
||||||
|
import org.redkale.boot.ApplicationListener;
|
||||||
|
import org.redkale.service.Service;
|
||||||
|
import org.redkale.util.AnyValue;
|
||||||
|
import org.redkale.util.RedkaleClassLoader;
|
||||||
|
import org.redkale.util.ResourceFactory;
|
||||||
|
|
||||||
|
import java.lang.reflect.InvocationTargetException;
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 服务监听
|
||||||
|
*
|
||||||
|
* @author: liangxy.
|
||||||
|
*/
|
||||||
|
public class ZhubListener implements ApplicationListener {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void preStart(Application application) {
|
||||||
|
|
||||||
|
CompletableFuture.runAsync(() -> {
|
||||||
|
ResourceFactory resourceFactory = application.getResourceFactory();
|
||||||
|
RedkaleClassLoader classLoader = application.getClassLoader();
|
||||||
|
|
||||||
|
AnyValue appConfig = application.getAppConfig();
|
||||||
|
AnyValue zhubs = appConfig.getAnyValue("zhubs");
|
||||||
|
AnyValue[] values = zhubs.getAnyValues("zhub");
|
||||||
|
for (AnyValue zhub : values) {
|
||||||
|
String className = zhub.getValue("value", ZHubClient.class.getCanonicalName());
|
||||||
|
try {
|
||||||
|
Class<?> clazz = classLoader.loadClass(className);
|
||||||
|
Service obj = (Service) clazz.getDeclaredConstructor().newInstance();
|
||||||
|
application.getResourceFactory().inject(obj);
|
||||||
|
obj.init(zhub);
|
||||||
|
resourceFactory.register(zhub.get("name"), clazz, obj);
|
||||||
|
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException | ClassNotFoundException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void preShutdown(Application application) {
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
@@ -1,7 +1,7 @@
|
|||||||
package dev.zhub.timer;
|
package net.tccn.timer;
|
||||||
|
|
||||||
import dev.zhub.timer.queue.TimerQueue;
|
import net.tccn.timer.queue.TimerQueue;
|
||||||
import dev.zhub.timer.task.Task;
|
import net.tccn.timer.task.Task;
|
||||||
|
|
||||||
import java.util.concurrent.ExecutorService;
|
import java.util.concurrent.ExecutorService;
|
||||||
import java.util.concurrent.Executors;
|
import java.util.concurrent.Executors;
|
||||||
@@ -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());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@@ -1,8 +1,8 @@
|
|||||||
package dev.zhub.timer;
|
package net.tccn.timer;
|
||||||
|
|
||||||
import dev.zhub.timer.scheduled.Scheduled;
|
import net.tccn.timer.scheduled.Scheduled;
|
||||||
import dev.zhub.timer.task.Job;
|
import net.tccn.timer.task.Job;
|
||||||
import dev.zhub.timer.task.Task;
|
import net.tccn.timer.task.Task;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.time.ZoneId;
|
import java.time.ZoneId;
|
||||||
@@ -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);
|
@@ -1,19 +1,22 @@
|
|||||||
package dev.zhub.timer;
|
package net.tccn.timer;
|
||||||
|
|
||||||
import dev.zhub.timer.scheduled.ScheduledCycle;
|
import net.tccn.timer.scheduled.ScheduledCycle;
|
||||||
|
import org.redkale.util.Utility;
|
||||||
|
|
||||||
import java.util.UUID;
|
|
||||||
import java.util.function.Supplier;
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
public class Timers {
|
public class Timers {
|
||||||
|
|
||||||
private static final TimerExecutor timerExecutor = new TimerExecutor(1);
|
private static TimerExecutor timerExecutor = new TimerExecutor(1);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 本地延时重试
|
* 本地延时重试
|
||||||
|
* @param supplier
|
||||||
|
* @param millis
|
||||||
|
* @param maxCount
|
||||||
*/
|
*/
|
||||||
public static void tryDelay(Supplier<Boolean> supplier, long millis, int maxCount) {
|
public static void tryDelay(Supplier<Boolean> supplier, long millis, int maxCount) {
|
||||||
timerExecutor.add(TimerTask.by("try-delay-task-" + UUID.randomUUID().toString().replaceAll("-", ""), ScheduledCycle.of(0), task -> {
|
timerExecutor.add(TimerTask.by("try-delay-task-" + Utility.uuid(), ScheduledCycle.of(0), task -> {
|
||||||
if (supplier.get() || task.getExecCount() == maxCount) {
|
if (supplier.get() || task.getExecCount() == maxCount) {
|
||||||
task.setComplete(true);
|
task.setComplete(true);
|
||||||
}
|
}
|
||||||
@@ -28,9 +31,11 @@ public class Timers {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 本地延时:延时时间极短的场景下使用 (如:1分钟内)
|
* 本地延时:延时时间极短的场景下使用 (如:1分钟内)
|
||||||
|
* @param runnable
|
||||||
|
* @param millis
|
||||||
*/
|
*/
|
||||||
public static void delay(Runnable runnable, long millis) {
|
public static void delay(Runnable runnable, long millis) {
|
||||||
timerExecutor.add(TimerTask.by("delay-task-" + UUID.randomUUID().toString().replaceAll("-", ""), ScheduledCycle.of(millis), task -> {
|
timerExecutor.add(TimerTask.by("delay-task-" + Utility.uuid(), ScheduledCycle.of(millis), task -> {
|
||||||
runnable.run();
|
runnable.run();
|
||||||
task.setComplete(true);
|
task.setComplete(true);
|
||||||
}));
|
}));
|
@@ -1,6 +1,6 @@
|
|||||||
package dev.zhub.timer.queue;
|
package net.tccn.timer.queue;
|
||||||
|
|
||||||
import dev.zhub.timer.task.Task;
|
import net.tccn.timer.task.Task;
|
||||||
|
|
||||||
import java.util.LinkedList;
|
import java.util.LinkedList;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
@@ -1,4 +1,4 @@
|
|||||||
package dev.zhub.timer.scheduled;
|
package net.tccn.timer.scheduled;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
|
|
@@ -1,4 +1,4 @@
|
|||||||
package dev.zhub.timer.scheduled;
|
package net.tccn.timer.scheduled;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.time.temporal.ChronoUnit;
|
import java.time.temporal.ChronoUnit;
|
@@ -1,4 +1,4 @@
|
|||||||
package dev.zhub.timer.scheduled;
|
package net.tccn.timer.scheduled;
|
||||||
|
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
@@ -1,4 +1,4 @@
|
|||||||
package dev.zhub.timer.task;
|
package net.tccn.timer.task;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author: liangxianyou at 2018/12/8 17:24.
|
* @author: liangxianyou at 2018/12/8 17:24.
|
@@ -1,7 +1,7 @@
|
|||||||
package dev.zhub.timer.task;
|
package net.tccn.timer.task;
|
||||||
|
|
||||||
import dev.zhub.timer.TimerExecutor;
|
import net.tccn.timer.TimerExecutor;
|
||||||
import dev.zhub.timer.scheduled.Scheduled;
|
import net.tccn.timer.scheduled.Scheduled;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author: liangxianyou at 2018/8/5 19:32.
|
* @author: liangxianyou at 2018/8/5 19:32.
|
||||||
@@ -63,7 +63,6 @@ public interface Task extends Runnable {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 得到总执行次数
|
* 得到总执行次数
|
||||||
*
|
|
||||||
* @return
|
* @return
|
||||||
*/
|
*/
|
||||||
int getExecCount();
|
int getExecCount();
|
@@ -1,4 +1,4 @@
|
|||||||
package dev.zhub.client;
|
package net.tccn.zhub;
|
||||||
|
|
||||||
// ================================================== lock ==================================================
|
// ================================================== lock ==================================================
|
||||||
public class Lock {
|
public class Lock {
|
107
src/main/java/net/tccn/zhub/Rpc.java
Normal file
107
src/main/java/net/tccn/zhub/Rpc.java
Normal file
@@ -0,0 +1,107 @@
|
|||||||
|
package net.tccn.zhub;
|
||||||
|
|
||||||
|
import org.redkale.convert.ConvertColumn;
|
||||||
|
import org.redkale.convert.json.JsonConvert;
|
||||||
|
import org.redkale.service.RetResult;
|
||||||
|
|
||||||
|
public class Rpc<T> {
|
||||||
|
private String ruk; // request unique key:
|
||||||
|
private String topic; // call topic
|
||||||
|
private T value; // call paras
|
||||||
|
|
||||||
|
private RpcResult rpcResult;
|
||||||
|
|
||||||
|
public Rpc() {
|
||||||
|
}
|
||||||
|
|
||||||
|
protected Rpc(String appname, String ruk, String topic, Object value) {
|
||||||
|
this.ruk = appname + "::" + ruk;
|
||||||
|
this.topic = topic;
|
||||||
|
this.value = (T) JsonConvert.root().convertTo(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;
|
||||||
|
}
|
||||||
|
|
||||||
|
@ConvertColumn(ignore = true)
|
||||||
|
public RpcResult getRpcResult() {
|
||||||
|
return rpcResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setRpcResult(RpcResult rpcResult) {
|
||||||
|
this.rpcResult = rpcResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
@ConvertColumn(ignore = true)
|
||||||
|
public String getBackTopic() {
|
||||||
|
return ruk.split("::")[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
public <R> RpcResult<R> render(int retcode, String retinfo) {
|
||||||
|
RpcResult<R> response = new RpcResult<>();
|
||||||
|
response.setRuk(ruk);
|
||||||
|
response.setRetcode(retcode);
|
||||||
|
response.setRetinfo(retinfo);
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public <R> RpcResult<R> render() {
|
||||||
|
RpcResult<R> response = new RpcResult<>();
|
||||||
|
response.setRuk(ruk);
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public RpcResult render(RetResult result) {
|
||||||
|
RpcResult resp = new RpcResult<>();
|
||||||
|
resp.setRuk(ruk);
|
||||||
|
resp.setRetcode(result.getRetcode());
|
||||||
|
resp.setRetinfo(result.getRetinfo());
|
||||||
|
resp.setResult(result.getResult());
|
||||||
|
return resp;
|
||||||
|
}
|
||||||
|
|
||||||
|
public <R> RpcResult<R> render(R result) {
|
||||||
|
RpcResult<R> response = new RpcResult<>();
|
||||||
|
response.setRuk(ruk);
|
||||||
|
response.setResult(result);
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public <R> RpcResult<R> retError(String retinfo) {
|
||||||
|
RpcResult<R> response = new RpcResult<>();
|
||||||
|
response.setRuk(ruk);
|
||||||
|
response.setRetcode(100);
|
||||||
|
response.setRetinfo(retinfo);
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public <R> RpcResult<R> retError(int retcode, String retinfo) {
|
||||||
|
RpcResult<R> response = new RpcResult<>();
|
||||||
|
response.setRuk(ruk);
|
||||||
|
response.setRetcode(retcode);
|
||||||
|
response.setRetinfo(retinfo);
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@@ -1,4 +1,4 @@
|
|||||||
package dev.zhub.client;
|
package net.tccn.zhub;
|
||||||
|
|
||||||
public class RpcResult<R> {
|
public class RpcResult<R> {
|
||||||
private String ruk;
|
private String ruk;
|
@@ -1,13 +1,11 @@
|
|||||||
package dev.zhub.client;
|
package net.tccn.zhub;
|
||||||
|
|
||||||
import com.google.gson.reflect.TypeToken;
|
import net.tccn.*;
|
||||||
import dev.zhub.*;
|
import net.tccn.timer.Timers;
|
||||||
import dev.zhub.timer.Timers;
|
import org.redkale.service.Local;
|
||||||
import lombok.Setter;
|
import org.redkale.service.Service;
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
import org.redkale.util.*;
|
||||||
import org.springframework.stereotype.Component;
|
|
||||||
|
|
||||||
import javax.annotation.PostConstruct;
|
|
||||||
import java.io.BufferedReader;
|
import java.io.BufferedReader;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.InputStreamReader;
|
import java.io.InputStreamReader;
|
||||||
@@ -22,68 +20,59 @@ import java.util.function.Function;
|
|||||||
import java.util.logging.Level;
|
import java.util.logging.Level;
|
||||||
import java.util.logging.Logger;
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
@Component
|
import static java.nio.charset.StandardCharsets.UTF_8;
|
||||||
public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer {
|
|
||||||
|
@Local
|
||||||
|
@AutoLoad(false)
|
||||||
|
@ResourceType(ZHubClient.class)
|
||||||
|
public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer, Service {
|
||||||
|
|
||||||
public Logger logger = Logger.getLogger(ZHubClient.class.getSimpleName());
|
public Logger logger = Logger.getLogger(ZHubClient.class.getSimpleName());
|
||||||
@Setter
|
|
||||||
@Value("${zhub.addr}")
|
|
||||||
private String addr = "127.0.0.1:1216";
|
private String addr = "127.0.0.1:1216";
|
||||||
@Setter
|
|
||||||
@Value("${zhub.groupid}")
|
|
||||||
private String groupid = "";
|
|
||||||
@Setter
|
|
||||||
@Value("${zhub.auth}")
|
|
||||||
private String auth = "";
|
private String auth = "";
|
||||||
@Setter
|
private String groupid = "";
|
||||||
@Value("${zhub.appid}")
|
|
||||||
protected String appid = "";
|
|
||||||
|
|
||||||
@PostConstruct
|
|
||||||
public void init() {
|
|
||||||
init(null);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
//private ReentrantLock lock = new ReentrantLock();
|
||||||
private Socket client;
|
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<Object>> rpcBackQueue = new LinkedBlockingQueue<>(); // RPC BACK MSG [=> Object]
|
private final LinkedBlockingQueue<Event<String>> rpcBackQueue = new LinkedBlockingQueue<>(); // RPC BACK MSG
|
||||||
private final LinkedBlockingQueue<Event<Object>> rpcCallQueue = new LinkedBlockingQueue<>(); // RPC CALL MSG [=> Object]
|
private final LinkedBlockingQueue<Event<String>> rpcCallQueue = new LinkedBlockingQueue<>(); // RPC CALL MSG
|
||||||
private final LinkedBlockingQueue<String> sendMsgQueue = new LinkedBlockingQueue<>(); // SEND MSG
|
private final LinkedBlockingQueue<String> sendMsgQueue = new LinkedBlockingQueue<>(); // SEND MSG
|
||||||
|
|
||||||
|
/*private BiConsumer<Runnable, Integer> threadBuilder = (r, n) -> {
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
new Thread(() -> r.run()).start();
|
||||||
|
}
|
||||||
|
};*/
|
||||||
|
|
||||||
private static Map<String, ZHubClient> mainHub = new HashMap<>(); // 127.0.0.1:1216 - ZHubClient
|
private static Map<String, ZHubClient> mainHub = new HashMap<>(); // 127.0.0.1:1216 - ZHubClient
|
||||||
|
|
||||||
public ZHubClient() {
|
@Override
|
||||||
|
public void init(AnyValue config) {
|
||||||
}
|
|
||||||
|
|
||||||
public ZHubClient(String addr, String groupid, String appid, String auth) {
|
|
||||||
this.addr = addr;
|
|
||||||
this.groupid = groupid;
|
|
||||||
this.appid = appid;
|
|
||||||
this.auth = auth;
|
|
||||||
init(null);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void init(Map<String, String> config) {
|
|
||||||
if (!preInit()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 自动注入
|
// 自动注入
|
||||||
if (config != null) {
|
if (config != null) {
|
||||||
addr = config.getOrDefault("addr", addr);
|
addr = config.getValue("addr", addr);
|
||||||
groupid = config.getOrDefault("groupid", groupid);
|
|
||||||
appid = config.getOrDefault("appname", appid);
|
// 合并 addr = host:port, 做历史兼容
|
||||||
|
int port = config.getIntValue("port", 0);
|
||||||
|
if (port != 0 && !addr.contains(":")) {
|
||||||
|
addr = addr + ":" + port;
|
||||||
|
}
|
||||||
|
|
||||||
|
auth = config.getOrDefault("auth", auth);
|
||||||
|
groupid = config.getValue("groupid", groupid);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 设置第一个启动的 实例为主实例
|
// 设置第一个启动的 实例为主实例
|
||||||
|
synchronized (ZHubClient.class) {
|
||||||
if (!mainHub.containsKey(addr)) { // 确保同步执行此 init 逻辑
|
if (!mainHub.containsKey(addr)) { // 确保同步执行此 init 逻辑
|
||||||
mainHub.put(addr, this);
|
mainHub.put(addr, this);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
CompletableFuture.runAsync(() -> {
|
CompletableFuture.runAsync(() -> {
|
||||||
if (!initSocket(0)) {
|
if (!initSocket(0)) {
|
||||||
@@ -124,7 +113,7 @@ public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer
|
|||||||
|
|
||||||
String value = "";
|
String value = "";
|
||||||
do {
|
do {
|
||||||
if (!value.isEmpty()) {
|
if (value.length() > 0) {
|
||||||
value += "\r\n";
|
value += "\r\n";
|
||||||
}
|
}
|
||||||
String s = reader.readLine();
|
String s = reader.readLine();
|
||||||
@@ -157,7 +146,7 @@ public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer
|
|||||||
}
|
}
|
||||||
|
|
||||||
// rpc back msg
|
// rpc back msg
|
||||||
if (appid.equals(topic)) {
|
if (APP_NAME.equals(topic)) {
|
||||||
rpcBackQueue.add(Event.of(topic, value));
|
rpcBackQueue.add(Event.of(topic, value));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -200,88 +189,93 @@ public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer
|
|||||||
}).thenAcceptAsync(x -> {
|
}).thenAcceptAsync(x -> {
|
||||||
// 定时调度事件,已加入耗时监控
|
// 定时调度事件,已加入耗时监控
|
||||||
new Thread(() -> {
|
new Thread(() -> {
|
||||||
ExecutorService pool = Executors.newFixedThreadPool(1);
|
ExecutorService executor = Executors.newSingleThreadExecutor();
|
||||||
while (true) {
|
while (true) {
|
||||||
Timer timer = null;
|
Timer timer = null;
|
||||||
try {
|
try {
|
||||||
timer = timerQueue.take();
|
timer = timerQueue.take();
|
||||||
|
|
||||||
long start = System.currentTimeMillis();
|
long start = System.currentTimeMillis();
|
||||||
pool.submit(timer.runnable).get(5, TimeUnit.SECONDS);
|
executor.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 | ExecutionException | TimeoutException e) {
|
||||||
|
if (e instanceof TimeoutException) {
|
||||||
|
executor = Executors.newSingleThreadExecutor();
|
||||||
|
logger.log(Level.WARNING, "TimeoutException [" + timer.name + "]", e);
|
||||||
|
} else {
|
||||||
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) {
|
|
||||||
logger.log(Level.WARNING, "timer [" + timer.name + "]", e);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}).start();
|
}).start();
|
||||||
|
|
||||||
// topic msg,已加入耗时监控
|
// topic msg,已加入耗时监控
|
||||||
new Thread(() -> {
|
new Thread(() -> {
|
||||||
ExecutorService pool = Executors.newFixedThreadPool(1);
|
ExecutorService executor = Executors.newSingleThreadExecutor();
|
||||||
while (true) {
|
while (true) {
|
||||||
Event<String> event = null;
|
Event<String> event = null;
|
||||||
try {
|
try {
|
||||||
event = topicQueue.take();
|
event = topicQueue.take();
|
||||||
|
logger.log(Level.FINE, "topic[" + event.topic + "] :" + event.value);
|
||||||
|
|
||||||
String topic = event.topic;
|
String topic = event.topic;
|
||||||
String value = event.value;
|
String value = event.value;
|
||||||
pool.submit(() -> accept(topic, value)).get(5, TimeUnit.SECONDS);
|
executor.submit(() -> accept(topic, value)).get(5, TimeUnit.SECONDS);
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException | ExecutionException | TimeoutException e) {
|
||||||
e.printStackTrace();
|
if (e instanceof TimeoutException) {
|
||||||
} catch (TimeoutException e) {
|
executor = Executors.newSingleThreadExecutor();
|
||||||
logger.log(Level.SEVERE, "topic[" + event.topic + "] event deal time out: " + 5 + " S, value: " + toStr(event.value), e);
|
logger.log(Level.WARNING, "TimeoutException, topic[" + event.topic + "], value[" + event.value + "]", e);
|
||||||
pool = Executors.newFixedThreadPool(1);
|
} else if (event != null) {
|
||||||
} 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);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}).start();
|
}
|
||||||
|
}, "ZHub-topic-accept").start();
|
||||||
|
|
||||||
// rpc back ,仅做数据解析,暂无耗时监控
|
// rpc back ,仅做数据解析,暂无耗时监控
|
||||||
new Thread(() -> {
|
new Thread(() -> {
|
||||||
|
ExecutorService executor = Executors.newSingleThreadExecutor();
|
||||||
while (true) {
|
while (true) {
|
||||||
Event<Object> event = null;
|
Event<String> event = null;
|
||||||
try {
|
try {
|
||||||
event = rpcBackQueue.take();
|
event = rpcBackQueue.take();
|
||||||
//if (event)
|
logger.info(String.format("rpc-back:[%s]", event.value));
|
||||||
logger.finest(String.format("rpc-back:[%s]: %s", event.topic, toStr(event.value)));
|
|
||||||
rpcAccept(event.value);
|
String value = event.value;
|
||||||
} catch (InterruptedException e) {
|
executor.submit(() -> rpcAccept(value)).get(5, TimeUnit.SECONDS);
|
||||||
e.printStackTrace();
|
} catch (InterruptedException | ExecutionException | TimeoutException e) {
|
||||||
} catch (Exception e) {
|
if (e instanceof TimeoutException) {
|
||||||
logger.log(Level.WARNING, "rpc-back[" + event.topic + "] event accept error :" + toStr(event.value), e);
|
executor = Executors.newSingleThreadExecutor();
|
||||||
|
logger.log(Level.WARNING, "rpc-back TimeoutException, topic[" + event.topic + "], value[" + event.value + "]", e);
|
||||||
|
} else if (event != null) {
|
||||||
|
logger.log(Level.WARNING, "rpc-back[" + event.value + "] event accept error :" + event.value, e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}).start();
|
}
|
||||||
|
}, "ZHub-rpc-call").start();
|
||||||
|
|
||||||
// rpc call,已加入耗时监控
|
// rpc call,已加入耗时监控
|
||||||
new Thread(() -> {
|
new Thread(() -> {
|
||||||
ExecutorService pool = Executors.newFixedThreadPool(1);
|
ExecutorService executor = Executors.newSingleThreadExecutor();
|
||||||
while (true) {
|
while (true) {
|
||||||
Event<Object> event = null;
|
Event<String> event = null;
|
||||||
try {
|
try {
|
||||||
event = rpcCallQueue.take();
|
event = rpcCallQueue.take();
|
||||||
|
logger.info(String.format("rpc-call:[%s] %s", event.topic, event.value));
|
||||||
|
|
||||||
logger.finest(String.format("rpc-call:[%s] %s", event.topic, toStr(event.value)));
|
|
||||||
String topic = event.topic;
|
String topic = event.topic;
|
||||||
Object value = event.value;
|
String value = event.value;
|
||||||
pool.submit(() -> rpcAccept(topic, value)).get(5, TimeUnit.SECONDS);
|
executor.submit(() -> accept(topic, value)).get(5, TimeUnit.SECONDS);
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException | ExecutionException | TimeoutException e) {
|
||||||
e.printStackTrace();
|
if (e instanceof TimeoutException) {
|
||||||
} catch (TimeoutException e) {
|
executor = Executors.newSingleThreadExecutor();
|
||||||
logger.log(Level.SEVERE, "topic[" + event.topic + "] event deal time out: " + 5 + " S, value: " + toStr(event.value), e);
|
logger.log(Level.WARNING, "rpc-call TimeoutException, topic[" + event.topic + "], value[" + event.value + "]", e);
|
||||||
pool = Executors.newFixedThreadPool(1);
|
} else if (event != null) {
|
||||||
} 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);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}).start();
|
}
|
||||||
|
}, "ZHub-rpc-call").start();
|
||||||
|
|
||||||
// send msg
|
// send msg
|
||||||
new Thread(() -> {
|
new Thread(() -> {
|
||||||
@@ -289,27 +283,57 @@ public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer
|
|||||||
String msg = null;
|
String msg = null;
|
||||||
try {
|
try {
|
||||||
msg = sendMsgQueue.take();
|
msg = sendMsgQueue.take();
|
||||||
|
writer.write(msg.getBytes(UTF_8));
|
||||||
// logger.log(Level.FINEST, "send-msg: [" + msg + "]");
|
|
||||||
writer.write(msg.getBytes());
|
|
||||||
writer.flush();
|
writer.flush();
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException | IOException e) {
|
||||||
e.printStackTrace();
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.log(Level.WARNING, "send-msg[" + msg + "] event accept error :", e);
|
logger.log(Level.WARNING, "send-msg[" + msg + "] event accept error :", e);
|
||||||
|
|
||||||
|
try {
|
||||||
|
Thread.sleep(5000);
|
||||||
|
assert msg != null;
|
||||||
|
writer.write(msg.getBytes(UTF_8));
|
||||||
|
writer.flush();
|
||||||
|
} catch (IOException | InterruptedException | NullPointerException ex) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}).start();
|
}).start();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public boolean acceptsConf(AnyValue config) {
|
||||||
|
if (config == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!getNodes(config).isEmpty()) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private HashMap<String, AnyValue> getNodes(AnyValue config) {
|
||||||
|
AnyValue[] zhubs = config.getAnyValues("zhub");
|
||||||
|
HashMap<String, AnyValue> confMap = new HashMap<>();
|
||||||
|
|
||||||
|
for (AnyValue zhub : zhubs) {
|
||||||
|
String[] names = zhub.getNames();
|
||||||
|
for (String name : names) {
|
||||||
|
confMap.put(name, zhub.getAnyValue(name));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return confMap;
|
||||||
|
}
|
||||||
|
|
||||||
// ---------------------
|
// ---------------------
|
||||||
// -- 消息发送 --
|
// -- 消息发送 --
|
||||||
protected boolean send(String... data) {
|
protected boolean send(String... data) {
|
||||||
if (data.length == 1) {
|
if (data.length == 1) {
|
||||||
sendMsgQueue.add(data[0] + "\r\n");
|
sendMsgQueue.add(data[0] + "\r\n");
|
||||||
} else if (data.length > 1) {
|
} else if (data.length > 1) {
|
||||||
StringBuilder buf = new StringBuilder();
|
StringBuffer buf = new StringBuffer();
|
||||||
buf.append("*" + data.length + "\r\n");
|
buf.append("*" + data.length + "\r\n");
|
||||||
for (String d : data) {
|
for (String d : data) {
|
||||||
buf.append("$" + strLength(d) + "\r\n");
|
buf.append("$" + strLength(d) + "\r\n");
|
||||||
@@ -347,6 +371,15 @@ 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 convert.convertTo(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 {
|
||||||
@@ -359,7 +392,7 @@ public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer
|
|||||||
client.setKeepAlive(true);
|
client.setKeepAlive(true);
|
||||||
|
|
||||||
writer = client.getOutputStream();
|
writer = client.getOutputStream();
|
||||||
reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
|
reader = new BufferedReader(new InputStreamReader(client.getInputStream(), UTF_8));
|
||||||
|
|
||||||
String groupid = getGroupid();
|
String groupid = getGroupid();
|
||||||
if (groupid == null || groupid.isEmpty()) {
|
if (groupid == null || groupid.isEmpty()) {
|
||||||
@@ -368,9 +401,9 @@ public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer
|
|||||||
send("auth", auth);
|
send("auth", auth);
|
||||||
send("groupid " + groupid);
|
send("groupid " + groupid);
|
||||||
|
|
||||||
StringBuilder buf = new StringBuilder("subscribe lock trylock");
|
StringBuffer buf = new StringBuffer("subscribe lock trylock");
|
||||||
if (mainHub.containsValue(this)) {
|
if (mainHub.containsValue(this)) {
|
||||||
buf.append(" ").append(appid);
|
buf.append(" " + APP_NAME);
|
||||||
}
|
}
|
||||||
for (String topic : getTopics()) {
|
for (String topic : getTopics()) {
|
||||||
buf.append(" ").append(topic);
|
buf.append(" ").append(topic);
|
||||||
@@ -378,11 +411,13 @@ public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer
|
|||||||
send(buf.toString());
|
send(buf.toString());
|
||||||
|
|
||||||
// 重连 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, "reconnection"));
|
logger.warning(String.format("ZHubClient[%s][%s] %s Succeed!", getGroupid(), i + 1, retry > 0 ? "reconnection" : "init"));
|
||||||
} else {
|
} else {
|
||||||
logger.fine(String.format("ZHubClient[%s] %s Succeed!", getGroupid(), "init"));
|
logger.fine(String.format("ZHubClient[%s] %s Succeed!", getGroupid(), retry > 0 ? "reconnection" : "init"));
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
@@ -413,15 +448,11 @@ 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 相同,将会做延时重置
|
||||||
@@ -549,33 +580,29 @@ public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer
|
|||||||
|
|
||||||
// ================================================== rpc ==================================================
|
// ================================================== rpc ==================================================
|
||||||
// -- 调用端 --
|
// -- 调用端 --
|
||||||
private static final Map<String, Rpc> rpcMap = new ConcurrentHashMap<>();
|
private static Map<String, Rpc> rpcMap = new ConcurrentHashMap<>();
|
||||||
// private static final Map<String, TypeToken> rpcRetType = new ConcurrentHashMap<>();
|
private static Map<String, TypeToken> rpcRetType = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
// rpc call
|
@Comment("rpc call")
|
||||||
public RpcResult<Void> rpc(String topic, Object v) {
|
public RpcResult<String> rpc(String topic, Object v) {
|
||||||
return rpc(topic, v, null);
|
return rpc(topic, v, IType.STRING);
|
||||||
}
|
}
|
||||||
|
|
||||||
// rpc call
|
@Comment("rpc call")
|
||||||
public <T, R> RpcResult<R> rpc(String topic, T v, TypeToken<R> typeToken) {
|
public <T, R> RpcResult<R> rpc(String topic, T v, TypeToken<R> typeToken) {
|
||||||
return rpc(topic, v, typeToken, 0);
|
return rpc(topic, v, typeToken, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
// rpc call
|
@Comment("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, topic, v);
|
Rpc rpc = new Rpc<>(APP_NAME, Utility.uuid(), topic, v);
|
||||||
rpc.setTypeToken(typeToken);
|
|
||||||
|
|
||||||
String ruk = rpc.getRuk();
|
String ruk = rpc.getRuk();
|
||||||
rpcMap.put(ruk, rpc);
|
rpcMap.put(ruk, rpc);
|
||||||
try {
|
if (typeToken != null) {
|
||||||
if (eventMap.containsKey(topic)) { // 本地调用
|
rpcRetType.put(ruk, typeToken);
|
||||||
rpcCallQueue.add(Event.of(topic, rpc));
|
|
||||||
} else {
|
|
||||||
rpc.setValue(toStr(rpc.getValue()));
|
|
||||||
publish(topic, rpc); // send("rpc", topic, toStr(rpc));
|
|
||||||
}
|
}
|
||||||
|
try {
|
||||||
|
publish(topic, rpc); // send("rpc", topic, toStr(rpc));
|
||||||
synchronized (rpc) {
|
synchronized (rpc) {
|
||||||
if (timeout <= 0) {
|
if (timeout <= 0) {
|
||||||
timeout = 1000 * 15;
|
timeout = 1000 * 15;
|
||||||
@@ -588,9 +615,9 @@ public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
RpcResult rpcResult = rpc.retError(505, "请求超时");
|
RpcResult rpcResult = rpc.render(505, "请求超时");
|
||||||
rpc.setRpcResult(rpcResult);
|
rpc.setRpcResult(rpcResult);
|
||||||
logger.warning("rpc timeout: " + gson.toJson(rpc));
|
logger.warning("rpc timeout: " + convert.convertTo(rpc));
|
||||||
rpc.notify();
|
rpc.notify();
|
||||||
}
|
}
|
||||||
}, timeout);
|
}, timeout);
|
||||||
@@ -601,14 +628,14 @@ public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer
|
|||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
// call error
|
// call error
|
||||||
RpcResult rpcResult = rpc.retError(501, "请求失败");
|
RpcResult rpcResult = rpc.render(501, "请求失败");
|
||||||
rpc.setRpcResult(rpcResult);
|
rpc.setRpcResult(rpcResult);
|
||||||
}
|
}
|
||||||
return rpc.getRpcResult();
|
return rpc.getRpcResult();
|
||||||
}
|
}
|
||||||
|
|
||||||
public <T, R> CompletableFuture<RpcResult<R>> rpcAsync(String topic, T v) {
|
public <T> CompletableFuture<RpcResult<String>> rpcAsync(String topic, T v) {
|
||||||
return CompletableFuture.supplyAsync(() -> rpc(topic, v, null));
|
return CompletableFuture.supplyAsync(() -> rpc(topic, v, IType.STRING));
|
||||||
}
|
}
|
||||||
|
|
||||||
public <T, R> CompletableFuture<RpcResult<R>> rpcAsync(String topic, T v, TypeToken<R> typeToken) {
|
public <T, R> CompletableFuture<RpcResult<R>> rpcAsync(String topic, T v, TypeToken<R> typeToken) {
|
||||||
@@ -624,43 +651,21 @@ public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer
|
|||||||
}
|
}
|
||||||
|
|
||||||
// RpcResult: {ruk:xxx-xxxx, retcode:0}
|
// RpcResult: {ruk:xxx-xxxx, retcode:0}
|
||||||
// rpc call back consumer
|
@Comment("rpc call back consumer")
|
||||||
private <T> void rpcAccept(T value) {
|
private void rpcAccept(String value) {
|
||||||
// 接收到 本地调用返回的 RpcResult
|
RpcResult resp = convert.convertFrom(new TypeToken<RpcResult<String>>() {
|
||||||
if (value instanceof RpcResult) {
|
}.getType(), value);
|
||||||
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<Object>) value).setResult(result);
|
|
||||||
}
|
|
||||||
|
|
||||||
rpc.setRpcResult((RpcResult) value);
|
|
||||||
synchronized (rpc) {
|
|
||||||
rpc.notify();
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
RpcResult resp = gson.fromJson((String) value, new TypeToken<RpcResult<String>>() {
|
|
||||||
}.getType());
|
|
||||||
|
|
||||||
String ruk = resp.getRuk();
|
String ruk = resp.getRuk();
|
||||||
Rpc rpc = rpcMap.remove(ruk);
|
Rpc rpc = rpcMap.remove(ruk);
|
||||||
if (rpc == null) {
|
if (rpc == null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
TypeToken typeToken = rpc.getTypeToken();
|
TypeToken typeToken = rpcRetType.get(ruk);
|
||||||
|
|
||||||
Object result = resp.getResult();
|
Object result = resp.getResult();
|
||||||
if (result != null && typeToken != null && !"java.lang.String".equals(typeToken.getType().getTypeName()) && !"java.lang.Void".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 = convert.convertFrom(typeToken.getType(), (String) resp.getResult());
|
||||||
}
|
}
|
||||||
|
|
||||||
resp.setResult(result);
|
resp.setResult(result);
|
||||||
@@ -673,36 +678,25 @@ public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer
|
|||||||
// -- 订阅端 --
|
// -- 订阅端 --
|
||||||
private Set<String> rpcTopics = new HashSet();
|
private Set<String> rpcTopics = new HashSet();
|
||||||
|
|
||||||
// rpc call consumer
|
@Comment("rpc call consumer")
|
||||||
public <R> void rpcSubscribe(String topic, Function<Rpc<String>, RpcResult<R>> fun) {
|
public <R> void rpcSubscribe(String topic, Function<Rpc<String>, RpcResult<R>> fun) {
|
||||||
rpcSubscribe(topic, IType.STRING, fun);
|
rpcSubscribe(topic, IType.STRING, fun);
|
||||||
}
|
}
|
||||||
|
|
||||||
// rpc call consumer
|
@Comment("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<T> consumer = v -> {
|
Consumer<String> consumer = v -> {
|
||||||
Rpc<T> rpc = null;
|
Rpc<T> rpc = null;
|
||||||
try {
|
try {
|
||||||
if (v instanceof String) {
|
rpc = convert.convertFrom(new TypeToken<Rpc<String>>() {
|
||||||
rpc = gson.fromJson((String) v, new TypeToken<Rpc<String>>() {
|
}.getType(), v);
|
||||||
}.getType());
|
|
||||||
} else {
|
|
||||||
rpc = (Rpc<T>) v;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 参数转换
|
// 参数转换
|
||||||
if (rpc.getValue() instanceof String && !"java.lang.String".equals(typeToken.getType().getTypeName())) {
|
T paras = convert.convertFrom(typeToken.getType(), (String) rpc.getValue());
|
||||||
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);
|
||||||
if (appid.equals(rpc.getBackTopic())) {
|
result.setResult(toStr(result.getResult()));
|
||||||
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("服务调用失败!"));
|
||||||
@@ -711,12 +705,6 @@ public class ZHubClient extends AbstractConsumer implements IConsumer, IProducer
|
|||||||
};
|
};
|
||||||
|
|
||||||
rpcTopics.add(topic);
|
rpcTopics.add(topic);
|
||||||
subscribe(topic, typeToken, consumer);
|
subscribe(topic, consumer);
|
||||||
}
|
|
||||||
|
|
||||||
public static void main(String[] args) {
|
|
||||||
System.out.println(IType.INT.getType());
|
|
||||||
Integer a = 1;
|
|
||||||
System.out.println(a.getClass());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
430
src/main/java/org/redkalex/cache/redis/MyRedisCacheSource.java
vendored
Normal file
430
src/main/java/org/redkalex/cache/redis/MyRedisCacheSource.java
vendored
Normal file
@@ -0,0 +1,430 @@
|
|||||||
|
package org.redkalex.cache.redis;
|
||||||
|
|
||||||
|
|
||||||
|
import org.redkale.convert.Convert;
|
||||||
|
import org.redkale.service.Local;
|
||||||
|
import org.redkale.source.CacheSource;
|
||||||
|
import org.redkale.util.AutoLoad;
|
||||||
|
import org.redkale.util.ResourceType;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
import java.lang.reflect.Type;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
@Local
|
||||||
|
@AutoLoad(false)
|
||||||
|
@ResourceType(CacheSource.class)
|
||||||
|
public class MyRedisCacheSource<V extends Object> extends RedisCacheSource<V> {
|
||||||
|
//--------------------- oth ------------------------------
|
||||||
|
public boolean setnx(String key, Object v) {
|
||||||
|
byte[][] bytes = Stream.of(key, v).map(x -> String.valueOf(x).getBytes(StandardCharsets.UTF_8)).toArray(byte[][]::new);
|
||||||
|
Serializable rs = send("SETNX", CacheEntryType.OBJECT, (Type) null, key, bytes).join();
|
||||||
|
return rs == null ? false : (long) rs == 1;
|
||||||
|
}
|
||||||
|
//--------------------- oth ------------------------------
|
||||||
|
|
||||||
|
//--------------------- bit ------------------------------
|
||||||
|
public boolean getBit(String key, int offset) {
|
||||||
|
byte[][] bytes = Stream.of(key, offset).map(x -> String.valueOf(x).getBytes(StandardCharsets.UTF_8)).toArray(byte[][]::new);
|
||||||
|
Serializable v = send("GETBIT", CacheEntryType.OBJECT, (Type) null, key, bytes).join();
|
||||||
|
return v == null ? false : (long) v == 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setBit(String key, int offset, boolean bool) {
|
||||||
|
byte[][] bytes = Stream.of(key, offset, bool ? 1 : 0).map(x -> String.valueOf(x).getBytes(StandardCharsets.UTF_8)).toArray(byte[][]::new);
|
||||||
|
send("SETBIT", CacheEntryType.OBJECT, (Type) null, key, bytes).join();
|
||||||
|
}
|
||||||
|
|
||||||
|
//--------------------- bit ------------------------------
|
||||||
|
//--------------------- lock ------------------------------
|
||||||
|
// 尝试加锁,成功返回0,否则返回上一锁剩余毫秒值
|
||||||
|
public int tryLock(String key, int millis) {
|
||||||
|
byte[][] bytes = Stream.of("" +
|
||||||
|
"if (redis.call('exists',KEYS[1]) == 0) then " +
|
||||||
|
"redis.call('psetex', KEYS[1], ARGV[1], 1) " +
|
||||||
|
"return 0; " +
|
||||||
|
"else " +
|
||||||
|
"return redis.call('PTTL', KEYS[1]); " +
|
||||||
|
"end; ", 1, key, millis).map(x -> String.valueOf(x).getBytes(StandardCharsets.UTF_8)).toArray(byte[][]::new);
|
||||||
|
int n = (int) send("EVAL", CacheEntryType.OBJECT, (Type) null, null, bytes).join();
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 加锁
|
||||||
|
public void lock(String key, int millis) {
|
||||||
|
int i;
|
||||||
|
do {
|
||||||
|
i = tryLock(key, millis);
|
||||||
|
try {
|
||||||
|
Thread.sleep(10);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
} while (i > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 解锁
|
||||||
|
public void unlock(String key) {
|
||||||
|
remove(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//--------------------- key ------------------------------
|
||||||
|
|
||||||
|
public long getTtl(String key) {
|
||||||
|
return (long) send("TTL", CacheEntryType.OBJECT, (Type) null, key, key.getBytes(StandardCharsets.UTF_8)).join();
|
||||||
|
}
|
||||||
|
|
||||||
|
public long getPttl(String key) {
|
||||||
|
return (long) send("PTTL", CacheEntryType.OBJECT, (Type) null, key, key.getBytes(StandardCharsets.UTF_8)).join();
|
||||||
|
}
|
||||||
|
|
||||||
|
public int remove(String... keys) {
|
||||||
|
if (keys == null || keys.length == 0) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
List<String> para = new ArrayList<>();
|
||||||
|
para.add("" +
|
||||||
|
" local args = ARGV;" +
|
||||||
|
" local x = 0;" +
|
||||||
|
" for i,v in ipairs(args) do" +
|
||||||
|
" local inx = redis.call('del', v);" +
|
||||||
|
" if(inx > 0) then" +
|
||||||
|
" x = x + 1;" +
|
||||||
|
" end" +
|
||||||
|
" end" +
|
||||||
|
" return x;");
|
||||||
|
|
||||||
|
para.add("0");
|
||||||
|
for (Object field : keys) {
|
||||||
|
para.add(String.valueOf(field));
|
||||||
|
}
|
||||||
|
byte[][] bytes = para.stream().map(x -> String.valueOf(x).getBytes(StandardCharsets.UTF_8)).toArray(byte[][]::new);
|
||||||
|
return (int) send("EVAL", CacheEntryType.OBJECT, (Type) null, null, bytes).join();
|
||||||
|
}
|
||||||
|
|
||||||
|
//--------------------- hmget ------------------------------
|
||||||
|
public <T extends Object> V getHm(String key, T field) {
|
||||||
|
// return (V) send("HMGET", CacheEntryType.OBJECT, (Type) null, key, key.getBytes(StandardCharsets.UTF_8), field.getBytes(StandardCharsets.UTF_8)).join();
|
||||||
|
Map<Object, V> map = getHms(key, field);
|
||||||
|
return map.get(field);
|
||||||
|
}
|
||||||
|
|
||||||
|
public <T extends Object> Map<T, V> getHms(String key, T... field) {
|
||||||
|
if (field == null || field.length == 0) {
|
||||||
|
return new HashMap<>();
|
||||||
|
}
|
||||||
|
byte[][] bytes = Stream.concat(Stream.of(key), Stream.of(field)).map(x -> String.valueOf(x).getBytes(StandardCharsets.UTF_8)).toArray(byte[][]::new);
|
||||||
|
Map<T, V> result = new HashMap<>();
|
||||||
|
|
||||||
|
List<V> vs = (List) send("HMGET", CacheEntryType.OBJECT, (Type) null, key, bytes).join();
|
||||||
|
for (int i = 0; i < field.length; i++) { // /*vs != null && vs.size() > i &&*/
|
||||||
|
if (vs.get(i) == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
result.put(field[i], vs.get(i));
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, V> getHmall(String key) {
|
||||||
|
List<V> vs = (List) send("HGETALL", CacheEntryType.OBJECT, (Type) null, key, key.getBytes(StandardCharsets.UTF_8)).join();
|
||||||
|
Map<String, V> result = new HashMap<>(vs.size() / 2);
|
||||||
|
for (int i = 0; i < vs.size(); i += 2) {
|
||||||
|
result.put(String.valueOf(vs.get(i)), vs.get(i + 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
//--------------------- hmset、hmdel、incr ------------------------------
|
||||||
|
public <T> void setHm(String key, T field, V value) {
|
||||||
|
byte[][] bytes = Stream.of(key, field, value).map(x -> x.toString().getBytes(StandardCharsets.UTF_8)).toArray(byte[][]::new);
|
||||||
|
send("HMSET", CacheEntryType.OBJECT, (Type) null, key, bytes).join();
|
||||||
|
}
|
||||||
|
|
||||||
|
public <T> void setHms(String key, Map<T, V> kv) {
|
||||||
|
List<String> args = new ArrayList();
|
||||||
|
args.add(key);
|
||||||
|
|
||||||
|
kv.forEach((k, v) -> {
|
||||||
|
args.add(String.valueOf(k));
|
||||||
|
args.add(String.valueOf(v));
|
||||||
|
});
|
||||||
|
|
||||||
|
byte[][] bytes = args.stream().map(x -> x.getBytes(StandardCharsets.UTF_8)).toArray(byte[][]::new);
|
||||||
|
send("HMSET", CacheEntryType.OBJECT, (Type) null, key, bytes).join();
|
||||||
|
}
|
||||||
|
|
||||||
|
public <T> Long incrHm(String key, T field, long n) {
|
||||||
|
byte[][] bytes = Stream.of(key, String.valueOf(field), String.valueOf(n)).map(x -> x.getBytes(StandardCharsets.UTF_8)).toArray(byte[][]::new);
|
||||||
|
return (Long) send("HINCRBY", CacheEntryType.OBJECT, (Type) null, key, bytes).join();
|
||||||
|
}
|
||||||
|
|
||||||
|
public <T> Double incrHm(String key, T field, double n) {
|
||||||
|
byte[][] bytes = Stream.of(key, String.valueOf(field), String.valueOf(n)).map(x -> x.getBytes(StandardCharsets.UTF_8)).toArray(byte[][]::new);
|
||||||
|
Serializable v = send("HINCRBYFLOAT", CacheEntryType.OBJECT, (Type) null, key, bytes).join();
|
||||||
|
if (v == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return Double.parseDouble(String.valueOf(v));
|
||||||
|
}
|
||||||
|
|
||||||
|
public <T> void hdel(String key, T... field) {
|
||||||
|
byte[][] bytes = Stream.concat(Stream.of(key), Stream.of(field)).map(x -> String.valueOf(x).getBytes(StandardCharsets.UTF_8)).toArray(byte[][]::new);
|
||||||
|
send("HDEL", null, (Type) null, key, bytes).join();
|
||||||
|
}
|
||||||
|
|
||||||
|
public <T> List<T> zexists(String key, T... fields) {
|
||||||
|
if (fields == null || fields.length == 0) {
|
||||||
|
return new ArrayList<>();
|
||||||
|
}
|
||||||
|
List<String> para = new ArrayList<>();
|
||||||
|
para.add("" +
|
||||||
|
" local key = KEYS[1];" +
|
||||||
|
" local args = ARGV;" +
|
||||||
|
" local result = {};" +
|
||||||
|
" for i,v in ipairs(args) do" +
|
||||||
|
" local inx = redis.call('ZREVRANK', key, v);" +
|
||||||
|
" if(inx) then" +
|
||||||
|
" table.insert(result,1,v);" +
|
||||||
|
" end" +
|
||||||
|
" end" +
|
||||||
|
" return result;");
|
||||||
|
para.add("1");
|
||||||
|
para.add(key);
|
||||||
|
for (Object field : fields) {
|
||||||
|
para.add(String.valueOf(field));
|
||||||
|
}
|
||||||
|
byte[][] bytes = para.stream().map(x -> String.valueOf(x).getBytes(StandardCharsets.UTF_8)).toArray(byte[][]::new);
|
||||||
|
return (List<T>) send("EVAL", CacheEntryType.OBJECT, (Type) null, null, bytes).join();
|
||||||
|
}
|
||||||
|
|
||||||
|
//--------------------- set ------------------------------
|
||||||
|
public <T> T srandomItem(String key) {
|
||||||
|
byte[][] bytes = Stream.of(key, 1).map(x -> formatValue(CacheEntryType.OBJECT, (Convert) null, (Type) null, x)).toArray(byte[][]::new);
|
||||||
|
List<T> list = (List) send("SRANDMEMBER", null, (Type) null, key, bytes).join();
|
||||||
|
return list != null && !list.isEmpty() ? list.get(0) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public <T> List<T> srandomItems(String key, int n) {
|
||||||
|
byte[][] bytes = Stream.of(key, n).map(x -> formatValue(CacheEntryType.OBJECT, (Convert) null, (Type) null, x)).toArray(byte[][]::new);
|
||||||
|
return (List) send("SRANDMEMBER", null, (Type) null, key, bytes).join();
|
||||||
|
}
|
||||||
|
|
||||||
|
//--------------------- list ------------------------------
|
||||||
|
public CompletableFuture<Void> appendListItemsAsync(String key, V... values) {
|
||||||
|
byte[][] bytes = Stream.concat(Stream.of(key), Stream.of(values)).map(x -> String.valueOf(x).getBytes(StandardCharsets.UTF_8)).toArray(byte[][]::new);
|
||||||
|
return (CompletableFuture) send("RPUSH", null, (Type) null, key, bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
public CompletableFuture<Void> lpushListItemAsync(String key, V value) {
|
||||||
|
return (CompletableFuture) send("LPUSH", null, (Type) null, key, key.getBytes(StandardCharsets.UTF_8), formatValue(CacheEntryType.OBJECT, (Convert) null, (Type) null, value));
|
||||||
|
}
|
||||||
|
|
||||||
|
public void lpushListItem(String key, V value) {
|
||||||
|
lpushListItemAsync(key, value).join();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void appendListItems(String key, V... values) {
|
||||||
|
appendListItemsAsync(key, values).join();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void appendSetItems(String key, V... values) {
|
||||||
|
// todo:
|
||||||
|
for (V v : values) {
|
||||||
|
appendSetItem(key, v);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
||||||
|
public CompletableFuture<Collection<V>> getCollectionAsync(String key, int offset, int limit) {
|
||||||
|
return (CompletableFuture) send("OBJECT", null, (Type) null, key, "ENCODING".getBytes(StandardCharsets.UTF_8), key.getBytes(StandardCharsets.UTF_8)).thenCompose(t -> {
|
||||||
|
if (t == null) return CompletableFuture.completedFuture(null);
|
||||||
|
if (new String((byte[]) t).contains("list")) { //list
|
||||||
|
return send("LRANGE", CacheEntryType.OBJECT, (Type) null, false, key, key.getBytes(StandardCharsets.UTF_8), String.valueOf(offset).getBytes(StandardCharsets.UTF_8), String.valueOf(offset + limit - 1).getBytes(StandardCharsets.UTF_8));
|
||||||
|
} else {
|
||||||
|
return send("SMEMBERS", CacheEntryType.OBJECT, (Type) null, true, key, key.getBytes(StandardCharsets.UTF_8));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public Collection<V> getCollection(String key, int offset, int limit) {
|
||||||
|
return getCollectionAsync(key, offset, limit).join();
|
||||||
|
}
|
||||||
|
|
||||||
|
public V brpop(String key, int seconds) {
|
||||||
|
byte[][] bytes = Stream.concat(Stream.of(key), Stream.of(seconds)).map(x -> String.valueOf(x).getBytes(StandardCharsets.UTF_8)).toArray(byte[][]::new);
|
||||||
|
return (V) send("BRPOP", null, (Type) null, key, bytes).join();
|
||||||
|
}
|
||||||
|
|
||||||
|
//--------------------- zset ------------------------------
|
||||||
|
public <N extends Number> void zadd(String key, Map<V, N> kv) {
|
||||||
|
if (kv == null || kv.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
List<String> args = new ArrayList();
|
||||||
|
args.add(key);
|
||||||
|
|
||||||
|
kv.forEach((k, v) -> {
|
||||||
|
args.add(String.valueOf(v));
|
||||||
|
args.add(String.valueOf(k));
|
||||||
|
});
|
||||||
|
|
||||||
|
byte[][] bytes = args.stream().map(x -> x.getBytes(StandardCharsets.UTF_8)).toArray(byte[][]::new);
|
||||||
|
send("ZADD", CacheEntryType.OBJECT, (Type) null, key, bytes).join();
|
||||||
|
}
|
||||||
|
|
||||||
|
public <N extends Number> double zincr(String key, Object number, N n) {
|
||||||
|
byte[][] bytes = Stream.of(key, n, number).map(x -> String.valueOf(x).getBytes(StandardCharsets.UTF_8)).toArray(byte[][]::new);
|
||||||
|
Serializable v = send("ZINCRBY", CacheEntryType.OBJECT, (Type) null, key, bytes).join();
|
||||||
|
return Double.parseDouble(String.valueOf(v));
|
||||||
|
}
|
||||||
|
|
||||||
|
public void zrem(String key, V... vs) {
|
||||||
|
List<String> args = new ArrayList();
|
||||||
|
args.add(key);
|
||||||
|
for (V v : vs) {
|
||||||
|
args.add(String.valueOf(v));
|
||||||
|
}
|
||||||
|
byte[][] bytes = args.stream().map(x -> x.getBytes(StandardCharsets.UTF_8)).toArray(byte[][]::new);
|
||||||
|
send("ZREM", CacheEntryType.OBJECT, (Type) null, key, bytes).join();
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getZrank(String key, V v) {
|
||||||
|
byte[][] bytes = Stream.of(key, v).map(x -> String.valueOf(x).getBytes(StandardCharsets.UTF_8)).toArray(byte[][]::new);
|
||||||
|
Long t = (Long) send("ZRANK", CacheEntryType.OBJECT, (Type) null, key, bytes).join();
|
||||||
|
|
||||||
|
return t == null ? -1 : (int) (long) t;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getZrevrank(String key, V v) {
|
||||||
|
byte[][] bytes = Stream.of(key, v).map(x -> String.valueOf(x).getBytes(StandardCharsets.UTF_8)).toArray(byte[][]::new);
|
||||||
|
Long t = (Long) send("ZREVRANK", CacheEntryType.OBJECT, (Type) null, key, bytes).join();
|
||||||
|
|
||||||
|
return t == null ? -1 : (int) (long) t;
|
||||||
|
}
|
||||||
|
|
||||||
|
//ZRANGE/ZREVRANGE key start stop
|
||||||
|
public List<V> getZset(String key) {
|
||||||
|
byte[][] bytes = Stream.of(key, 0, -1).map(x -> String.valueOf(x).getBytes(StandardCharsets.UTF_8)).toArray(byte[][]::new);
|
||||||
|
List<V> vs = (List<V>) send("ZREVRANGE", CacheEntryType.OBJECT, (Type) null, key, bytes).join();
|
||||||
|
List<V> vs2 = new ArrayList(vs.size());
|
||||||
|
|
||||||
|
for (int i = 0; i < vs.size(); ++i) {
|
||||||
|
if (i % 2 == 1) {
|
||||||
|
vs2.add(this.convert.convertFrom(this.objValueType, String.valueOf(vs.get(i))));
|
||||||
|
} else {
|
||||||
|
vs2.add(vs.get(i));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return vs2;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<V> getZset(String key, int offset, int limit) {
|
||||||
|
byte[][] bytes = Stream.of(key, offset, offset + limit - 1).map(x -> String.valueOf(x).getBytes(StandardCharsets.UTF_8)).toArray(byte[][]::new);
|
||||||
|
List<V> vs = (List<V>) send("ZREVRANGE", CacheEntryType.OBJECT, (Type) null, key, bytes).join();
|
||||||
|
List<V> vs2 = new ArrayList(vs.size());
|
||||||
|
|
||||||
|
for (int i = 0; i < vs.size(); ++i) {
|
||||||
|
if (i % 2 == 1) {
|
||||||
|
vs2.add(this.convert.convertFrom(this.objValueType, String.valueOf(vs.get(i))));
|
||||||
|
} else {
|
||||||
|
vs2.add(vs.get(i));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return vs2;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LinkedHashMap<V, Long> getZsetLongScore(String key) {
|
||||||
|
LinkedHashMap<V, Double> map = getZsetDoubleScore(key);
|
||||||
|
if (map.isEmpty()) {
|
||||||
|
return new LinkedHashMap<>();
|
||||||
|
}
|
||||||
|
|
||||||
|
LinkedHashMap<V, Long> map2 = new LinkedHashMap<>(map.size());
|
||||||
|
map.forEach((k, v) -> map2.put(k, (long) (double) v));
|
||||||
|
return map2;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LinkedHashMap<V, Long> getZsetItemsLongScore(String key) {
|
||||||
|
byte[][] bytes = Stream.of(key, 0, -1, "WITHSCORES").map(x -> String.valueOf(x).getBytes(StandardCharsets.UTF_8)).toArray(byte[][]::new);
|
||||||
|
List vs = (List) send("ZRANGE", CacheEntryType.OBJECT, (Type) null, key, bytes).join();
|
||||||
|
|
||||||
|
LinkedHashMap<V, Long> map = new LinkedHashMap<>();
|
||||||
|
for (int i = 0; i < vs.size(); i += 2) {
|
||||||
|
map.put((V) vs.get(i), (long) Double.parseDouble((String) vs.get(i + 1)));
|
||||||
|
}
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getZsetLongScore(String key, V v) {
|
||||||
|
Double score = getZsetDoubleScore(key, v);
|
||||||
|
if (score == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return (long) (double) score;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LinkedHashMap<V, Double> getZsetDoubleScore(String key) {
|
||||||
|
byte[][] bytes = Stream.of(key, 0, -1, "WITHSCORES").map(x -> String.valueOf(x).getBytes(StandardCharsets.UTF_8)).toArray(byte[][]::new);
|
||||||
|
List vs = (List) send("ZREVRANGE", CacheEntryType.OBJECT, (Type) null, key, bytes).join();
|
||||||
|
|
||||||
|
LinkedHashMap<V, Double> map = new LinkedHashMap<>();
|
||||||
|
for (int i = 0; i < vs.size(); i += 2) {
|
||||||
|
map.put((V) vs.get(i), Double.parseDouble((String) vs.get(i + 1)));
|
||||||
|
}
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Double getZsetDoubleScore(String key, V v) {
|
||||||
|
byte[][] bytes = Stream.of(key, v).map(x -> String.valueOf(x).getBytes(StandardCharsets.UTF_8)).toArray(byte[][]::new);
|
||||||
|
Serializable zscore = send("ZSCORE", CacheEntryType.OBJECT, (Type) null, key, bytes).join();
|
||||||
|
if (zscore == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Double.parseDouble(String.valueOf(zscore));
|
||||||
|
}
|
||||||
|
|
||||||
|
public LinkedHashMap<V, Long> getZsetLongScore(String key, int offset, int limit) {
|
||||||
|
byte[][] bytes = Stream.of(key, offset, offset + limit - 1, "WITHSCORES").map(x -> String.valueOf(x).getBytes(StandardCharsets.UTF_8)).toArray(byte[][]::new);
|
||||||
|
List vs = (List) send("ZREVRANGE", CacheEntryType.OBJECT, (Type) null, key, bytes).join();
|
||||||
|
|
||||||
|
LinkedHashMap<V, Long> map = new LinkedHashMap<>();
|
||||||
|
for (int i = 0; i < vs.size(); i += 2) {
|
||||||
|
map.put((V) vs.get(i), (long) Double.parseDouble((String) vs.get(i + 1)));
|
||||||
|
}
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LinkedHashMap<V, Double> getZsetDoubleScore(String key, int offset, int limit) {
|
||||||
|
byte[][] bytes = Stream.of(key, offset, offset + limit - 1, "WITHSCORES").map(x -> String.valueOf(x).getBytes(StandardCharsets.UTF_8)).toArray(byte[][]::new);
|
||||||
|
List vs = (List) send("ZREVRANGE", CacheEntryType.OBJECT, (Type) null, key, bytes).join();
|
||||||
|
|
||||||
|
LinkedHashMap<V, Double> map = new LinkedHashMap<>();
|
||||||
|
for (int i = 0; i < vs.size(); i += 2) {
|
||||||
|
map.put((V) vs.get(i), Double.parseDouble(vs.get(i + 1) + ""));
|
||||||
|
}
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----------
|
||||||
|
protected byte[] formatValue(CacheEntryType cacheType, Convert convert0, Type resultType, Object value) {
|
||||||
|
if (value == null) return "null".getBytes(StandardCharsets.UTF_8);
|
||||||
|
if (convert0 == null) convert0 = convert;
|
||||||
|
if (cacheType == CacheEntryType.LONG || cacheType == CacheEntryType.ATOMIC)
|
||||||
|
return String.valueOf(value).getBytes(StandardCharsets.UTF_8);
|
||||||
|
if (cacheType == CacheEntryType.STRING) return convert0.convertToBytes(String.class, value);
|
||||||
|
|
||||||
|
if (value instanceof String) return String.valueOf(value).getBytes(StandardCharsets.UTF_8);
|
||||||
|
if (value instanceof Number) return String.valueOf(value).getBytes(StandardCharsets.UTF_8);
|
||||||
|
return convert0.convertToBytes(resultType == null ? objValueType : resultType, value);
|
||||||
|
}
|
||||||
|
}
|
2240
src/main/java/org/redkalex/cache/redis/RedisCacheSource.java
vendored
Normal file
2240
src/main/java/org/redkalex/cache/redis/RedisCacheSource.java
vendored
Normal file
File diff suppressed because it is too large
Load Diff
244
src/main/java/org/redkalex/cache/redis/RedisTest.java
vendored
Normal file
244
src/main/java/org/redkalex/cache/redis/RedisTest.java
vendored
Normal file
@@ -0,0 +1,244 @@
|
|||||||
|
package org.redkalex.cache.redis;
|
||||||
|
|
||||||
|
import org.redkale.convert.json.JsonFactory;
|
||||||
|
import org.redkale.util.AnyValue;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class RedisTest {
|
||||||
|
|
||||||
|
static MyRedisCacheSource<String> source = new MyRedisCacheSource();
|
||||||
|
|
||||||
|
static {
|
||||||
|
AnyValue.DefaultAnyValue conf = new AnyValue.DefaultAnyValue();
|
||||||
|
conf.addValue("node", new AnyValue.DefaultAnyValue().addValue("addr", "47.111.150.118").addValue("port", "6064").addValue("password", "*Zhong9307!").addValue("db", 2));
|
||||||
|
|
||||||
|
source.defaultConvert = JsonFactory.root().getConvert();
|
||||||
|
source.initValueType(String.class); //value用String类型
|
||||||
|
source.init(conf);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
|
||||||
|
//System.out.println(source.remove("a", "b"));
|
||||||
|
|
||||||
|
// bit
|
||||||
|
/*source.initValueType(Integer.class);
|
||||||
|
source.remove("a");
|
||||||
|
boolean a = source.getBit("a", 1);
|
||||||
|
System.out.println(a);
|
||||||
|
|
||||||
|
source.setBit("a", 1, true);
|
||||||
|
a = source.getBit("a", 1);
|
||||||
|
System.out.println("bit-a-1: " + a);
|
||||||
|
|
||||||
|
source.setBit("a", 1, false);
|
||||||
|
a = source.getBit("a", 1);
|
||||||
|
System.out.println("bit-a-1: " + a);*/
|
||||||
|
|
||||||
|
/*source.remove("a");
|
||||||
|
|
||||||
|
// setnx
|
||||||
|
System.out.println(source.setnx("a", 1));
|
||||||
|
source.remove("a");
|
||||||
|
System.out.println(source.setnx("a", 1));
|
||||||
|
|
||||||
|
// set
|
||||||
|
source.remove("abx1");
|
||||||
|
source.appendSetItems("abx1", "a", "b", "c");
|
||||||
|
List<String> list = source.srandomItems("abx1", 2);
|
||||||
|
String str = source.srandomItem("abx1"); //r
|
||||||
|
System.out.println(list);//[r1, r2] */
|
||||||
|
|
||||||
|
/*int[] arr = {0};
|
||||||
|
ExecutorService executor = Executors.newFixedThreadPool(10);
|
||||||
|
CountDownLatch latch = new CountDownLatch(10_0000);
|
||||||
|
for (int i = 0; i < 10_0000; i++) {
|
||||||
|
executor.submit(() -> {
|
||||||
|
try {
|
||||||
|
source.lock("a", 50000);
|
||||||
|
arr[0]++;
|
||||||
|
System.out.println("Thread: " + Thread.currentThread().getName());
|
||||||
|
Thread.sleep(2000);
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
} finally {
|
||||||
|
source.unlock("a");
|
||||||
|
latch.countDown();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
latch.await();
|
||||||
|
System.out.println("n=" + arr[0]);
|
||||||
|
executor.shutdown();
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}*/
|
||||||
|
|
||||||
|
|
||||||
|
/*List<String> list = (List) source.getCollection("gamerank-comment-stat");
|
||||||
|
System.out.println(list);*/
|
||||||
|
|
||||||
|
/*for (int i = 0; i < 10; i++) {
|
||||||
|
String brpop = source.brpop("z", 2);
|
||||||
|
System.out.println(brpop);
|
||||||
|
}*/
|
||||||
|
|
||||||
|
// key 测试
|
||||||
|
/*source.set("a", "123321");
|
||||||
|
System.out.println(source.get("a")); // 123321
|
||||||
|
System.out.println(source.getTtl("a")); // -1
|
||||||
|
System.out.println(source.getPttl("a")); // -1
|
||||||
|
System.out.println(source.getPttl("x")); // -2*/
|
||||||
|
|
||||||
|
// hashmap 测试
|
||||||
|
/*source.remove("sk");
|
||||||
|
source.setHm("sk", "a", "1");
|
||||||
|
source.setHm("sk", "b", "2");
|
||||||
|
System.out.println(source.getHm("sk", "a")); // 1
|
||||||
|
source.remove("sk");
|
||||||
|
|
||||||
|
source.setHms("sk", Map.of("b", "5", "c", "3", "a", "1"));
|
||||||
|
source.hdel("sk", "a");
|
||||||
|
|
||||||
|
Map map = source.getHms("sk", "a", "x", "b", "c", "f"); // {b=5, c=3}
|
||||||
|
System.out.println(map);
|
||||||
|
System.out.println(source.getHmall("sk")); //{b=5, c=3}
|
||||||
|
System.out.println(source.incrHm("sk", "b", 1.1d)); // b = 6.1
|
||||||
|
System.out.println(source.incrHm("sk", "c", 1)); // c = 4
|
||||||
|
System.out.println(source.getHmall("sk")); //{b=6.1, c=4}
|
||||||
|
|
||||||
|
System.out.println("--------------");
|
||||||
|
System.out.println(source.hexists("sk", "b")); // true
|
||||||
|
System.out.println(source.getCollectionSize("sk")); // 2*/
|
||||||
|
|
||||||
|
|
||||||
|
Map<String, String> hms = source.getHms("supportusers", "5-kfeu0f", "xxxx", "3-0kbt7u8t", "95q- ");
|
||||||
|
hms.forEach((k, v) -> {
|
||||||
|
System.out.println(k + " : " + v);
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
/*MyRedisCacheSource<String> source2 = new MyRedisCacheSource();
|
||||||
|
source2.defaultConvert = JsonFactory.root().getConvert();
|
||||||
|
source2.initValueType(String.class); //value用String类型
|
||||||
|
source2.init(conf);*/
|
||||||
|
|
||||||
|
/*Map<String, String> gcMap = source.getHmall("hot-gamecomment");
|
||||||
|
gcMap.forEach((k,v) -> {
|
||||||
|
System.out.println(k + " : " + v);
|
||||||
|
});*/
|
||||||
|
|
||||||
|
|
||||||
|
//Map<String, String> gameinfo = source.getHms("gameinfo", "22759", "22838", "10097", "22751", "22632", "22711", "22195", "15821", "10099", "16313", "11345", "10534", "22768", "22647", "22924", "18461", "15871", "17099", "22640", "22644", "10744", "10264", "18032", "22815", "13584", "10031", "22818", "22452", "22810", "10513", "10557", "15848", "11923", "15920", "22808", "20073", "22809", "15840", "12332", "15803", "10597", "22624", "17113", "19578", "22664", "22621", "20722", "16226", "10523", "12304", "10597","11923","10031");
|
||||||
|
//Map<String, String> gameinfo = source.getHms("gameinfo", "22759","22838","10097","22751","22632","22711","22195","15821","10099","16313","11345","10534","22768","22647","22924","18461","15871","17099","22363","22640","22644","10744","10264","18032","22815","13584","22818","22452","22810","10513","10557","15848","15920","22808","20073","22809","15840","12332","15803","10597","22624","17113","19578","22627","22664","22621","20722","16226","10523","12304");
|
||||||
|
|
||||||
|
/*gameinfo.forEach((k,v ) -> {
|
||||||
|
System.out.println(v);
|
||||||
|
});*/
|
||||||
|
|
||||||
|
|
||||||
|
/*source.queryKeysStartsWith("articlebean:").forEach(x -> {
|
||||||
|
System.out.println(x);
|
||||||
|
//source.remove(x);
|
||||||
|
//System.out.println(source.getHmall(x));
|
||||||
|
});*/
|
||||||
|
|
||||||
|
// list 测试
|
||||||
|
/*MyRedisCacheSource<Integer> sourceInt = new MyRedisCacheSource();
|
||||||
|
sourceInt.defaultConvert = JsonFactory.root().getConvert();
|
||||||
|
sourceInt.initValueType(Integer.class); //value用String类型
|
||||||
|
sourceInt.init(conf);
|
||||||
|
sourceInt.remove("list");
|
||||||
|
Collection<Integer> list = sourceInt.getCollection("list");
|
||||||
|
System.out.println(list);
|
||||||
|
for (int i = 1; i <= 10; i++) {
|
||||||
|
sourceInt.appendListItem("list", i);
|
||||||
|
}
|
||||||
|
System.out.println(sourceInt.getCollection("list")); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
||||||
|
|
||||||
|
sourceInt.appendListItems("list", 11, 12, 13);
|
||||||
|
System.out.println(sourceInt.getCollection("list")); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
|
||||||
|
System.out.println(sourceInt.getCollection("list", 0, 5)); // [1, 2, 3, 4, 5]
|
||||||
|
System.out.println(sourceInt.getCollectionSize("list")); // 13
|
||||||
|
|
||||||
|
List<Integer> ids = new ArrayList<>(100);
|
||||||
|
for (int i = 0; i < 5000; i++) {
|
||||||
|
ids.add(i);
|
||||||
|
}
|
||||||
|
sourceInt.remove("abx");
|
||||||
|
sourceInt.appendListItems("abx", ids.toArray(Integer[]::new));
|
||||||
|
System.out.println(sourceInt.getCollection("abx"));*/
|
||||||
|
|
||||||
|
/*System.out.println(sourceInt.getCollectionSize("recommend-user-quality"));
|
||||||
|
Collection<Integer> uid = sourceInt.getCollection("recommend-user-quality");
|
||||||
|
System.out.println(uid);*/
|
||||||
|
|
||||||
|
// zset 测试
|
||||||
|
/*source.initValueType(String.class); //value用Integer类型
|
||||||
|
source.remove("zx");
|
||||||
|
source.zadd("zx", Map.of("a", 1, "b", 2));
|
||||||
|
|
||||||
|
source.zadd("zx", Map.of("a", 1, "c", 5L));
|
||||||
|
source.zadd("zx", Map.of("x", 20, "j", 3.5));
|
||||||
|
source.zadd("zx", Map.of("f", System.currentTimeMillis(), "c", 5L));
|
||||||
|
source.zadd("zx", Map.of("a", 1, "c", 5L));
|
||||||
|
|
||||||
|
System.out.println(source.zincr("zx", "a", 1.34)); // 2.34
|
||||||
|
System.out.println(source.getZsetDoubleScore("zx")); // {f=1592924555704, x=20, c=5, j=3, b=2.34, a=1}
|
||||||
|
source.zrem("zx", "b", "c", "e", "x");
|
||||||
|
System.out.println(source.getZsetLongScore("zx")); // {f=1592924555704, j=3, a=2}
|
||||||
|
|
||||||
|
System.out.println("--------------");
|
||||||
|
System.out.println(source.getZsetLongScore("zx", "f"));
|
||||||
|
|
||||||
|
System.out.println(source.getZrevrank("zx", "f")); // 0
|
||||||
|
System.out.println(source.getZrank("zx", "f")); // 2
|
||||||
|
System.out.println(source.getZrank("zx", "Y")); // -1
|
||||||
|
System.out.println(source.getCollectionSize("zx")); // 3
|
||||||
|
|
||||||
|
System.out.println(source.getZset("zx"));
|
||||||
|
System.out.println(source.zexists("zx", "f", "x", "a"));*/
|
||||||
|
|
||||||
|
/*LocalDate date = LocalDate.of(2019, 12, 31);
|
||||||
|
for (int i = 0; i < 60; i++) {
|
||||||
|
LocalDate localDate = date.plusDays(-i);
|
||||||
|
String day = localDate.format(DateTimeFormatter.ISO_LOCAL_DATE);
|
||||||
|
System.out.println(String.format("mkdir %s; mv *%s*.zip %s", day, day, day));
|
||||||
|
}*/
|
||||||
|
|
||||||
|
|
||||||
|
/*MyRedisCacheSource<UserDetail> source = new MyRedisCacheSource();
|
||||||
|
source.defaultConvert = JsonFactory.root().getConvert();
|
||||||
|
source.initValueType(UserDetail.class);
|
||||||
|
source.init(conf);
|
||||||
|
|
||||||
|
|
||||||
|
Map<String, UserDetail> map = source.getHmall("user-detail");
|
||||||
|
|
||||||
|
Integer[] array = map.values().stream().map(x -> x.getUserid()).toArray(Integer[]::new);
|
||||||
|
|
||||||
|
System.out.println(JsonConvert.root().convertTo(array));
|
||||||
|
|
||||||
|
Map<Integer, UserDetail> hms = source.getHms("user-detail", 11746, 11988, 11504, 11987, 11745, 11503, 11748, 11506, 11747, 11989, 11505, 11508, 11507, 11509, 11980, 11740, 11982, 11981, 11984, 11742, 11500, 11983, 11741, 11502, 11744, 11986, 11985, 11501, 11743, 11999, 11757, 11515, 1, 11514, 11998, 11756, 2, 11517, 11516, 11758, 3, 11519, 4, 5, 11518, 6, 7, 11991, 8, 11990, 9, 11993, 11751, 11750, 11992, 11753, 11511, 11995, 11994, 11510, 11752, 11755, 11513, 11997, 11512, 11996, 11754, 11724, 11966, 11965, 11723, 11968, 11726, 11967, 11725, 11728, 11969, 11727, 11729, 11960, 11720, 11962, 11961, 11722, 11964, 11721);
|
||||||
|
|
||||||
|
System.out.println(hms.size());*/
|
||||||
|
|
||||||
|
/*source.getCollection("article-comment-list", 19, 1).forEach(x -> System.out.println(x));
|
||||||
|
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
System.out.println("---" + Utility.now() + "---");
|
||||||
|
source.getHmall("ck").forEach((k, v) -> {
|
||||||
|
System.out.println(k + ":" + v);
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
Thread.sleep(60 * 1000);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}*/
|
||||||
|
}
|
||||||
|
}
|
1944
src/main/java/org/redkalex/cache/redis/RedissionCacheSource.java
vendored
Normal file
1944
src/main/java/org/redkalex/cache/redis/RedissionCacheSource.java
vendored
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1 @@
|
|||||||
|
net.tccn.ZhubProvider
|
@@ -0,0 +1 @@
|
|||||||
|
org.redkalex.cache.redis.RedisCacheSourceProvider
|
@@ -1,7 +0,0 @@
|
|||||||
|
|
||||||
# zhub 配置
|
|
||||||
zhub:
|
|
||||||
appid: local_api
|
|
||||||
addr: 127.0.0.1:1216
|
|
||||||
groupid: hub-api
|
|
||||||
auth: token-12345
|
|
@@ -1,108 +0,0 @@
|
|||||||
import org.junit.Before;
|
|
||||||
import org.junit.Test;
|
|
||||||
import net.tccn.IType;
|
|
||||||
import net.tccn.zhub.Lock;
|
|
||||||
import net.tccn.zhub.ZHubClient;
|
|
||||||
|
|
||||||
// @RestService(automapping = true)
|
|
||||||
public class HelloService {
|
|
||||||
|
|
||||||
// @Resource(name = "zhub")
|
|
||||||
private ZHubClient zhub;
|
|
||||||
|
|
||||||
@Before
|
|
||||||
public void init() {
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
//zhub = new ZHubClient("127.0.0.1:1216", "g-dev", "DEV-LOCAL", "zchd@123456");
|
|
||||||
zhub = new ZHubClient("127.0.0.1:1216", "g-dev", "DEV-LOCAL", "token-12345");
|
|
||||||
|
|
||||||
zhub.subscribe("tv:test", x -> {
|
|
||||||
System.out.println(x);
|
|
||||||
});
|
|
||||||
|
|
||||||
Lock lock = zhub.tryLock("lock-a", 5);
|
|
||||||
System.out.println("lock-1: " + lock.success());
|
|
||||||
|
|
||||||
//zhub.init(Kv.of("host", "47.111.150.118", "port", "6066", "groupid", "g-dev", "appname", "DEV-LOCAL"));
|
|
||||||
|
|
||||||
// Function<Rpc<T>, RpcResult<R>> fun
|
|
||||||
/*zhub.rpcSubscribe("x", new TypeToken<String>() {
|
|
||||||
}, r -> {
|
|
||||||
return r.buildResp(Map.of("v", r.getValue().toUpperCase() + ": Ok"));
|
|
||||||
});
|
|
||||||
|
|
||||||
zhub.subscribe("sport:reqtime", x -> {
|
|
||||||
//System.out.println(x);
|
|
||||||
});
|
|
||||||
zhub.subscribe("abx", x -> {
|
|
||||||
System.out.println(x);
|
|
||||||
});
|
|
||||||
|
|
||||||
try {
|
|
||||||
Thread.sleep(010);
|
|
||||||
} catch (InterruptedException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
|
|
||||||
zhub.delay("sport:reqtime", "别✈人家的✦女娃子❤🤞🏻", 0);
|
|
||||||
zhub.delay("sport:reqtime", "别人家的女娃子➾🤞🏻", 0);
|
|
||||||
zhub.delay("sport:reqtime", "❤别人家✉<E5AEB6>的女娃子❤🤞🏻", 0);*/
|
|
||||||
/*zhub.delay("sport:reqtime", "中文特殊符号:『』 $ £ ♀ ‖ 「」\n" +
|
|
||||||
"英文:# + = & ﹉ .. ^ \"\" ·{ } % – ' €\n" +
|
|
||||||
"数学:+× = - ° ± < > ℃ ㎡ ∑ ≥ ∫ ㏄ ⊥ ≯ ∠ ∴ ∈ ∧ ∵ ≮ ∪ ㎝ ㏑ ≌ ㎞ № § ℉ ÷ % ‰ ㎎ ㎏ ㎜ ㏒ ⊙ ∮ ∝ ∞ º ¹ ² ³ ½ ¾ ¼ ≈ ≡ ≠ ≤ ≦ ≧ ∽ ∷ / ∨ ∏ ∩ ⌒ √Ψ ¤ ‖ ¶\n" +
|
|
||||||
"特殊:♤ ♧ ♡ ♢ ♪ ♬ ♭ ✔ ✘ ♞ ♟ ↪ ↣ ♚ ♛ ♝ ☞ ☜ ⇔ ☆ ★ □ ■ ○ ● △ ▲ ▽ ▼ ◇ ◆ ♀ ♂ ※ ↓ ↑ ↔ ↖ ↙ ↗ ↘ ← → ♣ ♠ ♥ ◎ ◣ ◢ ◤ ◥ 卍 ℡ ⊙ ㊣ ® © ™ ㈱ 囍\n" +
|
|
||||||
"序号:①②③④⑤⑥⑦⑧⑨⑩㈠㈡㈢㈣㈤㈥㈦㈧㈨㈩⑴ ⑵ ⑶ ⑷ ⑸ ⑹ ⑺ ⑻ ⑼ ⑽ ⒈ ⒉ ⒊ ⒋ ⒌ ⒍ ⒎ ⒏ ⒐ ⒑ Ⅰ Ⅱ Ⅲ Ⅳ Ⅴ Ⅵ Ⅶ Ⅷ ⅨⅩ\n" +
|
|
||||||
"日文:アイウエオァィゥェォカキクケコガギグゲゴサシスセソザジズゼゾタチツテトダヂヅデドッナニヌネノハヒフヘホバビブベボパピプペポマミムメモャヤュユョラリヨルレロワヰヱヲンヴヵヶヽヾ゛゜ー、。「「あいうえおぁぃぅぇぉかきくけこがぎぐげごさしすせそざじずぜぞたちつてでどっなにぬねのはひふへ」」ほばびぶべぼぱぴぷぺぽまみむめもやゆよゃゅょらりるれろわをんゎ゛゜ー、。「」\n" +
|
|
||||||
"部首:犭 凵 巛 冖 氵 廴 讠 亻 钅 宀 亠 忄 辶 弋 饣 刂 阝 冫 卩 疒 艹 疋 豸 冂 匸 扌 丬 屮衤 礻 勹 彳 彡", 0);*/
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void rpcTest() {
|
|
||||||
//RpcResult<String> rpc = zhub.rpc("wx:users", Map.of("appId", "wxa554ec3ab3bf1fc7"), IConsumer.TYPE_TOKEN_STRING);
|
|
||||||
//RpcResult<String> rpc = zhub.rpc("a", "fa", IConsumer.TYPE_TOKEN_STRING);
|
|
||||||
zhub.publish("tv:test", "hello ym!");
|
|
||||||
|
|
||||||
zhub.subscribe("tv:abx", x -> {
|
|
||||||
System.out.println(x);
|
|
||||||
});
|
|
||||||
|
|
||||||
zhub.rpcSubscribe("rpc-x", IType.STRING, x -> {
|
|
||||||
return x.render(x.getValue().toUpperCase());
|
|
||||||
});
|
|
||||||
|
|
||||||
Lock lock = zhub.tryLock("lock-a", 5);
|
|
||||||
System.out.println("lock-2: " + lock.success());
|
|
||||||
|
|
||||||
try {
|
|
||||||
Thread.sleep(5 * 1000);
|
|
||||||
} catch (InterruptedException e) {
|
|
||||||
throw new RuntimeException(e);
|
|
||||||
}
|
|
||||||
|
|
||||||
Lock lock2 = zhub.tryLock("lock-a", 5);
|
|
||||||
System.out.println("lock-3: " + lock2.success());
|
|
||||||
/*try {
|
|
||||||
Thread.sleep(100);
|
|
||||||
} catch (InterruptedException e) {
|
|
||||||
throw new RuntimeException(e);
|
|
||||||
}*/
|
|
||||||
Lock lock3 = zhub.tryLock("lock-a", 5);
|
|
||||||
System.out.println("lock-4: " + lock3.success());
|
|
||||||
|
|
||||||
try {
|
|
||||||
Thread.sleep(3000 * 30000);
|
|
||||||
} catch (InterruptedException e) {
|
|
||||||
throw new RuntimeException(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void lockTest() {
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
/*RpcResult<FileToken> x = zhub.rpc("rpc:file:up-token", Map.of(), new TypeToken<>() {
|
|
||||||
});*/
|
|
||||||
}
|
|
412
test/net.tccn/mq/AppTest.java
Normal file
412
test/net.tccn/mq/AppTest.java
Normal file
@@ -0,0 +1,412 @@
|
|||||||
|
package net.tccn.mq;
|
||||||
|
|
||||||
|
import net.tccn.Event;
|
||||||
|
import net.tccn.timer.Timers;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.redkale.convert.json.JsonConvert;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.DelayQueue;
|
||||||
|
import java.util.concurrent.LinkedBlockingQueue;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.function.Function;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 消息发布订阅测试
|
||||||
|
*/
|
||||||
|
public class AppTest {
|
||||||
|
Logger logger = Logger.getLogger("");
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void runConsumer() {
|
||||||
|
try {
|
||||||
|
// String str = ", response = {\"success\":true,\"retcode\":0,\"result\":{\"age\":0,\"explevel\":1,\"face\":\"https://aimg.woaihaoyouxi.com/haogame/202106/pic/20210629095545FmGt-v9NYqyNZ_Q6_y3zM_RMrDgd.jpg\",\"followed\":0,\"gender\":0,\"idenstatus\":0,\"matchcatelist\":[{\"catename\":\"足球\",\"catepic\":\"https://aimg.woaihaoyouxi.com/haogame/202107/pic/20210714103556FoG5ICf_7BFx6Idyo3TYpJQ7tmfG.png\",\"matchcateid\":1},{\"catename\":\"篮球\",\"catepic\":\"https://aimg.woaihaoyouxi.com/haogame/202107/pic/20210714103636FklsXTn1f6Jlsam8Jk-yFB7Upo3C.png\",\"matchcateid\":2}],\"matchcates\":\"2,1\",\"mobile\":\"18515190967\",\"regtime\":1624931714781,\"sessionid\":\"d1fc447753bd4700ad29674a753030fa\",\"status\":10,\"userid\":100463,\"username\":\"绝尘\",\"userno\":100463}}";
|
||||||
|
String str = "hello你好";
|
||||||
|
|
||||||
|
System.out.println(str.length());
|
||||||
|
|
||||||
|
/*consumer.timer("a", () -> {
|
||||||
|
System.out.println(Utility.now() + " timer a 执行了");
|
||||||
|
try {
|
||||||
|
Thread.sleep(3000);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
consumer.timer("b", () -> {
|
||||||
|
System.out.println(Utility.now() + " ----------------- timer b 执行了");
|
||||||
|
});
|
||||||
|
//consumer.delay("a", "1", 200);
|
||||||
|
consumer.delay("a", "1", "2000");*/
|
||||||
|
|
||||||
|
/*Consumer<String> con = x -> {
|
||||||
|
logger.info("--->开始申请锁:" + System.currentTimeMillis());
|
||||||
|
Lock lock = consumer.tryLock("a", 20);
|
||||||
|
logger.info("===>成功申请锁:" + System.currentTimeMillis());
|
||||||
|
for (int i = 0; i < 20; i++) {
|
||||||
|
try {
|
||||||
|
Thread.sleep(500);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
System.out.println(x + ":" + i);
|
||||||
|
}
|
||||||
|
lock.unLock();
|
||||||
|
};
|
||||||
|
|
||||||
|
new Thread(() -> con.accept("x")).start();
|
||||||
|
new Thread(() -> con.accept("y")).start();
|
||||||
|
new Thread(() -> con.accept("z")).start();*/
|
||||||
|
|
||||||
|
|
||||||
|
Thread.sleep(60_000 * 60);
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void runProducer() {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private static LinkedBlockingQueue<String> queue = new LinkedBlockingQueue();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void t() {
|
||||||
|
List<String> list = new ArrayList<>();
|
||||||
|
list.toArray(String[]::new);
|
||||||
|
|
||||||
|
new Thread(() -> {
|
||||||
|
while (true) {
|
||||||
|
System.out.println("accept:");
|
||||||
|
String peek = null;
|
||||||
|
try {
|
||||||
|
System.out.println(!queue.isEmpty());
|
||||||
|
peek = queue.poll(100, TimeUnit.MILLISECONDS);
|
||||||
|
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
System.out.println(peek);
|
||||||
|
}
|
||||||
|
}).start();
|
||||||
|
|
||||||
|
for (int i = 0; i < 10; i++) {
|
||||||
|
try {
|
||||||
|
queue.put(i + "");
|
||||||
|
Thread.sleep(1000);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
try {
|
||||||
|
System.out.println("---");
|
||||||
|
Thread.sleep(1000 * 5);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void xx() {
|
||||||
|
Function<String, String> fun = x -> {
|
||||||
|
return x.toUpperCase();
|
||||||
|
};
|
||||||
|
|
||||||
|
System.out.println(fun.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// (27+5*23)/(63-59)
|
||||||
|
// [27+5*23] [/] [63-59]
|
||||||
|
// [27] + [5*23] [/] [63-59]
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 1. 按照优先级逐一拆解运算
|
||||||
|
* 括号, 乘除,加减
|
||||||
|
* 2. 逐一进行计算
|
||||||
|
*/
|
||||||
|
class C {
|
||||||
|
C A;
|
||||||
|
C B;
|
||||||
|
|
||||||
|
int c1; // 如果 A 只剩数字,将c1 转为整数存放到 c1
|
||||||
|
int c2;
|
||||||
|
String x; // + - * /
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void x() {
|
||||||
|
// (27+5*23)/(63-59)
|
||||||
|
|
||||||
|
String str = "(27+5*23)/(63-59)";
|
||||||
|
str = "27+5*23";
|
||||||
|
str = "258/((35+17)/(5*3+18-29)+3)(138-134)*41-6+10+24";
|
||||||
|
str = "5*3+18-29";
|
||||||
|
|
||||||
|
//System.out.println("258/((35+17)/(5*3+18-29)+3)(138-134)*41-6+10+24".replaceAll("\\)\\(", ")*("));
|
||||||
|
List<String> parse = parse(str.replaceAll("\\)\\(", ")\\*("));
|
||||||
|
|
||||||
|
|
||||||
|
System.out.println(c(str));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 因式分解:括号 -> 乘除 -> 加减
|
||||||
|
public List<String> parse(String str) {
|
||||||
|
// 找到一对
|
||||||
|
/*
|
||||||
|
|
||||||
|
258/()()
|
||||||
|
[258, /, (35+17)/(5*3+18-29)+3, 138-134, *, 41, -, 6, +, 10, +, 24]
|
||||||
|
|
||||||
|
*/
|
||||||
|
// 258/((35+17)/(5*3+18-29)+3)(138-134)*41-6+10+24
|
||||||
|
//str = "258 / (35+17)/(5*3+18-29)+3 138-134, * 41-6+10+24";
|
||||||
|
String[] strArr = str.split("");
|
||||||
|
|
||||||
|
// 一级括号、加、减、乘、除分解
|
||||||
|
List<String> arr = new ArrayList<>();
|
||||||
|
String tmp = "";
|
||||||
|
int n1 = 0; // 括号层级开始
|
||||||
|
int m1 = 0; // 括号层级结尾
|
||||||
|
for (String s : strArr) {
|
||||||
|
if (n1 > 0) { // 一级括号分解
|
||||||
|
if (")".equals(s) && (++m1) == n1) { // 一级括号结束
|
||||||
|
arr.add(tmp);
|
||||||
|
tmp = "";
|
||||||
|
n1 = 0;
|
||||||
|
m1 = 0;
|
||||||
|
} else {
|
||||||
|
if ("(".equals(s)) {
|
||||||
|
n1++;
|
||||||
|
}
|
||||||
|
tmp += s;
|
||||||
|
}
|
||||||
|
} else { // 无括号
|
||||||
|
if ("+".equals(s) || "-".equals(s) || "*".equals(s) || "/".equals(s)) {
|
||||||
|
if (!"".equals(tmp)) {
|
||||||
|
arr.add(tmp);
|
||||||
|
}
|
||||||
|
arr.add(s);
|
||||||
|
tmp = "";
|
||||||
|
} else if ("(".equals(s)) {
|
||||||
|
n1 = 1;
|
||||||
|
} else {
|
||||||
|
tmp += s;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!"".equals(tmp)) {
|
||||||
|
arr.add(tmp);
|
||||||
|
}
|
||||||
|
return arr;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int c(String str) {
|
||||||
|
List<String> arr = parse(str); // 预期 length >= 3 基数的基数,如:[27+5*23, /, 63-59], [60, /, 2, *, 164-23*7]
|
||||||
|
System.out.println(arr);
|
||||||
|
if (arr == null || arr.size() < 3) {
|
||||||
|
return -1; // 错误码-1:错误的计算式
|
||||||
|
}
|
||||||
|
|
||||||
|
List<String> _arr = new ArrayList<>();
|
||||||
|
// 按照优先级做合并计算 乘除优先
|
||||||
|
|
||||||
|
// 乘除
|
||||||
|
for (int i = 1; i < arr.size() - 1; i += 2) {
|
||||||
|
/*if ("*".equals(arr.get(i)) || "/".equals(arr.get(i))) {
|
||||||
|
if (_arr.size() > 0) {
|
||||||
|
_arr.remove(_arr.size() - 1);
|
||||||
|
}
|
||||||
|
int c = c(arr.get(i - 1), arr.get(i + 1), arr.get(i));
|
||||||
|
if (c < 0) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
_arr.add(c + "");
|
||||||
|
} else {
|
||||||
|
_arr.add(arr.get(i - 1));
|
||||||
|
_arr.add(arr.get(i));
|
||||||
|
_arr.add(arr.get(i + 1));
|
||||||
|
}*/
|
||||||
|
|
||||||
|
if ("*".equals(arr.get(i)) || "/".equals(arr.get(i))) {
|
||||||
|
int c = c(arr.get(i - 1), arr.get(i + 1), arr.get(i));
|
||||||
|
if (c < 0) {
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
_arr.add(c + "");
|
||||||
|
} else {
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_arr.size() == 1) { // 通过第一轮的 乘除计算,完成结果合并
|
||||||
|
return Integer.parseInt(_arr.get(0));
|
||||||
|
}
|
||||||
|
int c = 0;
|
||||||
|
for (int i = 1; i < _arr.size(); i += 2) {
|
||||||
|
int _c = c(_arr.get(i - 1), _arr.get(i + 1), _arr.get(i));
|
||||||
|
if (_c < 0) {
|
||||||
|
return _c;
|
||||||
|
}
|
||||||
|
c += _c;
|
||||||
|
}
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int c(String a, String b, String x) {
|
||||||
|
int _a = 0;
|
||||||
|
if (a.contains("(") || a.contains("+") || a.contains("-") || a.contains("*") || a.contains("/")) {
|
||||||
|
_a = c(a);
|
||||||
|
} else { // 预期 无 ( + - * / 的结果为标准数字
|
||||||
|
_a = Integer.parseInt(a);
|
||||||
|
}
|
||||||
|
int _b = 0;
|
||||||
|
if (b.contains("(") || b.contains("+") || b.contains("-") || b.contains("*") || b.contains("/")) {
|
||||||
|
_b = c(b);
|
||||||
|
} else { // 预期 无 ( + - * / 的结果为标准数字
|
||||||
|
_b = Integer.parseInt(b);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果出现负数(错误码)直接返回对应的负数
|
||||||
|
if (_a < 0) {
|
||||||
|
return _a;
|
||||||
|
}
|
||||||
|
if (_b < 0) {
|
||||||
|
return _b;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 定义错误标识: -1错误的计算式,-2除不尽,-3除数为0,-4大于200,
|
||||||
|
if ("+".equals(x)) {
|
||||||
|
return _a + _b;
|
||||||
|
} else if ("-".equals(x)) {
|
||||||
|
return _a - _b;
|
||||||
|
} else if ("*".equals(x)) {
|
||||||
|
return _a * _b;
|
||||||
|
} else if ("/".equals(x)) {
|
||||||
|
return _a % _b > 0 ? -2 : _a / _b; // 除不尽
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testxx() {
|
||||||
|
Event of = Event.of("A", Map.of("b", 1));
|
||||||
|
|
||||||
|
System.out.println(JsonConvert.root().convertTo(of));
|
||||||
|
|
||||||
|
String str = "❦别人家的女娃子🤞🏻ꚢ";
|
||||||
|
|
||||||
|
/*
|
||||||
|
System.out.println("别人家的女娃子🤞🏻".length());*/
|
||||||
|
System.out.println(strLength(str));
|
||||||
|
System.out.println(getWordCount(str));
|
||||||
|
/*try {
|
||||||
|
System.out.println("别人家的女娃子🤞🏻".getBytes("UTF-8").length);
|
||||||
|
} catch (UnsupportedEncodingException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
System.out.println("系统默认编码方式:" + System.getProperty("file.encoding"));*/
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public static int strLength(String value) {
|
||||||
|
int valueLength = 0;
|
||||||
|
String chinese = "[\u4e00-\u9fa5]";
|
||||||
|
for (int i = 0; i < value.length(); i++) {
|
||||||
|
String temp = value.substring(i, i + 1);
|
||||||
|
if (temp.matches(chinese)) {
|
||||||
|
valueLength += 2;
|
||||||
|
} else {
|
||||||
|
valueLength += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return valueLength;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getWordCount(String str) {
|
||||||
|
str = str.replaceAll("[^\\x00-\\xff]", "*");
|
||||||
|
return str.length();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void delay() {
|
||||||
|
DelayQueue<com.zdemo.zhub.Delays> delayQueue = new DelayQueue<>();
|
||||||
|
|
||||||
|
logger.info("加入延时任务1");
|
||||||
|
delayQueue.add(new com.zdemo.zhub.Delays(5000, () -> {
|
||||||
|
logger.info("任务1 延时任务执行了!");
|
||||||
|
}));
|
||||||
|
|
||||||
|
try {
|
||||||
|
Thread.sleep(1000);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info("加入延时任务2");
|
||||||
|
delayQueue.add(new com.zdemo.zhub.Delays(5000, () -> {
|
||||||
|
logger.info("任务2 延时任务执行了!");
|
||||||
|
}));
|
||||||
|
|
||||||
|
try {
|
||||||
|
while (true) {
|
||||||
|
com.zdemo.zhub.Delays delay = delayQueue.take();
|
||||||
|
|
||||||
|
delay.run();
|
||||||
|
}
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void regTest() {
|
||||||
|
// 按指定模式在字符串查找
|
||||||
|
String line = "This order was placed for QT3000! OK?";
|
||||||
|
String pattern = "(\\D*)(\\d+)(.*)";
|
||||||
|
|
||||||
|
// 创建 Pattern 对象
|
||||||
|
Pattern r = Pattern.compile(pattern);
|
||||||
|
|
||||||
|
// 现在创建 matcher 对象
|
||||||
|
Matcher m = r.matcher(line);
|
||||||
|
if (m.find()) {
|
||||||
|
System.out.println("Found value: " + m.group(0));
|
||||||
|
System.out.println("Found value: " + m.group(1));
|
||||||
|
System.out.println("Found value: " + m.group(2));
|
||||||
|
System.out.println("Found value: " + m.group(3));
|
||||||
|
} else {
|
||||||
|
System.out.println("NO MATCH");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void timersTest() {
|
||||||
|
Timers.tryDelay(() -> {
|
||||||
|
logger.info("xx:" + System.currentTimeMillis());
|
||||||
|
return true;
|
||||||
|
}, 1000, 5);
|
||||||
|
|
||||||
|
Timers.delay(() -> {
|
||||||
|
System.out.println("11");
|
||||||
|
}, 3000);
|
||||||
|
|
||||||
|
try {
|
||||||
|
Thread.sleep(100000);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
72
test/net.tccn/mq/Delays.java
Normal file
72
test/net.tccn/mq/Delays.java
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
package com.zdemo.zhub;
|
||||||
|
|
||||||
|
import java.util.concurrent.DelayQueue;
|
||||||
|
import java.util.concurrent.Delayed;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
public class Delays implements Delayed, Runnable {
|
||||||
|
public Logger logger = Logger.getLogger(Delays.class.getSimpleName());
|
||||||
|
|
||||||
|
private long time; // 执行时间
|
||||||
|
private Runnable runnable; // 任务到时间执行 runnable
|
||||||
|
|
||||||
|
public Delays(long timeout, Runnable runnable) {
|
||||||
|
this.time = System.currentTimeMillis() + timeout;
|
||||||
|
this.runnable = runnable;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public long getDelay(TimeUnit unit) {
|
||||||
|
return unit.convert(time - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int compareTo(Delayed other) {
|
||||||
|
if (other == this) { // compare zero ONLY if same object
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if (other instanceof Delays) {
|
||||||
|
Delays x = (Delays) other;
|
||||||
|
long diff = time - x.time;
|
||||||
|
if (diff < 0) {
|
||||||
|
return -1;
|
||||||
|
} else if (diff > 0) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
long d = (getDelay(TimeUnit.NANOSECONDS) -
|
||||||
|
other.getDelay(TimeUnit.NANOSECONDS));
|
||||||
|
return (d == 0) ? 0 : ((d < 0) ? -1 : 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
runnable.run();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===========
|
||||||
|
public static DelayQueue<Delays> delayQueue = new DelayQueue<>();
|
||||||
|
|
||||||
|
public static void addDelay(long timeout, Runnable runnable) {
|
||||||
|
delayQueue.add(new Delays(timeout, runnable));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void tryDelay(Supplier<Boolean> supplier, long delayMillis, int maxCount) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
static {
|
||||||
|
new Thread(() -> {
|
||||||
|
try {
|
||||||
|
while (true) {
|
||||||
|
Delays delay = delayQueue.take();
|
||||||
|
delay.run(); //异常会导致延时队列失败
|
||||||
|
}
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}).start();
|
||||||
|
}
|
||||||
|
}
|
244
test/net.tccn/mq/HelloService.java
Normal file
244
test/net.tccn/mq/HelloService.java
Normal file
@@ -0,0 +1,244 @@
|
|||||||
|
package net.tccn.mq;
|
||||||
|
|
||||||
|
import net.tccn.IType;
|
||||||
|
import net.tccn.zhub.RpcResult;
|
||||||
|
import net.tccn.zhub.ZHubClient;
|
||||||
|
import org.redkale.net.http.RestMapping;
|
||||||
|
import org.redkale.net.http.RestService;
|
||||||
|
import org.redkale.service.Service;
|
||||||
|
import org.redkale.util.AnyValue;
|
||||||
|
import org.redkale.util.TypeToken;
|
||||||
|
|
||||||
|
import javax.annotation.Resource;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
|
||||||
|
@RestService(automapping = true, name = "hello")
|
||||||
|
public class HelloService implements Service {
|
||||||
|
|
||||||
|
@Resource(name = "hub")
|
||||||
|
private ZHubClient zhub;
|
||||||
|
|
||||||
|
/*@Resource(name = "hubx")
|
||||||
|
private ZHubClient zhubx;
|
||||||
|
|
||||||
|
@Resource(name = "vvvvhub2")
|
||||||
|
private ZHubClient zhub2;*/
|
||||||
|
|
||||||
|
//private net.tccn.zhub.ZHubClient zhubx = null;
|
||||||
|
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void init(AnyValue config) {
|
||||||
|
|
||||||
|
/*CompletableFuture.runAsync(() -> {
|
||||||
|
zhubx = new net.tccn.zhub.ZHubClient("127.0.0.1", 1216, "g-dev", "DEV-LOCAL");
|
||||||
|
//zhubx = new net.tccn.zhub.ZHubClient("47.111.150.118", 6066, "g-dev", "DEV-LOCAL");
|
||||||
|
});*/
|
||||||
|
|
||||||
|
// Function<Rpc<T>, RpcResult<R>> fun
|
||||||
|
/*zhub.rpcSubscribe("x", new TypeToken<String>() {
|
||||||
|
}, r -> {
|
||||||
|
|
||||||
|
return r.buildResp(Map.of("v", r.getValue().toUpperCase() + ": Ok"));
|
||||||
|
});*/
|
||||||
|
zhub.rpcSubscribe("y", new TypeToken<String>() {
|
||||||
|
}, r -> {
|
||||||
|
|
||||||
|
return r.render(Map.of("v", r.getValue().toUpperCase() + ": Ok"));
|
||||||
|
});
|
||||||
|
|
||||||
|
zhub.subscribe("sport:reqtime", x -> {
|
||||||
|
System.out.println(x);
|
||||||
|
});
|
||||||
|
zhub.subscribe("abx1", x -> {
|
||||||
|
System.out.println(x);
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
Thread.sleep(010);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
/*zhub.delay("sport:reqtime", "别✈人家的✦女娃子❤🤞🏻", 0);
|
||||||
|
zhub.delay("sport:reqtime", "别人家的女娃子➾🤞🏻", 0);
|
||||||
|
zhub.delay("sport:reqtime", "❤别人家✉<E5AEB6>的女娃子❤🤞🏻", 0);
|
||||||
|
zhub.delay("sport:reqtime", "中文特殊符号:『』 $ £ ♀ ‖ 「」\n" +
|
||||||
|
"英文:# + = & ﹉ .. ^ \"\" ·{ } % – ' €\n" +
|
||||||
|
"数学:+× = - ° ± < > ℃ ㎡ ∑ ≥ ∫ ㏄ ⊥ ≯ ∠ ∴ ∈ ∧ ∵ ≮ ∪ ㎝ ㏑ ≌ ㎞ № § ℉ ÷ % ‰ ㎎ ㎏ ㎜ ㏒ ⊙ ∮ ∝ ∞ º ¹ ² ³ ½ ¾ ¼ ≈ ≡ ≠ ≤ ≦ ≧ ∽ ∷ / ∨ ∏ ∩ ⌒ √Ψ ¤ ‖ ¶\n" +
|
||||||
|
"特殊:♤ ♧ ♡ ♢ ♪ ♬ ♭ ✔ ✘ ♞ ♟ ↪ ↣ ♚ ♛ ♝ ☞ ☜ ⇔ ☆ ★ □ ■ ○ ● △ ▲ ▽ ▼ ◇ ◆ ♀ ♂ ※ ↓ ↑ ↔ ↖ ↙ ↗ ↘ ← → ♣ ♠ ♥ ◎ ◣ ◢ ◤ ◥ 卍 ℡ ⊙ ㊣ ® © ™ ㈱ 囍\n" +
|
||||||
|
"序号:①②③④⑤⑥⑦⑧⑨⑩㈠㈡㈢㈣㈤㈥㈦㈧㈨㈩⑴ ⑵ ⑶ ⑷ ⑸ ⑹ ⑺ ⑻ ⑼ ⑽ ⒈ ⒉ ⒊ ⒋ ⒌ ⒍ ⒎ ⒏ ⒐ ⒑ Ⅰ Ⅱ Ⅲ Ⅳ Ⅴ Ⅵ Ⅶ Ⅷ ⅨⅩ\n" +
|
||||||
|
"日文:アイウエオァィゥェォカキクケコガギグゲゴサシスセソザジズゼゾタチツテトダヂヅデドッナニヌネノハヒフヘホバビブベボパピプペポマミムメモャヤュユョラリヨルレロワヰヱヲンヴヵヶヽヾ゛゜ー、。「「あいうえおぁぃぅぇぉかきくけこがぎぐげごさしすせそざじずぜぞたちつてでどっなにぬねのはひふへ」」ほばびぶべぼぱぴぷぺぽまみむめもやゆよゃゅょらりるれろわをんゎ゛゜ー、。「」\n" +
|
||||||
|
"部首:犭 凵 巛 冖 氵 廴 讠 亻 钅 宀 亠 忄 辶 弋 饣 刂 阝 冫 卩 疒 艹 疋 豸 冂 匸 扌 丬 屮衤 礻 勹 彳 彡", 0);
|
||||||
|
*/
|
||||||
|
}
|
||||||
|
|
||||||
|
@RestMapping
|
||||||
|
public RpcResult x(String v) {
|
||||||
|
if (v == null) {
|
||||||
|
v = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
List<CompletableFuture> list = new ArrayList();
|
||||||
|
|
||||||
|
for (int i = 0; i < 100; i++) {
|
||||||
|
long start = System.currentTimeMillis();
|
||||||
|
/*RpcResult<FileToken> x = zhub.rpc("rpc:file:up-token", Map.of(), new TypeToken<>() {
|
||||||
|
});*/
|
||||||
|
|
||||||
|
/*list.add(zhub.rpcAsync("x", v + i, new TypeToken<>() {
|
||||||
|
}));*/
|
||||||
|
zhub.publish("x", v + i);
|
||||||
|
|
||||||
|
System.out.println("time: " + (System.currentTimeMillis() - start) + " ms");
|
||||||
|
//System.out.println(x.getResult().get("v"));
|
||||||
|
}
|
||||||
|
|
||||||
|
return zhub.rpc("x", v, IType.STRING);
|
||||||
|
}
|
||||||
|
|
||||||
|
@RestMapping
|
||||||
|
public RpcResult<String> d(String v) {
|
||||||
|
RpcResult<String> rpc = zhub.rpc("x", v, IType.STRING);
|
||||||
|
return rpc;
|
||||||
|
}
|
||||||
|
|
||||||
|
@RestMapping
|
||||||
|
public String y(String v) {
|
||||||
|
if (v == null) {
|
||||||
|
v = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = 0; i < 100; i++) {
|
||||||
|
long start = System.currentTimeMillis();
|
||||||
|
/*RpcResult<FileToken> x = zhub.rpc("rpc:file:up-token", Map.of(), new TypeToken<>() {
|
||||||
|
});*/
|
||||||
|
|
||||||
|
/*RpcResult<Object> x = zhubx.rpc("y", v + i, new com.google.gson.reflect.TypeToken<>() {
|
||||||
|
});*/
|
||||||
|
|
||||||
|
System.out.println("time: " + (System.currentTimeMillis() - start) + " ms");
|
||||||
|
|
||||||
|
//System.out.println(x.getResult());
|
||||||
|
}
|
||||||
|
|
||||||
|
return "ok";
|
||||||
|
}
|
||||||
|
|
||||||
|
@RestMapping(name = "send")
|
||||||
|
public String send() {
|
||||||
|
zhub.publish("abx1", 1);
|
||||||
|
return "ok";
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
// "\"别人家的女娃子\uD83E\uDD1E\uD83C\uDFFB\""
|
||||||
|
/*String s = "别人家的女娃子\uD83E\uDD1E\uD83C\uDFFB";
|
||||||
|
System.out.println("别人家的女娃子🤞🏻".length());
|
||||||
|
|
||||||
|
byte[] bytes = "别人家的女娃子🤞🏻".getBytes();
|
||||||
|
System.out.println(bytes.length);
|
||||||
|
|
||||||
|
System.out.println(unicodeToUtf8(s));
|
||||||
|
System.out.println(utf8ToUnicode("别人家的女娃子🤞🏻"));
|
||||||
|
*/
|
||||||
|
|
||||||
|
//ExecutorService pool = Executors.newFixedThreadPool(5);
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public static String utf8ToUnicode(String inStr) {
|
||||||
|
char[] myBuffer = inStr.toCharArray();
|
||||||
|
|
||||||
|
StringBuffer sb = new StringBuffer();
|
||||||
|
for (int i = 0; i < inStr.length(); i++) {
|
||||||
|
Character.UnicodeBlock ub = Character.UnicodeBlock.of(myBuffer[i]);
|
||||||
|
if (ub == Character.UnicodeBlock.BASIC_LATIN) {
|
||||||
|
//英文及数字等
|
||||||
|
sb.append(myBuffer[i]);
|
||||||
|
} else if (ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
|
||||||
|
//全角半角字符
|
||||||
|
int j = (int) myBuffer[i] - 65248;
|
||||||
|
sb.append((char) j);
|
||||||
|
} else {
|
||||||
|
//汉字
|
||||||
|
short s = (short) myBuffer[i];
|
||||||
|
String hexS = Integer.toHexString(s);
|
||||||
|
String unicode = "\\u" + hexS;
|
||||||
|
sb.append(unicode.toLowerCase());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sb.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String unicodeToUtf8(String theString) {
|
||||||
|
char aChar;
|
||||||
|
int len = theString.length();
|
||||||
|
StringBuffer outBuffer = new StringBuffer(len);
|
||||||
|
for (int x = 0; x < len; ) {
|
||||||
|
aChar = theString.charAt(x++);
|
||||||
|
if (aChar == '\\') {
|
||||||
|
aChar = theString.charAt(x++);
|
||||||
|
if (aChar == 'u') {
|
||||||
|
// Read the xxxx
|
||||||
|
int value = 0;
|
||||||
|
for (int i = 0; i < 4; i++) {
|
||||||
|
aChar = theString.charAt(x++);
|
||||||
|
switch (aChar) {
|
||||||
|
case '0':
|
||||||
|
case '1':
|
||||||
|
case '2':
|
||||||
|
case '3':
|
||||||
|
case '4':
|
||||||
|
case '5':
|
||||||
|
case '6':
|
||||||
|
case '7':
|
||||||
|
case '8':
|
||||||
|
case '9':
|
||||||
|
value = (value << 4) + aChar - '0';
|
||||||
|
break;
|
||||||
|
case 'a':
|
||||||
|
case 'b':
|
||||||
|
case 'c':
|
||||||
|
case 'd':
|
||||||
|
case 'e':
|
||||||
|
case 'f':
|
||||||
|
value = (value << 4) + 10 + aChar - 'a';
|
||||||
|
break;
|
||||||
|
case 'A':
|
||||||
|
case 'B':
|
||||||
|
case 'C':
|
||||||
|
case 'D':
|
||||||
|
case 'E':
|
||||||
|
case 'F':
|
||||||
|
value = (value << 4) + 10 + aChar - 'A';
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
throw new IllegalArgumentException(
|
||||||
|
"Malformed \\uxxxx encoding.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
outBuffer.append((char) value);
|
||||||
|
} else {
|
||||||
|
if (aChar == 't')
|
||||||
|
aChar = '\t';
|
||||||
|
else if (aChar == 'r')
|
||||||
|
aChar = '\r';
|
||||||
|
else if (aChar == 'n')
|
||||||
|
aChar = '\n';
|
||||||
|
else if (aChar == 'f')
|
||||||
|
aChar = '\f';
|
||||||
|
outBuffer.append(aChar);
|
||||||
|
}
|
||||||
|
} else
|
||||||
|
outBuffer.append(aChar);
|
||||||
|
}
|
||||||
|
return outBuffer.toString();
|
||||||
|
}
|
||||||
|
}
|
Reference in New Issue
Block a user