From 691c5a64f116a1c82ab6f4720711840d3a5b1236 Mon Sep 17 00:00:00 2001 From: hank <104381832> Date: Tue, 21 Jan 2020 21:33:00 +0800 Subject: [PATCH 01/11] 1 --- fastmq/consumer/pom.xml | 15 +++++++++++++++ fastmq/pipeline/pom.xml | 15 +++++++++++++++ fastmq/pom.xml | 28 ++++++++++++++++++++++++++++ fastmq/provider/pom.xml | 15 +++++++++++++++ pom.xml | 3 ++- 5 files changed, 75 insertions(+), 1 deletion(-) create mode 100644 fastmq/consumer/pom.xml create mode 100644 fastmq/pipeline/pom.xml create mode 100644 fastmq/pom.xml create mode 100644 fastmq/provider/pom.xml diff --git a/fastmq/consumer/pom.xml b/fastmq/consumer/pom.xml new file mode 100644 index 0000000..547a4b1 --- /dev/null +++ b/fastmq/consumer/pom.xml @@ -0,0 +1,15 @@ + + + + limitart-fastmq + top.limitart + 3.1.0 + + 4.0.0 + + limitart-fastmq-consumer + + + \ No newline at end of file diff --git a/fastmq/pipeline/pom.xml b/fastmq/pipeline/pom.xml new file mode 100644 index 0000000..11c16e9 --- /dev/null +++ b/fastmq/pipeline/pom.xml @@ -0,0 +1,15 @@ + + + + limitart-fastmq + top.limitart + 3.1.0 + + 4.0.0 + + limitart-fastmq-pipeline + + + \ No newline at end of file diff --git a/fastmq/pom.xml b/fastmq/pom.xml new file mode 100644 index 0000000..4fa35a7 --- /dev/null +++ b/fastmq/pom.xml @@ -0,0 +1,28 @@ + + + + limitart + top.limitart + 3.1.0 + + 4.0.0 + + limitart-fastmq + pom + + pipeline + consumer + provider + + + + + ${project.groupId} + limitart-core + ${project.version} + + + + \ No newline at end of file diff --git a/fastmq/provider/pom.xml b/fastmq/provider/pom.xml new file mode 100644 index 0000000..44cf0f7 --- /dev/null +++ b/fastmq/provider/pom.xml @@ -0,0 +1,15 @@ + + + + limitart-fastmq + top.limitart + 3.1.0 + + 4.0.0 + + limitart-fastmq-provider + + + \ No newline at end of file diff --git a/pom.xml b/pom.xml index 7013d72..d795153 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ 4.0.0 top.limitart limitart - 3.1.0 + 3.2.0-SNAPSHOT pom limitart @@ -31,6 +31,7 @@ db project-starter project-logic + fastmq http://maven.limitart.top -- Gitee From bcb2b57bff06a68f3e6191b43d64fe00d60868f5 Mon Sep 17 00:00:00 2001 From: hank <104381832> Date: Wed, 22 Jan 2020 22:05:00 +0800 Subject: [PATCH 02/11] 1 --- .../concurrent/DisruptorTaskQueue.java | 67 +- eclipse-java-google-style.xml | 337 ++++++++++ .../fastmq/pipeline/PipelineRingBuffer.java | 166 +++++ .../top/limitart/fastmq/pipeline/Request.java | 5 + .../limitart/fastmq/pipeline/Response.java | 5 + .../fastmq/pipeline/RingBufferTask.java | 5 + intellij-java-google-style.xml | 598 ++++++++++++++++++ 7 files changed, 1181 insertions(+), 2 deletions(-) create mode 100644 eclipse-java-google-style.xml create mode 100644 fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/PipelineRingBuffer.java create mode 100644 fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/Request.java create mode 100644 fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/Response.java create mode 100644 fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/RingBufferTask.java create mode 100644 intellij-java-google-style.xml diff --git a/core/src/main/java/top/limitart/concurrent/DisruptorTaskQueue.java b/core/src/main/java/top/limitart/concurrent/DisruptorTaskQueue.java index 9f954dd..0d88ded 100644 --- a/core/src/main/java/top/limitart/concurrent/DisruptorTaskQueue.java +++ b/core/src/main/java/top/limitart/concurrent/DisruptorTaskQueue.java @@ -17,11 +17,14 @@ package top.limitart.concurrent; import com.lmax.disruptor.BlockingWaitStrategy; import com.lmax.disruptor.ExceptionHandler; +import com.lmax.disruptor.InsufficientCapacityException; import com.lmax.disruptor.dsl.Disruptor; import com.lmax.disruptor.dsl.ProducerType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import top.limitart.base.Alone; +import top.limitart.base.Conditions; +import top.limitart.base.UncatchableException; import top.limitart.base.function.Process3; import top.limitart.base.function.Processes; @@ -31,10 +34,12 @@ import top.limitart.base.function.Processes; * @author Hank */ public class DisruptorTaskQueue extends AbstractTaskQueue { + private static final Logger LOGGER = LoggerFactory.getLogger(DisruptorTaskQueue.class); private final Disruptor> disruptor; private final SingletonThreadFactory threadFactory; private Process3 exception; + private ExecuteStrategy strategy = ExecuteStrategy.BLOCK_BUT_NOTICE; public static DisruptorTaskQueue create(SingletonThreadFactory threadFactory) { return new DisruptorTaskQueue(threadFactory); @@ -59,6 +64,7 @@ public class DisruptorTaskQueue extends AbstractTaskQueue { private DisruptorTaskQueue(String threadName) { this(threadName, 2 << 12); // 4096 } + /** * 构造函数 * @@ -76,11 +82,12 @@ public class DisruptorTaskQueue extends AbstractTaskQueue { }, bufferSize); } + /** * 构造函数 * * @param threadFactory - * @param bufferSize 指定RingBuffer的大小 + * @param bufferSize 指定RingBuffer的大小 */ @SuppressWarnings("unchecked") private DisruptorTaskQueue(SingletonThreadFactory threadFactory, int bufferSize) { @@ -133,9 +140,50 @@ public class DisruptorTaskQueue extends AbstractTaskQueue { return this; } + /** + * 设置执行队列满时的策略 + * + * @param strategy + * @return + */ + public DisruptorTaskQueue executeStrategy(ExecuteStrategy strategy) { + this.strategy = strategy; + return this; + } + @Override public void execute0(Runnable runnable) { - disruptor.getRingBuffer().publishEvent((event, sequence) -> event.set(runnable)); + Conditions.notNull(runnable); + try { + long next = disruptor.getRingBuffer().tryNext(); + publish(runnable, next); + } catch (InsufficientCapacityException e) { + //这里用不用tryPublishEvent,他内部会默认阻塞当前线程,知道能插入为止。用try让他快速失败,我们好调试我们的程序到底是消费过慢还是生产过快,因为此队列假设的是消费必须比生产快 + if (this.strategy == ExecuteStrategy.FAST_FAIL + || this.strategy == ExecuteStrategy.BLOCK_BUT_NOTICE) { + UncatchableException uncatchableException = new UncatchableException( + "task queue " + this.thread().getName() + + " is not enough to execute task, maybe customer is too slowly or provider is too fast! "); + LOGGER.error("no capacity", uncatchableException); + Processes.invoke(exception, runnable, + uncatchableException, + disruptor.getCursor() + 1); + } + if (this.strategy == ExecuteStrategy.BLOCK_BUT_NOTICE + || this.strategy == ExecuteStrategy.BLOCK) { + //阻塞 + long next = disruptor.getRingBuffer().next(); + publish(runnable, next); + } + } + } + + private void publish(Runnable runnable, long seq) { + try { + disruptor.getRingBuffer().get(seq).set(runnable); + } finally { + disruptor.getRingBuffer().publish(seq); + } } @Override @@ -150,4 +198,19 @@ public class DisruptorTaskQueue extends AbstractTaskQueue { LOGGER.info("thread " + threadFactory.get().getName() + " stop!"); } } + + public enum ExecuteStrategy { + /** + * 如果无法入队,则直接失败 + */ + FAST_FAIL, + /** + * 如果无法入队,则阻塞等待,但会警告 + */ + BLOCK_BUT_NOTICE, + /** + * 如果无法入队,则阻塞等待 + */ + BLOCK + } } diff --git a/eclipse-java-google-style.xml b/eclipse-java-google-style.xml new file mode 100644 index 0000000..096e983 --- /dev/null +++ b/eclipse-java-google-style.xml @@ -0,0 +1,337 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/PipelineRingBuffer.java b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/PipelineRingBuffer.java new file mode 100644 index 0000000..d10715e --- /dev/null +++ b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/PipelineRingBuffer.java @@ -0,0 +1,166 @@ +package top.limitart.fastmq.pipeline; + +import com.lmax.disruptor.InsufficientCapacityException; +import com.lmax.disruptor.RingBuffer; +import com.lmax.disruptor.Sequence; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import top.limitart.base.Alone; +import top.limitart.base.Conditions; +import top.limitart.base.UncatchableException; + +/** + * 总线 + */ +public class PipelineRingBuffer { + + private static final Logger LOGGER = LoggerFactory.getLogger(PipelineRingBuffer.class); + private final RingBuffer> buffer; + private final Sequence readCursor; + private EnqueueStrategy strategy = EnqueueStrategy.FAST_FAIL; + + public PipelineRingBuffer() { + this(2 << 12); + } + + public PipelineRingBuffer(int size) { + buffer = RingBuffer.createMultiProducer(Alone::of, size); + readCursor = new Sequence(); + buffer.addGatingSequences(readCursor); + } + + /** + * 设置执行队列满时的策略 + * + * @param strategy + * @return + */ + public PipelineRingBuffer enqueueStrategy(EnqueueStrategy strategy) { + this.strategy = strategy; + return this; + } + + public void enqueue(RingBufferTask task) { + Conditions.notNull(task); + try { + long seq = buffer.tryNext(); + publish(task, seq); + } catch (InsufficientCapacityException e) { + if (this.strategy == EnqueueStrategy.FAST_FAIL + || this.strategy == EnqueueStrategy.BLOCK_BUT_NOTICE) { + LOGGER.error("no capacity", new UncatchableException( + "buffer " + this + + " is not enough to enqueue task, maybe customer is too slowly or provider is too fast! ")); + } + if (this.strategy == EnqueueStrategy.BLOCK_BUT_NOTICE + || this.strategy == EnqueueStrategy.BLOCK) { + //阻塞 + long seq = buffer.next(); + publish(task, seq); + } + } + } + + public void enqueue(List tasks) { + Conditions.args(tasks != null && !tasks.isEmpty(), "task list is null or empty"); + long start = buffer.getCursor() + 1; + try { + long end = buffer.tryNext(tasks.size()); + publish(tasks, start, end); + } catch (InsufficientCapacityException e) { + if (this.strategy == EnqueueStrategy.FAST_FAIL + || this.strategy == EnqueueStrategy.BLOCK_BUT_NOTICE) { + LOGGER.error("no capacity", new UncatchableException( + "buffer " + this + + " is not enough to enqueue task, maybe customer is too slowly or provider is too fast! ")); + } + if (this.strategy == EnqueueStrategy.BLOCK_BUT_NOTICE + || this.strategy == EnqueueStrategy.BLOCK) { + //阻塞 + long end = buffer.next(tasks.size()); + publish(tasks, start, end); + } + } + } + + /** + * 消费一条数据 + * + * @return + */ + public RingBufferTask peek() { + List ringBufferTasks = peekAtMost(1); + if (ringBufferTasks.isEmpty()) { + return null; + } + return ringBufferTasks.get(0); + } + + /** + * 指定消费最多num条数据 + * + * @param num + * @return + */ + public List peekAtMost(int num) { + Conditions.positive(num); + List list = null; + if (num > 1) { + list = new LinkedList<>(); + } + int count = 0; + while (count < num) { + long now = readCursor.get(); + if (now >= buffer.getCursor()) { + break; + } + long next = now + 1; + if (!readCursor.compareAndSet(now, next)) { + continue; + } + if (list != null) { + list.add(buffer.get(next).get()); + } else { + list = Collections.singletonList(buffer.get(next).get()); + } + ++count; + } + return list; + } + + private void publish(List tasks, long low, long high) { + try { + for (int i = 0; i < tasks.size(); i++) { + buffer.get(low + i).set(tasks.get(i)); + } + } finally { + buffer.publish(low, high); + } + } + + private void publish(RingBufferTask tasks, long seq) { + try { + buffer.get(seq).set(tasks); + } finally { + buffer.publish(seq); + } + } + + public enum EnqueueStrategy { + /** + * 如果无法入队,则直接失败 + */ + FAST_FAIL, + /** + * 如果无法入队,则阻塞等待,但会警告 + */ + BLOCK_BUT_NOTICE, + /** + * 如果无法入队,则阻塞等待 + */ + BLOCK + } +} diff --git a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/Request.java b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/Request.java new file mode 100644 index 0000000..a62da83 --- /dev/null +++ b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/Request.java @@ -0,0 +1,5 @@ +package top.limitart.fastmq.pipeline; + +public interface Request extends RingBufferTask { + +} diff --git a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/Response.java b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/Response.java new file mode 100644 index 0000000..7a53fa2 --- /dev/null +++ b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/Response.java @@ -0,0 +1,5 @@ +package top.limitart.fastmq.pipeline; + +public interface Response extends RingBufferTask { + +} diff --git a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/RingBufferTask.java b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/RingBufferTask.java new file mode 100644 index 0000000..fb40a3a --- /dev/null +++ b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/RingBufferTask.java @@ -0,0 +1,5 @@ +package top.limitart.fastmq.pipeline; + +public interface RingBufferTask { + +} diff --git a/intellij-java-google-style.xml b/intellij-java-google-style.xml new file mode 100644 index 0000000..45bf14c --- /dev/null +++ b/intellij-java-google-style.xml @@ -0,0 +1,598 @@ + + + + + + \ No newline at end of file -- Gitee From 69a99d9a17e84a874debaa20725b67d14c2cf8d1 Mon Sep 17 00:00:00 2001 From: hank <104381832> Date: Thu, 23 Jan 2020 22:49:49 +0800 Subject: [PATCH 03/11] 1 --- .../collections/ConcurrentHashSet.java | 5 + .../java/top/limitart/util/CodecUtil.java | 6 +- .../main/java/top/limitart/util/EnumUtil.java | 4 + .../java/top/limitart/util/HTTPClient.java | 10 +- .../java/top/limitart/util/ObjectUtil.java | 6 +- demo/pom.xml | 5 + .../limitart/fastmq/PipelineServerDemo.java | 22 ++ fastmq/common/pom.xml | 21 ++ .../limitart/fastmq/common/binary/Consts.java | 9 + .../common/binary/ReqCustomerReadyMsg.java | 16 + .../common/binary/ReqRegisterZoneMsg.java | 17 + .../common/binary/ResRegisterZoneMsg.java | 17 + .../fastmq/common/binary/ResZoneClaimMsg.java | 14 + fastmq/pipeline/pom.xml | 13 +- .../fastmq/pipeline/AbstractBinaryServer.java | 7 + .../fastmq/pipeline/PipelineBinaryServer.java | 145 ++++++++ .../limitart/fastmq/pipeline/Response.java | 5 - .../fastmq/pipeline/RingBufferTask.java | 5 - .../{Request.java => SessionParamConst.java} | 4 +- .../fastmq/pipeline/binary/BinaryRequest.java | 7 + .../fastmq/pipeline/core/MessageSlot.java | 26 ++ .../fastmq/pipeline/core/Pipeline.java | 317 ++++++++++++++++++ .../{ => core}/PipelineRingBuffer.java | 75 +++-- .../pipeline/core/PipelineRingBufferSlot.java | 22 ++ fastmq/pom.xml | 1 + pom.xml | 35 +- 26 files changed, 758 insertions(+), 56 deletions(-) create mode 100644 demo/src/main/java/top/limitart/fastmq/PipelineServerDemo.java create mode 100644 fastmq/common/pom.xml create mode 100644 fastmq/common/src/main/java/top/limitart/fastmq/common/binary/Consts.java create mode 100644 fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqCustomerReadyMsg.java create mode 100644 fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqRegisterZoneMsg.java create mode 100644 fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ResRegisterZoneMsg.java create mode 100644 fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ResZoneClaimMsg.java create mode 100644 fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/AbstractBinaryServer.java create mode 100644 fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/PipelineBinaryServer.java delete mode 100644 fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/Response.java delete mode 100644 fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/RingBufferTask.java rename fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/{Request.java => SessionParamConst.java} (39%) create mode 100644 fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/binary/BinaryRequest.java create mode 100644 fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/core/MessageSlot.java create mode 100644 fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/core/Pipeline.java rename fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/{ => core}/PipelineRingBuffer.java (61%) create mode 100644 fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/core/PipelineRingBufferSlot.java diff --git a/core/src/main/java/top/limitart/collections/ConcurrentHashSet.java b/core/src/main/java/top/limitart/collections/ConcurrentHashSet.java index 14b402f..1fe11e1 100644 --- a/core/src/main/java/top/limitart/collections/ConcurrentHashSet.java +++ b/core/src/main/java/top/limitart/collections/ConcurrentHashSet.java @@ -15,6 +15,7 @@ */ package top.limitart.collections; +import java.util.Collection; import top.limitart.base.label.ThreadSafe; import java.util.AbstractSet; @@ -43,6 +44,10 @@ public class ConcurrentHashSet extends AbstractSet { map = new ConcurrentHashMap<>(initialCapacity); } + public ConcurrentHashSet(Collection collection) { + map = new ConcurrentHashMap<>(); + addAll(collection); + } @Override public Iterator iterator() { return map.keySet().iterator(); diff --git a/core/src/main/java/top/limitart/util/CodecUtil.java b/core/src/main/java/top/limitart/util/CodecUtil.java index 6bd22d0..59fc911 100644 --- a/core/src/main/java/top/limitart/util/CodecUtil.java +++ b/core/src/main/java/top/limitart/util/CodecUtil.java @@ -37,9 +37,13 @@ import java.util.zip.GZIPOutputStream; * @author hank * @version 2018/4/20 0020 11:06 */ -public class CodecUtil { +public final class CodecUtil { + private static final Logger LOGGER = LoggerFactory.getLogger(CodecUtil.class); + private CodecUtil() { + } + public static String urlEncode(String str) throws UnsupportedEncodingException { return URLEncoder.encode(str, StandardCharsets.UTF_8.name()); } diff --git a/core/src/main/java/top/limitart/util/EnumUtil.java b/core/src/main/java/top/limitart/util/EnumUtil.java index fa99fd3..4522fc9 100644 --- a/core/src/main/java/top/limitart/util/EnumUtil.java +++ b/core/src/main/java/top/limitart/util/EnumUtil.java @@ -24,6 +24,10 @@ import top.limitart.base.label.Nullable; * @version 2018/2/12 0012 20:22 */ public final class EnumUtil { + + private EnumUtil() { + } + /** * 获取序号对应的枚举类型 * diff --git a/core/src/main/java/top/limitart/util/HTTPClient.java b/core/src/main/java/top/limitart/util/HTTPClient.java index 5c44b7f..6289be6 100644 --- a/core/src/main/java/top/limitart/util/HTTPClient.java +++ b/core/src/main/java/top/limitart/util/HTTPClient.java @@ -33,10 +33,16 @@ import java.util.Map; import java.util.concurrent.Executor; import java.util.concurrent.Future; -/** HTTP客户端 Created by Hank on 2019/3/17 */ -public class HTTPClient { +/** + * HTTP客户端 Created by Hank on 2019/3/17 + */ +public final class HTTPClient { + private static final Logger LOGGER = LoggerFactory.getLogger(HTTPClient.class); + private HTTPClient() { + } + public static byte[] download(String uri) { return download(uri); } diff --git a/core/src/main/java/top/limitart/util/ObjectUtil.java b/core/src/main/java/top/limitart/util/ObjectUtil.java index dd8bd98..3e02ecd 100644 --- a/core/src/main/java/top/limitart/util/ObjectUtil.java +++ b/core/src/main/java/top/limitart/util/ObjectUtil.java @@ -8,7 +8,11 @@ import java.lang.reflect.Field; * @author hank * @version 2018/12/28 0028 20:27 */ -public class ObjectUtil { +public final class ObjectUtil { + + private ObjectUtil() { + } + /** * 通过反射字段拷贝 * diff --git a/demo/pom.xml b/demo/pom.xml index b46569b..23364ec 100644 --- a/demo/pom.xml +++ b/demo/pom.xml @@ -38,6 +38,11 @@ limitart-hotdep ${project.version} + + ${project.groupId} + limitart-fastmq-pipeline + ${project.version} + org.apache.logging.log4j diff --git a/demo/src/main/java/top/limitart/fastmq/PipelineServerDemo.java b/demo/src/main/java/top/limitart/fastmq/PipelineServerDemo.java new file mode 100644 index 0000000..ff1623d --- /dev/null +++ b/demo/src/main/java/top/limitart/fastmq/PipelineServerDemo.java @@ -0,0 +1,22 @@ +package top.limitart.fastmq; + +import top.limitart.fastmq.pipeline.PipelineBinaryServer; +import top.limitart.fastmq.pipeline.core.Pipeline; + +public class PipelineServerDemo { + + private static Pipeline pipeline = new Pipeline(); + private static PipelineBinaryServer binaryServer; + + static { + try { + binaryServer = new PipelineBinaryServer(pipeline, 9000); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static void main(String[] args) throws Exception { + binaryServer.run(args); + } +} diff --git a/fastmq/common/pom.xml b/fastmq/common/pom.xml new file mode 100644 index 0000000..30fc55f --- /dev/null +++ b/fastmq/common/pom.xml @@ -0,0 +1,21 @@ + + + + limitart-fastmq + top.limitart + 3.1.0 + + 4.0.0 + + limitart-fastmq-common + + + + ${project.groupId} + limitart-net + ${project.version} + + + \ No newline at end of file diff --git a/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/Consts.java b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/Consts.java new file mode 100644 index 0000000..e29739e --- /dev/null +++ b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/Consts.java @@ -0,0 +1,9 @@ +package top.limitart.fastmq.common.binary; + +public class Consts { + + public static final short REQ_REGISTER_ZONE_MSG = 1; + public static final short RES_REGISTER_ZONE_MSG = REQ_REGISTER_ZONE_MSG + 1; + public static final short RES_CUSTOMER_READY_MSG = RES_REGISTER_ZONE_MSG + 1; + public static final short RES_ZONE_CLAIM_MSG = RES_CUSTOMER_READY_MSG + 1; +} diff --git a/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqCustomerReadyMsg.java b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqCustomerReadyMsg.java new file mode 100644 index 0000000..3a281e8 --- /dev/null +++ b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqCustomerReadyMsg.java @@ -0,0 +1,16 @@ +package top.limitart.fastmq.common.binary; + +import top.limitart.net.binary.BinaryMessage; + +public class ReqCustomerReadyMsg extends BinaryMessage { + + //集群编号 + public String zone; + //TOKEN + public String token; + + @Override + public short id() { + return Consts.RES_CUSTOMER_READY_MSG; + } +} diff --git a/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqRegisterZoneMsg.java b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqRegisterZoneMsg.java new file mode 100644 index 0000000..9f81bc9 --- /dev/null +++ b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqRegisterZoneMsg.java @@ -0,0 +1,17 @@ +package top.limitart.fastmq.common.binary; + +import java.util.List; +import top.limitart.net.binary.BinaryMessage; + +public class ReqRegisterZoneMsg extends BinaryMessage { + + //集群编号 + public String zone; + //标签 + public List tags; + + @Override + public short id() { + return Consts.REQ_REGISTER_ZONE_MSG; + } +} diff --git a/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ResRegisterZoneMsg.java b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ResRegisterZoneMsg.java new file mode 100644 index 0000000..a08d4c2 --- /dev/null +++ b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ResRegisterZoneMsg.java @@ -0,0 +1,17 @@ +package top.limitart.fastmq.common.binary; + +import top.limitart.net.binary.BinaryMessage; + +public class ResRegisterZoneMsg extends BinaryMessage { + + /** + * 0 成功 1失败 + */ + public byte code; + public String token; + + @Override + public short id() { + return Consts.RES_REGISTER_ZONE_MSG; + } +} diff --git a/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ResZoneClaimMsg.java b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ResZoneClaimMsg.java new file mode 100644 index 0000000..a4e9531 --- /dev/null +++ b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ResZoneClaimMsg.java @@ -0,0 +1,14 @@ +package top.limitart.fastmq.common.binary; + + +import top.limitart.net.binary.BinaryMessage; + +public class ResZoneClaimMsg extends BinaryMessage { + + public static final ResZoneClaimMsg INSTANCE = new ResZoneClaimMsg(); + + @Override + public short id() { + return Consts.RES_ZONE_CLAIM_MSG; + } +} diff --git a/fastmq/pipeline/pom.xml b/fastmq/pipeline/pom.xml index 11c16e9..a47aa43 100644 --- a/fastmq/pipeline/pom.xml +++ b/fastmq/pipeline/pom.xml @@ -11,5 +11,16 @@ limitart-fastmq-pipeline - + + + ${project.groupId} + limitart-net + ${project.version} + + + ${project.groupId} + limitart-fastmq-common + ${project.version} + + \ No newline at end of file diff --git a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/AbstractBinaryServer.java b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/AbstractBinaryServer.java new file mode 100644 index 0000000..7ad6fcb --- /dev/null +++ b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/AbstractBinaryServer.java @@ -0,0 +1,7 @@ +package top.limitart.fastmq.pipeline; + +import top.limitart.fastmq.pipeline.core.Pipeline; + +public class AbstractBinaryServer { + private Pipeline pipeline; +} diff --git a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/PipelineBinaryServer.java b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/PipelineBinaryServer.java new file mode 100644 index 0000000..beadfbf --- /dev/null +++ b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/PipelineBinaryServer.java @@ -0,0 +1,145 @@ +package top.limitart.fastmq.pipeline; + + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import top.limitart.base.ApplicationBootstrap; +import top.limitart.fastmq.common.binary.ReqCustomerReadyMsg; +import top.limitart.fastmq.common.binary.ReqRegisterZoneMsg; +import top.limitart.fastmq.common.binary.ResRegisterZoneMsg; +import top.limitart.fastmq.common.binary.ResZoneClaimMsg; +import top.limitart.fastmq.pipeline.binary.BinaryRequest; +import top.limitart.fastmq.pipeline.core.Pipeline; +import top.limitart.fastmq.pipeline.core.Pipeline.States; +import top.limitart.mapping.Mapper; +import top.limitart.mapping.Request; +import top.limitart.mapping.Router; +import top.limitart.net.AddressPair; +import top.limitart.net.NettySession; +import top.limitart.net.binary.BinaryEndPoint; +import top.limitart.net.binary.BinaryMessage; +import top.limitart.net.binary.BinaryRequestParam; +import top.limitart.util.StringUtil; + +@Mapper +public class PipelineBinaryServer extends ApplicationBootstrap { + + private static Logger LOGGER = LoggerFactory.getLogger(PipelineBinaryServer.class); + private Pipeline pipeline; + private BinaryEndPoint endPoint; + private int port; + + public PipelineBinaryServer(Pipeline pipeline, int port) throws Exception { + this.pipeline = pipeline; + this.port = port; + endPoint = BinaryEndPoint.server().router(Router.empty(BinaryMessage.class, BinaryRequest.class) + .registerMapperClass(PipelineBinaryServer.class, c -> this)) + .onConnected((s, b) -> onConnected(s, b)).onMessageIn((m, s, r) -> onMessageIn(m, s, r)) + .name("binary-pipeline-server") + .onExceptionThrown( + (s, t) -> LOGGER.error("session " + s, t) + ).build(); + } + + private void onMessageIn(BinaryMessage msg, NettySession session, + Router router) { + BinaryRequest binaryRequestParam = (BinaryRequest) router.contextInstance(); + //TODO 可能有一些参数加入上下文 + binaryRequestParam.session(session); + router.request(msg, binaryRequestParam, Router.MethodInvoker::invoke); + } + + private void onConnected(NettySession session, Boolean connectedOrDisconnected) { + if (!connectedOrDisconnected) { + String zone = session.params().getString(SessionParamConst.ZONE); + if (zone != null) { + pipeline.inactiveZone(zone); + LOGGER.error("session {} disconnected, inactive zone {}", session, zone); + } + } + } + + @Override + protected void onStart(String[] args) throws Exception { + endPoint.start(AddressPair.withPort(port), (s, b, t) -> { + if (b) { + LOGGER.info("pipeline binary start success!"); + } else { + LOGGER.error("bind error", t); + System.exit(1); + } + }); + } + + @Override + protected void onDestroy(String[] args) { + endPoint.stop(); + } + + /** + * 生产者注册 + * + * @param msg + */ + public void providerRegister(@Request ReqRegisterZoneMsg msg, BinaryRequest context) { + ResRegisterZoneMsg res = new ResRegisterZoneMsg(); + if (StringUtil.empty(msg.zone)) { + res.code = 1; + context.session().writeNow(res); + LOGGER.error("session {} send a null zone", context.session()); + return; + } + if (!pipeline.registerBuffer(msg.zone, msg.tags)) { + //如果这个队列本来存在且并未处于激活状态就需要该客户端来认领 + States zoneState = pipeline.getZoneState(msg.zone); + if (zoneState != null && zoneState != States.ACTIVE) { + context.session().writeNow(ResZoneClaimMsg.INSTANCE); + LOGGER.info("session {} need claim", context.session()); + } else { + res.code = 1; + context.session().writeNow(res); + LOGGER.info("zone {} does not belong to session {}", msg.zone, context.session()); + } + return; + } + res.code = 0; + res.token = pipeline.getZoneToken(msg.zone); + context.session().writeNow(res); + LOGGER.info("session {} , zone {} register success,then tell me ready!", context.session(), + msg.zone); + } + + public void providerReady(@Request ReqCustomerReadyMsg msg, BinaryRequest context) { + //先看参数 + if (StringUtil.empty(msg.zone)) { + LOGGER.error("session {} send a null zone for ready", context.session()); + context.session().close(); + return; + } + if (StringUtil.empty(msg.token)) { + LOGGER.error("session {} send a null token for ready", context.session()); + context.session().close(); + return; + } + States zoneState = pipeline.getZoneState(msg.zone); + if (zoneState == null) { + LOGGER.error("session {} does not register for zone {}", context.session(), msg.zone); + context.session().close(); + return; + } + if (zoneState == States.ACTIVE) { + LOGGER.error("can not active zone {} twice for session {}", msg.zone, context.session()); + context.session().close(); + return; + } + String zoneToken = pipeline.getZoneToken(msg.zone); + if (!zoneToken.equals(msg.token)) { + LOGGER.error("can not active zone {} with a wrong token for session {}", msg.zone, + context.session()); + context.session().close(); + return; + } + pipeline.activeZone(msg.zone); + context.session().params().putString(SessionParamConst.ZONE, msg.zone); + } +} diff --git a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/Response.java b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/Response.java deleted file mode 100644 index 7a53fa2..0000000 --- a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/Response.java +++ /dev/null @@ -1,5 +0,0 @@ -package top.limitart.fastmq.pipeline; - -public interface Response extends RingBufferTask { - -} diff --git a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/RingBufferTask.java b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/RingBufferTask.java deleted file mode 100644 index fb40a3a..0000000 --- a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/RingBufferTask.java +++ /dev/null @@ -1,5 +0,0 @@ -package top.limitart.fastmq.pipeline; - -public interface RingBufferTask { - -} diff --git a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/Request.java b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/SessionParamConst.java similarity index 39% rename from fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/Request.java rename to fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/SessionParamConst.java index a62da83..893335e 100644 --- a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/Request.java +++ b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/SessionParamConst.java @@ -1,5 +1,5 @@ package top.limitart.fastmq.pipeline; -public interface Request extends RingBufferTask { - +public class SessionParamConst { + public static int ZONE = 1; } diff --git a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/binary/BinaryRequest.java b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/binary/BinaryRequest.java new file mode 100644 index 0000000..21cfcbf --- /dev/null +++ b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/binary/BinaryRequest.java @@ -0,0 +1,7 @@ +package top.limitart.fastmq.pipeline.binary; + +import top.limitart.net.binary.BinaryRequestParam; + +public class BinaryRequest extends BinaryRequestParam { + +} diff --git a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/core/MessageSlot.java b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/core/MessageSlot.java new file mode 100644 index 0000000..c0750d0 --- /dev/null +++ b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/core/MessageSlot.java @@ -0,0 +1,26 @@ +package top.limitart.fastmq.pipeline.core; + +public class MessageSlot implements PipelineRingBufferSlot { + + private byte[] value; + + @Override + public void setValue(byte[] bytes) { + this.value = bytes; + } + + @Override + public byte[] getValue() { + return this.value; + } + + @Override + public void active() { + + } + + @Override + public void inactive() { + + } +} diff --git a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/core/Pipeline.java b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/core/Pipeline.java new file mode 100644 index 0000000..55274b2 --- /dev/null +++ b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/core/Pipeline.java @@ -0,0 +1,317 @@ +package top.limitart.fastmq.pipeline.core; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; +import java.util.regex.Pattern; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import top.limitart.base.Conditions; +import top.limitart.base.UniqueID; +import top.limitart.collections.ConcurrentHashSet; +import top.limitart.collections.ImmutableSet; +import top.limitart.concurrent.TaskQueue; +import top.limitart.util.StringUtil; +import top.limitart.util.TimeUtil; + +/** + * 消息总线 + */ +public class Pipeline { + + private static Logger LOGGER = LoggerFactory.getLogger(Pipeline.class); + private static final long HANG_TO_SHUTDOWN_INTERVAL = TimeUnit.SECONDS.toMillis(10); + //TAG + private Map> tagAndZones = new HashMap<>(); + //所有队列 + private Map zoneAndQueue = new HashMap<>(); + //轮询线程 + private final TaskQueue queue = TaskQueue.create("buffer-robin"); + + private Lock lock = new ReentrantLock(); + + public Pipeline() { + queue.schedule(this::dealShutdownAndHang, 10, TimeUnit.MINUTES); + } + + private void dealShutdownAndHang() { + lock.lock(); + try { + List waitToDelete = new LinkedList<>(); + for (Puller value : zoneAndQueue.values()) { + if (value.stateData.state == States.SHUTDOWN) { + waitToDelete.add(value.zone); + } else if (value.stateData.state == States.HANG + || value.stateData.state == States.REGISTER) { + if (TimeUtil.now() - value.stateData.changeTime > HANG_TO_SHUTDOWN_INTERVAL) { + value.changeState(States.SHUTDOWN); + LOGGER.warn("zone {}'s state turn to {} from {},please check!", value.zone, States.HANG, + States.SHUTDOWN); + } + } + } + for (String zone : waitToDelete) { + if (!removeBufferByZone(zone)) { + LOGGER.error("remove zone {} failed???", zone); + continue; + } + LOGGER.info("remove zone {} from Pipeline", zone); + } + } finally { + lock.unlock(); + } + } + + /** + * 通过集群编号删除队列 + * + * @param zone 整个集群唯一编号 + * @return + */ + private boolean removeBufferByZone(String zone) { + if (StringUtil.empty(zone)) { + LOGGER.error("can not remove buffer because zone null or empty"); + return false; + } + //TAG + for (Set value : tagAndZones.values()) { + value.removeIf(v -> v.equals(zone)); + } + return zoneAndQueue.remove(zone) != null; + } + + public List> getBuffersByTags(Set tags) { + Conditions.notNull(tags); + List> list = new ArrayList<>(); + try { + lock.lock(); + for (Entry> entry : tagAndZones.entrySet()) { + String key = entry.getKey(); + if (tags.contains(key)) { + Set value = entry.getValue(); + for (String zone : value) { + PipelineRingBuffer bufferByZone = getBufferByZone(zone); + if (bufferByZone != null) { + list.add(bufferByZone); + } + } + } + } + } finally { + lock.unlock(); + } + return list; + } + + public List> getBuffersByMatchedTags(Pattern tagPattern) { + List> list = new ArrayList<>(); + try { + lock.lock(); + for (Entry> entry : tagAndZones.entrySet()) { + String key = entry.getKey(); + if (StringUtil.matchReg(tagPattern, key)) { + Set value = entry.getValue(); + for (String zone : value) { + PipelineRingBuffer bufferByZone = getBufferByZone(zone); + if (bufferByZone != null) { + list.add(bufferByZone); + } + } + } + } + } finally { + lock.unlock(); + } + return list; + } + + public PipelineRingBuffer getBufferByZone(String zone) { + if (StringUtil.empty(zone)) { + LOGGER.error("can not get buffer because zone null or empty"); + return null; + } + try { + lock.lock(); + Puller puller = getPullerByZone(zone); + if (puller == null) { + return null; + } + return puller.buffer; + } finally { + lock.unlock(); + } + } + + public States getZoneState(String zone) { + Puller pullerByZone = getPullerByZone(zone); + if (pullerByZone == null) { + return null; + } + return pullerByZone.stateData.state; + } + + public void activeZone(String zone) { + Puller pullerByZone = getPullerByZone(zone); + if (pullerByZone != null) { + pullerByZone.changeState(States.ACTIVE); + LOGGER.info("zone {} active", zone); + } + } + + public void inactiveZone(String zone) { + Puller pullerByZone = getPullerByZone(zone); + if (pullerByZone != null) { + pullerByZone.changeState(States.HANG); + LOGGER.info("zone {} inactive", zone); + } + } + + public void shutdownZone(String zone) { + Puller pullerByZone = getPullerByZone(zone); + if (pullerByZone != null) { + pullerByZone.changeState(States.SHUTDOWN); + LOGGER.info("zone {} ready to shutdown", zone); + } + } + + public String getZoneToken(String zone) { + Puller pullerByZone = getPullerByZone(zone); + if (pullerByZone == null) { + return null; + } + return pullerByZone.token; + } + + private Puller getPullerByZone(String zone) { + Conditions.notNull(zone); + return zoneAndQueue.get(zone); + } + + /** + * 注册一个队列
生产者和消费者会根据唯一编号zone和个性化tag来发送和消费 + * + * @param zone 整个集群唯一编号 + * @param tags 该单位的自定义标签 + */ + public boolean registerBuffer(String zone, List tags) { + if (StringUtil.empty(zone)) { + LOGGER.error("zone null or empty"); + return false; + } + try { + lock.lock(); + if (zoneAndQueue.containsKey(zone)) { + LOGGER.error("zone duplicated {}", zone); + return false; + } + Set tagSet = new HashSet<>(); + if (tags != null) { + tagSet.addAll(tags); + tagSet.forEach(tag -> tagAndZones.computeIfAbsent(tag, (k) -> new HashSet<>()).add(zone)); + } + zoneAndQueue.put(zone, new Puller(zone, tagSet)); + LOGGER.info("zone {} register in pipeline", zone); + return true; + } finally { + lock.unlock(); + } + } + + private static class Puller { + + private String zone; + private Set tags; + private State stateData = new State(); + private PipelineRingBuffer buffer; + private String token = UniqueID.UUID(); + + public Puller(String zone, Set tags) { + this.zone = zone; + if (tags != null) { + this.tags = new ConcurrentHashSet<>(tags); + } else { + this.tags = new ConcurrentHashSet<>(); + } + buffer = new PipelineRingBuffer<>( + () -> new MessageSlot()); + } + + public Set getTags() { + return ImmutableSet.of(this.tags); + } + + public void changeState(States state) { + this.stateData.changeState(state); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Puller puller = (Puller) o; + return zone.equals(puller.zone); + } + + @Override + public int hashCode() { + return Objects.hash(zone); + } + } + + private static class State { + + private volatile States state = States.REGISTER; + private volatile long changeTime = TimeUtil.now(); + private Lock lock = new ReentrantLock(); + + public States getState() { + return this.state; + } + + public long getChangeTime() { + return changeTime; + } + + public void changeState(States newState) { + try { + lock.lock(); + this.state = newState; + changeTime = TimeUtil.now(); + } finally { + lock.unlock(); + } + } + } + + public enum States { + /** + * 注册中(正在校验合法性,无法消费消息) + */ + REGISTER, + /** + * 激活模式(可以正常消费消息) + */ + ACTIVE, + /** + * 挂起模式(异常,不能消费消息,需要重新激活,队列不会被清除) + */ + HANG, + /** + * 关闭(关闭模式的消息队列会被轮询清除) + */ + SHUTDOWN, + } +} diff --git a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/PipelineRingBuffer.java b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/core/PipelineRingBuffer.java similarity index 61% rename from fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/PipelineRingBuffer.java rename to fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/core/PipelineRingBuffer.java index d10715e..c568eea 100644 --- a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/PipelineRingBuffer.java +++ b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/core/PipelineRingBuffer.java @@ -1,4 +1,19 @@ -package top.limitart.fastmq.pipeline; +/* + * Copyright (c) 2016-present The Limitart Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package top.limitart.fastmq.pipeline.core; import com.lmax.disruptor.InsufficientCapacityException; import com.lmax.disruptor.RingBuffer; @@ -8,26 +23,26 @@ import java.util.LinkedList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import top.limitart.base.Alone; import top.limitart.base.Conditions; import top.limitart.base.UncatchableException; +import top.limitart.fastmq.pipeline.core.PipelineRingBufferSlot.PipelineRingBufferSlotFactory; /** - * 总线 + * 快速失败环形队列 */ -public class PipelineRingBuffer { +public class PipelineRingBuffer { private static final Logger LOGGER = LoggerFactory.getLogger(PipelineRingBuffer.class); - private final RingBuffer> buffer; + private final RingBuffer> buffer; private final Sequence readCursor; private EnqueueStrategy strategy = EnqueueStrategy.FAST_FAIL; - public PipelineRingBuffer() { - this(2 << 12); + public PipelineRingBuffer(PipelineRingBufferSlotFactory factory) { + this(2 << 12, factory); } - public PipelineRingBuffer(int size) { - buffer = RingBuffer.createMultiProducer(Alone::of, size); + public PipelineRingBuffer(int size, PipelineRingBufferSlotFactory factory) { + buffer = RingBuffer.createMultiProducer(() -> factory.newSlot(), size); readCursor = new Sequence(); buffer.addGatingSequences(readCursor); } @@ -43,7 +58,7 @@ public class PipelineRingBuffer { return this; } - public void enqueue(RingBufferTask task) { + public void enqueue(V task) { Conditions.notNull(task); try { long seq = buffer.tryNext(); @@ -64,7 +79,7 @@ public class PipelineRingBuffer { } } - public void enqueue(List tasks) { + public void enqueue(List tasks) { Conditions.args(tasks != null && !tasks.isEmpty(), "task list is null or empty"); long start = buffer.getCursor() + 1; try { @@ -91,8 +106,8 @@ public class PipelineRingBuffer { * * @return */ - public RingBufferTask peek() { - List ringBufferTasks = peekAtMost(1); + public V peek() { + List ringBufferTasks = peekAtMost(1); if (ringBufferTasks.isEmpty()) { return null; } @@ -105,9 +120,9 @@ public class PipelineRingBuffer { * @param num * @return */ - public List peekAtMost(int num) { + public List peekAtMost(int num) { Conditions.positive(num); - List list = null; + List list = null; if (num > 1) { list = new LinkedList<>(); } @@ -121,29 +136,47 @@ public class PipelineRingBuffer { if (!readCursor.compareAndSet(now, next)) { continue; } + PipelineRingBufferSlot slot = buffer.get(next); if (list != null) { - list.add(buffer.get(next).get()); + list.add(slot.getValue()); } else { - list = Collections.singletonList(buffer.get(next).get()); + list = Collections.singletonList(slot.getValue()); + } + try { + slot.inactive(); + } catch (Exception e) { + LOGGER.error("inactive callback error", e); } ++count; } return list; } - private void publish(List tasks, long low, long high) { + private void publish(List tasks, long low, long high) { try { for (int i = 0; i < tasks.size(); i++) { - buffer.get(low + i).set(tasks.get(i)); + PipelineRingBufferSlot slot = buffer.get(low + i); + slot.setValue(tasks.get(i)); + try { + slot.active(); + } catch (Exception e) { + LOGGER.error("active callback error", e); + } } } finally { buffer.publish(low, high); } } - private void publish(RingBufferTask tasks, long seq) { + private void publish(V tasks, long seq) { try { - buffer.get(seq).set(tasks); + PipelineRingBufferSlot slot = buffer.get(seq); + slot.setValue(tasks); + try { + slot.active(); + } catch (Exception e) { + LOGGER.error("active callback error", e); + } } finally { buffer.publish(seq); } diff --git a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/core/PipelineRingBufferSlot.java b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/core/PipelineRingBufferSlot.java new file mode 100644 index 0000000..7f9a463 --- /dev/null +++ b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/core/PipelineRingBufferSlot.java @@ -0,0 +1,22 @@ +package top.limitart.fastmq.pipeline.core; + +public interface PipelineRingBufferSlot { + + void setValue(V v); + + V getValue(); + + void active(); + + void inactive(); + + /** + * 环形队列的可复用插槽 + * + * @param + */ + interface PipelineRingBufferSlotFactory { + + PipelineRingBufferSlot newSlot(); + } +} diff --git a/fastmq/pom.xml b/fastmq/pom.xml index 4fa35a7..1ad3570 100644 --- a/fastmq/pom.xml +++ b/fastmq/pom.xml @@ -15,6 +15,7 @@ pipeline consumer provider + common diff --git a/pom.xml b/pom.xml index d795153..18ac044 100644 --- a/pom.xml +++ b/pom.xml @@ -177,12 +177,12 @@ org.ow2.asm asm - 6.0 + 7.3.1 org.javassist javassist - 3.25.0-GA + 3.26.0-GA @@ -196,88 +196,87 @@ com.lmax disruptor - 3.4.0 + 3.4.2 org.slf4j slf4j-api - 1.7.25 + 1.7.30 org.slf4j slf4j-jdk14 - 1.7.25 + 1.7.30 test io.netty netty-all - 4.1.22.Final + 4.1.44.Final org.apache.httpcomponents httpclient - 4.5.7 + 4.5.11 org.apache.httpcomponents fluent-hc - 4.5.7 + 4.5.11 com.google.protobuf protobuf-java - 3.6.1 + 3.11.1 com.fasterxml.jackson.datatype jackson-datatype-jdk8 - 2.9.4 + 2.10.1 com.fasterxml.jackson.datatype jackson-datatype-jsr310 - 2.9.4 + 2.10.1 com.zaxxer HikariCP - 3.0.0 + 3.4.2 com.alibaba druid - 1.1.9 + 1.1.21 org.freemarker freemarker - 2.3.28 + 2.3.29 org.apache.poi poi - 4.0.0 + 4.1.1 org.apache.poi poi-ooxml - 4.0.0 + 4.1.1 - junit junit - 4.12 + 4.13 test -- Gitee From ceaddb2f800a3b2e21ec23e1e5e93a827c4b9fde Mon Sep 17 00:00:00 2001 From: hank <104381832> Date: Fri, 24 Jan 2020 00:04:33 +0800 Subject: [PATCH 04/11] 1 --- fastmq/consumer/pom.xml | 13 ++++++++++++- .../fastmq/consumer/ConsumerBinaryClient.java | 16 ++++++++++++++++ .../fastmq/pipeline/PipelineRestServer.java | 5 +++++ fastmq/provider/pom.xml | 13 ++++++++++++- 4 files changed, 45 insertions(+), 2 deletions(-) create mode 100644 fastmq/consumer/src/main/java/top/limitart/fastmq/consumer/ConsumerBinaryClient.java create mode 100644 fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/PipelineRestServer.java diff --git a/fastmq/consumer/pom.xml b/fastmq/consumer/pom.xml index 547a4b1..0b90ab0 100644 --- a/fastmq/consumer/pom.xml +++ b/fastmq/consumer/pom.xml @@ -11,5 +11,16 @@ limitart-fastmq-consumer - + + + ${project.groupId} + limitart-net + ${project.version} + + + ${project.groupId} + limitart-fastmq-common + ${project.version} + + \ No newline at end of file diff --git a/fastmq/consumer/src/main/java/top/limitart/fastmq/consumer/ConsumerBinaryClient.java b/fastmq/consumer/src/main/java/top/limitart/fastmq/consumer/ConsumerBinaryClient.java new file mode 100644 index 0000000..f846166 --- /dev/null +++ b/fastmq/consumer/src/main/java/top/limitart/fastmq/consumer/ConsumerBinaryClient.java @@ -0,0 +1,16 @@ +package top.limitart.fastmq.consumer; + +import top.limitart.mapping.Mapper; +import top.limitart.mapping.Router; +import top.limitart.net.binary.BinaryEndPoint; +import top.limitart.net.binary.BinaryMessage; + +@Mapper +public class ConsumerBinaryClient { + private BinaryEndPoint client; + + public ConsumerBinaryClient() { + Router router = Router.empty().registerMapperClass(BinaryMessage.class,binaryre) + this.client = BinaryEndPoint.client().router().timeoutSeconds().build(); + } +} diff --git a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/PipelineRestServer.java b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/PipelineRestServer.java new file mode 100644 index 0000000..f57964d --- /dev/null +++ b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/PipelineRestServer.java @@ -0,0 +1,5 @@ +package top.limitart.fastmq.pipeline; + +public class PipelineRestServer { + +} diff --git a/fastmq/provider/pom.xml b/fastmq/provider/pom.xml index 44cf0f7..af1872a 100644 --- a/fastmq/provider/pom.xml +++ b/fastmq/provider/pom.xml @@ -11,5 +11,16 @@ limitart-fastmq-provider - + + + ${project.groupId} + limitart-net + ${project.version} + + + ${project.groupId} + limitart-fastmq-common + ${project.version} + + \ No newline at end of file -- Gitee From 44bc56671005a94576711d8641e3530aceddcd2d Mon Sep 17 00:00:00 2001 From: HankXV <104381832@qq.com> Date: Tue, 28 Jan 2020 23:51:41 +0800 Subject: [PATCH 05/11] 1 --- config/pom.xml | 2 +- core/pom.xml | 2 +- db/pom.xml | 2 +- demo/pom.xml | 12 +- .../limitart/fastmq/PipelineConsumerDemo.java | 27 + fastmq/common/pom.xml | 2 +- .../fastmq/common}/SessionParamConst.java | 3 +- .../fastmq/common}/binary/BinaryRequest.java | 2 +- .../limitart/fastmq/common/binary/Consts.java | 3 + .../fastmq/common/binary/ReqHeartBeatMsg.java | 11 + ...ZoneClaimMsg.java => ReqZoneClaimMsg.java} | 4 +- .../fastmq/common/binary/ResHeartBeatMsg.java | 11 + .../binary/ResPipelineEstablishedMsg.java | 12 + fastmq/consumer/pom.xml | 2 +- .../fastmq/consumer/ConsumerBinaryClient.java | 187 ++++++- fastmq/pipeline/pom.xml | 2 +- .../fastmq/pipeline/PipelineBinaryServer.java | 198 ++++--- .../fastmq/pipeline/core/Pipeline.java | 41 +- fastmq/pom.xml | 2 +- fastmq/provider/pom.xml | 2 +- .../fastmq/provider/ProviderBinaryClient.java | 46 ++ game/pom.xml | 2 +- hotdep/pom.xml | 2 +- net/pom.xml | 2 +- .../java/top/limitart/mapping/RouterImpl.java | 516 +++++++++--------- pom.xml | 39 +- project-logic/pom.xml | 2 +- project-starter/pom.xml | 2 +- update-version.sh | 2 + 29 files changed, 769 insertions(+), 371 deletions(-) create mode 100644 demo/src/main/java/top/limitart/fastmq/PipelineConsumerDemo.java rename fastmq/{pipeline/src/main/java/top/limitart/fastmq/pipeline => common/src/main/java/top/limitart/fastmq/common}/SessionParamConst.java (47%) rename fastmq/{pipeline/src/main/java/top/limitart/fastmq/pipeline => common/src/main/java/top/limitart/fastmq/common}/binary/BinaryRequest.java (71%) create mode 100644 fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqHeartBeatMsg.java rename fastmq/common/src/main/java/top/limitart/fastmq/common/binary/{ResZoneClaimMsg.java => ReqZoneClaimMsg.java} (60%) create mode 100644 fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ResHeartBeatMsg.java create mode 100644 fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ResPipelineEstablishedMsg.java create mode 100644 fastmq/provider/src/main/java/top/limitart/fastmq/provider/ProviderBinaryClient.java create mode 100644 update-version.sh diff --git a/config/pom.xml b/config/pom.xml index 7921366..509adf2 100644 --- a/config/pom.xml +++ b/config/pom.xml @@ -5,7 +5,7 @@ limitart top.limitart - 3.1.0 + 3.2.0-SNAPSHOT 4.0.0 diff --git a/core/pom.xml b/core/pom.xml index 1213408..de313a3 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -5,7 +5,7 @@ top.limitart limitart - 3.1.0 + 3.2.0-SNAPSHOT 4.0.0 diff --git a/db/pom.xml b/db/pom.xml index 04650b8..4773a36 100644 --- a/db/pom.xml +++ b/db/pom.xml @@ -5,7 +5,7 @@ limitart top.limitart - 3.1.0 + 3.2.0-SNAPSHOT 4.0.0 diff --git a/demo/pom.xml b/demo/pom.xml index 23364ec..be93c80 100644 --- a/demo/pom.xml +++ b/demo/pom.xml @@ -5,7 +5,7 @@ top.limitart limitart - 3.1.0 + 3.2.0-SNAPSHOT 4.0.0 @@ -43,6 +43,16 @@ limitart-fastmq-pipeline ${project.version}
+ + ${project.groupId} + limitart-fastmq-consumer + ${project.version} + + + ${project.groupId} + limitart-fastmq-provider + ${project.version} + org.apache.logging.log4j diff --git a/demo/src/main/java/top/limitart/fastmq/PipelineConsumerDemo.java b/demo/src/main/java/top/limitart/fastmq/PipelineConsumerDemo.java new file mode 100644 index 0000000..8d0e05f --- /dev/null +++ b/demo/src/main/java/top/limitart/fastmq/PipelineConsumerDemo.java @@ -0,0 +1,27 @@ +package top.limitart.fastmq; + +import java.util.LinkedList; +import java.util.List; +import top.limitart.fastmq.consumer.ConsumerBinaryClient; +import top.limitart.fastmq.pipeline.PipelineBinaryServer; +import top.limitart.fastmq.pipeline.core.Pipeline; + +public class PipelineConsumerDemo { + + private static ConsumerBinaryClient consumerClient; + + static { + try { + List tags = new LinkedList<>(); + tags.add("fuck"); + tags.add("shit"); + consumerClient = new ConsumerBinaryClient("127.0.0.1",9000,"test_zone",tags); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static void main(String[] args) throws Exception { + consumerClient.run(args); + } +} diff --git a/fastmq/common/pom.xml b/fastmq/common/pom.xml index 30fc55f..5c084c7 100644 --- a/fastmq/common/pom.xml +++ b/fastmq/common/pom.xml @@ -5,7 +5,7 @@ limitart-fastmq top.limitart - 3.1.0 + 3.2.0-SNAPSHOT 4.0.0 diff --git a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/SessionParamConst.java b/fastmq/common/src/main/java/top/limitart/fastmq/common/SessionParamConst.java similarity index 47% rename from fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/SessionParamConst.java rename to fastmq/common/src/main/java/top/limitart/fastmq/common/SessionParamConst.java index 893335e..9938e60 100644 --- a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/SessionParamConst.java +++ b/fastmq/common/src/main/java/top/limitart/fastmq/common/SessionParamConst.java @@ -1,5 +1,6 @@ -package top.limitart.fastmq.pipeline; +package top.limitart.fastmq.common; public class SessionParamConst { public static int ZONE = 1; + public static int HEART_BEAT = 2; } diff --git a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/binary/BinaryRequest.java b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/BinaryRequest.java similarity index 71% rename from fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/binary/BinaryRequest.java rename to fastmq/common/src/main/java/top/limitart/fastmq/common/binary/BinaryRequest.java index 21cfcbf..f4e0343 100644 --- a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/binary/BinaryRequest.java +++ b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/BinaryRequest.java @@ -1,4 +1,4 @@ -package top.limitart.fastmq.pipeline.binary; +package top.limitart.fastmq.common.binary; import top.limitart.net.binary.BinaryRequestParam; diff --git a/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/Consts.java b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/Consts.java index e29739e..cf1c3ed 100644 --- a/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/Consts.java +++ b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/Consts.java @@ -6,4 +6,7 @@ public class Consts { public static final short RES_REGISTER_ZONE_MSG = REQ_REGISTER_ZONE_MSG + 1; public static final short RES_CUSTOMER_READY_MSG = RES_REGISTER_ZONE_MSG + 1; public static final short RES_ZONE_CLAIM_MSG = RES_CUSTOMER_READY_MSG + 1; + public static final short REQ_HEART_BEAT = RES_ZONE_CLAIM_MSG + 1; + public static final short RES_HEART_BEAT = REQ_HEART_BEAT + 1; + public static final short RES_PIPELINE_ESTANBLISHED = RES_HEART_BEAT + 1; } diff --git a/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqHeartBeatMsg.java b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqHeartBeatMsg.java new file mode 100644 index 0000000..578a9d6 --- /dev/null +++ b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqHeartBeatMsg.java @@ -0,0 +1,11 @@ +package top.limitart.fastmq.common.binary; + +import top.limitart.net.binary.BinaryMessage; + +public class ReqHeartBeatMsg extends BinaryMessage { + public static final ReqHeartBeatMsg INSTANCE = new ReqHeartBeatMsg(); + @Override + public short id() { + return Consts.REQ_HEART_BEAT; + } +} diff --git a/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ResZoneClaimMsg.java b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqZoneClaimMsg.java similarity index 60% rename from fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ResZoneClaimMsg.java rename to fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqZoneClaimMsg.java index a4e9531..3bd3ef8 100644 --- a/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ResZoneClaimMsg.java +++ b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqZoneClaimMsg.java @@ -3,9 +3,9 @@ package top.limitart.fastmq.common.binary; import top.limitart.net.binary.BinaryMessage; -public class ResZoneClaimMsg extends BinaryMessage { +public class ReqZoneClaimMsg extends BinaryMessage { - public static final ResZoneClaimMsg INSTANCE = new ResZoneClaimMsg(); + public static final ReqZoneClaimMsg INSTANCE = new ReqZoneClaimMsg(); @Override public short id() { diff --git a/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ResHeartBeatMsg.java b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ResHeartBeatMsg.java new file mode 100644 index 0000000..65d72bd --- /dev/null +++ b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ResHeartBeatMsg.java @@ -0,0 +1,11 @@ +package top.limitart.fastmq.common.binary; + +import top.limitart.net.binary.BinaryMessage; + +public class ResHeartBeatMsg extends BinaryMessage { + public static final ResHeartBeatMsg INSTANCE = new ResHeartBeatMsg(); + @Override + public short id() { + return Consts.RES_HEART_BEAT; + } +} diff --git a/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ResPipelineEstablishedMsg.java b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ResPipelineEstablishedMsg.java new file mode 100644 index 0000000..486ae37 --- /dev/null +++ b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ResPipelineEstablishedMsg.java @@ -0,0 +1,12 @@ +package top.limitart.fastmq.common.binary; + +import top.limitart.net.binary.BinaryMessage; + +public class ResPipelineEstablishedMsg extends BinaryMessage { + public static final ResPipelineEstablishedMsg INSTANCE = new ResPipelineEstablishedMsg(); + + @Override + public short id() { + return Consts.RES_REGISTER_ZONE_MSG; + } +} diff --git a/fastmq/consumer/pom.xml b/fastmq/consumer/pom.xml index 0b90ab0..dc76891 100644 --- a/fastmq/consumer/pom.xml +++ b/fastmq/consumer/pom.xml @@ -5,7 +5,7 @@ limitart-fastmq top.limitart - 3.1.0 + 3.2.0-SNAPSHOT 4.0.0 diff --git a/fastmq/consumer/src/main/java/top/limitart/fastmq/consumer/ConsumerBinaryClient.java b/fastmq/consumer/src/main/java/top/limitart/fastmq/consumer/ConsumerBinaryClient.java index f846166..4fae084 100644 --- a/fastmq/consumer/src/main/java/top/limitart/fastmq/consumer/ConsumerBinaryClient.java +++ b/fastmq/consumer/src/main/java/top/limitart/fastmq/consumer/ConsumerBinaryClient.java @@ -1,16 +1,193 @@ package top.limitart.fastmq.consumer; +import io.netty.channel.EventLoop; +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Collections; +import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import top.limitart.base.ApplicationBootstrap; +import top.limitart.collections.ImmutableList; +import top.limitart.fastmq.common.binary.BinaryRequest; +import top.limitart.fastmq.common.binary.ReqCustomerReadyMsg; +import top.limitart.fastmq.common.binary.ReqHeartBeatMsg; +import top.limitart.fastmq.common.binary.ReqRegisterZoneMsg; +import top.limitart.fastmq.common.binary.ResHeartBeatMsg; +import top.limitart.fastmq.common.binary.ResPipelineEstablishedMsg; +import top.limitart.fastmq.common.binary.ResRegisterZoneMsg; +import top.limitart.fastmq.common.binary.ReqZoneClaimMsg; import top.limitart.mapping.Mapper; +import top.limitart.mapping.Request; import top.limitart.mapping.Router; +import top.limitart.net.AddressPair; +import top.limitart.net.NettySession; +import top.limitart.net.Session; import top.limitart.net.binary.BinaryEndPoint; import top.limitart.net.binary.BinaryMessage; +import top.limitart.net.binary.BinaryRequestParam; +import top.limitart.util.FileUtil; +import top.limitart.util.StringUtil; -@Mapper -public class ConsumerBinaryClient { +public class ConsumerBinaryClient extends ApplicationBootstrap { + private static final Logger LOGGER = LoggerFactory.getLogger(ConsumerBinaryClient.class); + private static final String TOKEN_FILE = "pipeline-token.tmp"; private BinaryEndPoint client; + private ConsumerBinaryHandler clientHandler; + private AddressPair remoteAddress; + private String token; + private String zone; + private List tags; - public ConsumerBinaryClient() { - Router router = Router.empty().registerMapperClass(BinaryMessage.class,binaryre) - this.client = BinaryEndPoint.client().router().timeoutSeconds().build(); + public ConsumerBinaryClient(String remoteIp, int port, String zone, List tags) + throws Exception { + this.remoteAddress = AddressPair.withIP(remoteIp, port); + this.zone = zone; + if (tags != null) { + this.tags = ImmutableList.of(tags); + } else { + this.tags = Collections.emptyList(); + } + this.clientHandler = new ConsumerBinaryHandler(); + Router router = + Router.empty(BinaryMessage.class, BinaryRequest.class) + .registerMapperClass(ConsumerBinaryHandler.class, (c) -> this.clientHandler); + this.client = + BinaryEndPoint.client() + .router(router) + .onMessageIn((m, s, r) -> onMessageIn(m, s, r)) + // .timeoutSeconds(5) + .autoReconnect(10) + .onConnected((s, b) -> onConnected(s, b)) + .build(); + File file = new File("." + File.separator + TOKEN_FILE); + if (file.exists()) { + byte[] content = FileUtil.readFile(file); + this.token = new String(content, StandardCharsets.UTF_8); + LOGGER.info("read token on disk {}", this.token); + } else { + LOGGER.info("can not find token on disk , ignore it!"); + } + } + + private void onMessageIn( + BinaryMessage msg, + NettySession session, + Router router) { + BinaryRequest binaryRequestParam = (BinaryRequest) router.contextInstance(); + // TODO 可能有一些参数加入上下文 + binaryRequestParam.session(session); + router.request(msg, binaryRequestParam, Router.MethodInvoker::invoke); + } + + private void onConnected(NettySession session, Boolean connectedOrNot) { + if (connectedOrNot) { + this.clientHandler.signOnPipeline(session); + } + } + + @Override + protected void onStart(String[] args) throws Exception { + this.client.start(this.remoteAddress); + } + + @Override + protected void onDestroy(String[] args) {} + + @Mapper + private class ConsumerBinaryHandler { + /** + * 向Pipeline注册一个通道 + * + * @param session + */ + private void signOnPipeline(NettySession session) { + ReqRegisterZoneMsg msg = new ReqRegisterZoneMsg(); + msg.zone = ConsumerBinaryClient.this.zone; + msg.tags = ConsumerBinaryClient.this.tags; + session.writeNow( + msg, + (b, t) -> { + if (!b) { + LOGGER.error("sign on pipeline error", t); + } else { + LOGGER.info("sign on pipeline {} ...", remoteAddress); + } + }); + } + + /** + * pipeline回复注册结果 + * + * @param msg + * @param request + */ + public void onRegisterZoneResponse(@Request ResRegisterZoneMsg msg, BinaryRequest request) { + if (msg.code != 0) { + LOGGER.error("sign on pipeline {} fail!", remoteAddress); + return; + } + if (StringUtil.empty(msg.token)) { + LOGGER.error("pipeline {} response a empty token???", request.session()); + return; + } + ConsumerBinaryClient.this.token = msg.token; + try { + FileUtil.writeNewFile( + "." + File.separator, + TOKEN_FILE, + ConsumerBinaryClient.this.token.getBytes(StandardCharsets.UTF_8)); + LOGGER.info("write token {} on {}", msg.token, TOKEN_FILE); + } catch (IOException e) { + LOGGER.error("write token on disk error", e); + return; + } + LOGGER.info("sign on pipeline {} success!", remoteAddress); + ready(request.session()); + } + + private void ready(Session session) { + ReqCustomerReadyMsg msg = new ReqCustomerReadyMsg(); + msg.zone = ConsumerBinaryClient.this.zone; + msg.token = ConsumerBinaryClient.this.token; + session.writeNow( + msg, + (b, t) -> { + if (b) { + LOGGER.info("send ready to pipeline {}", session); + } else { + LOGGER.error("send ready to pipeline {} error", session); + } + }); + } + + /** + * pipeline通知消费者认领 + * + * @param msg + * @param request + */ + public void onNeedClaim(@Request ReqZoneClaimMsg msg, BinaryRequest request) { + if (StringUtil.empty(ConsumerBinaryClient.this.token)) { + LOGGER.error("no old token to claim pipeline {}", remoteAddress); + return; + } + ready(request.session()); + } + + /** + * 与pipeline建立通道 + * + * @param msg + */ + public void onPipelineEstablished( + @Request ResPipelineEstablishedMsg msg, BinaryRequest request) { + LOGGER.info("pipeline {} established!", remoteAddress); + } + + public void onHeartBeat(@Request ReqHeartBeatMsg msg, BinaryRequest request) { + request.session().writeNow(ResHeartBeatMsg.INSTANCE); + } } } diff --git a/fastmq/pipeline/pom.xml b/fastmq/pipeline/pom.xml index a47aa43..e6740cd 100644 --- a/fastmq/pipeline/pom.xml +++ b/fastmq/pipeline/pom.xml @@ -5,7 +5,7 @@ limitart-fastmq top.limitart - 3.1.0 + 3.2.0-SNAPSHOT 4.0.0 diff --git a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/PipelineBinaryServer.java b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/PipelineBinaryServer.java index beadfbf..bee721b 100644 --- a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/PipelineBinaryServer.java +++ b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/PipelineBinaryServer.java @@ -1,14 +1,19 @@ package top.limitart.fastmq.pipeline; - +import io.netty.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import top.limitart.base.ApplicationBootstrap; +import top.limitart.fastmq.common.SessionParamConst; +import top.limitart.fastmq.common.binary.BinaryRequest; import top.limitart.fastmq.common.binary.ReqCustomerReadyMsg; +import top.limitart.fastmq.common.binary.ReqHeartBeatMsg; import top.limitart.fastmq.common.binary.ReqRegisterZoneMsg; +import top.limitart.fastmq.common.binary.ResHeartBeatMsg; +import top.limitart.fastmq.common.binary.ResPipelineEstablishedMsg; import top.limitart.fastmq.common.binary.ResRegisterZoneMsg; -import top.limitart.fastmq.common.binary.ResZoneClaimMsg; -import top.limitart.fastmq.pipeline.binary.BinaryRequest; +import top.limitart.fastmq.common.binary.ReqZoneClaimMsg; import top.limitart.fastmq.pipeline.core.Pipeline; import top.limitart.fastmq.pipeline.core.Pipeline.States; import top.limitart.mapping.Mapper; @@ -21,30 +26,36 @@ import top.limitart.net.binary.BinaryMessage; import top.limitart.net.binary.BinaryRequestParam; import top.limitart.util.StringUtil; -@Mapper public class PipelineBinaryServer extends ApplicationBootstrap { private static Logger LOGGER = LoggerFactory.getLogger(PipelineBinaryServer.class); private Pipeline pipeline; private BinaryEndPoint endPoint; + private PipelineBinaryHandler handler; private int port; public PipelineBinaryServer(Pipeline pipeline, int port) throws Exception { this.pipeline = pipeline; this.port = port; - endPoint = BinaryEndPoint.server().router(Router.empty(BinaryMessage.class, BinaryRequest.class) - .registerMapperClass(PipelineBinaryServer.class, c -> this)) - .onConnected((s, b) -> onConnected(s, b)).onMessageIn((m, s, r) -> onMessageIn(m, s, r)) - .name("binary-pipeline-server") - .onExceptionThrown( - (s, t) -> LOGGER.error("session " + s, t) - ).build(); + this.handler = new PipelineBinaryHandler(); + endPoint = + BinaryEndPoint.server() + .router( + Router.empty(BinaryMessage.class, BinaryRequest.class) + .registerMapperClass(PipelineBinaryHandler.class, c -> this.handler)) + .onConnected((s, b) -> onConnected(s, b)) + .onMessageIn((m, s, r) -> onMessageIn(m, s, r)) + .name("binary-pipeline-server") +// .onExceptionThrown((s, t) -> LOGGER.error("session " + s, t)) + .build(); } - private void onMessageIn(BinaryMessage msg, NettySession session, + private void onMessageIn( + BinaryMessage msg, + NettySession session, Router router) { BinaryRequest binaryRequestParam = (BinaryRequest) router.contextInstance(); - //TODO 可能有一些参数加入上下文 + // TODO 可能有一些参数加入上下文 binaryRequestParam.session(session); router.request(msg, binaryRequestParam, Router.MethodInvoker::invoke); } @@ -56,19 +67,32 @@ public class PipelineBinaryServer extends ApplicationBootstrap { pipeline.inactiveZone(zone); LOGGER.error("session {} disconnected, inactive zone {}", session, zone); } + ScheduledFuture scheduledFuture = session.params().getObj(SessionParamConst.HEART_BEAT); + if (scheduledFuture != null) { + scheduledFuture.cancel(true); + } + } else { + ScheduledFuture scheduledFuture = + session + .thread() + .scheduleAtFixedRate( + () -> session.writeNow(ReqHeartBeatMsg.INSTANCE), 5, 5, TimeUnit.SECONDS); + session.params().putObj(SessionParamConst.HEART_BEAT, scheduledFuture); } } @Override protected void onStart(String[] args) throws Exception { - endPoint.start(AddressPair.withPort(port), (s, b, t) -> { - if (b) { - LOGGER.info("pipeline binary start success!"); - } else { - LOGGER.error("bind error", t); - System.exit(1); - } - }); + endPoint.start( + AddressPair.withPort(port), + (s, b, t) -> { + if (b) { + LOGGER.info("pipeline binary start success!"); + } else { + LOGGER.error("bind error", t); + System.exit(1); + } + }); } @Override @@ -76,70 +100,86 @@ public class PipelineBinaryServer extends ApplicationBootstrap { endPoint.stop(); } - /** - * 生产者注册 - * - * @param msg - */ - public void providerRegister(@Request ReqRegisterZoneMsg msg, BinaryRequest context) { - ResRegisterZoneMsg res = new ResRegisterZoneMsg(); - if (StringUtil.empty(msg.zone)) { - res.code = 1; - context.session().writeNow(res); - LOGGER.error("session {} send a null zone", context.session()); - return; - } - if (!pipeline.registerBuffer(msg.zone, msg.tags)) { - //如果这个队列本来存在且并未处于激活状态就需要该客户端来认领 - States zoneState = pipeline.getZoneState(msg.zone); - if (zoneState != null && zoneState != States.ACTIVE) { - context.session().writeNow(ResZoneClaimMsg.INSTANCE); - LOGGER.info("session {} need claim", context.session()); - } else { + @Mapper + private class PipelineBinaryHandler { + /** + * 消费者注册 + * + * @param msg + */ + public void consumerRegister(@Request ReqRegisterZoneMsg msg, BinaryRequest context) { + ResRegisterZoneMsg res = new ResRegisterZoneMsg(); + if (StringUtil.empty(msg.zone)) { res.code = 1; context.session().writeNow(res); - LOGGER.info("zone {} does not belong to session {}", msg.zone, context.session()); + LOGGER.error("session {} send a null zone", context.session()); + return; + } + if (!pipeline.registerBuffer(msg.zone, msg.tags)) { + // 如果这个队列本来存在且并未处于激活状态就需要该客户端来认领 + States zoneState = pipeline.getZoneState(msg.zone); + if (zoneState != null && zoneState != States.ACTIVE) { + context.session().writeNow(ReqZoneClaimMsg.INSTANCE); + LOGGER.info("session {} need claim", context.session()); + } else { + res.code = 1; + context.session().writeNow(res); + LOGGER.info("zone {} does not belong to session {}", msg.zone, context.session()); + } + return; } - return; + res.code = 0; + res.token = pipeline.getZoneToken(msg.zone); + context.session().writeNow(res); + LOGGER.info( + "session {} , zone {} register success,then tell me ready!", context.session(), msg.zone); } - res.code = 0; - res.token = pipeline.getZoneToken(msg.zone); - context.session().writeNow(res); - LOGGER.info("session {} , zone {} register success,then tell me ready!", context.session(), - msg.zone); - } - public void providerReady(@Request ReqCustomerReadyMsg msg, BinaryRequest context) { - //先看参数 - if (StringUtil.empty(msg.zone)) { - LOGGER.error("session {} send a null zone for ready", context.session()); - context.session().close(); - return; - } - if (StringUtil.empty(msg.token)) { - LOGGER.error("session {} send a null token for ready", context.session()); - context.session().close(); - return; - } - States zoneState = pipeline.getZoneState(msg.zone); - if (zoneState == null) { - LOGGER.error("session {} does not register for zone {}", context.session(), msg.zone); - context.session().close(); - return; - } - if (zoneState == States.ACTIVE) { - LOGGER.error("can not active zone {} twice for session {}", msg.zone, context.session()); - context.session().close(); - return; + /** + * 消费者准备好 + * + * @param msg + * @param context + */ + public void consumerReady(@Request ReqCustomerReadyMsg msg, BinaryRequest context) { + // 先看参数 + if (StringUtil.empty(msg.zone)) { + LOGGER.error("session {} send a null zone for ready", context.session()); + context.session().close(); + return; + } + if (StringUtil.empty(msg.token)) { + LOGGER.error("session {} send a null token for ready", context.session()); + context.session().close(); + return; + } + States zoneState = pipeline.getZoneState(msg.zone); + if (zoneState == null) { + LOGGER.error("session {} does not register for zone {}", context.session(), msg.zone); + context.session().close(); + return; + } + if (zoneState == States.ACTIVE) { + LOGGER.error("can not active zone {} twice for session {}", msg.zone, context.session()); + context.session().close(); + return; + } + String zoneToken = pipeline.getZoneToken(msg.zone); + if (!zoneToken.equals(msg.token)) { + LOGGER.error( + "can not active zone {} with a wrong token for session {}", + msg.zone, + context.session()); + context.session().close(); + return; + } + pipeline.activeZone(msg.zone); + context.session().params().putString(SessionParamConst.ZONE, msg.zone); + context.session().writeNow(ResPipelineEstablishedMsg.INSTANCE); } - String zoneToken = pipeline.getZoneToken(msg.zone); - if (!zoneToken.equals(msg.token)) { - LOGGER.error("can not active zone {} with a wrong token for session {}", msg.zone, - context.session()); - context.session().close(); - return; + + public void onHeartBeatResponse(@Request ResHeartBeatMsg msg) { + // DO NOTHING } - pipeline.activeZone(msg.zone); - context.session().params().putString(SessionParamConst.ZONE, msg.zone); } } diff --git a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/core/Pipeline.java b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/core/Pipeline.java index 55274b2..abdb4d3 100644 --- a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/core/Pipeline.java +++ b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/core/Pipeline.java @@ -23,18 +23,16 @@ import top.limitart.concurrent.TaskQueue; import top.limitart.util.StringUtil; import top.limitart.util.TimeUtil; -/** - * 消息总线 - */ +/** 消息总线 */ public class Pipeline { private static Logger LOGGER = LoggerFactory.getLogger(Pipeline.class); private static final long HANG_TO_SHUTDOWN_INTERVAL = TimeUnit.SECONDS.toMillis(10); - //TAG + // TAG private Map> tagAndZones = new HashMap<>(); - //所有队列 + // 所有队列 private Map zoneAndQueue = new HashMap<>(); - //轮询线程 + // 轮询线程 private final TaskQueue queue = TaskQueue.create("buffer-robin"); private Lock lock = new ReentrantLock(); @@ -54,8 +52,11 @@ public class Pipeline { || value.stateData.state == States.REGISTER) { if (TimeUtil.now() - value.stateData.changeTime > HANG_TO_SHUTDOWN_INTERVAL) { value.changeState(States.SHUTDOWN); - LOGGER.warn("zone {}'s state turn to {} from {},please check!", value.zone, States.HANG, - States.SHUTDOWN); + LOGGER.warn( + "zone {}'s state turn to {} from {},please check!", + value.zone, + States.SHUTDOWN, + States.HANG); } } } @@ -82,7 +83,7 @@ public class Pipeline { LOGGER.error("can not remove buffer because zone null or empty"); return false; } - //TAG + // TAG for (Set value : tagAndZones.values()) { value.removeIf(v -> v.equals(zone)); } @@ -197,7 +198,8 @@ public class Pipeline { } /** - * 注册一个队列
生产者和消费者会根据唯一编号zone和个性化tag来发送和消费 + * 注册一个队列
+ * 生产者和消费者会根据唯一编号zone和个性化tag来发送和消费 * * @param zone 整个集群唯一编号 * @param tags 该单位的自定义标签 @@ -241,8 +243,7 @@ public class Pipeline { } else { this.tags = new ConcurrentHashSet<>(); } - buffer = new PipelineRingBuffer<>( - () -> new MessageSlot()); + buffer = new PipelineRingBuffer<>(() -> new MessageSlot()); } public Set getTags() { @@ -297,21 +298,13 @@ public class Pipeline { } public enum States { - /** - * 注册中(正在校验合法性,无法消费消息) - */ + /** 注册中(正在校验合法性,无法消费消息) */ REGISTER, - /** - * 激活模式(可以正常消费消息) - */ + /** 激活模式(可以正常消费消息) */ ACTIVE, - /** - * 挂起模式(异常,不能消费消息,需要重新激活,队列不会被清除) - */ + /** 挂起模式(异常,不能消费消息,需要重新激活,队列不会被清除) */ HANG, - /** - * 关闭(关闭模式的消息队列会被轮询清除) - */ + /** 关闭(关闭模式的消息队列会被轮询清除) */ SHUTDOWN, } } diff --git a/fastmq/pom.xml b/fastmq/pom.xml index 1ad3570..e1d3fe6 100644 --- a/fastmq/pom.xml +++ b/fastmq/pom.xml @@ -5,7 +5,7 @@ limitart top.limitart - 3.1.0 + 3.2.0-SNAPSHOT 4.0.0 diff --git a/fastmq/provider/pom.xml b/fastmq/provider/pom.xml index af1872a..dea3394 100644 --- a/fastmq/provider/pom.xml +++ b/fastmq/provider/pom.xml @@ -5,7 +5,7 @@ limitart-fastmq top.limitart - 3.1.0 + 3.2.0-SNAPSHOT 4.0.0 diff --git a/fastmq/provider/src/main/java/top/limitart/fastmq/provider/ProviderBinaryClient.java b/fastmq/provider/src/main/java/top/limitart/fastmq/provider/ProviderBinaryClient.java new file mode 100644 index 0000000..9372563 --- /dev/null +++ b/fastmq/provider/src/main/java/top/limitart/fastmq/provider/ProviderBinaryClient.java @@ -0,0 +1,46 @@ +package top.limitart.fastmq.provider; + +import top.limitart.base.ApplicationBootstrap; +import top.limitart.fastmq.common.binary.BinaryRequest; +import top.limitart.mapping.Mapper; +import top.limitart.mapping.Router; +import top.limitart.net.AddressPair; +import top.limitart.net.NettySession; +import top.limitart.net.binary.BinaryEndPoint; +import top.limitart.net.binary.BinaryMessage; + +@Mapper +public class ProviderBinaryClient extends ApplicationBootstrap { + private BinaryEndPoint client; + private AddressPair remoteAddress; + private String token; + + public ProviderBinaryClient(String remoteIp, int port) throws Exception { + this.remoteAddress = AddressPair.withIP(remoteIp, port); + Router router = + Router.empty(BinaryMessage.class, BinaryRequest.class) + .registerMapperClass(ProviderBinaryClient.class, (c) -> this); + this.client = + BinaryEndPoint.client() + .router(router) + .timeoutSeconds(5) + .autoReconnect(10) + .onConnected((s, b) -> onConnected(s, b)) + .build(); + } + + private void onConnected(NettySession session, Boolean connectedOrNot) { + + } + + @Override + protected void onStart(String[] args) throws Exception { + this.client.start(this.remoteAddress); + } + + @Override + protected void onDestroy(String[] args) { + + this.client.stop(); + } +} diff --git a/game/pom.xml b/game/pom.xml index f1a2ee2..7e495be 100644 --- a/game/pom.xml +++ b/game/pom.xml @@ -5,7 +5,7 @@ limitart top.limitart - 3.1.0 + 3.2.0-SNAPSHOT 4.0.0 diff --git a/hotdep/pom.xml b/hotdep/pom.xml index 9f253af..0944d49 100644 --- a/hotdep/pom.xml +++ b/hotdep/pom.xml @@ -5,7 +5,7 @@ limitart top.limitart - 3.1.0 + 3.2.0-SNAPSHOT 4.0.0 diff --git a/net/pom.xml b/net/pom.xml index e6482d5..c5080c6 100644 --- a/net/pom.xml +++ b/net/pom.xml @@ -5,7 +5,7 @@ limitart top.limitart - 3.1.0 + 3.2.0-SNAPSHOT 4.0.0 diff --git a/net/src/main/java/top/limitart/mapping/RouterImpl.java b/net/src/main/java/top/limitart/mapping/RouterImpl.java index b0b4014..8b468c7 100644 --- a/net/src/main/java/top/limitart/mapping/RouterImpl.java +++ b/net/src/main/java/top/limitart/mapping/RouterImpl.java @@ -40,275 +40,305 @@ import java.util.function.Consumer; * @author hank * @version 2018/10/8 0008 20:48 */ -public class RouterImpl implements Router { - private static final Logger LOGGER = LoggerFactory.getLogger(RouterImpl.class); - // !!这里的asm应用经测试在JAVA8下最优 - private final Map, Context> msgs = new ConcurrentHashMap<>(); - private final Map, Object> managerInstances = new ConcurrentHashMap<>(); - private Class mClass; - private Class cClass; - private final ConstructorAccess contextMethod; +public class RouterImpl + implements Router { + private static final Logger LOGGER = LoggerFactory.getLogger(RouterImpl.class); + // !!这里的asm应用经测试在JAVA8下最优 + private final Map, Context> msgs = new ConcurrentHashMap<>(); + private final Map, Object> managerInstances = new ConcurrentHashMap<>(); + private Class mClass; + private Class cClass; + private final ConstructorAccess contextMethod; - /** - * 创造一个空的消息工厂 - * - * @return - */ - public static Router empty(Class mClass, Class cClass) { - return new RouterImpl(mClass, cClass); - } + /** + * 创造一个空的消息工厂 + * + * @return + */ + public static Router empty( + Class mClass, Class cClass) { + return new RouterImpl(mClass, cClass); + } - /** - * 通过扫描包创建消息工厂 - * - * @param scanPackage - * @param confirmInstance 指定manager的 实例 - * @return - * @throws IOException - * @throws ReflectiveOperationException - */ - public static Router create( - Class mClass, - Class cClass, - String scanPackage, - Function1, Object> confirmInstance) - throws Exception { - Conditions.notNull(scanPackage, "scanPackage"); - RouterImpl factory = new RouterImpl(mClass, cClass); - List> classesByPackage = - ReflectionUtil.getClassesBySuperClass(scanPackage, Object.class); - for (Class clazz : classesByPackage) { - factory.registerMapperClass(clazz, confirmInstance); - } - return factory; + /** + * 通过扫描包创建消息工厂 + * + * @param scanPackage + * @param confirmInstance 指定manager的 实例 + * @return + * @throws IOException + * @throws ReflectiveOperationException + */ + public static Router create( + Class mClass, + Class cClass, + String scanPackage, + Function1, Object> confirmInstance) + throws Exception { + Conditions.notNull(scanPackage, "scanPackage"); + RouterImpl factory = new RouterImpl(mClass, cClass); + List> classesByPackage = + ReflectionUtil.getClassesBySuperClass(scanPackage, Object.class); + for (Class clazz : classesByPackage) { + factory.registerMapperClass(clazz, confirmInstance); } + return factory; + } - /** - * 通过包扫描创建消息工厂 - * - * @param scanPackage 包名 - * @return - * @throws ReflectiveOperationException - * @throws IOException - */ - public static Router create( - Class mClass, Class cClass, String scanPackage) - throws IOException, ReflectiveOperationException, RequestDuplicatedException { - Conditions.notNull(scanPackage, "scanPackage"); - RouterImpl factory = new RouterImpl(mClass, cClass); - List> classesByPackage = - ReflectionUtil.getClassesBySuperClass(scanPackage, Object.class); - for (Class clazz : classesByPackage) { - factory.registerMapperClass(clazz, null); + /** + * 通过包扫描创建消息工厂 + * + * @param scanPackage 包名 + * @return + * @throws ReflectiveOperationException + * @throws IOException + */ + public static Router create( + Class mClass, Class cClass, String scanPackage) + throws IOException, ReflectiveOperationException, RequestDuplicatedException { + Conditions.notNull(scanPackage, "scanPackage"); + RouterImpl factory = new RouterImpl(mClass, cClass); + List> classesByPackage = + ReflectionUtil.getClassesBySuperClass(scanPackage, Object.class); + for (Class clazz : classesByPackage) { + if (clazz.getAnnotation(Mapper.class) == null) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("{} has no @Mapper annotation", clazz.getName()); } - return factory; + continue; + } + factory.registerMapperClass(clazz, null); } + return factory; + } - public RouterImpl(Class mClass, Class cClass) { - this.mClass = mClass; - this.cClass = cClass; - this.contextMethod = ConstructorAccess.get(this.cClass); - } + public RouterImpl(Class mClass, Class cClass) { + this.mClass = mClass; + this.cClass = cClass; + this.contextMethod = ConstructorAccess.get(this.cClass); + } - /** - * 注册一个manager - * - * @param mapperClass - * @throws InstantiationException - * @throws IllegalAccessException - */ - @Override - public Router registerMapperClass(Class mapperClass) - throws IllegalAccessException, InstantiationException, RequestDuplicatedException { - return registerMapperClass(mapperClass, null); - } + /** + * 注册一个manager + * + * @param mapperClass + * @throws InstantiationException + * @throws IllegalAccessException + */ + @Override + public Router registerMapperClass(Class mapperClass) + throws IllegalAccessException, InstantiationException, RequestDuplicatedException { + return registerMapperClass(mapperClass, null); + } - /** - * 注册一个manager - * - * @param mapperClass 类 - * @param confirmInstance 指定manager的 实例 - */ - public Router registerMapperClass( - Class mapperClass, Function1, Object> confirmInstance) - throws IllegalAccessException, InstantiationException, RequestDuplicatedException { - Mapper manager = mapperClass.getAnnotation(Mapper.class); - if (manager == null) { - return this; - } - // 扫描方法 - MethodAccess methodAccess = MethodAccess.get(mapperClass); - for (int i = 0; i < methodAccess.getMethods().size(); ++i) { - Method method = methodAccess.getMethods().get(i); - //扫描该方法的参数 - Class[] parameterTypes = method.getParameterTypes(); - Annotation[][] parameterAnnotations = method.getParameterAnnotations(); - //找到标记为@Request的参数和RequestContext的位置,Request必须,因为要判定是什么消息,Conext非必须 - List> paramList = new ArrayList<>(2); - Class msgType = null; - Class contextType = null; - for (int j = 0; j < parameterTypes.length; j++) { - Class parameterType = parameterTypes[j]; + /** + * 注册一个manager + * + * @param mapperClass 类 + * @param confirmInstance 指定manager的 实例 + */ + public Router registerMapperClass( + Class mapperClass, Function1, Object> confirmInstance) + throws IllegalAccessException, InstantiationException, RequestDuplicatedException { + Mapper manager = mapperClass.getAnnotation(Mapper.class); + if (manager == null) { + throw new InstantiationException(mapperClass.getName() + " has no @Mapper annotation"); + } + // 扫描方法 + MethodAccess methodAccess = MethodAccess.get(mapperClass); + for (int i = 0; i < methodAccess.getMethods().size(); ++i) { + Method method = methodAccess.getMethods().get(i); + // 扫描该方法的参数 + Class[] parameterTypes = method.getParameterTypes(); + Annotation[][] parameterAnnotations = method.getParameterAnnotations(); + // 找到标记为@Request的参数和RequestContext的位置,Request必须,因为要判定是什么消息,Conext非必须 + List> paramList = new ArrayList<>(2); + Class msgType = null; + Class contextType = null; + for (int j = 0; j < parameterTypes.length; j++) { + Class parameterType = parameterTypes[j]; - for (Annotation annotation : parameterAnnotations[j]) { - if (annotation.annotationType() == Request.class) { - if (msgType != null) { - throw new RequestDuplicatedException("one method more than one Request(@Request)???"); - } - msgType = parameterType; - paramList.add(msgType); - break; - } - } - if (ReflectionUtil.isInheritFrom(parameterType, RequestContext.class)) { - contextType = parameterType; - paramList.add(contextType); - } - } - if (msgType == null) { - continue; + for (Annotation annotation : parameterAnnotations[j]) { + if (annotation.annotationType() == Request.class) { + if (msgType != null) { + throw new RequestDuplicatedException("one method more than one Request(@Request)???"); } - //没有找到必要的消息类型就返回 - if (!Modifier.isPublic(method.getModifiers())) { - throw new IllegalAccessError( - "method must be PUBLIC:" - + mapperClass.getName() - + "." - + ReflectionUtil.getMethodOverloadName(method)); - } - if (!mClass.isAssignableFrom(msgType)) { - LOGGER.info("{} IS NOT a {},IGNORE.", msgType.getName(), mClass.getName()); - continue; - } - if (contextType != null && !cClass.isAssignableFrom(contextType)) { - throw new IllegalAccessException( - mapperClass.getName() - + "." - + ReflectionUtil.getMethodOverloadName(method) - + " param can only be ASSIGNABLE from " - + cClass.getName()); - } - ConstructorAccess constructorAccess = - (ConstructorAccess) ConstructorAccess.get(msgType); - if (msgs.containsKey(msgType)) { - throw new RequestDuplicatedException(msgType.getName()); - } - Context messageContext = new Context(); - messageContext.conAccess = constructorAccess; - messageContext.managerClazz = mapperClass; - messageContext.methodName = method.getName(); - messageContext.paramTypes = paramList.toArray(new Class[0]); - messageContext.methodAccess = methodAccess; - msgs.put((Class) msgType, messageContext); - if (!managerInstances.containsKey(mapperClass)) { - managerInstances.put(mapperClass, confirmInstance != null ? confirmInstance.apply(mapperClass) : mapperClass.newInstance()); - } - LOGGER.info("register request " + msgType.getName() + " at " + mapperClass.getName()); + msgType = parameterType; + paramList.add(msgType); + break; + } } - return this; - } - - /** - * 替换掉manager的实例 - * - * @param request - * @param newInstance - */ - public void replaceInstance(Class mapperClass, MESSAGE request, Object newInstance) { - Conditions.notNull(mapperClass, "mapperClass"); - Conditions.notNull(request, "request"); - Conditions.notNull(newInstance, "newInstance"); - if (managerInstances.containsKey(mapperClass)) { - managerInstances.put(mapperClass, newInstance); + if (ReflectionUtil.isInheritFrom(parameterType, RequestContext.class)) { + contextType = parameterType; + paramList.add(contextType); } + } + if (msgType == null) { + continue; + } + // 没有找到必要的消息类型就返回 + if (!Modifier.isPublic(method.getModifiers())) { + throw new IllegalAccessError( + "method must be PUBLIC:" + + mapperClass.getName() + + "." + + ReflectionUtil.getMethodOverloadName(method)); + } + if (!mClass.isAssignableFrom(msgType)) { + LOGGER.info("{} IS NOT a {},IGNORE.", msgType.getName(), mClass.getName()); + continue; + } + if (contextType != null && !cClass.isAssignableFrom(contextType)) { + throw new IllegalAccessException( + mapperClass.getName() + + "." + + ReflectionUtil.getMethodOverloadName(method) + + " param can only be ASSIGNABLE from " + + cClass.getName()); + } + ConstructorAccess constructorAccess = + (ConstructorAccess) ConstructorAccess.get(msgType); + if (msgs.containsKey(msgType)) { + throw new RequestDuplicatedException(msgType.getName()); + } + Context messageContext = new Context(); + messageContext.conAccess = constructorAccess; + messageContext.managerClazz = mapperClass; + messageContext.methodName = method.getName(); + messageContext.paramTypes = paramList.toArray(new Class[0]); + messageContext.methodAccess = methodAccess; + msgs.put((Class) msgType, messageContext); + if (!managerInstances.containsKey(mapperClass)) { + managerInstances.put( + mapperClass, + confirmInstance != null + ? confirmInstance.apply(mapperClass) + : mapperClass.newInstance()); + } + LOGGER.info("register request " + msgType.getName() + " at " + mapperClass.getName()); } + return this; + } - @Override - public void foreachRequestClass(Consumer> consumer) { - msgs.keySet().forEach(consumer); + /** + * 替换掉manager的实例 + * + * @param request + * @param newInstance + */ + public void replaceInstance(Class mapperClass, MESSAGE request, Object newInstance) { + Conditions.notNull(mapperClass, "mapperClass"); + Conditions.notNull(request, "request"); + Conditions.notNull(newInstance, "newInstance"); + if (managerInstances.containsKey(mapperClass)) { + managerInstances.put(mapperClass, newInstance); } + } - /** - * 根据ID获取一个消息实例 - * - * @param requestClass - * @return - */ - @Override - public MESSAGE requestInstance(Class requestClass) { - if (!msgs.containsKey(requestClass)) { - return null; - } - Context messageContext = msgs.get(requestClass); - return messageContext.conAccess.newInstance(); - } + @Override + public void foreachRequestClass(Consumer> consumer) { + msgs.keySet().forEach(consumer); + } - /** - * 根据ID获取一个消息实例 - * - * @return - */ - @Override - public CONTEXT contextInstance() { - return (CONTEXT) contextMethod.newInstance(); + /** + * 根据ID获取一个消息实例 + * + * @param requestClass + * @return + */ + @Override + public MESSAGE requestInstance(Class requestClass) { + if (!msgs.containsKey(requestClass)) { + return null; } + Context messageContext = msgs.get(requestClass); + return messageContext.conAccess.newInstance(); + } - @Override - public void request(MESSAGE msg, CONTEXT context, Process1 proc) { - Conditions.notNull(msg, "request"); - Context messageContext = msgs.get(msg.getClass()); - if (messageContext == null) { - LOGGER.error("request empty,id:" + msg.getClass().getName()); - // 消息上下文不存在 - return; - } - Object object = managerInstances.get(messageContext.managerClazz); - proc.accept(new Invoker(messageContext.methodAccess, object, messageContext.methodName, messageContext.paramTypes, msg, context)); - } + /** + * 根据ID获取一个消息实例 + * + * @return + */ + @Override + public CONTEXT contextInstance() { + return (CONTEXT) contextMethod.newInstance(); + } - private class Context { - private ConstructorAccess conAccess; - private MethodAccess methodAccess; - private String methodName; - private Class[] paramTypes; - private Class managerClazz; + @Override + public void request(MESSAGE msg, CONTEXT context, Process1 proc) { + Conditions.notNull(msg, "request"); + Context messageContext = msgs.get(msg.getClass()); + if (messageContext == null) { + LOGGER.error("request empty,id:" + msg.getClass().getName()); + // 消息上下文不存在 + return; } + Object object = managerInstances.get(messageContext.managerClazz); + proc.accept( + new Invoker( + messageContext.methodAccess, + object, + messageContext.methodName, + messageContext.paramTypes, + msg, + context)); + } - public class Invoker implements MethodInvoker { - private MethodAccess methodAccess; - private Object object; - private Class[] paramTypes; - private MESSAGE msg; - private String methodName; - private CONTEXT param; + private class Context { + private ConstructorAccess conAccess; + private MethodAccess methodAccess; + private String methodName; + private Class[] paramTypes; + private Class managerClazz; + } - public Invoker(MethodAccess methodAccess, Object object, String methodName,Class[] paramTypes, MESSAGE msg) { - this(methodAccess, object, methodName, paramTypes, msg, null); - } + public class Invoker implements MethodInvoker { + private MethodAccess methodAccess; + private Object object; + private Class[] paramTypes; + private MESSAGE msg; + private String methodName; + private CONTEXT param; - public Invoker(MethodAccess methodAccess, Object object, String methodName, Class[] paramTypes,MESSAGE msg, CONTEXT param) { - this.methodAccess = methodAccess; - this.object = object; - this.methodName = methodName; - this.msg = msg; - this.param = param; - this.paramTypes = paramTypes; - } + public Invoker( + MethodAccess methodAccess, + Object object, + String methodName, + Class[] paramTypes, + MESSAGE msg) { + this(methodAccess, object, methodName, paramTypes, msg, null); + } - @Override - public Object invoke() { - //这里就是通过paramtype的位置确定参数位置,后面如果参数继续灵活增多,这里方法需要修改 - Object[] paramInstance = new Object[paramTypes.length]; - for (int i = 0; i < paramTypes.length; i++) { - if(paramTypes[i]!=null){ - if(paramTypes[i] == msg.getClass()){ - paramInstance[i] = msg; - }else if(param!=null && paramTypes[i] == param.getClass()){ - paramInstance[i] = param; - } - } - } - return methodAccess.invoke(object, methodName, paramTypes, paramInstance); + public Invoker( + MethodAccess methodAccess, + Object object, + String methodName, + Class[] paramTypes, + MESSAGE msg, + CONTEXT param) { + this.methodAccess = methodAccess; + this.object = object; + this.methodName = methodName; + this.msg = msg; + this.param = param; + this.paramTypes = paramTypes; + } + + @Override + public Object invoke() { + // 这里就是通过paramtype的位置确定参数位置,后面如果参数继续灵活增多,这里方法需要修改 + Object[] paramInstance = new Object[paramTypes.length]; + for (int i = 0; i < paramTypes.length; i++) { + if (paramTypes[i] != null) { + if (paramTypes[i] == msg.getClass()) { + paramInstance[i] = msg; + } else if (param != null && paramTypes[i] == param.getClass()) { + paramInstance[i] = param; + } } + } + return methodAccess.invoke(object, methodName, paramTypes, paramInstance); } + } } diff --git a/pom.xml b/pom.xml index 18ac044..a4a4454 100644 --- a/pom.xml +++ b/pom.xml @@ -54,6 +54,7 @@ http://www.limitart.top https://git.oschina.net/HankXV/Limitart.git + limitart-releases @@ -68,6 +69,14 @@ + + org.codehaus.mojo + versions-maven-plugin + 2.7 + + false + + org.apache.maven.plugins maven-dependency-plugin @@ -171,13 +180,39 @@ + + + default-profile + + true + + ${java.home}/../lib/tools.jar + + + + ${java.home}/../lib/tools.jar + + + + + + + + + + + + + + + org.ow2.asm asm - 7.3.1 + 7.0 org.javassist @@ -190,7 +225,7 @@ tools 1.8 system - ${env.JAVA_HOME}/lib/tools.jar + ${tools-jar} diff --git a/project-logic/pom.xml b/project-logic/pom.xml index 48537df..c183d83 100644 --- a/project-logic/pom.xml +++ b/project-logic/pom.xml @@ -5,7 +5,7 @@ limitart top.limitart - 3.1.0 + 3.2.0-SNAPSHOT 4.0.0 diff --git a/project-starter/pom.xml b/project-starter/pom.xml index b2d046b..779df2d 100644 --- a/project-starter/pom.xml +++ b/project-starter/pom.xml @@ -5,7 +5,7 @@ limitart top.limitart - 3.1.0 + 3.2.0-SNAPSHOT 4.0.0 diff --git a/update-version.sh b/update-version.sh new file mode 100644 index 0000000..5bd9102 --- /dev/null +++ b/update-version.sh @@ -0,0 +1,2 @@ +#!/usr/bin/env bash +mvn -N versions:update-child-modules \ No newline at end of file -- Gitee From 5ab186996b445df0d09f87239cef50a4a2860bb6 Mon Sep 17 00:00:00 2001 From: HankXV <104381832@qq.com> Date: Thu, 30 Jan 2020 23:08:06 +0800 Subject: [PATCH 06/11] 1 --- .../limitart/collections/ConcurrentTable.java | 1 + .../top/limitart/collections/HashedTable.java | 1 + .../java/top/limitart/collections/Table.java | 1 + .../db/{DBHandler.java => DBHelper.java} | 15 +++-- .../{FakeDBHandler.java => FakeDBHelper.java} | 7 +- .../{ResultHandler.java => QueryResult.java} | 2 +- ...mpleDBHandler.java => SimpleDBHelper.java} | 10 +-- .../java/top/limitart/db/sql/Prepare.java | 17 +---- .../limitart/fastmq/PipelineConsumerDemo.java | 11 ++- .../limitart/fastmq/common/binary/Consts.java | 8 ++- .../binary/ReqBroadcastMsgToPipelineMsg.java | 11 +++ .../ReqBroadcastMsgToPipelineWithTagsMsg.java | 11 +++ .../fastmq/common/binary/ReqPullMsg.java | 12 ++++ .../binary/ReqPushMsgToPipelineMsg.java | 11 +++ .../ReqPushMsgToPipelineWithTagsMsg.java | 11 +++ .../binary/ResPipelineEstablishedMsg.java | 2 +- .../fastmq/common/binary/ResPullMsg.java | 14 ++++ .../fastmq/consumer/ConsumerBinaryClient.java | 58 +++++++++++++++- .../fastmq/consumer/ConsumerMsgHandler.java | 5 ++ .../fastmq/pipeline/PipelineBinaryServer.java | 67 ++++++++++++++++++- .../binary/PipelineBinarySession.java | 32 +++++++++ .../fastmq/pipeline/core/Pipeline.java | 21 ++++-- .../java/top/limitart/net/NettyEndPoint.java | 4 +- 23 files changed, 283 insertions(+), 49 deletions(-) rename db/src/main/java/top/limitart/db/{DBHandler.java => DBHelper.java} (84%) rename db/src/main/java/top/limitart/db/{FakeDBHandler.java => FakeDBHelper.java} (86%) rename db/src/main/java/top/limitart/db/{ResultHandler.java => QueryResult.java} (95%) rename db/src/main/java/top/limitart/db/{SimpleDBHandler.java => SimpleDBHelper.java} (93%) create mode 100644 fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqBroadcastMsgToPipelineMsg.java create mode 100644 fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqBroadcastMsgToPipelineWithTagsMsg.java create mode 100644 fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqPullMsg.java create mode 100644 fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqPushMsgToPipelineMsg.java create mode 100644 fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqPushMsgToPipelineWithTagsMsg.java create mode 100644 fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ResPullMsg.java create mode 100644 fastmq/consumer/src/main/java/top/limitart/fastmq/consumer/ConsumerMsgHandler.java create mode 100644 fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/binary/PipelineBinarySession.java diff --git a/core/src/main/java/top/limitart/collections/ConcurrentTable.java b/core/src/main/java/top/limitart/collections/ConcurrentTable.java index fc48314..9a4b4ea 100644 --- a/core/src/main/java/top/limitart/collections/ConcurrentTable.java +++ b/core/src/main/java/top/limitart/collections/ConcurrentTable.java @@ -26,6 +26,7 @@ import java.util.concurrent.ConcurrentHashMap; * @author hank */ @ThreadSafe +@Deprecated public class ConcurrentTable implements Table { private final Map> maps = new ConcurrentHashMap<>(); diff --git a/core/src/main/java/top/limitart/collections/HashedTable.java b/core/src/main/java/top/limitart/collections/HashedTable.java index f3dbfb0..898167a 100644 --- a/core/src/main/java/top/limitart/collections/HashedTable.java +++ b/core/src/main/java/top/limitart/collections/HashedTable.java @@ -25,6 +25,7 @@ import java.util.*; * @author hank */ @ThreadUnsafe +@Deprecated public class HashedTable implements Table { private final Map> maps = new HashMap<>(); diff --git a/core/src/main/java/top/limitart/collections/Table.java b/core/src/main/java/top/limitart/collections/Table.java index 1f54029..fe4df44 100644 --- a/core/src/main/java/top/limitart/collections/Table.java +++ b/core/src/main/java/top/limitart/collections/Table.java @@ -10,6 +10,7 @@ import java.util.Set; * @author hank * @version 2017/12/18 0018 19:34 */ +@Deprecated public interface Table { static Table empty() { return new HashedTable<>(); diff --git a/db/src/main/java/top/limitart/db/DBHandler.java b/db/src/main/java/top/limitart/db/DBHelper.java similarity index 84% rename from db/src/main/java/top/limitart/db/DBHandler.java rename to db/src/main/java/top/limitart/db/DBHelper.java index c221012..e17658b 100644 --- a/db/src/main/java/top/limitart/db/DBHandler.java +++ b/db/src/main/java/top/limitart/db/DBHelper.java @@ -29,15 +29,15 @@ import java.util.List; * @author hank * @version 2018/4/14 0014 16:47 */ -public interface DBHandler extends AutoCloseable { +public interface DBHelper extends AutoCloseable { /** * 创建一个实际的数据库 * * @param dataSource * @return */ - static DBHandler createReal(DBDataSource dataSource) { - return new SimpleDBHandler(dataSource); + static DBHelper createSimple(DBDataSource dataSource) { + return new SimpleDBHelper(dataSource); } /** @@ -45,8 +45,9 @@ public interface DBHandler extends AutoCloseable { * * @return */ - static DBHandler createFake() { - return new FakeDBHandler(); + @Deprecated + static DBHelper createFake() { + return new FakeDBHelper(); } /** @@ -74,7 +75,7 @@ public interface DBHandler extends AutoCloseable { * @return * @throws SQLException */ - List selectList(Select select, ResultHandler handler) throws SQLException; + List selectList(Select select, QueryResult handler) throws SQLException; /** * 查找单个实例 @@ -85,7 +86,7 @@ public interface DBHandler extends AutoCloseable { * @return * @throws SQLException */ - T selectOne(Select select, ResultHandler handler) throws SQLException; + T selectOne(Select select, QueryResult handler) throws SQLException; /** * 更新(插入、更新、删除) diff --git a/db/src/main/java/top/limitart/db/FakeDBHandler.java b/db/src/main/java/top/limitart/db/FakeDBHelper.java similarity index 86% rename from db/src/main/java/top/limitart/db/FakeDBHandler.java rename to db/src/main/java/top/limitart/db/FakeDBHelper.java index 00f61c3..31cf85d 100644 --- a/db/src/main/java/top/limitart/db/FakeDBHandler.java +++ b/db/src/main/java/top/limitart/db/FakeDBHelper.java @@ -29,19 +29,20 @@ import java.util.List; * @author hank * @version 2018/4/14 0014 16:47 */ -public class FakeDBHandler implements DBHandler { +@Deprecated +public class FakeDBHelper implements DBHelper { @Override public DataSource dataSource() { throw new UnsupportedOperationException(); } @Override - public List selectList(Select select, ResultHandler handler) throws SQLException { + public List selectList(Select select, QueryResult handler) throws SQLException { return Collections.EMPTY_LIST; } @Override - public T selectOne(Select select, ResultHandler handler) throws SQLException { + public T selectOne(Select select, QueryResult handler) throws SQLException { return null; } diff --git a/db/src/main/java/top/limitart/db/ResultHandler.java b/db/src/main/java/top/limitart/db/QueryResult.java similarity index 95% rename from db/src/main/java/top/limitart/db/ResultHandler.java rename to db/src/main/java/top/limitart/db/QueryResult.java index b7fc8c2..54a1f68 100644 --- a/db/src/main/java/top/limitart/db/ResultHandler.java +++ b/db/src/main/java/top/limitart/db/QueryResult.java @@ -18,6 +18,6 @@ package top.limitart.db; import java.sql.ResultSet; import java.sql.SQLException; -public interface ResultHandler { +public interface QueryResult { T parse(ResultSet resultSet) throws SQLException; } diff --git a/db/src/main/java/top/limitart/db/SimpleDBHandler.java b/db/src/main/java/top/limitart/db/SimpleDBHelper.java similarity index 93% rename from db/src/main/java/top/limitart/db/SimpleDBHandler.java rename to db/src/main/java/top/limitart/db/SimpleDBHelper.java index c5dfe5c..d045446 100644 --- a/db/src/main/java/top/limitart/db/SimpleDBHandler.java +++ b/db/src/main/java/top/limitart/db/SimpleDBHelper.java @@ -33,13 +33,13 @@ import java.util.List; * @author hank * @version 2018/4/14 0014 16:47 */ -public class SimpleDBHandler implements DBHandler { - private static Logger LOGGER = LoggerFactory.getLogger(SimpleDBHandler.class); +public class SimpleDBHelper implements DBHelper { + private static Logger LOGGER = LoggerFactory.getLogger(SimpleDBHelper.class); private static long SLOW_SQL = 100; private final DataSource dataSource; /** @param dataSource */ - public SimpleDBHandler(DBDataSource dataSource) { + public SimpleDBHelper(DBDataSource dataSource) { this.dataSource = dataSource; } @@ -49,7 +49,7 @@ public class SimpleDBHandler implements DBHandler { } @Override - public List selectList(Select select, ResultHandler handler) throws SQLException { + public List selectList(Select select, QueryResult handler) throws SQLException { try (Connection con = connection(); PreparedStatement preparedStatement = select.withParams(con); ResultSet resultSet = preparedStatement.executeQuery()) { @@ -62,7 +62,7 @@ public class SimpleDBHandler implements DBHandler { } @Override - public T selectOne(Select select, ResultHandler handler) throws SQLException { + public T selectOne(Select select, QueryResult handler) throws SQLException { try (Connection con = connection(); PreparedStatement preparedStatement = select.withParams(con); ResultSet resultSet = preparedStatement.executeQuery()) { diff --git a/db/src/main/java/top/limitart/db/sql/Prepare.java b/db/src/main/java/top/limitart/db/sql/Prepare.java index c0ff306..53fb277 100644 --- a/db/src/main/java/top/limitart/db/sql/Prepare.java +++ b/db/src/main/java/top/limitart/db/sql/Prepare.java @@ -21,23 +21,8 @@ package top.limitart.db.sql; * @author hank * @version 2018/4/14 0014 16:47 */ +@Deprecated public interface Prepare { - static void main(String[] args) { - SQL insert = Prepare.insert().into("account").values("id", 1, "name", "hank"); - System.out.println(insert.sql()); - SQL delete = Prepare.delete().from("account").where(Where.create().whereEquals("id", 1)); - System.out.println(delete.sql()); - Update update = - Prepare.update("account") - .set("id", 1, "age", 10) - .where(Where.create().whereEquals("name", "hank")); - System.out.println(update.sql()); - Select select = - Prepare.select("id", "age") - .from("account") - .where(Where.create().whereEquals("name", "hank")); - System.out.println(select.sql()); - } /** * 开始编写插入语句 diff --git a/demo/src/main/java/top/limitart/fastmq/PipelineConsumerDemo.java b/demo/src/main/java/top/limitart/fastmq/PipelineConsumerDemo.java index 8d0e05f..b4f2142 100644 --- a/demo/src/main/java/top/limitart/fastmq/PipelineConsumerDemo.java +++ b/demo/src/main/java/top/limitart/fastmq/PipelineConsumerDemo.java @@ -1,10 +1,9 @@ package top.limitart.fastmq; +import java.nio.charset.StandardCharsets; import java.util.LinkedList; import java.util.List; import top.limitart.fastmq.consumer.ConsumerBinaryClient; -import top.limitart.fastmq.pipeline.PipelineBinaryServer; -import top.limitart.fastmq.pipeline.core.Pipeline; public class PipelineConsumerDemo { @@ -15,7 +14,13 @@ public class PipelineConsumerDemo { List tags = new LinkedList<>(); tags.add("fuck"); tags.add("shit"); - consumerClient = new ConsumerBinaryClient("127.0.0.1",9000,"test_zone",tags); + consumerClient = + new ConsumerBinaryClient( + "127.0.0.1", + 9000, + "test_zone", + tags, + msg -> System.out.println(new String(msg, StandardCharsets.UTF_8))); } catch (Exception e) { e.printStackTrace(); } diff --git a/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/Consts.java b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/Consts.java index cf1c3ed..7d46251 100644 --- a/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/Consts.java +++ b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/Consts.java @@ -8,5 +8,11 @@ public class Consts { public static final short RES_ZONE_CLAIM_MSG = RES_CUSTOMER_READY_MSG + 1; public static final short REQ_HEART_BEAT = RES_ZONE_CLAIM_MSG + 1; public static final short RES_HEART_BEAT = REQ_HEART_BEAT + 1; - public static final short RES_PIPELINE_ESTANBLISHED = RES_HEART_BEAT + 1; + public static final short RES_PIPELINE_ESTABLISHED = RES_HEART_BEAT + 1; + public static final short REQ_PULL = RES_PIPELINE_ESTABLISHED + 1; + public static final short RES_PULL = REQ_PULL + 1; + public static final short REQ_PUSH_MSG_TO_PIPELINE = RES_PULL + 1; + public static final short REQ_BROADCAST_MSG_TO_PIPELINE = REQ_PUSH_MSG_TO_PIPELINE + 1; + public static final short REQ_PUSH_MSG_TO_PIPELINE_WITH_TAGS = REQ_BROADCAST_MSG_TO_PIPELINE + 1; + public static final short REQ_BROADCAST_MSG_TO_PIPELINE_WITH_TAGS = REQ_PUSH_MSG_TO_PIPELINE_WITH_TAGS + 1; } diff --git a/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqBroadcastMsgToPipelineMsg.java b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqBroadcastMsgToPipelineMsg.java new file mode 100644 index 0000000..7333f40 --- /dev/null +++ b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqBroadcastMsgToPipelineMsg.java @@ -0,0 +1,11 @@ +package top.limitart.fastmq.common.binary; + +import top.limitart.net.binary.BinaryMessage; + +public class ReqBroadcastMsgToPipelineMsg extends BinaryMessage { + + @Override + public short id() { + return Consts.REQ_BROADCAST_MSG_TO_PIPELINE; + } +} diff --git a/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqBroadcastMsgToPipelineWithTagsMsg.java b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqBroadcastMsgToPipelineWithTagsMsg.java new file mode 100644 index 0000000..3e60859 --- /dev/null +++ b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqBroadcastMsgToPipelineWithTagsMsg.java @@ -0,0 +1,11 @@ +package top.limitart.fastmq.common.binary; + +import top.limitart.net.binary.BinaryMessage; + +public class ReqBroadcastMsgToPipelineWithTagsMsg extends BinaryMessage { + + @Override + public short id() { + return Consts.REQ_BROADCAST_MSG_TO_PIPELINE_WITH_TAGS; + } +} diff --git a/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqPullMsg.java b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqPullMsg.java new file mode 100644 index 0000000..e2828a0 --- /dev/null +++ b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqPullMsg.java @@ -0,0 +1,12 @@ +package top.limitart.fastmq.common.binary; + +import top.limitart.net.binary.BinaryMessage; + +public class ReqPullMsg extends BinaryMessage { + public int pullNum; + + @Override + public short id() { + return Consts.REQ_PULL; + } +} diff --git a/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqPushMsgToPipelineMsg.java b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqPushMsgToPipelineMsg.java new file mode 100644 index 0000000..f89762c --- /dev/null +++ b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqPushMsgToPipelineMsg.java @@ -0,0 +1,11 @@ +package top.limitart.fastmq.common.binary; + +import top.limitart.net.binary.BinaryMessage; + +public class ReqPushMsgToPipelineMsg extends BinaryMessage { + + @Override + public short id() { + return Consts.REQ_PUSH_MSG_TO_PIPELINE; + } +} diff --git a/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqPushMsgToPipelineWithTagsMsg.java b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqPushMsgToPipelineWithTagsMsg.java new file mode 100644 index 0000000..14e0ae3 --- /dev/null +++ b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqPushMsgToPipelineWithTagsMsg.java @@ -0,0 +1,11 @@ +package top.limitart.fastmq.common.binary; + +import top.limitart.net.binary.BinaryMessage; + +public class ReqPushMsgToPipelineWithTagsMsg extends BinaryMessage { + + @Override + public short id() { + return Consts.REQ_PUSH_MSG_TO_PIPELINE_WITH_TAGS; + } +} diff --git a/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ResPipelineEstablishedMsg.java b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ResPipelineEstablishedMsg.java index 486ae37..0c5632f 100644 --- a/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ResPipelineEstablishedMsg.java +++ b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ResPipelineEstablishedMsg.java @@ -7,6 +7,6 @@ public class ResPipelineEstablishedMsg extends BinaryMessage { @Override public short id() { - return Consts.RES_REGISTER_ZONE_MSG; + return Consts.RES_PIPELINE_ESTABLISHED; } } diff --git a/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ResPullMsg.java b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ResPullMsg.java new file mode 100644 index 0000000..63e7f4b --- /dev/null +++ b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ResPullMsg.java @@ -0,0 +1,14 @@ +package top.limitart.fastmq.common.binary; + +import java.util.LinkedList; +import java.util.List; +import top.limitart.net.binary.BinaryMessage; + +public class ResPullMsg extends BinaryMessage { + public List msgs = new LinkedList<>(); + + @Override + public short id() { + return Consts.RES_PULL; + } +} diff --git a/fastmq/consumer/src/main/java/top/limitart/fastmq/consumer/ConsumerBinaryClient.java b/fastmq/consumer/src/main/java/top/limitart/fastmq/consumer/ConsumerBinaryClient.java index 4fae084..3d320b4 100644 --- a/fastmq/consumer/src/main/java/top/limitart/fastmq/consumer/ConsumerBinaryClient.java +++ b/fastmq/consumer/src/main/java/top/limitart/fastmq/consumer/ConsumerBinaryClient.java @@ -6,16 +6,21 @@ import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.List; +import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import top.limitart.base.ApplicationBootstrap; +import top.limitart.base.Conditions; import top.limitart.collections.ImmutableList; +import top.limitart.concurrent.TaskQueue; import top.limitart.fastmq.common.binary.BinaryRequest; import top.limitart.fastmq.common.binary.ReqCustomerReadyMsg; import top.limitart.fastmq.common.binary.ReqHeartBeatMsg; +import top.limitart.fastmq.common.binary.ReqPullMsg; import top.limitart.fastmq.common.binary.ReqRegisterZoneMsg; import top.limitart.fastmq.common.binary.ResHeartBeatMsg; import top.limitart.fastmq.common.binary.ResPipelineEstablishedMsg; +import top.limitart.fastmq.common.binary.ResPullMsg; import top.limitart.fastmq.common.binary.ResRegisterZoneMsg; import top.limitart.fastmq.common.binary.ReqZoneClaimMsg; import top.limitart.mapping.Mapper; @@ -29,18 +34,25 @@ import top.limitart.net.binary.BinaryMessage; import top.limitart.net.binary.BinaryRequestParam; import top.limitart.util.FileUtil; import top.limitart.util.StringUtil; +import top.limitart.util.TimeUtil; public class ConsumerBinaryClient extends ApplicationBootstrap { private static final Logger LOGGER = LoggerFactory.getLogger(ConsumerBinaryClient.class); private static final String TOKEN_FILE = "pipeline-token.tmp"; + private static final long PULL_REQUEST_INTERVAL = TimeUnit.SECONDS.toMillis(5); private BinaryEndPoint client; private ConsumerBinaryHandler clientHandler; private AddressPair remoteAddress; private String token; private String zone; private List tags; + private volatile long lastReceiveMsgTime; + private TaskQueue msgThread = TaskQueue.create("msg-consume"); + private ConsumerMsgHandler msgHandler; + private Session session; - public ConsumerBinaryClient(String remoteIp, int port, String zone, List tags) + public ConsumerBinaryClient( + String remoteIp, int port, String zone, List tags, ConsumerMsgHandler msgHandler) throws Exception { this.remoteAddress = AddressPair.withIP(remoteIp, port); this.zone = zone; @@ -49,6 +61,7 @@ public class ConsumerBinaryClient extends ApplicationBootstrap { } else { this.tags = Collections.emptyList(); } + this.msgHandler = Conditions.notNull(msgHandler); this.clientHandler = new ConsumerBinaryHandler(); Router router = Router.empty(BinaryMessage.class, BinaryRequest.class) @@ -69,6 +82,28 @@ public class ConsumerBinaryClient extends ApplicationBootstrap { } else { LOGGER.info("can not find token on disk , ignore it!"); } + msgThread.scheduleAtFixedRate(() -> secondTick(), 0, 1, TimeUnit.SECONDS); + } + + private void secondTick() { + if (TimeUtil.now() - lastReceiveMsgTime > PULL_REQUEST_INTERVAL) { + requestPullMsg(); + } + } + + private void requestPullMsg() { + if (session != null) { + ReqPullMsg msg = new ReqPullMsg(); + msg.pullNum = 20; // TODO + session.writeNow( + msg, + (b, t) -> { + if (b) { + this.lastReceiveMsgTime = TimeUtil.now(); + LOGGER.info("send msg pull request to pipeline {}", session); + } + }); + } } private void onMessageIn( @@ -84,6 +119,8 @@ public class ConsumerBinaryClient extends ApplicationBootstrap { private void onConnected(NettySession session, Boolean connectedOrNot) { if (connectedOrNot) { this.clientHandler.signOnPipeline(session); + } else { + this.session = null; } } @@ -93,7 +130,9 @@ public class ConsumerBinaryClient extends ApplicationBootstrap { } @Override - protected void onDestroy(String[] args) {} + protected void onDestroy(String[] args) { + msgThread.shutdown(); + } @Mapper private class ConsumerBinaryHandler { @@ -183,11 +222,26 @@ public class ConsumerBinaryClient extends ApplicationBootstrap { */ public void onPipelineEstablished( @Request ResPipelineEstablishedMsg msg, BinaryRequest request) { + ConsumerBinaryClient.this.session = request.session(); LOGGER.info("pipeline {} established!", remoteAddress); } public void onHeartBeat(@Request ReqHeartBeatMsg msg, BinaryRequest request) { request.session().writeNow(ResHeartBeatMsg.INSTANCE); } + + public void onMsgPull(@Request ResPullMsg msg) { + msgThread.execute( + () -> { + for (byte[] bytes : msg.msgs) { + try { + ConsumerBinaryClient.this.msgHandler.onMsg(bytes); + } catch (Exception e) { + LOGGER.error("msg handle error", e); + } + } + requestPullMsg(); + }); + } } } diff --git a/fastmq/consumer/src/main/java/top/limitart/fastmq/consumer/ConsumerMsgHandler.java b/fastmq/consumer/src/main/java/top/limitart/fastmq/consumer/ConsumerMsgHandler.java new file mode 100644 index 0000000..a66eae5 --- /dev/null +++ b/fastmq/consumer/src/main/java/top/limitart/fastmq/consumer/ConsumerMsgHandler.java @@ -0,0 +1,5 @@ +package top.limitart.fastmq.consumer; + +public interface ConsumerMsgHandler { + void onMsg(byte[] msg); +} diff --git a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/PipelineBinaryServer.java b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/PipelineBinaryServer.java index bee721b..013736c 100644 --- a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/PipelineBinaryServer.java +++ b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/PipelineBinaryServer.java @@ -1,6 +1,11 @@ package top.limitart.fastmq.pipeline; +import io.netty.channel.EventLoop; import io.netty.util.concurrent.ScheduledFuture; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -9,21 +14,27 @@ import top.limitart.fastmq.common.SessionParamConst; import top.limitart.fastmq.common.binary.BinaryRequest; import top.limitart.fastmq.common.binary.ReqCustomerReadyMsg; import top.limitart.fastmq.common.binary.ReqHeartBeatMsg; +import top.limitart.fastmq.common.binary.ReqPullMsg; import top.limitart.fastmq.common.binary.ReqRegisterZoneMsg; import top.limitart.fastmq.common.binary.ResHeartBeatMsg; import top.limitart.fastmq.common.binary.ResPipelineEstablishedMsg; +import top.limitart.fastmq.common.binary.ResPullMsg; import top.limitart.fastmq.common.binary.ResRegisterZoneMsg; import top.limitart.fastmq.common.binary.ReqZoneClaimMsg; +import top.limitart.fastmq.pipeline.binary.PipelineBinarySession; import top.limitart.fastmq.pipeline.core.Pipeline; import top.limitart.fastmq.pipeline.core.Pipeline.States; +import top.limitart.fastmq.pipeline.core.PipelineRingBuffer; import top.limitart.mapping.Mapper; import top.limitart.mapping.Request; import top.limitart.mapping.Router; import top.limitart.net.AddressPair; import top.limitart.net.NettySession; +import top.limitart.net.Session; import top.limitart.net.binary.BinaryEndPoint; import top.limitart.net.binary.BinaryMessage; import top.limitart.net.binary.BinaryRequestParam; +import top.limitart.util.GameMathUtil; import top.limitart.util.StringUtil; public class PipelineBinaryServer extends ApplicationBootstrap { @@ -33,6 +44,7 @@ public class PipelineBinaryServer extends ApplicationBootstrap { private BinaryEndPoint endPoint; private PipelineBinaryHandler handler; private int port; + private Map prs = new ConcurrentHashMap<>(); public PipelineBinaryServer(Pipeline pipeline, int port) throws Exception { this.pipeline = pipeline; @@ -46,7 +58,7 @@ public class PipelineBinaryServer extends ApplicationBootstrap { .onConnected((s, b) -> onConnected(s, b)) .onMessageIn((m, s, r) -> onMessageIn(m, s, r)) .name("binary-pipeline-server") -// .onExceptionThrown((s, t) -> LOGGER.error("session " + s, t)) + // .onExceptionThrown((s, t) -> LOGGER.error("session " + s, t)) .build(); } @@ -70,6 +82,7 @@ public class PipelineBinaryServer extends ApplicationBootstrap { ScheduledFuture scheduledFuture = session.params().getObj(SessionParamConst.HEART_BEAT); if (scheduledFuture != null) { scheduledFuture.cancel(true); + LOGGER.info("{} cancel heartbeat echo", session); } } else { ScheduledFuture scheduledFuture = @@ -78,6 +91,7 @@ public class PipelineBinaryServer extends ApplicationBootstrap { .scheduleAtFixedRate( () -> session.writeNow(ReqHeartBeatMsg.INSTANCE), 5, 5, TimeUnit.SECONDS); session.params().putObj(SessionParamConst.HEART_BEAT, scheduledFuture); + LOGGER.info("{} start heartbeat echo"); } } @@ -98,6 +112,11 @@ public class PipelineBinaryServer extends ApplicationBootstrap { @Override protected void onDestroy(String[] args) { endPoint.stop(); + try { + pipeline.close(); + } catch (IOException e) { + LOGGER.error("close pipeline error", e); + } } @Mapper @@ -178,8 +197,54 @@ public class PipelineBinaryServer extends ApplicationBootstrap { context.session().writeNow(ResPipelineEstablishedMsg.INSTANCE); } + private String pullerZone(Session session) { + return session.params().getString(SessionParamConst.ZONE); + } + public void onHeartBeatResponse(@Request ResHeartBeatMsg msg) { // DO NOTHING } + + public void onPullRequest(@Request ReqPullMsg msg, BinaryRequest request) { + Session session = request.session(); + String zone = pullerZone(session); + if (StringUtil.empty(zone)) { + LOGGER.error("session {} is not validated", session); + return; + } + PipelineRingBuffer buffer = PipelineBinaryServer.this.pipeline.getBufferByZone(zone); + if (buffer == null) { + LOGGER.error("session {} , zone {} has no buffer", session, zone); + return; + } + int pullNum = GameMathUtil.fixedBetween(msg.pullNum, 1, 100); + List bytes = buffer.peekAtMost(pullNum); + if (bytes.isEmpty()) { + if (prs.containsKey(zone)) { + LOGGER.warn("session {} , zone {} has no msg , hangout but already", session, zone); + return; + } + prs.put(zone, new PipelineBinarySession(session, pullNum)); + LOGGER.info("session {} , zone {} has no msg , hangout success", session, zone); + return; + } + prs.remove(zone); // TODO 不删除 复用 + pushMsgsToCustomer(zone, session, bytes); + } + + private void pushMsgsToCustomer( + String zone, Session session, List bytes) { + ResPullMsg msg = new ResPullMsg(); + msg.msgs = bytes; + session.writeNow( + msg, + (b, t) -> { + if (b) { + LOGGER.info("send msgs to session {} , zone {}, num {}", session, zone, bytes.size()); + } else { + LOGGER.error("send msgs to session " + session + " , zone " + zone + " fail", t); + } + }); + } } } diff --git a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/binary/PipelineBinarySession.java b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/binary/PipelineBinarySession.java new file mode 100644 index 0000000..7a14c0b --- /dev/null +++ b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/binary/PipelineBinarySession.java @@ -0,0 +1,32 @@ +package top.limitart.fastmq.pipeline.binary; + +import io.netty.channel.EventLoop; +import top.limitart.base.Conditions; +import top.limitart.net.Session; +import top.limitart.net.binary.BinaryMessage; + +public class PipelineBinarySession { + private Session session; + private int alreadyRequest; + + public PipelineBinarySession(Session session, int num) { + this.session = Conditions.notNull(session); + this.alreadyRequest = num; + } + + public Session session() { + return this.session; + } + + public void cancelRequest() { + this.alreadyRequest = 0; + } + + public void setupRequest(int num) { + this.alreadyRequest = num; + } + + public int requestNum() { + return this.alreadyRequest; + } +} diff --git a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/core/Pipeline.java b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/core/Pipeline.java index abdb4d3..5517040 100644 --- a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/core/Pipeline.java +++ b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/core/Pipeline.java @@ -1,5 +1,7 @@ package top.limitart.fastmq.pipeline.core; +import java.io.Closeable; +import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -24,12 +26,12 @@ import top.limitart.util.StringUtil; import top.limitart.util.TimeUtil; /** 消息总线 */ -public class Pipeline { +public class Pipeline implements Closeable { private static Logger LOGGER = LoggerFactory.getLogger(Pipeline.class); private static final long HANG_TO_SHUTDOWN_INTERVAL = TimeUnit.SECONDS.toMillis(10); // TAG - private Map> tagAndZones = new HashMap<>(); + private Map> tagAndZone = new HashMap<>(); // 所有队列 private Map zoneAndQueue = new HashMap<>(); // 轮询线程 @@ -38,7 +40,7 @@ public class Pipeline { private Lock lock = new ReentrantLock(); public Pipeline() { - queue.schedule(this::dealShutdownAndHang, 10, TimeUnit.MINUTES); + queue.scheduleAtFixedRate(this::dealShutdownAndHang, 5,5, TimeUnit.MINUTES); } private void dealShutdownAndHang() { @@ -84,7 +86,7 @@ public class Pipeline { return false; } // TAG - for (Set value : tagAndZones.values()) { + for (Set value : tagAndZone.values()) { value.removeIf(v -> v.equals(zone)); } return zoneAndQueue.remove(zone) != null; @@ -95,7 +97,7 @@ public class Pipeline { List> list = new ArrayList<>(); try { lock.lock(); - for (Entry> entry : tagAndZones.entrySet()) { + for (Entry> entry : tagAndZone.entrySet()) { String key = entry.getKey(); if (tags.contains(key)) { Set value = entry.getValue(); @@ -117,7 +119,7 @@ public class Pipeline { List> list = new ArrayList<>(); try { lock.lock(); - for (Entry> entry : tagAndZones.entrySet()) { + for (Entry> entry : tagAndZone.entrySet()) { String key = entry.getKey(); if (StringUtil.matchReg(tagPattern, key)) { Set value = entry.getValue(); @@ -218,7 +220,7 @@ public class Pipeline { Set tagSet = new HashSet<>(); if (tags != null) { tagSet.addAll(tags); - tagSet.forEach(tag -> tagAndZones.computeIfAbsent(tag, (k) -> new HashSet<>()).add(zone)); + tagSet.forEach(tag -> tagAndZone.computeIfAbsent(tag, (k) -> new HashSet<>()).add(zone)); } zoneAndQueue.put(zone, new Puller(zone, tagSet)); LOGGER.info("zone {} register in pipeline", zone); @@ -228,6 +230,11 @@ public class Pipeline { } } + @Override + public void close() throws IOException { + queue.shutdown(); + } + private static class Puller { private String zone; diff --git a/net/src/main/java/top/limitart/net/NettyEndPoint.java b/net/src/main/java/top/limitart/net/NettyEndPoint.java index b794a66..01c679b 100644 --- a/net/src/main/java/top/limitart/net/NettyEndPoint.java +++ b/net/src/main/java/top/limitart/net/NettyEndPoint.java @@ -144,9 +144,9 @@ public abstract class NettyEndPoint AddressPair addressPair, int waitSeconds, Process3, Boolean, Throwable> listener) { stop(); LOGGER.info( - "{} try connect {} server: {} after {} seconds...", + "{} try connect {} server:{} after {} seconds...", name(), - type.local() ? "local" : "", + type.local() ? "local" : "remote", addressPair, waitSeconds); if (waitSeconds > 0) { -- Gitee From b30c7d5e0c6361f02c80000ed492422de6cf3235 Mon Sep 17 00:00:00 2001 From: hank <104381832> Date: Sat, 1 Feb 2020 19:24:53 +0800 Subject: [PATCH 07/11] 1 --- .gitignore | 1 + .../java/top/limitart/base/BinaryMeta.java | 16 +- .../java/top/limitart/base/IntCounter.java | 6 +- .../java/top/limitart/base/LongCounter.java | 8 +- .../top/limitart/base/SmoothRandomWeight.java | 8 +- .../limitart/collections/AbstractIntMap.java | 6 +- .../limitart/collections/AbstractLongMap.java | 6 +- .../limitart/collections/EnumIntCounter.java | 6 +- .../util/{GameMathUtil.java => MathUtil.java} | 4 +- .../top/limitart/util/GameMathUtilTest.java | 12 +- .../limitart/fastmq/PipelineConsumerDemo.java | 9 +- .../limitart/fastmq/PipelineProviderDemo.java | 35 ++++ .../limitart/fastmq/common/binary/Consts.java | 1 + .../binary/ReqBroadcastMsgToPipelineMsg.java | 2 + .../ReqBroadcastMsgToPipelineWithTagsMsg.java | 4 + .../binary/ReqPushMsgToPipelineMsg.java | 3 + .../ReqPushMsgToPipelineWithTagsMsg.java | 4 + .../common/binary/ResPushMsgResultMsg.java | 28 ++++ .../fastmq/consumer/ConsumerBinaryClient.java | 10 +- .../fastmq/pipeline/PipelineBinaryServer.java | 151 +++++++++++++++++- .../fastmq/pipeline/core/Pipeline.java | 58 +++++-- .../pipeline/core/PipelineRingBuffer.java | 22 ++- .../fastmq/provider/ProviderBinaryClient.java | 78 ++++++++- .../game/poker/TexasPokerCalculator.java | 4 +- .../top/limitart/game/poker/PokersTest.java | 4 +- pipeline-token.tmp | 1 + 26 files changed, 417 insertions(+), 70 deletions(-) rename core/src/main/java/top/limitart/util/{GameMathUtil.java => MathUtil.java} (99%) create mode 100644 demo/src/main/java/top/limitart/fastmq/PipelineProviderDemo.java create mode 100644 fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ResPushMsgResultMsg.java create mode 100644 pipeline-token.tmp diff --git a/.gitignore b/.gitignore index c5b3f1d..c70c359 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ target /.idea /limitart.iml +.tmp diff --git a/core/src/main/java/top/limitart/base/BinaryMeta.java b/core/src/main/java/top/limitart/base/BinaryMeta.java index eaf18e0..8caa0a0 100644 --- a/core/src/main/java/top/limitart/base/BinaryMeta.java +++ b/core/src/main/java/top/limitart/base/BinaryMeta.java @@ -42,6 +42,7 @@ import java.util.concurrent.ConcurrentHashMap; */ @SuppressWarnings({"rawtypes", "unchecked"}) public class BinaryMeta implements Closeable { + private static boolean COMPRESS_INT32_64 = true; private static final Map, ConstructorAccess> messageMetaCache = new ConcurrentHashMap<>(); @@ -62,7 +63,8 @@ public class BinaryMeta implements Closeable { replaceBuffer(buffer); } - public BinaryMeta() {} + public BinaryMeta() { + } /** * 替换buffer @@ -80,7 +82,9 @@ public class BinaryMeta implements Closeable { return buffer; } - /** 仅仅置空,不减少引用计数 */ + /** + * 仅仅置空,不减少引用计数 + */ public void softClose() { Conditions.notNull(this.buffer, "already release"); this.buffer = null; @@ -268,6 +272,8 @@ public class BinaryMeta implements Closeable { putMessageMetaList((List) object); } else if (component == String.class) { putStringList((List) object); + } else if (component == byte[].class) { + putByteArrayList((List) object); } } else { if (type == Byte.class) { @@ -487,6 +493,8 @@ public class BinaryMeta implements Closeable { field.set(this, getMessageMetaList((Class) component)); } else if (component == String.class) { field.set(this, getStringList()); + } else if (component == byte[].class) { + field.set(this, getByteArrayList()); } } else { if (type == Byte.class) { @@ -1055,7 +1063,9 @@ public class BinaryMeta implements Closeable { return new ArrayList<>(); default: List list = new ArrayList<>(); - list.add(getByteArray()); + for (int i = 0; i < len; i++) { + list.add(getByteArray()); + } return list; } } diff --git a/core/src/main/java/top/limitart/base/IntCounter.java b/core/src/main/java/top/limitart/base/IntCounter.java index c903488..b042d68 100644 --- a/core/src/main/java/top/limitart/base/IntCounter.java +++ b/core/src/main/java/top/limitart/base/IntCounter.java @@ -16,7 +16,7 @@ package top.limitart.base; import top.limitart.base.label.ThreadUnsafe; -import top.limitart.util.GameMathUtil; +import top.limitart.util.MathUtil; /** * int计数器 @@ -90,7 +90,7 @@ public class IntCounter { * @return */ protected int setCount(int value) { - return this.count = GameMathUtil.fixedBetween(value, low(), high()); + return this.count = MathUtil.fixedBetween(value, low(), high()); } /** @@ -147,7 +147,7 @@ public class IntCounter { */ public int getAndAdd(int delta) { int old = getCount(); - setCount(GameMathUtil.safeAdd(old, delta)); + setCount(MathUtil.safeAdd(old, delta)); return old; } diff --git a/core/src/main/java/top/limitart/base/LongCounter.java b/core/src/main/java/top/limitart/base/LongCounter.java index 8bb27a1..8effee0 100644 --- a/core/src/main/java/top/limitart/base/LongCounter.java +++ b/core/src/main/java/top/limitart/base/LongCounter.java @@ -16,7 +16,7 @@ package top.limitart.base; import top.limitart.base.label.ThreadUnsafe; -import top.limitart.util.GameMathUtil; +import top.limitart.util.MathUtil; /** * 计数器 @@ -87,7 +87,7 @@ public class LongCounter { * @return */ public long setCount(long value) { - return this.count = GameMathUtil.fixedBetween(value, low(), high()); + return this.count = MathUtil.fixedBetween(value, low(), high()); } /** @@ -115,7 +115,7 @@ public class LongCounter { * @return */ public long addAndGet(long delta) { - return setCount(GameMathUtil.safeAdd(getCount(), delta)); + return setCount(MathUtil.safeAdd(getCount(), delta)); } /** @@ -144,7 +144,7 @@ public class LongCounter { */ public long getAndAdd(long delta) { long old = getCount(); - setCount(GameMathUtil.safeAdd(old, delta)); + setCount(MathUtil.safeAdd(old, delta)); return old; } diff --git a/core/src/main/java/top/limitart/base/SmoothRandomWeight.java b/core/src/main/java/top/limitart/base/SmoothRandomWeight.java index 05e9c92..ad7818b 100644 --- a/core/src/main/java/top/limitart/base/SmoothRandomWeight.java +++ b/core/src/main/java/top/limitart/base/SmoothRandomWeight.java @@ -19,7 +19,7 @@ package top.limitart.base; import top.limitart.base.label.ThreadSafe; -import top.limitart.util.GameMathUtil; +import top.limitart.util.MathUtil; import top.limitart.util.RandomUtil; /** 平滑加权随机Created by Hank on 2019/4/26 */ @@ -47,7 +47,7 @@ public class SmoothRandomWeight { int sum = 0; boolean allSame = true; // 降低数据量级 - int gcd = GameMathUtil.gcd(weights); + int gcd = MathUtil.gcd(weights); for (int i = 0; i < weights.length; i++) { this.weights[i] = weights[i] / gcd; sum += this.weights[i]; @@ -57,7 +57,7 @@ public class SmoothRandomWeight { } this.allSame = allSame; this.sum = sum; - this.deviationFactor = GameMathUtil.fixedBetween(deviationFactor, 0, 1); + this.deviationFactor = MathUtil.fixedBetween(deviationFactor, 0, 1); this.curFactor = deviationFactor; } @@ -66,7 +66,7 @@ public class SmoothRandomWeight { // 如果长度都不一样,直接全部重置 reset(weights, this.deviationFactor); } else { - int gcd = GameMathUtil.gcd(weights); + int gcd = MathUtil.gcd(weights); int sum = 0; boolean allSame = true; for (int i = 0; i < weights.length; i++) { diff --git a/core/src/main/java/top/limitart/collections/AbstractIntMap.java b/core/src/main/java/top/limitart/collections/AbstractIntMap.java index ec99d2a..cc9a9a6 100644 --- a/core/src/main/java/top/limitart/collections/AbstractIntMap.java +++ b/core/src/main/java/top/limitart/collections/AbstractIntMap.java @@ -16,7 +16,7 @@ package top.limitart.collections; import top.limitart.base.NotImplementedException; -import top.limitart.util.GameMathUtil; +import top.limitart.util.MathUtil; import java.util.Collection; import java.util.Map; @@ -102,7 +102,7 @@ public abstract class AbstractIntMap implements IntMap { */ @Override public int addAndGet(K key, int delta) { - return accumulateAndGet(key, delta, GameMathUtil::safeAdd); + return accumulateAndGet(key, delta, MathUtil::safeAdd); } /** @@ -136,7 +136,7 @@ public abstract class AbstractIntMap implements IntMap { */ @Override public int getAndAdd(K key, int delta) { - return getAndAccumulate(key, delta, GameMathUtil::safeAdd); + return getAndAccumulate(key, delta, MathUtil::safeAdd); } /** diff --git a/core/src/main/java/top/limitart/collections/AbstractLongMap.java b/core/src/main/java/top/limitart/collections/AbstractLongMap.java index 621dbcb..7b87771 100644 --- a/core/src/main/java/top/limitart/collections/AbstractLongMap.java +++ b/core/src/main/java/top/limitart/collections/AbstractLongMap.java @@ -16,7 +16,7 @@ package top.limitart.collections; import top.limitart.base.NotImplementedException; -import top.limitart.util.GameMathUtil; +import top.limitart.util.MathUtil; import java.util.Collection; import java.util.Map; @@ -102,7 +102,7 @@ public abstract class AbstractLongMap implements LongMap { */ @Override public long addAndGet(K key, long delta) { - return accumulateAndGet(key, delta, GameMathUtil::safeAdd); + return accumulateAndGet(key, delta, MathUtil::safeAdd); } /** @@ -136,7 +136,7 @@ public abstract class AbstractLongMap implements LongMap { */ @Override public long getAndAdd(K key, long delta) { - return getAndAccumulate(key, delta, GameMathUtil::safeAdd); + return getAndAccumulate(key, delta, MathUtil::safeAdd); } /** diff --git a/core/src/main/java/top/limitart/collections/EnumIntCounter.java b/core/src/main/java/top/limitart/collections/EnumIntCounter.java index 2fd3b31..e141251 100644 --- a/core/src/main/java/top/limitart/collections/EnumIntCounter.java +++ b/core/src/main/java/top/limitart/collections/EnumIntCounter.java @@ -17,7 +17,7 @@ package top.limitart.collections; import top.limitart.base.label.ThreadUnsafe; import top.limitart.util.EnumUtil; -import top.limitart.util.GameMathUtil; +import top.limitart.util.MathUtil; import java.util.Arrays; import java.util.Iterator; @@ -148,7 +148,7 @@ public class EnumIntCounter> implements Iterable { * @return */ public int addAndGet(E key, int delta) { - int result = GameMathUtil.safeAdd(getCount(key), delta); + int result = MathUtil.safeAdd(getCount(key), delta); putCount(key, result); return result; } @@ -182,7 +182,7 @@ public class EnumIntCounter> implements Iterable { */ public int getAndAdd(E key, int delta) { int old = getCount(key); - putCount(key, GameMathUtil.safeAdd(old, delta)); + putCount(key, MathUtil.safeAdd(old, delta)); return old; } diff --git a/core/src/main/java/top/limitart/util/GameMathUtil.java b/core/src/main/java/top/limitart/util/MathUtil.java similarity index 99% rename from core/src/main/java/top/limitart/util/GameMathUtil.java rename to core/src/main/java/top/limitart/util/MathUtil.java index b2de412..8b27d34 100644 --- a/core/src/main/java/top/limitart/util/GameMathUtil.java +++ b/core/src/main/java/top/limitart/util/MathUtil.java @@ -27,8 +27,8 @@ import java.util.List; * * @author hank */ -public final class GameMathUtil { - private GameMathUtil() {} +public final class MathUtil { + private MathUtil() {} /** * 安全相加,如果越界返回int最大值 diff --git a/core/src/test/java/top/limitart/util/GameMathUtilTest.java b/core/src/test/java/top/limitart/util/GameMathUtilTest.java index 5c80219..76a9c9e 100644 --- a/core/src/test/java/top/limitart/util/GameMathUtilTest.java +++ b/core/src/test/java/top/limitart/util/GameMathUtilTest.java @@ -30,11 +30,11 @@ public class GameMathUtilTest { @Test public void safeTest() { - Assert.assertTrue(GameMathUtil.safeAdd(10, 11) == 21); - Assert.assertTrue(GameMathUtil.safeAdd(Integer.MAX_VALUE, 1) == Integer.MAX_VALUE); - Assert.assertTrue(GameMathUtil.safeSub(10, 11) == -1); - Assert.assertTrue(GameMathUtil.safeSub(Integer.MIN_VALUE, 1) == Integer.MIN_VALUE); - Assert.assertTrue(GameMathUtil.safeMulti(10, 11) == 110); - Assert.assertTrue(GameMathUtil.safeMulti(Integer.MAX_VALUE, 10) == Integer.MAX_VALUE); + Assert.assertTrue(MathUtil.safeAdd(10, 11) == 21); + Assert.assertTrue(MathUtil.safeAdd(Integer.MAX_VALUE, 1) == Integer.MAX_VALUE); + Assert.assertTrue(MathUtil.safeSub(10, 11) == -1); + Assert.assertTrue(MathUtil.safeSub(Integer.MIN_VALUE, 1) == Integer.MIN_VALUE); + Assert.assertTrue(MathUtil.safeMulti(10, 11) == 110); + Assert.assertTrue(MathUtil.safeMulti(Integer.MAX_VALUE, 10) == Integer.MAX_VALUE); } } diff --git a/demo/src/main/java/top/limitart/fastmq/PipelineConsumerDemo.java b/demo/src/main/java/top/limitart/fastmq/PipelineConsumerDemo.java index b4f2142..52540aa 100644 --- a/demo/src/main/java/top/limitart/fastmq/PipelineConsumerDemo.java +++ b/demo/src/main/java/top/limitart/fastmq/PipelineConsumerDemo.java @@ -20,7 +20,14 @@ public class PipelineConsumerDemo { 9000, "test_zone", tags, - msg -> System.out.println(new String(msg, StandardCharsets.UTF_8))); + msg -> {System.out.println(new String(msg, StandardCharsets.UTF_8)) + ; + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }); } catch (Exception e) { e.printStackTrace(); } diff --git a/demo/src/main/java/top/limitart/fastmq/PipelineProviderDemo.java b/demo/src/main/java/top/limitart/fastmq/PipelineProviderDemo.java new file mode 100644 index 0000000..2f354ef --- /dev/null +++ b/demo/src/main/java/top/limitart/fastmq/PipelineProviderDemo.java @@ -0,0 +1,35 @@ +package top.limitart.fastmq; + +import java.nio.charset.StandardCharsets; +import java.util.LinkedList; +import java.util.List; +import top.limitart.fastmq.provider.ProviderBinaryClient; + +public class PipelineProviderDemo { + + private static ProviderBinaryClient providerClient; + + static { + try { + List tags = new LinkedList<>(); + tags.add("fuck"); + tags.add("shit"); + providerClient = + new ProviderBinaryClient( + "127.0.0.1", + 9000); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static void main(String[] args) throws Exception { + providerClient.run(args); + int count = 0; + while (true) { + providerClient.sendMsg("test_zone", ("hello fastmq !" + count++) + .getBytes(StandardCharsets.UTF_8)); + Thread.sleep(30); + } + } +} diff --git a/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/Consts.java b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/Consts.java index 7d46251..a1ce336 100644 --- a/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/Consts.java +++ b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/Consts.java @@ -15,4 +15,5 @@ public class Consts { public static final short REQ_BROADCAST_MSG_TO_PIPELINE = REQ_PUSH_MSG_TO_PIPELINE + 1; public static final short REQ_PUSH_MSG_TO_PIPELINE_WITH_TAGS = REQ_BROADCAST_MSG_TO_PIPELINE + 1; public static final short REQ_BROADCAST_MSG_TO_PIPELINE_WITH_TAGS = REQ_PUSH_MSG_TO_PIPELINE_WITH_TAGS + 1; + public static final short RES_PUSH_MSG_RESULT = REQ_BROADCAST_MSG_TO_PIPELINE_WITH_TAGS + 1; } diff --git a/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqBroadcastMsgToPipelineMsg.java b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqBroadcastMsgToPipelineMsg.java index 7333f40..770fa27 100644 --- a/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqBroadcastMsgToPipelineMsg.java +++ b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqBroadcastMsgToPipelineMsg.java @@ -4,6 +4,8 @@ import top.limitart.net.binary.BinaryMessage; public class ReqBroadcastMsgToPipelineMsg extends BinaryMessage { + public byte[] bytes; + @Override public short id() { return Consts.REQ_BROADCAST_MSG_TO_PIPELINE; diff --git a/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqBroadcastMsgToPipelineWithTagsMsg.java b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqBroadcastMsgToPipelineWithTagsMsg.java index 3e60859..9f55fe7 100644 --- a/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqBroadcastMsgToPipelineWithTagsMsg.java +++ b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqBroadcastMsgToPipelineWithTagsMsg.java @@ -1,9 +1,13 @@ package top.limitart.fastmq.common.binary; +import java.util.List; import top.limitart.net.binary.BinaryMessage; public class ReqBroadcastMsgToPipelineWithTagsMsg extends BinaryMessage { + public List tags; + public byte[] bytes; + @Override public short id() { return Consts.REQ_BROADCAST_MSG_TO_PIPELINE_WITH_TAGS; diff --git a/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqPushMsgToPipelineMsg.java b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqPushMsgToPipelineMsg.java index f89762c..2f65f00 100644 --- a/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqPushMsgToPipelineMsg.java +++ b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqPushMsgToPipelineMsg.java @@ -4,6 +4,9 @@ import top.limitart.net.binary.BinaryMessage; public class ReqPushMsgToPipelineMsg extends BinaryMessage { + public String zone; + public byte[] bytes; + @Override public short id() { return Consts.REQ_PUSH_MSG_TO_PIPELINE; diff --git a/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqPushMsgToPipelineWithTagsMsg.java b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqPushMsgToPipelineWithTagsMsg.java index 14e0ae3..2dabbda 100644 --- a/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqPushMsgToPipelineWithTagsMsg.java +++ b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ReqPushMsgToPipelineWithTagsMsg.java @@ -1,9 +1,13 @@ package top.limitart.fastmq.common.binary; +import java.util.List; import top.limitart.net.binary.BinaryMessage; public class ReqPushMsgToPipelineWithTagsMsg extends BinaryMessage { + public List tags; + public byte[] bytes; + @Override public short id() { return Consts.REQ_PUSH_MSG_TO_PIPELINE_WITH_TAGS; diff --git a/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ResPushMsgResultMsg.java b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ResPushMsgResultMsg.java new file mode 100644 index 0000000..452a2d7 --- /dev/null +++ b/fastmq/common/src/main/java/top/limitart/fastmq/common/binary/ResPushMsgResultMsg.java @@ -0,0 +1,28 @@ +package top.limitart.fastmq.common.binary; + +import top.limitart.net.binary.BinaryByteMessage; + +public class ResPushMsgResultMsg extends BinaryByteMessage { + + public static final ResPushMsgResultMsg SUCCESS = new ResPushMsgResultMsg(); + public static final ResPushMsgResultMsg NO_ZONE = new ResPushMsgResultMsg(1); + public static final ResPushMsgResultMsg ZONE_EMPTY = new ResPushMsgResultMsg(2); + public static final ResPushMsgResultMsg ZONE_NOT_ACTIVE = new ResPushMsgResultMsg(3); + public static final ResPushMsgResultMsg ZONE_HAS_NO_BUFFER = new ResPushMsgResultMsg(4); + public static final ResPushMsgResultMsg ZONE_BUFFER_HAS_NO_CAPACITY = new ResPushMsgResultMsg(5); + public static final ResPushMsgResultMsg TAG_EMPTY = new ResPushMsgResultMsg(6); + public static final ResPushMsgResultMsg CAN_NOT_FIND_ZONE_BY_TAGS = new ResPushMsgResultMsg(7); + public static final ResPushMsgResultMsg NO_MSG_CONTENT = new ResPushMsgResultMsg(8); + public ResPushMsgResultMsg(int i) { + super((byte) i); + } + + public ResPushMsgResultMsg() { + super(); + } + + @Override + public short id() { + return Consts.RES_PUSH_MSG_RESULT; + } +} diff --git a/fastmq/consumer/src/main/java/top/limitart/fastmq/consumer/ConsumerBinaryClient.java b/fastmq/consumer/src/main/java/top/limitart/fastmq/consumer/ConsumerBinaryClient.java index 3d320b4..ee5fe59 100644 --- a/fastmq/consumer/src/main/java/top/limitart/fastmq/consumer/ConsumerBinaryClient.java +++ b/fastmq/consumer/src/main/java/top/limitart/fastmq/consumer/ConsumerBinaryClient.java @@ -7,6 +7,7 @@ import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import top.limitart.base.ApplicationBootstrap; @@ -37,6 +38,7 @@ import top.limitart.util.StringUtil; import top.limitart.util.TimeUtil; public class ConsumerBinaryClient extends ApplicationBootstrap { + private static final Logger LOGGER = LoggerFactory.getLogger(ConsumerBinaryClient.class); private static final String TOKEN_FILE = "pipeline-token.tmp"; private static final long PULL_REQUEST_INTERVAL = TimeUnit.SECONDS.toMillis(5); @@ -50,6 +52,7 @@ public class ConsumerBinaryClient extends ApplicationBootstrap { private TaskQueue msgThread = TaskQueue.create("msg-consume"); private ConsumerMsgHandler msgHandler; private Session session; + private boolean handling = false; public ConsumerBinaryClient( String remoteIp, int port, String zone, List tags, ConsumerMsgHandler msgHandler) @@ -86,7 +89,7 @@ public class ConsumerBinaryClient extends ApplicationBootstrap { } private void secondTick() { - if (TimeUtil.now() - lastReceiveMsgTime > PULL_REQUEST_INTERVAL) { + if (TimeUtil.now() - lastReceiveMsgTime > PULL_REQUEST_INTERVAL && !handling) { requestPullMsg(); } } @@ -100,7 +103,7 @@ public class ConsumerBinaryClient extends ApplicationBootstrap { (b, t) -> { if (b) { this.lastReceiveMsgTime = TimeUtil.now(); - LOGGER.info("send msg pull request to pipeline {}", session); + LOGGER.debug("send msg pull request to pipeline {}", session); } }); } @@ -136,6 +139,7 @@ public class ConsumerBinaryClient extends ApplicationBootstrap { @Mapper private class ConsumerBinaryHandler { + /** * 向Pipeline注册一个通道 * @@ -233,6 +237,7 @@ public class ConsumerBinaryClient extends ApplicationBootstrap { public void onMsgPull(@Request ResPullMsg msg) { msgThread.execute( () -> { + handling = true; for (byte[] bytes : msg.msgs) { try { ConsumerBinaryClient.this.msgHandler.onMsg(bytes); @@ -240,6 +245,7 @@ public class ConsumerBinaryClient extends ApplicationBootstrap { LOGGER.error("msg handle error", e); } } + handling = false; requestPullMsg(); }); } diff --git a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/PipelineBinaryServer.java b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/PipelineBinaryServer.java index 013736c..2c17bdc 100644 --- a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/PipelineBinaryServer.java +++ b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/PipelineBinaryServer.java @@ -3,6 +3,8 @@ package top.limitart.fastmq.pipeline; import io.netty.channel.EventLoop; import io.netty.util.concurrent.ScheduledFuture; import java.io.IOException; +import java.util.HashSet; +import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -12,13 +14,18 @@ import org.slf4j.LoggerFactory; import top.limitart.base.ApplicationBootstrap; import top.limitart.fastmq.common.SessionParamConst; import top.limitart.fastmq.common.binary.BinaryRequest; +import top.limitart.fastmq.common.binary.ReqBroadcastMsgToPipelineMsg; +import top.limitart.fastmq.common.binary.ReqBroadcastMsgToPipelineWithTagsMsg; import top.limitart.fastmq.common.binary.ReqCustomerReadyMsg; import top.limitart.fastmq.common.binary.ReqHeartBeatMsg; import top.limitart.fastmq.common.binary.ReqPullMsg; +import top.limitart.fastmq.common.binary.ReqPushMsgToPipelineMsg; +import top.limitart.fastmq.common.binary.ReqPushMsgToPipelineWithTagsMsg; import top.limitart.fastmq.common.binary.ReqRegisterZoneMsg; import top.limitart.fastmq.common.binary.ResHeartBeatMsg; import top.limitart.fastmq.common.binary.ResPipelineEstablishedMsg; import top.limitart.fastmq.common.binary.ResPullMsg; +import top.limitart.fastmq.common.binary.ResPushMsgResultMsg; import top.limitart.fastmq.common.binary.ResRegisterZoneMsg; import top.limitart.fastmq.common.binary.ReqZoneClaimMsg; import top.limitart.fastmq.pipeline.binary.PipelineBinarySession; @@ -34,7 +41,8 @@ import top.limitart.net.Session; import top.limitart.net.binary.BinaryEndPoint; import top.limitart.net.binary.BinaryMessage; import top.limitart.net.binary.BinaryRequestParam; -import top.limitart.util.GameMathUtil; +import top.limitart.util.MathUtil; +import top.limitart.util.RandomUtil; import top.limitart.util.StringUtil; public class PipelineBinaryServer extends ApplicationBootstrap { @@ -91,7 +99,7 @@ public class PipelineBinaryServer extends ApplicationBootstrap { .scheduleAtFixedRate( () -> session.writeNow(ReqHeartBeatMsg.INSTANCE), 5, 5, TimeUnit.SECONDS); session.params().putObj(SessionParamConst.HEART_BEAT, scheduledFuture); - LOGGER.info("{} start heartbeat echo"); + LOGGER.info("{} start heartbeat echo", session); } } @@ -121,6 +129,7 @@ public class PipelineBinaryServer extends ApplicationBootstrap { @Mapper private class PipelineBinaryHandler { + /** * 消费者注册 * @@ -212,12 +221,13 @@ public class PipelineBinaryServer extends ApplicationBootstrap { LOGGER.error("session {} is not validated", session); return; } - PipelineRingBuffer buffer = PipelineBinaryServer.this.pipeline.getBufferByZone(zone); + PipelineRingBuffer buffer = PipelineBinaryServer.this.pipeline + .getBufferByZone(zone, true); if (buffer == null) { LOGGER.error("session {} , zone {} has no buffer", session, zone); return; } - int pullNum = GameMathUtil.fixedBetween(msg.pullNum, 1, 100); + int pullNum = MathUtil.fixedBetween(msg.pullNum, 1, 100); List bytes = buffer.peekAtMost(pullNum); if (bytes.isEmpty()) { if (prs.containsKey(zone)) { @@ -229,10 +239,10 @@ public class PipelineBinaryServer extends ApplicationBootstrap { return; } prs.remove(zone); // TODO 不删除 复用 - pushMsgsToCustomer(zone, session, bytes); + pushMsgsToConsumer(zone, session, bytes); } - private void pushMsgsToCustomer( + private void pushMsgsToConsumer( String zone, Session session, List bytes) { ResPullMsg msg = new ResPullMsg(); msg.msgs = bytes; @@ -240,11 +250,138 @@ public class PipelineBinaryServer extends ApplicationBootstrap { msg, (b, t) -> { if (b) { - LOGGER.info("send msgs to session {} , zone {}, num {}", session, zone, bytes.size()); + LOGGER + .debug("send msgs to session {} , zone {}, num {}", session, zone, bytes.size()); } else { LOGGER.error("send msgs to session " + session + " , zone " + zone + " fail", t); } }); } + + public void receiveProviderMsg(@Request ReqPushMsgToPipelineMsg msg, BinaryRequest request) { + if (StringUtil.empty(msg.zone)) { + request.session().writeNow(ResPushMsgResultMsg.ZONE_EMPTY); + return; + } + if (msg.bytes == null || msg.bytes.length == 0) { + request.session().writeNow(ResPushMsgResultMsg.NO_MSG_CONTENT); + return; + } + States zoneState = PipelineBinaryServer.this.pipeline.getZoneState(msg.zone); + if (zoneState == null) { + request.session().writeNow(ResPushMsgResultMsg.NO_ZONE); + return; + } + if (zoneState != States.ACTIVE) { + request.session().writeNow(ResPushMsgResultMsg.ZONE_NOT_ACTIVE); + return; + } + PipelineRingBuffer buffer = PipelineBinaryServer.this.pipeline + .getBufferByZone(msg.zone, true); + if (buffer == null) { + request.session().writeNow(ResPushMsgResultMsg.ZONE_HAS_NO_BUFFER); + return; + } + if (!buffer.enqueue(msg.bytes)) { + request.session().writeNow(ResPushMsgResultMsg.ZONE_BUFFER_HAS_NO_CAPACITY); + return; + } + request.session().writeNow(ResPushMsgResultMsg.SUCCESS); + noticeConsumers(msg.zone); + } + + public void receiveProviderMsg(@Request ReqPushMsgToPipelineWithTagsMsg msg, + BinaryRequest request) { + if (msg.tags == null || msg.tags.isEmpty()) { + request.session().writeNow(ResPushMsgResultMsg.TAG_EMPTY); + return; + } + if (msg.bytes == null || msg.bytes.length == 0) { + request.session().writeNow(ResPushMsgResultMsg.NO_MSG_CONTENT); + return; + } + List> buffers = PipelineBinaryServer.this.pipeline + .getBuffersByTags(new HashSet<>(msg.tags), true); + if (buffers.isEmpty()) { + request.session().writeNow(ResPushMsgResultMsg.CAN_NOT_FIND_ZONE_BY_TAGS); + return; + } + PipelineRingBuffer buffer = buffers + .get(RandomUtil.nextInt(0, buffers.size() - 1)); + if (!buffer.enqueue(msg.bytes)) { + request.session().writeNow(ResPushMsgResultMsg.ZONE_BUFFER_HAS_NO_CAPACITY); + return; + } + request.session().writeNow(ResPushMsgResultMsg.SUCCESS); + noticeConsumers(buffer.getZone()); + } + + public void receiveProviderMsg(@Request ReqBroadcastMsgToPipelineMsg msg, + BinaryRequest request) { + if (msg.bytes == null || msg.bytes.length == 0) { + request.session().writeNow(ResPushMsgResultMsg.NO_MSG_CONTENT); + return; + } + List> allBuffers = PipelineBinaryServer.this.pipeline + .getAllBuffers(true); + boolean allFail = true; + for (PipelineRingBuffer buffer : allBuffers) { + if (!buffer.enqueue(msg.bytes)) { + request.session().writeNow(ResPushMsgResultMsg.ZONE_BUFFER_HAS_NO_CAPACITY); + continue; + } + allFail = false; + noticeConsumers(buffer.getZone()); + } + if (!allFail) { + request.session().writeNow(ResPushMsgResultMsg.SUCCESS); + } + + } + + public void receiveProviderMsg(@Request ReqBroadcastMsgToPipelineWithTagsMsg msg, + BinaryRequest request) { + if (msg.tags == null || msg.tags.isEmpty()) { + request.session().writeNow(ResPushMsgResultMsg.TAG_EMPTY); + return; + } + if (msg.bytes == null || msg.bytes.length == 0) { + request.session().writeNow(ResPushMsgResultMsg.NO_MSG_CONTENT); + return; + } + List> buffers = PipelineBinaryServer.this.pipeline + .getBuffersByTags(new HashSet<>(msg.tags), true); + if (buffers.isEmpty()) { + request.session().writeNow(ResPushMsgResultMsg.CAN_NOT_FIND_ZONE_BY_TAGS); + return; + } + boolean allFail = true; + for (PipelineRingBuffer buffer : buffers) { + if (!buffer.enqueue(msg.bytes)) { + request.session().writeNow(ResPushMsgResultMsg.ZONE_BUFFER_HAS_NO_CAPACITY); + continue; + } + allFail = false; + noticeConsumers(buffer.getZone()); + } + if (!allFail) { + request.session().writeNow(ResPushMsgResultMsg.SUCCESS); + } + } + + private void noticeConsumers(String zone) { + PipelineBinarySession pipelineBinarySession = prs.get(zone); + if (pipelineBinarySession == null) { + return; + } + PipelineRingBuffer buffer = PipelineBinaryServer.this.pipeline + .getBufferByZone(zone, true); + List bytes = buffer.peekAtMost(pipelineBinarySession.requestNum()); + if (bytes.isEmpty()) { + return; + } + prs.remove(zone); + pushMsgsToConsumer(zone, pipelineBinarySession.session(), bytes); + } } } diff --git a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/core/Pipeline.java b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/core/Pipeline.java index 5517040..bcdf367 100644 --- a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/core/Pipeline.java +++ b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/core/Pipeline.java @@ -14,6 +14,7 @@ import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; +import java.util.function.Consumer; import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -25,7 +26,9 @@ import top.limitart.concurrent.TaskQueue; import top.limitart.util.StringUtil; import top.limitart.util.TimeUtil; -/** 消息总线 */ +/** + * 消息总线 + */ public class Pipeline implements Closeable { private static Logger LOGGER = LoggerFactory.getLogger(Pipeline.class); @@ -40,9 +43,10 @@ public class Pipeline implements Closeable { private Lock lock = new ReentrantLock(); public Pipeline() { - queue.scheduleAtFixedRate(this::dealShutdownAndHang, 5,5, TimeUnit.MINUTES); + queue.scheduleAtFixedRate(this::dealShutdownAndHang, 5, 5, TimeUnit.MINUTES); } + private void dealShutdownAndHang() { lock.lock(); try { @@ -92,7 +96,22 @@ public class Pipeline implements Closeable { return zoneAndQueue.remove(zone) != null; } - public List> getBuffersByTags(Set tags) { + public List> getAllBuffers(boolean onlyActive) { + List> list = new ArrayList<>(); + try { + lock.lock(); + zoneAndQueue.values().forEach((v) -> { + if (!onlyActive || v.stateData.state == States.ACTIVE) { + list.add(v.buffer); + } + }); + return list; + } finally { + lock.unlock(); + } + } + + public List> getBuffersByTags(Set tags, boolean onlyActive) { Conditions.notNull(tags); List> list = new ArrayList<>(); try { @@ -102,7 +121,7 @@ public class Pipeline implements Closeable { if (tags.contains(key)) { Set value = entry.getValue(); for (String zone : value) { - PipelineRingBuffer bufferByZone = getBufferByZone(zone); + PipelineRingBuffer bufferByZone = getBufferByZone(zone, onlyActive); if (bufferByZone != null) { list.add(bufferByZone); } @@ -115,7 +134,8 @@ public class Pipeline implements Closeable { return list; } - public List> getBuffersByMatchedTags(Pattern tagPattern) { + public List> getBuffersByMatchedTags(Pattern tagPattern, + boolean onlyActive) { List> list = new ArrayList<>(); try { lock.lock(); @@ -124,7 +144,7 @@ public class Pipeline implements Closeable { if (StringUtil.matchReg(tagPattern, key)) { Set value = entry.getValue(); for (String zone : value) { - PipelineRingBuffer bufferByZone = getBufferByZone(zone); + PipelineRingBuffer bufferByZone = getBufferByZone(zone, onlyActive); if (bufferByZone != null) { list.add(bufferByZone); } @@ -137,7 +157,7 @@ public class Pipeline implements Closeable { return list; } - public PipelineRingBuffer getBufferByZone(String zone) { + public PipelineRingBuffer getBufferByZone(String zone, boolean onlyActive) { if (StringUtil.empty(zone)) { LOGGER.error("can not get buffer because zone null or empty"); return null; @@ -148,6 +168,9 @@ public class Pipeline implements Closeable { if (puller == null) { return null; } + if (onlyActive && puller.stateData.state != States.ACTIVE) { + return null; + } return puller.buffer; } finally { lock.unlock(); @@ -200,8 +223,7 @@ public class Pipeline implements Closeable { } /** - * 注册一个队列
- * 生产者和消费者会根据唯一编号zone和个性化tag来发送和消费 + * 注册一个队列
生产者和消费者会根据唯一编号zone和个性化tag来发送和消费 * * @param zone 整个集群唯一编号 * @param tags 该单位的自定义标签 @@ -250,7 +272,7 @@ public class Pipeline implements Closeable { } else { this.tags = new ConcurrentHashSet<>(); } - buffer = new PipelineRingBuffer<>(() -> new MessageSlot()); + buffer = new PipelineRingBuffer<>(zone, () -> new MessageSlot()); } public Set getTags() { @@ -305,13 +327,21 @@ public class Pipeline implements Closeable { } public enum States { - /** 注册中(正在校验合法性,无法消费消息) */ + /** + * 注册中(正在校验合法性,无法消费消息) + */ REGISTER, - /** 激活模式(可以正常消费消息) */ + /** + * 激活模式(可以正常消费消息) + */ ACTIVE, - /** 挂起模式(异常,不能消费消息,需要重新激活,队列不会被清除) */ + /** + * 挂起模式(异常,不能消费消息,需要重新激活,队列不会被清除) + */ HANG, - /** 关闭(关闭模式的消息队列会被轮询清除) */ + /** + * 关闭(关闭模式的消息队列会被轮询清除) + */ SHUTDOWN, } } diff --git a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/core/PipelineRingBuffer.java b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/core/PipelineRingBuffer.java index c568eea..0249620 100644 --- a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/core/PipelineRingBuffer.java +++ b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/core/PipelineRingBuffer.java @@ -33,20 +33,26 @@ import top.limitart.fastmq.pipeline.core.PipelineRingBufferSlot.PipelineRingBuff public class PipelineRingBuffer { private static final Logger LOGGER = LoggerFactory.getLogger(PipelineRingBuffer.class); + private final String zone; private final RingBuffer> buffer; private final Sequence readCursor; private EnqueueStrategy strategy = EnqueueStrategy.FAST_FAIL; - public PipelineRingBuffer(PipelineRingBufferSlotFactory factory) { - this(2 << 12, factory); + public PipelineRingBuffer(String zone, PipelineRingBufferSlotFactory factory) { + this(zone, 2 << 12, factory); } - public PipelineRingBuffer(int size, PipelineRingBufferSlotFactory factory) { + public PipelineRingBuffer(String zone, int size, PipelineRingBufferSlotFactory factory) { + this.zone = zone; buffer = RingBuffer.createMultiProducer(() -> factory.newSlot(), size); readCursor = new Sequence(); buffer.addGatingSequences(readCursor); } + public String getZone() { + return zone; + } + /** * 设置执行队列满时的策略 * @@ -58,11 +64,12 @@ public class PipelineRingBuffer { return this; } - public void enqueue(V task) { + public boolean enqueue(V task) { Conditions.notNull(task); try { long seq = buffer.tryNext(); publish(task, seq); + return true; } catch (InsufficientCapacityException e) { if (this.strategy == EnqueueStrategy.FAST_FAIL || this.strategy == EnqueueStrategy.BLOCK_BUT_NOTICE) { @@ -75,16 +82,19 @@ public class PipelineRingBuffer { //阻塞 long seq = buffer.next(); publish(task, seq); + return true; } } + return false; } - public void enqueue(List tasks) { + public boolean enqueue(List tasks) { Conditions.args(tasks != null && !tasks.isEmpty(), "task list is null or empty"); long start = buffer.getCursor() + 1; try { long end = buffer.tryNext(tasks.size()); publish(tasks, start, end); + return true; } catch (InsufficientCapacityException e) { if (this.strategy == EnqueueStrategy.FAST_FAIL || this.strategy == EnqueueStrategy.BLOCK_BUT_NOTICE) { @@ -97,8 +107,10 @@ public class PipelineRingBuffer { //阻塞 long end = buffer.next(tasks.size()); publish(tasks, start, end); + return true; } } + return false; } /** diff --git a/fastmq/provider/src/main/java/top/limitart/fastmq/provider/ProviderBinaryClient.java b/fastmq/provider/src/main/java/top/limitart/fastmq/provider/ProviderBinaryClient.java index 9372563..1a82796 100644 --- a/fastmq/provider/src/main/java/top/limitart/fastmq/provider/ProviderBinaryClient.java +++ b/fastmq/provider/src/main/java/top/limitart/fastmq/provider/ProviderBinaryClient.java @@ -1,36 +1,95 @@ package top.limitart.fastmq.provider; +import java.util.List; import top.limitart.base.ApplicationBootstrap; +import top.limitart.base.Conditions; import top.limitart.fastmq.common.binary.BinaryRequest; +import top.limitart.fastmq.common.binary.ReqBroadcastMsgToPipelineMsg; +import top.limitart.fastmq.common.binary.ReqBroadcastMsgToPipelineWithTagsMsg; +import top.limitart.fastmq.common.binary.ReqHeartBeatMsg; +import top.limitart.fastmq.common.binary.ReqPushMsgToPipelineMsg; +import top.limitart.fastmq.common.binary.ReqPushMsgToPipelineWithTagsMsg; +import top.limitart.fastmq.common.binary.ResHeartBeatMsg; import top.limitart.mapping.Mapper; +import top.limitart.mapping.Request; import top.limitart.mapping.Router; import top.limitart.net.AddressPair; import top.limitart.net.NettySession; import top.limitart.net.binary.BinaryEndPoint; import top.limitart.net.binary.BinaryMessage; -@Mapper + public class ProviderBinaryClient extends ApplicationBootstrap { + private BinaryEndPoint client; private AddressPair remoteAddress; - private String token; + private ProviderBinaryHandler providerBinaryHandler; + private NettySession session; public ProviderBinaryClient(String remoteIp, int port) throws Exception { this.remoteAddress = AddressPair.withIP(remoteIp, port); + providerBinaryHandler = new ProviderBinaryHandler(); Router router = Router.empty(BinaryMessage.class, BinaryRequest.class) - .registerMapperClass(ProviderBinaryClient.class, (c) -> this); + .registerMapperClass(ProviderBinaryHandler.class, (c) -> providerBinaryHandler); this.client = BinaryEndPoint.client() .router(router) - .timeoutSeconds(5) .autoReconnect(10) .onConnected((s, b) -> onConnected(s, b)) .build(); } - private void onConnected(NettySession session, Boolean connectedOrNot) { + public void sendMsgWithTags(List tags, byte[] bytes) { + if(this.session == null || !this.session.writable()){ + //todo + return; + } + ReqPushMsgToPipelineWithTagsMsg msg = new ReqPushMsgToPipelineWithTagsMsg(); + msg.bytes = bytes; + msg.tags = tags; + session.writeNow(msg); + } + + public void sendMsg(String zone, byte[] bytes) { + if(this.session == null || !this.session.writable()){ + //todo + return; + } + ReqPushMsgToPipelineMsg msg = new ReqPushMsgToPipelineMsg(); + msg.zone = zone; + msg.bytes = bytes; + session.writeNow(msg); + } + + public void broadcastMsgWithTags(List tags, byte[] bytes) { + if(this.session == null || !this.session.writable()){ + //todo + return; + } + ReqBroadcastMsgToPipelineWithTagsMsg msg = new ReqBroadcastMsgToPipelineWithTagsMsg(); + msg.bytes = bytes; + msg.tags = tags; + session.writeNow(msg); + } + public void broadcastMsg(byte[] bytes) { + if(this.session == null || !this.session.writable()){ + //todo + return; + } + Conditions.notNull(bytes); + ReqBroadcastMsgToPipelineMsg msg = new ReqBroadcastMsgToPipelineMsg(); + msg.bytes = bytes; + session.writeNow(msg); + } + + private void onConnected(NettySession session, Boolean connectedOrNot) { + if (connectedOrNot) { + this.session = session; + } else { + this.session = null; + } } @Override @@ -40,7 +99,14 @@ public class ProviderBinaryClient extends ApplicationBootstrap { @Override protected void onDestroy(String[] args) { - this.client.stop(); } + + @Mapper + private class ProviderBinaryHandler { + + public void onHeartBeat(@Request ReqHeartBeatMsg msg, BinaryRequest request) { + request.session().writeNow(ResHeartBeatMsg.INSTANCE); + } + } } diff --git a/game/src/main/java/top/limitart/game/poker/TexasPokerCalculator.java b/game/src/main/java/top/limitart/game/poker/TexasPokerCalculator.java index b597826..53b8585 100644 --- a/game/src/main/java/top/limitart/game/poker/TexasPokerCalculator.java +++ b/game/src/main/java/top/limitart/game/poker/TexasPokerCalculator.java @@ -17,7 +17,7 @@ package top.limitart.game.poker; import top.limitart.util.CollectionUtil; import top.limitart.util.EnumUtil; -import top.limitart.util.GameMathUtil; +import top.limitart.util.MathUtil; import java.util.ArrayList; import java.util.List; @@ -86,7 +86,7 @@ public class TexasPokerCalculator { sum.add(tableCard); } // 从所有牌中任意选取五张的集合 - List> cnm = GameMathUtil.CNM(sum, 5); + List> cnm = MathUtil.CNM(sum, 5); // 所有组合中牌型最大的一种 long maxValue = 0; TexasPokerCalculator maxEval = null; diff --git a/game/src/test/java/top/limitart/game/poker/PokersTest.java b/game/src/test/java/top/limitart/game/poker/PokersTest.java index 3ec73ce..858a04c 100644 --- a/game/src/test/java/top/limitart/game/poker/PokersTest.java +++ b/game/src/test/java/top/limitart/game/poker/PokersTest.java @@ -5,7 +5,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; import top.limitart.util.CollectionUtil; -import top.limitart.util.GameMathUtil; +import top.limitart.util.MathUtil; import top.limitart.util.StringUtil; import java.util.ArrayList; @@ -28,7 +28,7 @@ public class PokersTest { break; } } - fiveCards = GameMathUtil.CNM(bytes, 5); + fiveCards = MathUtil.CNM(bytes, 5); } @After diff --git a/pipeline-token.tmp b/pipeline-token.tmp new file mode 100644 index 0000000..7c1f7b1 --- /dev/null +++ b/pipeline-token.tmp @@ -0,0 +1 @@ +68785719AFEF4B4CB46093088F03DFBD \ No newline at end of file -- Gitee From 0a882f90129800b72628356771cdf6ec3e6536b1 Mon Sep 17 00:00:00 2001 From: hank <104381832> Date: Mon, 3 Feb 2020 15:07:03 +0800 Subject: [PATCH 08/11] 1 --- .../fastmq/pipeline/PipelineBinaryServer.java | 3 +- fastmq/pom.xml | 11 +----- pom.xml | 1 + rpc/pom.xml | 36 +++++++++++++++++++ rpc/service-center/pom.xml | 15 ++++++++ rpc/service-consumer/pom.xml | 15 ++++++++ rpc/service-provider/pom.xml | 15 ++++++++ service-center/pom.xml | 15 ++++++++ service-consumer/pom.xml | 15 ++++++++ service-provider/pom.xml | 15 ++++++++ 10 files changed, 129 insertions(+), 12 deletions(-) create mode 100644 rpc/pom.xml create mode 100644 rpc/service-center/pom.xml create mode 100644 rpc/service-consumer/pom.xml create mode 100644 rpc/service-provider/pom.xml create mode 100644 service-center/pom.xml create mode 100644 service-consumer/pom.xml create mode 100644 service-provider/pom.xml diff --git a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/PipelineBinaryServer.java b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/PipelineBinaryServer.java index 2c17bdc..184fcac 100644 --- a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/PipelineBinaryServer.java +++ b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/PipelineBinaryServer.java @@ -4,7 +4,6 @@ import io.netty.channel.EventLoop; import io.netty.util.concurrent.ScheduledFuture; import java.io.IOException; import java.util.HashSet; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -231,7 +230,7 @@ public class PipelineBinaryServer extends ApplicationBootstrap { List bytes = buffer.peekAtMost(pullNum); if (bytes.isEmpty()) { if (prs.containsKey(zone)) { - LOGGER.warn("session {} , zone {} has no msg , hangout but already", session, zone); + LOGGER.debug("session {} , zone {} has no msg , hangout but already", session, zone); return; } prs.put(zone, new PipelineBinarySession(session, pullNum)); diff --git a/fastmq/pom.xml b/fastmq/pom.xml index e1d3fe6..3cb5ac9 100644 --- a/fastmq/pom.xml +++ b/fastmq/pom.xml @@ -15,15 +15,6 @@ pipeline consumer provider - common + common - - - - ${project.groupId} - limitart-core - ${project.version} - - - \ No newline at end of file diff --git a/pom.xml b/pom.xml index a4a4454..8558416 100644 --- a/pom.xml +++ b/pom.xml @@ -32,6 +32,7 @@ project-starter project-logic fastmq + rpc http://maven.limitart.top diff --git a/rpc/pom.xml b/rpc/pom.xml new file mode 100644 index 0000000..a67dcbd --- /dev/null +++ b/rpc/pom.xml @@ -0,0 +1,36 @@ + + + + limitart + top.limitart + 3.2.0-SNAPSHOT + + 4.0.0 + + limitart-rpc + pom + + service-center + service-provider + service-consumer + + + + ${project.groupId} + limitart-fastmq + ${project.version} + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-jdk14 + test + + + + \ No newline at end of file diff --git a/rpc/service-center/pom.xml b/rpc/service-center/pom.xml new file mode 100644 index 0000000..581f95f --- /dev/null +++ b/rpc/service-center/pom.xml @@ -0,0 +1,15 @@ + + + + limitart-rpc + top.limitart + 3.2.0-SNAPSHOT + + 4.0.0 + + limitart-rpc-service-center + + + \ No newline at end of file diff --git a/rpc/service-consumer/pom.xml b/rpc/service-consumer/pom.xml new file mode 100644 index 0000000..dc7e8cf --- /dev/null +++ b/rpc/service-consumer/pom.xml @@ -0,0 +1,15 @@ + + + + limitart-rpc + top.limitart + 3.2.0-SNAPSHOT + + 4.0.0 + + limitart-rpc-service-consumer + + + \ No newline at end of file diff --git a/rpc/service-provider/pom.xml b/rpc/service-provider/pom.xml new file mode 100644 index 0000000..73d16bb --- /dev/null +++ b/rpc/service-provider/pom.xml @@ -0,0 +1,15 @@ + + + + limitart-rpc + top.limitart + 3.2.0-SNAPSHOT + + 4.0.0 + + limitart-rpc-service-provider + + + \ No newline at end of file diff --git a/service-center/pom.xml b/service-center/pom.xml new file mode 100644 index 0000000..d36b495 --- /dev/null +++ b/service-center/pom.xml @@ -0,0 +1,15 @@ + + + + limitart + top.limitart + 3.2.0-SNAPSHOT + + 4.0.0 + + limitart-rpc-service-center + + + \ No newline at end of file diff --git a/service-consumer/pom.xml b/service-consumer/pom.xml new file mode 100644 index 0000000..4e350cb --- /dev/null +++ b/service-consumer/pom.xml @@ -0,0 +1,15 @@ + + + + limitart + top.limitart + 3.2.0-SNAPSHOT + + 4.0.0 + + limitart-rpc-service-consumer + + + \ No newline at end of file diff --git a/service-provider/pom.xml b/service-provider/pom.xml new file mode 100644 index 0000000..c7ef87b --- /dev/null +++ b/service-provider/pom.xml @@ -0,0 +1,15 @@ + + + + limitart + top.limitart + 3.2.0-SNAPSHOT + + 4.0.0 + + limitart-rpc-service-provider + + + \ No newline at end of file -- Gitee From 248c7208d59ec9e12d7d713261ef8d2b65fab5a7 Mon Sep 17 00:00:00 2001 From: hank <104381832> Date: Mon, 3 Feb 2020 21:27:11 +0800 Subject: [PATCH 09/11] 1 --- .../{ => demo}/script/HelloScriptImpl.java | 2 +- .../limitart/demo/base/EnumBehaviorDemo.java | 13 + .../collections/ConcurrentLRUCacheDemo.java | 58 + .../{ => demo}/collections/RankMapDemo.java | 3 +- .../demo/concurrent/TaskQueueCronDemo.java | 34 + .../limitart/demo/config/ConfigMetaDemo.java | 14 + .../top/limitart/demo/config/D_ChipRank.java | 44 + .../top/limitart/demo/config/D_WinRank.java | 56 + .../{ => demo}/config/DataTypeDemo.java | 4 +- .../limitart/demo/config/ExcelModelDemo.java | 35 + .../limitart/{ => demo}/config/Person.java | 2 +- .../{ => demo}/config/PersonDataType.java | 3 +- .../demo}/base/EnumBehaviorDemo.java | 2 +- .../collections/ConcurrentLRUCacheDemo.java | 2 +- .../demo/demo/collections/RankMapDemo.java | 82 + .../demo}/concurrent/TaskQueueCronDemo.java | 2 +- .../demo}/config/ConfigMetaDemo.java | 2 +- .../{ => demo/demo}/config/D_ChipRank.java | 2 +- .../{ => demo/demo}/config/D_WinRank.java | 2 +- .../demo/demo/config/DataTypeDemo.java | 45 + .../demo}/config/ExcelModelDemo.java | 2 +- .../top/limitart/demo/demo/config/Person.java | 48 + .../demo/demo/config/PersonDataType.java | 52 + .../{ => demo/demo}/event/EventDemo.java | 2 +- .../demo}/event/EventProviderDemo.java | 4 +- .../demo/fastmq/PipelineConsumerDemo.java | 39 + .../demo/fastmq/PipelineProviderDemo.java | 35 + .../demo/demo/fastmq/PipelineServerDemo.java | 22 + .../{ => demo/demo}/game/htb/HTBDemo.java | 14 +- .../{ => demo/demo}/game/htb/HTBRoleDemo.java | 2 +- .../demo}/game/htb/HTBTableDemo.java | 2 +- .../demo}/game/scene8/SceneDemo.java | 4 +- .../{ => demo/demo}/logging/LoggerDemo.java | 2 +- .../{ => demo/demo}/mapping/RouterDemo.java | 2 +- .../demo}/mapping/StringMapperClass.java | 2 +- .../{ => demo/demo}/mapping/StringPoster.java | 2 +- .../demo}/mapping/StringQuestParam.java | 2 +- .../demo}/mapping/StringRequest.java | 2 +- .../demo/demo/net/BinaryClientDemo.java | 42 + .../demo/demo/net/BinaryMessageDemo.java | 28 + .../demo/demo/net/BinaryMessageDemo2.java | 29 + .../demo/demo/net/BinaryScriptManager.java | 26 + .../demo/net/BinaryScriptManagerImpl.java | 27 + .../demo/demo/net/BinaryServerDemo.java | 49 + .../demo/demo/net/BinarySessionRole.java | 6 + .../demo/demo/net/FlashSSLServerDemo.java | 13 + .../{ => demo/demo}/net/HTTPSServerDemo.java | 2 +- .../demo/demo/net/HTTPServerDemo.java | 41 + .../demo/demo/net/LocalEndPointDemo.java | 39 + .../limitart/demo/demo/net/MessageMapper.java | 47 + .../demo/demo/net/MessagePackageTest.java | 96 ++ .../demo/demo/net/ProtobufClientDemo.java | 30 + .../demo}/net/ProtobufMessageDemo.java | 2 +- .../demo/demo/net/ProtobufServerDemo.java | 46 + .../demo}/net/ProtobufSessionRole.java | 2 +- .../demo}/net/WebSocketServerDemo.java | 9 +- .../demo}/redefinable/HelloRedefine.java | 2 +- .../demo}/redefinable/RedefinableDemo.java | 2 +- .../demo}/redefinable/ScriptEntrance.java | 2 +- .../demo}/script/AutoReloadScriptDemo.java | 2 +- .../{ => demo/demo}/script/HelloScript.java | 2 +- .../demo}/script/ScriptSourceDemo.java | 2 +- .../{ => demo/demo}/singleton/SingletonA.java | 2 +- .../{ => demo/demo}/singleton/SingletonB.java | 2 +- .../{ => demo/demo}/singleton/SingletonC.java | 2 +- .../{ => demo/demo}/singleton/SingletonD.java | 2 +- .../demo}/singleton/SingletonDemo.java | 2 +- .../top/limitart/demo/event/EventDemo.java | 19 + .../demo/event/EventProviderDemo.java | 34 + .../fastmq/PipelineConsumerDemo.java | 8 +- .../fastmq/PipelineProviderDemo.java | 8 +- .../{ => demo}/fastmq/PipelineServerDemo.java | 8 +- .../top/limitart/demo/logging/LoggerDemo.java | 27 + .../top/limitart/demo/mapping/RouterDemo.java | 19 + .../demo/mapping/StringMapperClass.java | 15 + .../limitart/demo/mapping/StringPoster.java | 7 + .../demo/mapping/StringQuestParam.java | 10 + .../limitart/demo/mapping/StringRequest.java | 17 + .../{ => demo}/net/BinaryClientDemo.java | 6 +- .../{ => demo}/net/BinaryMessageDemo.java | 2 +- .../{ => demo}/net/BinaryMessageDemo2.java | 2 +- .../{ => demo}/net/BinaryScriptManager.java | 2 +- .../net/BinaryScriptManagerImpl.java | 2 +- .../{ => demo}/net/BinaryServerDemo.java | 4 +- .../{ => demo}/net/BinarySessionRole.java | 3 +- .../{ => demo}/net/FlashSSLServerDemo.java | 3 +- .../limitart/demo/net/HTTPSServerDemo.java | 25 + .../{ => demo}/net/HTTPServerDemo.java | 3 +- .../{ => demo}/net/LocalEndPointDemo.java | 5 +- .../{ => demo}/net/MessageMapper.java | 4 +- .../{ => demo}/net/MessagePackageTest.java | 2 +- .../{ => demo}/net/ProtobufClientDemo.java | 4 +- .../demo/net/ProtobufMessageDemo.java | 1334 +++++++++++++++++ .../{ => demo}/net/ProtobufServerDemo.java | 4 +- .../demo/net/ProtobufSessionRole.java | 7 + .../demo/net/WebSocketServerDemo.java | 56 + .../demo/redefinable/HelloRedefine.java | 7 + .../demo/redefinable/RedefinableDemo.java | 11 + .../demo/redefinable/ScriptEntrance.java | 24 + .../demo/script/AutoReloadScriptDemo.java | 36 + .../top/limitart/demo/script/HelloScript.java | 27 + .../demo/script/ScriptSourceDemo.java | 42 + .../limitart/demo/singleton/SingletonA.java | 14 + .../limitart/demo/singleton/SingletonB.java | 20 + .../limitart/demo/singleton/SingletonC.java | 34 + .../limitart/demo/singleton/SingletonD.java | 36 + .../demo/singleton/SingletonDemo.java | 30 + ...lient.java => MQConsumerBinaryClient.java} | 25 +- .../fastmq/pipeline/AbstractBinaryServer.java | 7 - ...erver.java => MQPipelineBinaryServer.java} | 20 +- ...tServer.java => MQPipelineRestServer.java} | 2 +- ...lient.java => MQProviderBinaryClient.java} | 4 +- game/limitart-game.iml | 42 + pom.xml | 2 +- rpc/pom.xml | 18 +- rpc/service-center/pom.xml | 22 +- .../top/limitart/rpc/RPCServiceCenter.java | 28 + rpc/service-common/pom.xml | 21 + .../top/limitart/rpc/srvcommon/RPCMeta.java | 233 +++ .../limitart/rpc/srvcommon/RPCService.java | 35 + .../srvcommon/RPCServiceExecuteException.java | 33 + .../rpc/srvcommon/RPCServiceIOException.java | 36 + .../srvcommon/RPCServiceProxyException.java | 33 + .../rpc/srvcommon/RpcExecuteClientMsg.java | 68 + .../rpc/srvcommon/RpcResultServerMsg.java | 95 ++ .../top/limitart/rpc/srvcommon/RpcUtil.java | 73 + rpc/service-consumer/pom.xml | 27 +- .../rpc/srvconsumer/RPCServiceConsumer.java | 320 ++++ .../rpc/srvconsumer/RemoteFuture.java | 51 + rpc/service-provider/pom.xml | 32 +- .../rpc/srvprovider/RPCServiceProvider.java | 296 ++++ .../rpc/srvprovider/RpcServiceInstance.java | 47 + 132 files changed, 4560 insertions(+), 132 deletions(-) rename demo/script/top/limitart/{ => demo}/script/HelloScriptImpl.java (87%) create mode 100644 demo/src/main/java/top/limitart/demo/base/EnumBehaviorDemo.java create mode 100644 demo/src/main/java/top/limitart/demo/collections/ConcurrentLRUCacheDemo.java rename demo/src/main/java/top/limitart/{ => demo}/collections/RankMapDemo.java (95%) create mode 100644 demo/src/main/java/top/limitart/demo/concurrent/TaskQueueCronDemo.java create mode 100644 demo/src/main/java/top/limitart/demo/config/ConfigMetaDemo.java create mode 100644 demo/src/main/java/top/limitart/demo/config/D_ChipRank.java create mode 100644 demo/src/main/java/top/limitart/demo/config/D_WinRank.java rename demo/src/main/java/top/limitart/{ => demo}/config/DataTypeDemo.java (92%) create mode 100644 demo/src/main/java/top/limitart/demo/config/ExcelModelDemo.java rename demo/src/main/java/top/limitart/{ => demo}/config/Person.java (97%) rename demo/src/main/java/top/limitart/{ => demo}/config/PersonDataType.java (94%) rename demo/src/main/java/top/limitart/{ => demo/demo}/base/EnumBehaviorDemo.java (80%) rename demo/src/main/java/top/limitart/{ => demo/demo}/collections/ConcurrentLRUCacheDemo.java (97%) create mode 100644 demo/src/main/java/top/limitart/demo/demo/collections/RankMapDemo.java rename demo/src/main/java/top/limitart/{ => demo/demo}/concurrent/TaskQueueCronDemo.java (97%) rename demo/src/main/java/top/limitart/{ => demo/demo}/config/ConfigMetaDemo.java (84%) rename demo/src/main/java/top/limitart/{ => demo/demo}/config/D_ChipRank.java (96%) rename demo/src/main/java/top/limitart/{ => demo/demo}/config/D_WinRank.java (97%) create mode 100644 demo/src/main/java/top/limitart/demo/demo/config/DataTypeDemo.java rename demo/src/main/java/top/limitart/{ => demo/demo}/config/ExcelModelDemo.java (96%) create mode 100644 demo/src/main/java/top/limitart/demo/demo/config/Person.java create mode 100644 demo/src/main/java/top/limitart/demo/demo/config/PersonDataType.java rename demo/src/main/java/top/limitart/{ => demo/demo}/event/EventDemo.java (87%) rename demo/src/main/java/top/limitart/{ => demo/demo}/event/EventProviderDemo.java (91%) create mode 100644 demo/src/main/java/top/limitart/demo/demo/fastmq/PipelineConsumerDemo.java create mode 100644 demo/src/main/java/top/limitart/demo/demo/fastmq/PipelineProviderDemo.java create mode 100644 demo/src/main/java/top/limitart/demo/demo/fastmq/PipelineServerDemo.java rename demo/src/main/java/top/limitart/{ => demo/demo}/game/htb/HTBDemo.java (82%) rename demo/src/main/java/top/limitart/{ => demo/demo}/game/htb/HTBRoleDemo.java (96%) rename demo/src/main/java/top/limitart/{ => demo/demo}/game/htb/HTBTableDemo.java (96%) rename demo/src/main/java/top/limitart/{ => demo/demo}/game/scene8/SceneDemo.java (96%) rename demo/src/main/java/top/limitart/{ => demo/demo}/logging/LoggerDemo.java (95%) rename demo/src/main/java/top/limitart/{ => demo/demo}/mapping/RouterDemo.java (94%) rename demo/src/main/java/top/limitart/{ => demo/demo}/mapping/StringMapperClass.java (86%) rename demo/src/main/java/top/limitart/{ => demo/demo}/mapping/StringPoster.java (71%) rename demo/src/main/java/top/limitart/{ => demo/demo}/mapping/StringQuestParam.java (77%) rename demo/src/main/java/top/limitart/{ => demo/demo}/mapping/StringRequest.java (86%) create mode 100644 demo/src/main/java/top/limitart/demo/demo/net/BinaryClientDemo.java create mode 100644 demo/src/main/java/top/limitart/demo/demo/net/BinaryMessageDemo.java create mode 100644 demo/src/main/java/top/limitart/demo/demo/net/BinaryMessageDemo2.java create mode 100644 demo/src/main/java/top/limitart/demo/demo/net/BinaryScriptManager.java create mode 100644 demo/src/main/java/top/limitart/demo/demo/net/BinaryScriptManagerImpl.java create mode 100644 demo/src/main/java/top/limitart/demo/demo/net/BinaryServerDemo.java create mode 100644 demo/src/main/java/top/limitart/demo/demo/net/BinarySessionRole.java create mode 100644 demo/src/main/java/top/limitart/demo/demo/net/FlashSSLServerDemo.java rename demo/src/main/java/top/limitart/{ => demo/demo}/net/HTTPSServerDemo.java (95%) create mode 100644 demo/src/main/java/top/limitart/demo/demo/net/HTTPServerDemo.java create mode 100644 demo/src/main/java/top/limitart/demo/demo/net/LocalEndPointDemo.java create mode 100644 demo/src/main/java/top/limitart/demo/demo/net/MessageMapper.java create mode 100644 demo/src/main/java/top/limitart/demo/demo/net/MessagePackageTest.java create mode 100644 demo/src/main/java/top/limitart/demo/demo/net/ProtobufClientDemo.java rename demo/src/main/java/top/limitart/{ => demo/demo}/net/ProtobufMessageDemo.java (99%) create mode 100644 demo/src/main/java/top/limitart/demo/demo/net/ProtobufServerDemo.java rename demo/src/main/java/top/limitart/{ => demo/demo}/net/ProtobufSessionRole.java (78%) rename demo/src/main/java/top/limitart/{ => demo/demo}/net/WebSocketServerDemo.java (88%) rename demo/src/main/java/top/limitart/{ => demo/demo}/redefinable/HelloRedefine.java (71%) rename demo/src/main/java/top/limitart/{ => demo/demo}/redefinable/RedefinableDemo.java (88%) rename demo/src/main/java/top/limitart/{ => demo/demo}/redefinable/ScriptEntrance.java (93%) rename demo/src/main/java/top/limitart/{ => demo/demo}/script/AutoReloadScriptDemo.java (97%) rename demo/src/main/java/top/limitart/{ => demo/demo}/script/HelloScript.java (95%) rename demo/src/main/java/top/limitart/{ => demo/demo}/script/ScriptSourceDemo.java (97%) rename demo/src/main/java/top/limitart/{ => demo/demo}/singleton/SingletonA.java (78%) rename demo/src/main/java/top/limitart/{ => demo/demo}/singleton/SingletonB.java (87%) rename demo/src/main/java/top/limitart/{ => demo/demo}/singleton/SingletonC.java (95%) rename demo/src/main/java/top/limitart/{ => demo/demo}/singleton/SingletonD.java (96%) rename demo/src/main/java/top/limitart/{ => demo/demo}/singleton/SingletonDemo.java (92%) create mode 100644 demo/src/main/java/top/limitart/demo/event/EventDemo.java create mode 100644 demo/src/main/java/top/limitart/demo/event/EventProviderDemo.java rename demo/src/main/java/top/limitart/{ => demo}/fastmq/PipelineConsumerDemo.java (81%) rename demo/src/main/java/top/limitart/{ => demo}/fastmq/PipelineProviderDemo.java (78%) rename demo/src/main/java/top/limitart/{ => demo}/fastmq/PipelineServerDemo.java (60%) create mode 100644 demo/src/main/java/top/limitart/demo/logging/LoggerDemo.java create mode 100644 demo/src/main/java/top/limitart/demo/mapping/RouterDemo.java create mode 100644 demo/src/main/java/top/limitart/demo/mapping/StringMapperClass.java create mode 100644 demo/src/main/java/top/limitart/demo/mapping/StringPoster.java create mode 100644 demo/src/main/java/top/limitart/demo/mapping/StringQuestParam.java create mode 100644 demo/src/main/java/top/limitart/demo/mapping/StringRequest.java rename demo/src/main/java/top/limitart/{ => demo}/net/BinaryClientDemo.java (89%) rename demo/src/main/java/top/limitart/{ => demo}/net/BinaryMessageDemo.java (96%) rename demo/src/main/java/top/limitart/{ => demo}/net/BinaryMessageDemo2.java (96%) rename demo/src/main/java/top/limitart/{ => demo}/net/BinaryScriptManager.java (96%) rename demo/src/main/java/top/limitart/{ => demo}/net/BinaryScriptManagerImpl.java (96%) rename demo/src/main/java/top/limitart/{ => demo}/net/BinaryServerDemo.java (94%) rename demo/src/main/java/top/limitart/{ => demo}/net/BinarySessionRole.java (62%) rename demo/src/main/java/top/limitart/{ => demo}/net/FlashSSLServerDemo.java (80%) create mode 100644 demo/src/main/java/top/limitart/demo/net/HTTPSServerDemo.java rename demo/src/main/java/top/limitart/{ => demo}/net/HTTPServerDemo.java (95%) rename demo/src/main/java/top/limitart/{ => demo}/net/LocalEndPointDemo.java (87%) rename demo/src/main/java/top/limitart/{ => demo}/net/MessageMapper.java (93%) rename demo/src/main/java/top/limitart/{ => demo}/net/MessagePackageTest.java (98%) rename demo/src/main/java/top/limitart/{ => demo}/net/ProtobufClientDemo.java (88%) create mode 100644 demo/src/main/java/top/limitart/demo/net/ProtobufMessageDemo.java rename demo/src/main/java/top/limitart/{ => demo}/net/ProtobufServerDemo.java (93%) create mode 100644 demo/src/main/java/top/limitart/demo/net/ProtobufSessionRole.java create mode 100644 demo/src/main/java/top/limitart/demo/net/WebSocketServerDemo.java create mode 100644 demo/src/main/java/top/limitart/demo/redefinable/HelloRedefine.java create mode 100644 demo/src/main/java/top/limitart/demo/redefinable/RedefinableDemo.java create mode 100644 demo/src/main/java/top/limitart/demo/redefinable/ScriptEntrance.java create mode 100644 demo/src/main/java/top/limitart/demo/script/AutoReloadScriptDemo.java create mode 100644 demo/src/main/java/top/limitart/demo/script/HelloScript.java create mode 100644 demo/src/main/java/top/limitart/demo/script/ScriptSourceDemo.java create mode 100644 demo/src/main/java/top/limitart/demo/singleton/SingletonA.java create mode 100644 demo/src/main/java/top/limitart/demo/singleton/SingletonB.java create mode 100644 demo/src/main/java/top/limitart/demo/singleton/SingletonC.java create mode 100644 demo/src/main/java/top/limitart/demo/singleton/SingletonD.java create mode 100644 demo/src/main/java/top/limitart/demo/singleton/SingletonDemo.java rename fastmq/consumer/src/main/java/top/limitart/fastmq/consumer/{ConsumerBinaryClient.java => MQConsumerBinaryClient.java} (91%) delete mode 100644 fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/AbstractBinaryServer.java rename fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/{PipelineBinaryServer.java => MQPipelineBinaryServer.java} (94%) rename fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/{PipelineRestServer.java => MQPipelineRestServer.java} (53%) rename fastmq/provider/src/main/java/top/limitart/fastmq/provider/{ProviderBinaryClient.java => MQProviderBinaryClient.java} (95%) create mode 100644 game/limitart-game.iml create mode 100644 rpc/service-center/src/main/java/top/limitart/rpc/RPCServiceCenter.java create mode 100644 rpc/service-common/pom.xml create mode 100644 rpc/service-common/src/main/java/top/limitart/rpc/srvcommon/RPCMeta.java create mode 100644 rpc/service-common/src/main/java/top/limitart/rpc/srvcommon/RPCService.java create mode 100644 rpc/service-common/src/main/java/top/limitart/rpc/srvcommon/RPCServiceExecuteException.java create mode 100644 rpc/service-common/src/main/java/top/limitart/rpc/srvcommon/RPCServiceIOException.java create mode 100644 rpc/service-common/src/main/java/top/limitart/rpc/srvcommon/RPCServiceProxyException.java create mode 100644 rpc/service-common/src/main/java/top/limitart/rpc/srvcommon/RpcExecuteClientMsg.java create mode 100644 rpc/service-common/src/main/java/top/limitart/rpc/srvcommon/RpcResultServerMsg.java create mode 100644 rpc/service-common/src/main/java/top/limitart/rpc/srvcommon/RpcUtil.java create mode 100644 rpc/service-consumer/src/main/java/top/limitart/rpc/srvconsumer/RPCServiceConsumer.java create mode 100644 rpc/service-consumer/src/main/java/top/limitart/rpc/srvconsumer/RemoteFuture.java create mode 100644 rpc/service-provider/src/main/java/top/limitart/rpc/srvprovider/RPCServiceProvider.java create mode 100644 rpc/service-provider/src/main/java/top/limitart/rpc/srvprovider/RpcServiceInstance.java diff --git a/demo/script/top/limitart/script/HelloScriptImpl.java b/demo/script/top/limitart/demo/script/HelloScriptImpl.java similarity index 87% rename from demo/script/top/limitart/script/HelloScriptImpl.java rename to demo/script/top/limitart/demo/script/HelloScriptImpl.java index 3a50352..d2804e7 100644 --- a/demo/script/top/limitart/script/HelloScriptImpl.java +++ b/demo/script/top/limitart/demo/script/HelloScriptImpl.java @@ -1,4 +1,4 @@ -package top.limitart.script; +package top.limitart.demo.script; public class HelloScriptImpl implements HelloScript { @Override diff --git a/demo/src/main/java/top/limitart/demo/base/EnumBehaviorDemo.java b/demo/src/main/java/top/limitart/demo/base/EnumBehaviorDemo.java new file mode 100644 index 0000000..7f66ca3 --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/base/EnumBehaviorDemo.java @@ -0,0 +1,13 @@ +package top.limitart.demo.base; + +import top.limitart.base.EnumBehavior; + +/** + * @author hank + * @version 2019/5/30 0030 17:28 + */ +public enum EnumBehaviorDemo implements EnumBehavior { + A, + B, + C, +} diff --git a/demo/src/main/java/top/limitart/demo/collections/ConcurrentLRUCacheDemo.java b/demo/src/main/java/top/limitart/demo/collections/ConcurrentLRUCacheDemo.java new file mode 100644 index 0000000..6fe1922 --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/collections/ConcurrentLRUCacheDemo.java @@ -0,0 +1,58 @@ +package top.limitart.demo.collections; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicInteger; +import top.limitart.collections.ConcurrentLRUCache; + +/** + * @author hank + * @version 2018/11/13 0013 21:31 + */ +public class ConcurrentLRUCacheDemo { + public static void main(String[] args) throws InterruptedException { + ConcurrentLRUCache cache = new ConcurrentLRUCache<>(5, true); + ExecutorService executorService = Executors.newCachedThreadPool(); + AtomicInteger counter = new AtomicInteger(0); + for (; ; ) { + try { + Thread.sleep(50); + } catch (InterruptedException e) { + e.printStackTrace(); + } + executorService.execute( + () -> { + int andIncrement = counter.getAndIncrement(); + cache.put(andIncrement, new CacheObj(andIncrement)); + }); + } + } + + public static class CacheObj extends ConcurrentLRUCache.LRUCacheable { + private int value; + + public CacheObj(int value) { + this.value = value; + } + + @Override + public String toString() { + return "CacheObj{" + "value=" + value + '}'; + } + + @Override + protected long aliveTime() { + return 1000; + } + + @Override + protected boolean removable0() { + return true; + } + + @Override + public void onRemoved(int currentSize) { + System.out.println("removed " + this); + } + } +} diff --git a/demo/src/main/java/top/limitart/collections/RankMapDemo.java b/demo/src/main/java/top/limitart/demo/collections/RankMapDemo.java similarity index 95% rename from demo/src/main/java/top/limitart/collections/RankMapDemo.java rename to demo/src/main/java/top/limitart/demo/collections/RankMapDemo.java index 4db5211..9b210cb 100644 --- a/demo/src/main/java/top/limitart/collections/RankMapDemo.java +++ b/demo/src/main/java/top/limitart/demo/collections/RankMapDemo.java @@ -1,8 +1,9 @@ -package top.limitart.collections; +package top.limitart.demo.collections; import top.limitart.base.CompareChain; import java.util.Comparator; +import top.limitart.collections.RankMap; public class RankMapDemo { private static final Comparator COMPARATOR = diff --git a/demo/src/main/java/top/limitart/demo/concurrent/TaskQueueCronDemo.java b/demo/src/main/java/top/limitart/demo/concurrent/TaskQueueCronDemo.java new file mode 100644 index 0000000..0040b5a --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/concurrent/TaskQueueCronDemo.java @@ -0,0 +1,34 @@ +package top.limitart.demo.concurrent; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.text.ParseException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import top.limitart.concurrent.TaskQueue; +import top.limitart.concurrent.TaskQueueGroup; + +/** + * @author hank + * @version 2018/12/11 0011 13:55 + */ +public class TaskQueueCronDemo { + private static Logger LOGGER = LoggerFactory.getLogger(TaskQueueCronDemo.class); + + public static void main(String[] args) throws ParseException, ExecutionException, InterruptedException { + TaskQueue queue = TaskQueue.create("test"); + queue.execute(()-> System.out.println("execute")); + queue.submit(()-> System.out.println("submit")).get(); + queue.schedule(()-> System.out.println("schedule"), 1, TimeUnit.SECONDS); + queue.schedule("cron1", "0 22 14 11 12 ? 2018", () -> System.out.println("tick1")); + queue.schedule("cron1", "*/5 * * * * ? *", () -> System.out.println("tick2")); + queue.schedule("cron1", "0 * * * * ? *", () -> System.out.println("tick3")); + + TaskQueueGroup group = new TaskQueueGroup("limitart",5,s->TaskQueue.create(s)); + group.next().execute(()-> System.out.println("execute1")); + group.next().execute(()-> System.out.println("execute2")); + group.next().execute(()-> System.out.println("execute3")); + group.next().execute(()-> System.out.println("execute4")); + } +} diff --git a/demo/src/main/java/top/limitart/demo/config/ConfigMetaDemo.java b/demo/src/main/java/top/limitart/demo/config/ConfigMetaDemo.java new file mode 100644 index 0000000..9a23cc1 --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/config/ConfigMetaDemo.java @@ -0,0 +1,14 @@ +package top.limitart.demo.config; + +import top.limitart.config.ConfigMeta; + +/** + * @author hank + * @version 2018/12/28 0028 11:19 + */ +public class ConfigMetaDemo extends ConfigMeta { + @Override + public Integer primaryKey() { + return null; + } +} diff --git a/demo/src/main/java/top/limitart/demo/config/D_ChipRank.java b/demo/src/main/java/top/limitart/demo/config/D_ChipRank.java new file mode 100644 index 0000000..7ce7855 --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/config/D_ChipRank.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2016-present The Limitart Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package top.limitart.demo.config; + +import top.limitart.config.ConfigMeta; + +/** + * 最高奖金排行奖励 from dat_proto at 2018-12-24T14:33:18.841 + * + * @author limitart + */ +public class D_ChipRank extends ConfigMeta { + /** 起始排名 */ + private int startRank; + /** 奖励数量 */ + private long count; + /** 起始排名 */ + public int getStartRank() { + return this.startRank; + } + /** 奖励数量 */ + public long getCount() { + return this.count; + } + + @Override + public Integer primaryKey() { + return this.startRank; + } +} diff --git a/demo/src/main/java/top/limitart/demo/config/D_WinRank.java b/demo/src/main/java/top/limitart/demo/config/D_WinRank.java new file mode 100644 index 0000000..3e05136 --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/config/D_WinRank.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2016-present The Limitart Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package top.limitart.demo.config; + +import top.limitart.config.ConfigMeta; + +/** + * 胜利场数排行奖励 from dat_proto at 2018-12-24T14:33:18.841 + * + * @author limitart + */ +public class D_WinRank extends ConfigMeta { + /** 起始排名 */ + private int startRank; + /** 奖励数量 */ + private long count; + /** 整型数组测试 */ + private int[] array; + /** 整型二维数组测试 */ + private int[][] array2; + /** 起始排名 */ + public int getStartRank() { + return this.startRank; + } + /** 奖励数量 */ + public long getCount() { + return this.count; + } + /** 整型数组测试 */ + public int[] getArray() { + return this.array; + } + /** 整型二维数组测试 */ + public int[][] getArray2() { + return this.array2; + } + + @Override + public Integer primaryKey() { + return this.startRank; + } +} diff --git a/demo/src/main/java/top/limitart/config/DataTypeDemo.java b/demo/src/main/java/top/limitart/demo/config/DataTypeDemo.java similarity index 92% rename from demo/src/main/java/top/limitart/config/DataTypeDemo.java rename to demo/src/main/java/top/limitart/demo/config/DataTypeDemo.java index 6def3a2..5de8c6b 100644 --- a/demo/src/main/java/top/limitart/config/DataTypeDemo.java +++ b/demo/src/main/java/top/limitart/demo/config/DataTypeDemo.java @@ -16,8 +16,10 @@ * */ -package top.limitart.config; +package top.limitart.demo.config; +import top.limitart.config.IntArray2DType; +import top.limitart.config.IntArrayType; import top.limitart.json.JSON; import top.limitart.util.CollectionUtil; diff --git a/demo/src/main/java/top/limitart/demo/config/ExcelModelDemo.java b/demo/src/main/java/top/limitart/demo/config/ExcelModelDemo.java new file mode 100644 index 0000000..07575cd --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/config/ExcelModelDemo.java @@ -0,0 +1,35 @@ +package top.limitart.demo.config; + +import java.util.Collections; +import java.util.Map; +import top.limitart.config.ConfigContainers; +import top.limitart.config.DataParser; +import top.limitart.config.ExcelModel; +import top.limitart.config.SheetHead; + +/** + * @author hank + * @version 2018/12/26 0026 21:20 + */ +public class ExcelModelDemo { + public static void main(String[] args) throws Exception { + DataParser parser = + new DataParser() { + @Override + protected void initDataType() {} + }; + ExcelModel excelModel = + ExcelModel.loadFromExcel( + parser, ExcelModel.class.getClassLoader().getResource("./dat_proto.xlsx").getPath()); + Map stringMap = excelModel.readData(SheetHead.CellHolder.all()); + ConfigContainers configContainers = + ConfigContainers.loadFromExcelModels( + "top.limitart.config", + Collections.singletonList(excelModel), + SheetHead.CellHolder.SERVER); + byte[] bytes = configContainers.toBytes(parser); + ConfigContainers configContainers1 = + ConfigContainers.loadFromBtyes("top.limitart.config", parser, bytes); + excelModel.close(); + } +} diff --git a/demo/src/main/java/top/limitart/config/Person.java b/demo/src/main/java/top/limitart/demo/config/Person.java similarity index 97% rename from demo/src/main/java/top/limitart/config/Person.java rename to demo/src/main/java/top/limitart/demo/config/Person.java index b9948af..805b050 100644 --- a/demo/src/main/java/top/limitart/config/Person.java +++ b/demo/src/main/java/top/limitart/demo/config/Person.java @@ -16,7 +16,7 @@ * */ -package top.limitart.config; +package top.limitart.demo.config; import top.limitart.base.BinaryMeta; diff --git a/demo/src/main/java/top/limitart/config/PersonDataType.java b/demo/src/main/java/top/limitart/demo/config/PersonDataType.java similarity index 94% rename from demo/src/main/java/top/limitart/config/PersonDataType.java rename to demo/src/main/java/top/limitart/demo/config/PersonDataType.java index 6c9ea37..241b442 100644 --- a/demo/src/main/java/top/limitart/config/PersonDataType.java +++ b/demo/src/main/java/top/limitart/demo/config/PersonDataType.java @@ -16,9 +16,10 @@ * */ -package top.limitart.config; +package top.limitart.demo.config; import top.limitart.base.BinaryMeta; +import top.limitart.config.JSONParsingType; /** Created by Hank on 2018/12/23 */ public class PersonDataType extends JSONParsingType { diff --git a/demo/src/main/java/top/limitart/base/EnumBehaviorDemo.java b/demo/src/main/java/top/limitart/demo/demo/base/EnumBehaviorDemo.java similarity index 80% rename from demo/src/main/java/top/limitart/base/EnumBehaviorDemo.java rename to demo/src/main/java/top/limitart/demo/demo/base/EnumBehaviorDemo.java index f42b921..880a986 100644 --- a/demo/src/main/java/top/limitart/base/EnumBehaviorDemo.java +++ b/demo/src/main/java/top/limitart/demo/demo/base/EnumBehaviorDemo.java @@ -1,4 +1,4 @@ -package top.limitart.base; +package top.limitart.demo.base; /** * @author hank diff --git a/demo/src/main/java/top/limitart/collections/ConcurrentLRUCacheDemo.java b/demo/src/main/java/top/limitart/demo/demo/collections/ConcurrentLRUCacheDemo.java similarity index 97% rename from demo/src/main/java/top/limitart/collections/ConcurrentLRUCacheDemo.java rename to demo/src/main/java/top/limitart/demo/demo/collections/ConcurrentLRUCacheDemo.java index b313af6..0572847 100644 --- a/demo/src/main/java/top/limitart/collections/ConcurrentLRUCacheDemo.java +++ b/demo/src/main/java/top/limitart/demo/demo/collections/ConcurrentLRUCacheDemo.java @@ -1,4 +1,4 @@ -package top.limitart.collections; +package top.limitart.demo.collections; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; diff --git a/demo/src/main/java/top/limitart/demo/demo/collections/RankMapDemo.java b/demo/src/main/java/top/limitart/demo/demo/collections/RankMapDemo.java new file mode 100644 index 0000000..7425a6a --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/demo/collections/RankMapDemo.java @@ -0,0 +1,82 @@ +package top.limitart.demo.collections; + +import top.limitart.demo.base.CompareChain; + +import java.util.Comparator; + +public class RankMapDemo { + private static final Comparator COMPARATOR = + CompareChain.build( + (o1, o2) -> CompareChain.start(o2.price * o2.item.getNum(), o1.price * o1.item.num)); + + public static void main(String[] args) { + RankMap rankMap = RankMap.create(COMPARATOR, 100); + Item i1 = new Item(2); + Bean b1 = new Bean(1, i1, 100); + Item i2 = new Item(3); + Bean b2 = new Bean(2, i2, 100); + Item i3 = new Item(3); + Bean b3 = new Bean(3, i3, 500); + Item i4 = new Item(3); + rankMap.putIfAbsent(b1); + rankMap.putIfAbsent(b2); + System.out.println(rankMap.getAll()); + rankMap.update(b1.key(), v -> v.price = 200); + System.out.println(rankMap.getAll()); + rankMap.putIfAbsent(b3); + System.out.println(rankMap.getAll()); + rankMap.updateOrPut(4L, v -> v.price = 1, () -> new Bean(4, i4, 1)); + System.out.println(rankMap.getAll()); + } + + public static class Bean implements RankMap.LongRankObj { + private long id; + private Item item; + private int price; + + public Bean(long id, Item item, int price) { + this.item = item; + this.price = price; + this.id = id; + } + + public Bean copy() { + return new Bean(this.id, this.item.copy(), this.price); + } + + @Override + public Long key() { + return id; + } + + @Override + public String toString() { + return "Bean{" + "id=" + id + ", item=" + item + ", price=" + price + '}'; + } + } + + public static class Item { + private int num; + + public Item copy() { + return new Item(num); + } + + public Item(int num) { + this.num = num; + } + + public int getNum() { + return num; + } + + public void setNum(int num) { + this.num = num; + } + + @Override + public String toString() { + return "Item{" + "num=" + num + '}'; + } + } +} diff --git a/demo/src/main/java/top/limitart/concurrent/TaskQueueCronDemo.java b/demo/src/main/java/top/limitart/demo/demo/concurrent/TaskQueueCronDemo.java similarity index 97% rename from demo/src/main/java/top/limitart/concurrent/TaskQueueCronDemo.java rename to demo/src/main/java/top/limitart/demo/demo/concurrent/TaskQueueCronDemo.java index 6dd7184..8437f54 100644 --- a/demo/src/main/java/top/limitart/concurrent/TaskQueueCronDemo.java +++ b/demo/src/main/java/top/limitart/demo/demo/concurrent/TaskQueueCronDemo.java @@ -1,4 +1,4 @@ -package top.limitart.concurrent; +package top.limitart.demo.concurrent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/demo/src/main/java/top/limitart/config/ConfigMetaDemo.java b/demo/src/main/java/top/limitart/demo/demo/config/ConfigMetaDemo.java similarity index 84% rename from demo/src/main/java/top/limitart/config/ConfigMetaDemo.java rename to demo/src/main/java/top/limitart/demo/demo/config/ConfigMetaDemo.java index cf0519e..f88a458 100644 --- a/demo/src/main/java/top/limitart/config/ConfigMetaDemo.java +++ b/demo/src/main/java/top/limitart/demo/demo/config/ConfigMetaDemo.java @@ -1,4 +1,4 @@ -package top.limitart.config; +package top.limitart.demo.config; /** * @author hank diff --git a/demo/src/main/java/top/limitart/config/D_ChipRank.java b/demo/src/main/java/top/limitart/demo/demo/config/D_ChipRank.java similarity index 96% rename from demo/src/main/java/top/limitart/config/D_ChipRank.java rename to demo/src/main/java/top/limitart/demo/demo/config/D_ChipRank.java index 0bdf3ed..6165c56 100644 --- a/demo/src/main/java/top/limitart/config/D_ChipRank.java +++ b/demo/src/main/java/top/limitart/demo/demo/config/D_ChipRank.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package top.limitart.config; +package top.limitart.demo.config; /** * 最高奖金排行奖励 from dat_proto at 2018-12-24T14:33:18.841 diff --git a/demo/src/main/java/top/limitart/config/D_WinRank.java b/demo/src/main/java/top/limitart/demo/demo/config/D_WinRank.java similarity index 97% rename from demo/src/main/java/top/limitart/config/D_WinRank.java rename to demo/src/main/java/top/limitart/demo/demo/config/D_WinRank.java index 4bdbe13..9026518 100644 --- a/demo/src/main/java/top/limitart/config/D_WinRank.java +++ b/demo/src/main/java/top/limitart/demo/demo/config/D_WinRank.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package top.limitart.config; +package top.limitart.demo.config; /** * 胜利场数排行奖励 from dat_proto at 2018-12-24T14:33:18.841 diff --git a/demo/src/main/java/top/limitart/demo/demo/config/DataTypeDemo.java b/demo/src/main/java/top/limitart/demo/demo/config/DataTypeDemo.java new file mode 100644 index 0000000..f1c574a --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/demo/config/DataTypeDemo.java @@ -0,0 +1,45 @@ +/* + * + * * Copyright (c) 2016-present The Limitart Project + * * + * * Licensed under the Apache License, Version 2.0 (the "License"); + * * you may not use this file except in compliance with the License. + * * You may obtain a copy of the License at + * * + * * http://www.apache.org/licenses/LICENSE-2.0 + * * + * * Unless required by applicable law or agreed to in writing, software + * * distributed under the License is distributed on an "AS IS" BASIS, + * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * * See the License for the specific language governing permissions and + * * limitations under the License. + * + */ + +package top.limitart.demo.config; + +import top.limitart.demo.json.JSON; +import top.limitart.demo.util.CollectionUtil; + +/** Created by Hank on 2018/12/23 */ +public class DataTypeDemo { + public static void main(String[] args) throws Exception { + Person person = new Person(); + person.setName("hank"); + person.setAge(18); + String source = JSON.getDefault().toStr(person); + PersonDataType parser = new PersonDataType(); + Person parse = parser.parse(source); + System.out.println(parse); + + String intArray = "[1,2,3,4,5]"; + IntArrayType intArrayType = new IntArrayType(); + int[] parse1 = intArrayType.parse(intArray); + System.out.println(CollectionUtil.toString(parse1)); + + String intArray2 = "[[1,2,3],[2,3,4]]"; + IntArray2DType intArray2DType = new IntArray2DType(); + int[][] parse2 = intArray2DType.parse(intArray2); + System.out.println(CollectionUtil.toString(parse2)); + } +} diff --git a/demo/src/main/java/top/limitart/config/ExcelModelDemo.java b/demo/src/main/java/top/limitart/demo/demo/config/ExcelModelDemo.java similarity index 96% rename from demo/src/main/java/top/limitart/config/ExcelModelDemo.java rename to demo/src/main/java/top/limitart/demo/demo/config/ExcelModelDemo.java index 7c5a9e5..0cbf037 100644 --- a/demo/src/main/java/top/limitart/config/ExcelModelDemo.java +++ b/demo/src/main/java/top/limitart/demo/demo/config/ExcelModelDemo.java @@ -1,4 +1,4 @@ -package top.limitart.config; +package top.limitart.demo.config; import java.util.Collections; import java.util.Map; diff --git a/demo/src/main/java/top/limitart/demo/demo/config/Person.java b/demo/src/main/java/top/limitart/demo/demo/config/Person.java new file mode 100644 index 0000000..757d7f7 --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/demo/config/Person.java @@ -0,0 +1,48 @@ +/* + * + * * Copyright (c) 2016-present The Limitart Project + * * + * * Licensed under the Apache License, Version 2.0 (the "License"); + * * you may not use this file except in compliance with the License. + * * You may obtain a copy of the License at + * * + * * http://www.apache.org/licenses/LICENSE-2.0 + * * + * * Unless required by applicable law or agreed to in writing, software + * * distributed under the License is distributed on an "AS IS" BASIS, + * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * * See the License for the specific language governing permissions and + * * limitations under the License. + * + */ + +package top.limitart.demo.config; + +import top.limitart.demo.base.BinaryMeta; + +/** Created by Hank on 2018/12/23 */ +public class Person extends BinaryMeta { + private String name; + private int age; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + @Override + public String toString() { + return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; + } +} diff --git a/demo/src/main/java/top/limitart/demo/demo/config/PersonDataType.java b/demo/src/main/java/top/limitart/demo/demo/config/PersonDataType.java new file mode 100644 index 0000000..2806f01 --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/demo/config/PersonDataType.java @@ -0,0 +1,52 @@ +/* + * + * * Copyright (c) 2016-present The Limitart Project + * * + * * Licensed under the Apache License, Version 2.0 (the "License"); + * * you may not use this file except in compliance with the License. + * * You may obtain a copy of the License at + * * + * * http://www.apache.org/licenses/LICENSE-2.0 + * * + * * Unless required by applicable law or agreed to in writing, software + * * distributed under the License is distributed on an "AS IS" BASIS, + * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * * See the License for the specific language governing permissions and + * * limitations under the License. + * + */ + +package top.limitart.demo.config; + +import top.limitart.demo.base.BinaryMeta; + +/** Created by Hank on 2018/12/23 */ +public class PersonDataType extends JSONParsingType { + @Override + public String name() { + return "Person"; + } + + @Override + public String alias() { + return "person"; + } + + @Override + public String nameOfR() { + return Person.class.getName(); + } + + @Override + public Class classOfR() { + return Person.class; + } + + @Override + public void serialize(BinaryMeta buf, Person value) {} + + @Override + public Person deserialize(BinaryMeta buf) throws Exception { + return buf.getMessageMeta(Person.class); + } +} diff --git a/demo/src/main/java/top/limitart/event/EventDemo.java b/demo/src/main/java/top/limitart/demo/demo/event/EventDemo.java similarity index 87% rename from demo/src/main/java/top/limitart/event/EventDemo.java rename to demo/src/main/java/top/limitart/demo/demo/event/EventDemo.java index 31090cb..c1f6107 100644 --- a/demo/src/main/java/top/limitart/event/EventDemo.java +++ b/demo/src/main/java/top/limitart/demo/demo/event/EventDemo.java @@ -1,4 +1,4 @@ -package top.limitart.event; +package top.limitart.demo.event; /** * @author hank diff --git a/demo/src/main/java/top/limitart/event/EventProviderDemo.java b/demo/src/main/java/top/limitart/demo/demo/event/EventProviderDemo.java similarity index 91% rename from demo/src/main/java/top/limitart/event/EventProviderDemo.java rename to demo/src/main/java/top/limitart/demo/demo/event/EventProviderDemo.java index 3f1d4e7..6829047 100644 --- a/demo/src/main/java/top/limitart/event/EventProviderDemo.java +++ b/demo/src/main/java/top/limitart/demo/demo/event/EventProviderDemo.java @@ -1,6 +1,6 @@ -package top.limitart.event; +package top.limitart.demo.event; -import top.limitart.concurrent.TaskQueue; +import top.limitart.demo.concurrent.TaskQueue; /** * @author hank diff --git a/demo/src/main/java/top/limitart/demo/demo/fastmq/PipelineConsumerDemo.java b/demo/src/main/java/top/limitart/demo/demo/fastmq/PipelineConsumerDemo.java new file mode 100644 index 0000000..92cc01f --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/demo/fastmq/PipelineConsumerDemo.java @@ -0,0 +1,39 @@ +package top.limitart.demo.fastmq; + +import java.nio.charset.StandardCharsets; +import java.util.LinkedList; +import java.util.List; +import top.limitart.demo.fastmq.consumer.MQConsumerBinaryClient; + +public class PipelineConsumerDemo { + + private static MQConsumerBinaryClient consumerClient; + + static { + try { + List tags = new LinkedList<>(); + tags.add("fuck"); + tags.add("shit"); + consumerClient = + new MQConsumerBinaryClient( + "127.0.0.1", + 9000, + "test_zone", + tags, + msg -> {System.out.println(new String(msg, StandardCharsets.UTF_8)) + ; + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static void main(String[] args) throws Exception { + consumerClient.run(args); + } +} diff --git a/demo/src/main/java/top/limitart/demo/demo/fastmq/PipelineProviderDemo.java b/demo/src/main/java/top/limitart/demo/demo/fastmq/PipelineProviderDemo.java new file mode 100644 index 0000000..5f0d572 --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/demo/fastmq/PipelineProviderDemo.java @@ -0,0 +1,35 @@ +package top.limitart.demo.fastmq; + +import java.nio.charset.StandardCharsets; +import java.util.LinkedList; +import java.util.List; +import top.limitart.demo.fastmq.provider.MQProviderBinaryClient; + +public class PipelineProviderDemo { + + private static MQProviderBinaryClient providerClient; + + static { + try { + List tags = new LinkedList<>(); + tags.add("fuck"); + tags.add("shit"); + providerClient = + new MQProviderBinaryClient( + "127.0.0.1", + 9000); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static void main(String[] args) throws Exception { + providerClient.run(args); + int count = 0; + while (true) { + providerClient.sendMsg("test_zone", ("hello fastmq !" + count++) + .getBytes(StandardCharsets.UTF_8)); + Thread.sleep(30); + } + } +} diff --git a/demo/src/main/java/top/limitart/demo/demo/fastmq/PipelineServerDemo.java b/demo/src/main/java/top/limitart/demo/demo/fastmq/PipelineServerDemo.java new file mode 100644 index 0000000..6b193e1 --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/demo/fastmq/PipelineServerDemo.java @@ -0,0 +1,22 @@ +package top.limitart.demo.fastmq; + +import top.limitart.demo.fastmq.pipeline.MQPipelineBinaryServer; +import top.limitart.demo.fastmq.pipeline.core.Pipeline; + +public class PipelineServerDemo { + + private static Pipeline pipeline = new Pipeline(); + private static MQPipelineBinaryServer binaryServer; + + static { + try { + binaryServer = new MQPipelineBinaryServer(pipeline, 9000); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static void main(String[] args) throws Exception { + binaryServer.run(args); + } +} diff --git a/demo/src/main/java/top/limitart/game/htb/HTBDemo.java b/demo/src/main/java/top/limitart/demo/demo/game/htb/HTBDemo.java similarity index 82% rename from demo/src/main/java/top/limitart/game/htb/HTBDemo.java rename to demo/src/main/java/top/limitart/demo/demo/game/htb/HTBDemo.java index fc20cbd..8118db6 100644 --- a/demo/src/main/java/top/limitart/game/htb/HTBDemo.java +++ b/demo/src/main/java/top/limitart/demo/demo/game/htb/HTBDemo.java @@ -1,11 +1,11 @@ -package top.limitart.game.htb; +package top.limitart.demo.game.htb; -import top.limitart.game.FPSBootstrap; -import top.limitart.game.FPSLimiter; -import top.limitart.game.FPSRunner; -import top.limitart.game.SimpleFPSRunner; -import top.limitart.game.htb.event.RRoleStartHandleEvent; -import top.limitart.game.htb.event.TBattleTurnEndEvent; +import top.limitart.demo.game.FPSBootstrap; +import top.limitart.demo.game.FPSLimiter; +import top.limitart.demo.game.FPSRunner; +import top.limitart.demo.game.SimpleFPSRunner; +import top.limitart.demo.game.htb.event.RRoleStartHandleEvent; +import top.limitart.demo.game.htb.event.TBattleTurnEndEvent; /** * @author hank diff --git a/demo/src/main/java/top/limitart/game/htb/HTBRoleDemo.java b/demo/src/main/java/top/limitart/demo/demo/game/htb/HTBRoleDemo.java similarity index 96% rename from demo/src/main/java/top/limitart/game/htb/HTBRoleDemo.java rename to demo/src/main/java/top/limitart/demo/demo/game/htb/HTBRoleDemo.java index b7ea00a..2c61242 100644 --- a/demo/src/main/java/top/limitart/game/htb/HTBRoleDemo.java +++ b/demo/src/main/java/top/limitart/demo/demo/game/htb/HTBRoleDemo.java @@ -16,7 +16,7 @@ * */ -package top.limitart.game.htb; +package top.limitart.demo.game.htb; /** Created by Hank on 2019/6/30 */ public class HTBRoleDemo extends HTBRole { diff --git a/demo/src/main/java/top/limitart/game/htb/HTBTableDemo.java b/demo/src/main/java/top/limitart/demo/demo/game/htb/HTBTableDemo.java similarity index 96% rename from demo/src/main/java/top/limitart/game/htb/HTBTableDemo.java rename to demo/src/main/java/top/limitart/demo/demo/game/htb/HTBTableDemo.java index bc5dde0..8d38069 100644 --- a/demo/src/main/java/top/limitart/game/htb/HTBTableDemo.java +++ b/demo/src/main/java/top/limitart/demo/demo/game/htb/HTBTableDemo.java @@ -16,7 +16,7 @@ * */ -package top.limitart.game.htb; +package top.limitart.demo.game.htb; /** Created by Hank on 2019/6/30 */ public class HTBTableDemo extends HTBTable { diff --git a/demo/src/main/java/top/limitart/game/scene8/SceneDemo.java b/demo/src/main/java/top/limitart/demo/demo/game/scene8/SceneDemo.java similarity index 96% rename from demo/src/main/java/top/limitart/game/scene8/SceneDemo.java rename to demo/src/main/java/top/limitart/demo/demo/game/scene8/SceneDemo.java index 0b289cd..170c097 100644 --- a/demo/src/main/java/top/limitart/game/scene8/SceneDemo.java +++ b/demo/src/main/java/top/limitart/demo/demo/game/scene8/SceneDemo.java @@ -1,6 +1,6 @@ -package top.limitart.game.scene8; +package top.limitart.demo.game.scene8; -import top.limitart.game.FPSBootstrap; +import top.limitart.demo.game.FPSBootstrap; /** * @author hank diff --git a/demo/src/main/java/top/limitart/logging/LoggerDemo.java b/demo/src/main/java/top/limitart/demo/demo/logging/LoggerDemo.java similarity index 95% rename from demo/src/main/java/top/limitart/logging/LoggerDemo.java rename to demo/src/main/java/top/limitart/demo/demo/logging/LoggerDemo.java index 84da38b..1f18ccd 100644 --- a/demo/src/main/java/top/limitart/logging/LoggerDemo.java +++ b/demo/src/main/java/top/limitart/demo/demo/logging/LoggerDemo.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package top.limitart.logging; +package top.limitart.demo.logging; public class LoggerDemo { private static final Logger LOGGER = Loggers.create(); diff --git a/demo/src/main/java/top/limitart/mapping/RouterDemo.java b/demo/src/main/java/top/limitart/demo/demo/mapping/RouterDemo.java similarity index 94% rename from demo/src/main/java/top/limitart/mapping/RouterDemo.java rename to demo/src/main/java/top/limitart/demo/demo/mapping/RouterDemo.java index 46bb1dd..a6065fe 100644 --- a/demo/src/main/java/top/limitart/mapping/RouterDemo.java +++ b/demo/src/main/java/top/limitart/demo/demo/mapping/RouterDemo.java @@ -1,4 +1,4 @@ -package top.limitart.mapping; +package top.limitart.demo.mapping; /** * @author hank diff --git a/demo/src/main/java/top/limitart/mapping/StringMapperClass.java b/demo/src/main/java/top/limitart/demo/demo/mapping/StringMapperClass.java similarity index 86% rename from demo/src/main/java/top/limitart/mapping/StringMapperClass.java rename to demo/src/main/java/top/limitart/demo/demo/mapping/StringMapperClass.java index 85845cc..482cc3e 100644 --- a/demo/src/main/java/top/limitart/mapping/StringMapperClass.java +++ b/demo/src/main/java/top/limitart/demo/demo/mapping/StringMapperClass.java @@ -1,4 +1,4 @@ -package top.limitart.mapping; +package top.limitart.demo.mapping; /** * @author hank diff --git a/demo/src/main/java/top/limitart/mapping/StringPoster.java b/demo/src/main/java/top/limitart/demo/demo/mapping/StringPoster.java similarity index 71% rename from demo/src/main/java/top/limitart/mapping/StringPoster.java rename to demo/src/main/java/top/limitart/demo/demo/mapping/StringPoster.java index 068705f..b7985fc 100644 --- a/demo/src/main/java/top/limitart/mapping/StringPoster.java +++ b/demo/src/main/java/top/limitart/demo/demo/mapping/StringPoster.java @@ -1,4 +1,4 @@ -package top.limitart.mapping; +package top.limitart.demo.mapping; /** * @author hank diff --git a/demo/src/main/java/top/limitart/mapping/StringQuestParam.java b/demo/src/main/java/top/limitart/demo/demo/mapping/StringQuestParam.java similarity index 77% rename from demo/src/main/java/top/limitart/mapping/StringQuestParam.java rename to demo/src/main/java/top/limitart/demo/demo/mapping/StringQuestParam.java index 52cc8f3..36630fd 100644 --- a/demo/src/main/java/top/limitart/mapping/StringQuestParam.java +++ b/demo/src/main/java/top/limitart/demo/demo/mapping/StringQuestParam.java @@ -1,4 +1,4 @@ -package top.limitart.mapping; +package top.limitart.demo.mapping; /** * @author hank diff --git a/demo/src/main/java/top/limitart/mapping/StringRequest.java b/demo/src/main/java/top/limitart/demo/demo/mapping/StringRequest.java similarity index 86% rename from demo/src/main/java/top/limitart/mapping/StringRequest.java rename to demo/src/main/java/top/limitart/demo/demo/mapping/StringRequest.java index a6183e4..33e662d 100644 --- a/demo/src/main/java/top/limitart/mapping/StringRequest.java +++ b/demo/src/main/java/top/limitart/demo/demo/mapping/StringRequest.java @@ -1,4 +1,4 @@ -package top.limitart.mapping; +package top.limitart.demo.mapping; /** * @author hank diff --git a/demo/src/main/java/top/limitart/demo/demo/net/BinaryClientDemo.java b/demo/src/main/java/top/limitart/demo/demo/net/BinaryClientDemo.java new file mode 100644 index 0000000..dab5e3e --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/demo/net/BinaryClientDemo.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2016-present The Limitart Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package top.limitart.demo.net; + +import top.limitart.demo.mapping.Router; +import top.limitart.demo.net.binary.BinaryEndPoint; +import top.limitart.demo.net.binary.BinaryMessage; +import top.limitart.demo.net.binary.BinaryRequestParam; + +/** @author hank */ +public class BinaryClientDemo { + public static void main(String[] args) throws Exception { + BinaryEndPoint.builder(false) + .router( + Router.empty(BinaryMessage.class, BinaryRequestParam.class) + .registerMapperClass(MessageMapper.class)) + .onConnected( + (s, state) -> { + if (state) { + try { + s.writeNow(new BinaryMessageDemo()); + } catch (Exception ignored) { + } + } + }) + .build() + .start(AddressPair.withIP("127.0.0.1", 7878)); + } +} diff --git a/demo/src/main/java/top/limitart/demo/demo/net/BinaryMessageDemo.java b/demo/src/main/java/top/limitart/demo/demo/net/BinaryMessageDemo.java new file mode 100644 index 0000000..2e3aeb5 --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/demo/net/BinaryMessageDemo.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2016-present The Limitart Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package top.limitart.demo.net; + +import top.limitart.demo.net.binary.BinaryMessage; +import top.limitart.demo.net.binary.BinaryMessages; + +public class BinaryMessageDemo extends BinaryMessage { + public final String content = "hello limitart!"; + + @Override + public short id() { + return BinaryMessages.createID(0X00, 0X01); + } +} diff --git a/demo/src/main/java/top/limitart/demo/demo/net/BinaryMessageDemo2.java b/demo/src/main/java/top/limitart/demo/demo/net/BinaryMessageDemo2.java new file mode 100644 index 0000000..f58677f --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/demo/net/BinaryMessageDemo2.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2016-present The Limitart Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package top.limitart.demo.net; + +import top.limitart.demo.net.binary.BinaryMessage; +import top.limitart.demo.net.binary.BinaryMessages; + +/** @author hank */ +public class BinaryMessageDemo2 extends BinaryMessage { + public final String content = "hello script manager"; + + @Override + public short id() { + return BinaryMessages.createID(0X00, 0X02); + } +} diff --git a/demo/src/main/java/top/limitart/demo/demo/net/BinaryScriptManager.java b/demo/src/main/java/top/limitart/demo/demo/net/BinaryScriptManager.java new file mode 100644 index 0000000..c5108d4 --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/demo/net/BinaryScriptManager.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2016-present The Limitart Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package top.limitart.demo.net; + +import top.limitart.demo.mapping.Mapper; +import top.limitart.demo.mapping.Request; +import top.limitart.demo.net.binary.BinaryRequestParam; + +/** @author hank */ +@Mapper +public abstract class BinaryScriptManager { + public abstract void helloScriptManager(@Request BinaryMessageDemo2 msg, BinaryRequestParam param); +} diff --git a/demo/src/main/java/top/limitart/demo/demo/net/BinaryScriptManagerImpl.java b/demo/src/main/java/top/limitart/demo/demo/net/BinaryScriptManagerImpl.java new file mode 100644 index 0000000..a72f731 --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/demo/net/BinaryScriptManagerImpl.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2016-present The Limitart Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package top.limitart.demo.net; + +import top.limitart.demo.net.binary.BinaryRequestParam; + +/** @author hank */ +public class BinaryScriptManagerImpl extends BinaryScriptManager { + + @Override + public void helloScriptManager(BinaryMessageDemo2 msg, BinaryRequestParam param) { + System.out.println(msg.content); + } +} diff --git a/demo/src/main/java/top/limitart/demo/demo/net/BinaryServerDemo.java b/demo/src/main/java/top/limitart/demo/demo/net/BinaryServerDemo.java new file mode 100644 index 0000000..d53ef43 --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/demo/net/BinaryServerDemo.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2016-present The Limitart Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package top.limitart.demo.net; + +import top.limitart.demo.mapping.Router; +import top.limitart.demo.net.binary.BinaryEndPoint; +import top.limitart.demo.net.binary.BinaryMessage; +import top.limitart.demo.net.binary.BinaryRequestParam; + +/** @author hank */ +public class BinaryServerDemo { + static final BinarySessionRole role = new BinarySessionRole(); + + public static void main(String[] args) throws Exception { + BinaryEndPoint.builder(true) + .router( + Router.empty(BinaryMessage.class, BinaryRequestParam.class) + .registerMapperClass(MessageMapper.class)) + .onConnected( + (s, b) -> { + if (b) { + role.joinWhenFree( + s, + () -> {System.out.println("join session success!"); + NettySession where = role.where(); + }, + Throwable::printStackTrace); + } else { + role.leave(s); + System.out.println("leave session success"); + } + }) + .build() + .start(AddressPair.withPort(7878)); + } +} diff --git a/demo/src/main/java/top/limitart/demo/demo/net/BinarySessionRole.java b/demo/src/main/java/top/limitart/demo/demo/net/BinarySessionRole.java new file mode 100644 index 0000000..cee0285 --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/demo/net/BinarySessionRole.java @@ -0,0 +1,6 @@ +package top.limitart.demo.net; + + +import top.limitart.demo.net.binary.BinaryMessage; + +public class BinarySessionRole extends NettySessionActor {} diff --git a/demo/src/main/java/top/limitart/demo/demo/net/FlashSSLServerDemo.java b/demo/src/main/java/top/limitart/demo/demo/net/FlashSSLServerDemo.java new file mode 100644 index 0000000..3d6bbbf --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/demo/net/FlashSSLServerDemo.java @@ -0,0 +1,13 @@ +package top.limitart.demo.net; + +import top.limitart.demo.net.flashssl.FlashSSLEndPoint; + +/** + * @author hank + * @version 2018/10/15 0015 21:23 + */ +public class FlashSSLServerDemo { + public static void main(String[] args) throws Exception { + FlashSSLEndPoint.builder().build().start(AddressPair.withPort(843)); + } +} diff --git a/demo/src/main/java/top/limitart/net/HTTPSServerDemo.java b/demo/src/main/java/top/limitart/demo/demo/net/HTTPSServerDemo.java similarity index 95% rename from demo/src/main/java/top/limitart/net/HTTPSServerDemo.java rename to demo/src/main/java/top/limitart/demo/demo/net/HTTPSServerDemo.java index a29cbc2..725de75 100644 --- a/demo/src/main/java/top/limitart/net/HTTPSServerDemo.java +++ b/demo/src/main/java/top/limitart/demo/demo/net/HTTPSServerDemo.java @@ -16,7 +16,7 @@ * */ -package top.limitart.net; +package top.limitart.demo.net; /** Created by Hank on 2018/10/14 */ public class HTTPSServerDemo { diff --git a/demo/src/main/java/top/limitart/demo/demo/net/HTTPServerDemo.java b/demo/src/main/java/top/limitart/demo/demo/net/HTTPServerDemo.java new file mode 100644 index 0000000..1a3b9eb --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/demo/net/HTTPServerDemo.java @@ -0,0 +1,41 @@ +/* + * + * * Copyright (c) 2016-present The Limitart Project + * * + * * Licensed under the Apache License, Version 2.0 (the "License"); + * * you may not use this file except in compliance with the License. + * * You may obtain a copy of the License at + * * + * * http://www.apache.org/licenses/LICENSE-2.0 + * * + * * Unless required by applicable law or agreed to in writing, software + * * distributed under the License is distributed on an "AS IS" BASIS, + * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * * See the License for the specific language governing permissions and + * * limitations under the License. + * + */ + +package top.limitart.demo.net; + +import top.limitart.demo.net.http.HTTPEndPoint; + +import java.nio.charset.StandardCharsets; +import java.util.concurrent.Executors; + +/** Created by Hank on 2018/10/14 */ +public class HTTPServerDemo { + public static void main(String[] args) throws Exception { + HTTPEndPoint.builder() + .onMessageIn( + (s, i) -> { + if (i.getUrl().equals("/limitart")) { + return "hello limitart!".getBytes(StandardCharsets.UTF_8); + } + return null; + }, + () -> Executors.newSingleThreadScheduledExecutor()) + .build() + .start(AddressPair.withPort(8080)); + } +} diff --git a/demo/src/main/java/top/limitart/demo/demo/net/LocalEndPointDemo.java b/demo/src/main/java/top/limitart/demo/demo/net/LocalEndPointDemo.java new file mode 100644 index 0000000..94b926e --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/demo/net/LocalEndPointDemo.java @@ -0,0 +1,39 @@ +package top.limitart.demo.net; + +import top.limitart.demo.mapping.Router; +import top.limitart.demo.net.binary.BinaryEndPoint; +import top.limitart.demo.net.binary.BinaryMessage; +import top.limitart.demo.net.binary.BinaryRequestParam; + +/** + * @author hank + * @version 2018/10/15 0015 14:14 + */ +public class LocalEndPointDemo { + + public static void main(String[] args) throws Exception { + // server + BinaryEndPoint.builder(NettyEndPointType.SERVER_LOCAL) + .router( + Router.empty(BinaryMessage.class, BinaryRequestParam.class) + .registerMapperClass(MessageMapper.class)) + .build() + .start(AddressPair.withLocalHost(1)); + // client + BinaryEndPoint.builder(NettyEndPointType.CLIENT_LOCAL) + .router( + Router.empty(BinaryMessage.class, BinaryRequestParam.class) + .registerMapperClass(MessageMapper.class)) + .onConnected( + (s, state) -> { + if (state) { + try { + s.writeNow(new BinaryMessageDemo()); + } catch (Exception ignored) { + } + } + }) + .build() + .start(AddressPair.withLocalHost(1)); + } +} diff --git a/demo/src/main/java/top/limitart/demo/demo/net/MessageMapper.java b/demo/src/main/java/top/limitart/demo/demo/net/MessageMapper.java new file mode 100644 index 0000000..d660d67 --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/demo/net/MessageMapper.java @@ -0,0 +1,47 @@ +/* + * + * * Copyright (c) 2016-present The Limitart Project + * * + * * Licensed under the Apache License, Version 2.0 (the "License"); + * * you may not use this file except in compliance with the License. + * * You may obtain a copy of the License at + * * + * * http://www.apache.org/licenses/LICENSE-2.0 + * * + * * Unless required by applicable law or agreed to in writing, software + * * distributed under the License is distributed on an "AS IS" BASIS, + * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * * See the License for the specific language governing permissions and + * * limitations under the License. + * + */ + +package top.limitart.demo.net; + +import com.google.protobuf.Message; +import io.netty.channel.EventLoop; +import top.limitart.demo.mapping.Mapper; +import top.limitart.demo.mapping.Request; +import top.limitart.demo.net.binary.BinaryMessage; +import top.limitart.demo.net.binary.BinaryRequestParam; +import top.limitart.demo.net.protobuf.ProtobufRequestParam; + +/** Created by Hank on 2018/10/13 */ +@Mapper +public class MessageMapper { + public void doMessageDemo(@Request BinaryMessageDemo msg, BinaryRequestParam param) { + Session session = param.session(); + System.out.println(msg.content); + session.writeNow(msg); + } + + public void doMessageDemo2(@Request ProtobufMessageDemo.Demo2 msg, ProtobufRequestParam param) { + Session session = param.session(); + System.out.println("demo2:" + msg.getId()); + } + + public void doMessageDemo1(@Request ProtobufMessageDemo.Demo1 msg, ProtobufRequestParam param) { + Session session = param.session(); + System.out.println("demo1:" + msg.getName()); + } +} diff --git a/demo/src/main/java/top/limitart/demo/demo/net/MessagePackageTest.java b/demo/src/main/java/top/limitart/demo/demo/net/MessagePackageTest.java new file mode 100644 index 0000000..ba19297 --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/demo/net/MessagePackageTest.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2016-present The Limitart Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package top.limitart.demo.net; + +import top.limitart.demo.base.BinaryMeta; +import top.limitart.demo.net.binary.BinaryByteMessage; +import top.limitart.demo.net.binary.BinaryMessage; +import top.limitart.demo.net.binary.BinaryMessages; + +/** + * 消息生成测试 + * + * @author limitart + */ +public class MessagePackageTest { + private static final byte PACKAGE_ID = 1; + + /** + * 消息Bean测试 + * + * @author limitart + */ + public static class MetaInfo extends BinaryMeta { + /** 测试ID */ + public int ID; + /** 测试名字 */ + public String str; + /** 测试列表 */ + public java.util.List list = new java.util.ArrayList<>(); + } + + /** + * 消息测试 + * + * @author limitart + */ + public static class MessageTest extends BinaryMessage { + /** ID */ + public int ID; + /** 名称 */ + public String name; + /** bean列表 */ + public java.util.List metas = new java.util.ArrayList<>(); + + @Override + public short id() { + return BinaryMessages.createID(PACKAGE_ID, 1); + } + } + + /** + * 消息测试1 + * + * @author limitart + */ + public static class MessageTest1 extends BinaryMessage { + /** ID */ + public int ID; + /** 名称 */ + public String name; + /** bean列表 */ + public java.util.List metas = new java.util.ArrayList<>(); + + @Override + public short id() { + return BinaryMessages.createID(PACKAGE_ID, 2); + } + } + + public static class MessageEnumTest extends BinaryByteMessage { + /** */ + public static MessageEnumTest XXX1 = new MessageEnumTest((byte) 1); + + public MessageEnumTest(byte code) { + super(code); + } + + @Override + public short id() { + return BinaryMessages.createID(PACKAGE_ID, 3); + } + } +} diff --git a/demo/src/main/java/top/limitart/demo/demo/net/ProtobufClientDemo.java b/demo/src/main/java/top/limitart/demo/demo/net/ProtobufClientDemo.java new file mode 100644 index 0000000..68e1366 --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/demo/net/ProtobufClientDemo.java @@ -0,0 +1,30 @@ +package top.limitart.demo.net; + +import com.google.protobuf.Message; +import top.limitart.demo.mapping.Router; +import top.limitart.demo.net.protobuf.ProtobufEndPoint; +import top.limitart.demo.net.protobuf.ProtobufRequestParam; + +/** + * @author hank + * @version 2018/10/12 0012 21:29 + */ +public class ProtobufClientDemo { + public static void main(String[] args) throws Exception { + ProtobufEndPoint.builder(false) + .router( + Router.empty(Message.class, ProtobufRequestParam.class) + .registerMapperClass(MessageMapper.class)) + .onConnected( + (s, state) -> { + if (state) { + try { + s.writeNow(ProtobufMessageDemo.Demo2.newBuilder().setId(1111).build()); + } catch (Exception ignored) { + } + } + }) + .build() + .start(AddressPair.withIP("127.0.0.1", 7878)); + } +} diff --git a/demo/src/main/java/top/limitart/net/ProtobufMessageDemo.java b/demo/src/main/java/top/limitart/demo/demo/net/ProtobufMessageDemo.java similarity index 99% rename from demo/src/main/java/top/limitart/net/ProtobufMessageDemo.java rename to demo/src/main/java/top/limitart/demo/demo/net/ProtobufMessageDemo.java index 24a0a67..7a08964 100644 --- a/demo/src/main/java/top/limitart/net/ProtobufMessageDemo.java +++ b/demo/src/main/java/top/limitart/demo/demo/net/ProtobufMessageDemo.java @@ -1,7 +1,7 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: protobuf3.proto -package top.limitart.net; +package top.limitart.demo.net; public final class ProtobufMessageDemo { private ProtobufMessageDemo() {} diff --git a/demo/src/main/java/top/limitart/demo/demo/net/ProtobufServerDemo.java b/demo/src/main/java/top/limitart/demo/demo/net/ProtobufServerDemo.java new file mode 100644 index 0000000..bb9a52d --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/demo/net/ProtobufServerDemo.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2016-present The Limitart Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package top.limitart.demo.net; + +import com.google.protobuf.Message; +import top.limitart.demo.mapping.Router; +import top.limitart.demo.net.protobuf.ProtobufEndPoint; +import top.limitart.demo.net.protobuf.ProtobufRequestParam; + +/** @author hank */ +public class ProtobufServerDemo { + static final ProtobufSessionRole role = new ProtobufSessionRole(); + + public static void main(String[] args) throws Exception { + ProtobufEndPoint.builder(true) + .router( + Router.empty(Message.class, ProtobufRequestParam.class) + .registerMapperClass(MessageMapper.class)) + .onConnected( + (s, b) -> { + if (b) { + role.joinWhenFree( + s, + () -> System.out.println("join session success!"),e->{}); + } else { + role.leave(s); + System.out.println("leave session success"); + } + }) + .build() + .start(AddressPair.withPort(7878)); + } +} diff --git a/demo/src/main/java/top/limitart/net/ProtobufSessionRole.java b/demo/src/main/java/top/limitart/demo/demo/net/ProtobufSessionRole.java similarity index 78% rename from demo/src/main/java/top/limitart/net/ProtobufSessionRole.java rename to demo/src/main/java/top/limitart/demo/demo/net/ProtobufSessionRole.java index 5735461..2140594 100644 --- a/demo/src/main/java/top/limitart/net/ProtobufSessionRole.java +++ b/demo/src/main/java/top/limitart/demo/demo/net/ProtobufSessionRole.java @@ -1,4 +1,4 @@ -package top.limitart.net; +package top.limitart.demo.net; import com.google.protobuf.Message; diff --git a/demo/src/main/java/top/limitart/net/WebSocketServerDemo.java b/demo/src/main/java/top/limitart/demo/demo/net/WebSocketServerDemo.java similarity index 88% rename from demo/src/main/java/top/limitart/net/WebSocketServerDemo.java rename to demo/src/main/java/top/limitart/demo/demo/net/WebSocketServerDemo.java index 72fc86f..5ddf1d9 100644 --- a/demo/src/main/java/top/limitart/net/WebSocketServerDemo.java +++ b/demo/src/main/java/top/limitart/demo/demo/net/WebSocketServerDemo.java @@ -16,14 +16,13 @@ * */ -package top.limitart.net; +package top.limitart.demo.net; import io.netty.channel.EventLoop; import io.netty.handler.codec.http.websocketx.WebSocketFrame; -import top.limitart.net.binary.BinaryMessage; -import top.limitart.net.http.HTTPRequest; -import top.limitart.net.http.HTTPSession; -import top.limitart.net.websocket.WebSocketEndPoint; +import top.limitart.demo.net.http.HTTPRequest; +import top.limitart.demo.net.http.HTTPSession; +import top.limitart.demo.net.websocket.WebSocketEndPoint; /** Created by Hank on 2019/2/24 */ public class WebSocketServerDemo { diff --git a/demo/src/main/java/top/limitart/redefinable/HelloRedefine.java b/demo/src/main/java/top/limitart/demo/demo/redefinable/HelloRedefine.java similarity index 71% rename from demo/src/main/java/top/limitart/redefinable/HelloRedefine.java rename to demo/src/main/java/top/limitart/demo/demo/redefinable/HelloRedefine.java index cb437bb..c4677b4 100644 --- a/demo/src/main/java/top/limitart/redefinable/HelloRedefine.java +++ b/demo/src/main/java/top/limitart/demo/demo/redefinable/HelloRedefine.java @@ -1,4 +1,4 @@ -package top.limitart.redefinable; +package top.limitart.demo.redefinable; public class HelloRedefine { public void hello(){ diff --git a/demo/src/main/java/top/limitart/redefinable/RedefinableDemo.java b/demo/src/main/java/top/limitart/demo/demo/redefinable/RedefinableDemo.java similarity index 88% rename from demo/src/main/java/top/limitart/redefinable/RedefinableDemo.java rename to demo/src/main/java/top/limitart/demo/demo/redefinable/RedefinableDemo.java index 378b2d9..19b651a 100644 --- a/demo/src/main/java/top/limitart/redefinable/RedefinableDemo.java +++ b/demo/src/main/java/top/limitart/demo/demo/redefinable/RedefinableDemo.java @@ -1,4 +1,4 @@ -package top.limitart.redefinable; +package top.limitart.demo.redefinable; import java.io.File; diff --git a/demo/src/main/java/top/limitart/redefinable/ScriptEntrance.java b/demo/src/main/java/top/limitart/demo/demo/redefinable/ScriptEntrance.java similarity index 93% rename from demo/src/main/java/top/limitart/redefinable/ScriptEntrance.java rename to demo/src/main/java/top/limitart/demo/demo/redefinable/ScriptEntrance.java index b976e91..6f37cec 100644 --- a/demo/src/main/java/top/limitart/redefinable/ScriptEntrance.java +++ b/demo/src/main/java/top/limitart/demo/demo/redefinable/ScriptEntrance.java @@ -1,4 +1,4 @@ -package top.limitart.redefinable; +package top.limitart.demo.redefinable; public class ScriptEntrance extends RedefinableModule { private HelloRedefine helloRedefine = new HelloRedefine(); diff --git a/demo/src/main/java/top/limitart/script/AutoReloadScriptDemo.java b/demo/src/main/java/top/limitart/demo/demo/script/AutoReloadScriptDemo.java similarity index 97% rename from demo/src/main/java/top/limitart/script/AutoReloadScriptDemo.java rename to demo/src/main/java/top/limitart/demo/demo/script/AutoReloadScriptDemo.java index ec7400c..b1ba048 100644 --- a/demo/src/main/java/top/limitart/script/AutoReloadScriptDemo.java +++ b/demo/src/main/java/top/limitart/demo/demo/script/AutoReloadScriptDemo.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package top.limitart.script; +package top.limitart.demo.script; import java.io.IOException; diff --git a/demo/src/main/java/top/limitart/script/HelloScript.java b/demo/src/main/java/top/limitart/demo/demo/script/HelloScript.java similarity index 95% rename from demo/src/main/java/top/limitart/script/HelloScript.java rename to demo/src/main/java/top/limitart/demo/demo/script/HelloScript.java index f0882f0..6969197 100644 --- a/demo/src/main/java/top/limitart/script/HelloScript.java +++ b/demo/src/main/java/top/limitart/demo/demo/script/HelloScript.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package top.limitart.script; +package top.limitart.demo.script; /** * 脚本引用测试 diff --git a/demo/src/main/java/top/limitart/script/ScriptSourceDemo.java b/demo/src/main/java/top/limitart/demo/demo/script/ScriptSourceDemo.java similarity index 97% rename from demo/src/main/java/top/limitart/script/ScriptSourceDemo.java rename to demo/src/main/java/top/limitart/demo/demo/script/ScriptSourceDemo.java index 737d9cd..fdc07b0 100644 --- a/demo/src/main/java/top/limitart/script/ScriptSourceDemo.java +++ b/demo/src/main/java/top/limitart/demo/demo/script/ScriptSourceDemo.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package top.limitart.script; +package top.limitart.demo.script; /** * 脚本编译测试 diff --git a/demo/src/main/java/top/limitart/singleton/SingletonA.java b/demo/src/main/java/top/limitart/demo/demo/singleton/SingletonA.java similarity index 78% rename from demo/src/main/java/top/limitart/singleton/SingletonA.java rename to demo/src/main/java/top/limitart/demo/demo/singleton/SingletonA.java index ddb8b96..cfe150f 100644 --- a/demo/src/main/java/top/limitart/singleton/SingletonA.java +++ b/demo/src/main/java/top/limitart/demo/demo/singleton/SingletonA.java @@ -1,4 +1,4 @@ -package top.limitart.singleton; +package top.limitart.demo.singleton; @Singleton public class SingletonA { diff --git a/demo/src/main/java/top/limitart/singleton/SingletonB.java b/demo/src/main/java/top/limitart/demo/demo/singleton/SingletonB.java similarity index 87% rename from demo/src/main/java/top/limitart/singleton/SingletonB.java rename to demo/src/main/java/top/limitart/demo/demo/singleton/SingletonB.java index 287d7a9..d144bc2 100644 --- a/demo/src/main/java/top/limitart/singleton/SingletonB.java +++ b/demo/src/main/java/top/limitart/demo/demo/singleton/SingletonB.java @@ -1,4 +1,4 @@ -package top.limitart.singleton; +package top.limitart.demo.singleton; @Singleton public class SingletonB { diff --git a/demo/src/main/java/top/limitart/singleton/SingletonC.java b/demo/src/main/java/top/limitart/demo/demo/singleton/SingletonC.java similarity index 95% rename from demo/src/main/java/top/limitart/singleton/SingletonC.java rename to demo/src/main/java/top/limitart/demo/demo/singleton/SingletonC.java index b0eec76..1887203 100644 --- a/demo/src/main/java/top/limitart/singleton/SingletonC.java +++ b/demo/src/main/java/top/limitart/demo/demo/singleton/SingletonC.java @@ -16,7 +16,7 @@ * */ -package top.limitart.singleton; +package top.limitart.demo.singleton; /** Created by Hank on 2018/12/11 */ @Singleton diff --git a/demo/src/main/java/top/limitart/singleton/SingletonD.java b/demo/src/main/java/top/limitart/demo/demo/singleton/SingletonD.java similarity index 96% rename from demo/src/main/java/top/limitart/singleton/SingletonD.java rename to demo/src/main/java/top/limitart/demo/demo/singleton/SingletonD.java index 0dd180e..583294c 100644 --- a/demo/src/main/java/top/limitart/singleton/SingletonD.java +++ b/demo/src/main/java/top/limitart/demo/demo/singleton/SingletonD.java @@ -16,7 +16,7 @@ * */ -package top.limitart.singleton; +package top.limitart.demo.singleton; /** Created by Hank on 2018/12/11 */ @Singleton diff --git a/demo/src/main/java/top/limitart/singleton/SingletonDemo.java b/demo/src/main/java/top/limitart/demo/demo/singleton/SingletonDemo.java similarity index 92% rename from demo/src/main/java/top/limitart/singleton/SingletonDemo.java rename to demo/src/main/java/top/limitart/demo/demo/singleton/SingletonDemo.java index 47b091b..9f0e25e 100644 --- a/demo/src/main/java/top/limitart/singleton/SingletonDemo.java +++ b/demo/src/main/java/top/limitart/demo/demo/singleton/SingletonDemo.java @@ -1,4 +1,4 @@ -package top.limitart.singleton; +package top.limitart.demo.singleton; public class SingletonDemo { @Ref SingletonB singletonB; diff --git a/demo/src/main/java/top/limitart/demo/event/EventDemo.java b/demo/src/main/java/top/limitart/demo/event/EventDemo.java new file mode 100644 index 0000000..34a0da1 --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/event/EventDemo.java @@ -0,0 +1,19 @@ +package top.limitart.demo.event; + +import top.limitart.event.Event; + +/** + * @author hank + * @version 2019/3/25 0025 14:48 + */ +public class EventDemo implements Event { + private String name; + + public EventDemo(String name) { + this.name = name; + } + + public String getName() { + return name; + } +} diff --git a/demo/src/main/java/top/limitart/demo/event/EventProviderDemo.java b/demo/src/main/java/top/limitart/demo/event/EventProviderDemo.java new file mode 100644 index 0000000..48b2293 --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/event/EventProviderDemo.java @@ -0,0 +1,34 @@ +package top.limitart.demo.event; + +import top.limitart.concurrent.TaskQueue; +import top.limitart.event.AbstractEventProvider; +import top.limitart.event.Event; +import top.limitart.event.EventProvider; + +/** + * @author hank + * @version 2019/3/25 0025 14:49 + */ +public class EventProviderDemo extends AbstractEventProvider { + public static void main(String[] args) { + TaskQueue executor = TaskQueue.create("event demo thread"); + EventProvider demo = new EventProviderDemo(); + int listen = + demo.listen( + EventDemo.class, + null, + e -> System.out.println(Thread.currentThread().getName() + "," + e.getName())); + demo.listen( + EventDemo.class, + executor, + e -> System.out.println(Thread.currentThread().getName() + "," + e.getName())); + demo.notListen(EventDemo.class, listen); + demo.post(new EventDemo("event demo")); + demo.post(new EventDemo("event demo1")); + } + + @Override + protected boolean onPost(Event event) { + return true; + } +} diff --git a/demo/src/main/java/top/limitart/fastmq/PipelineConsumerDemo.java b/demo/src/main/java/top/limitart/demo/fastmq/PipelineConsumerDemo.java similarity index 81% rename from demo/src/main/java/top/limitart/fastmq/PipelineConsumerDemo.java rename to demo/src/main/java/top/limitart/demo/fastmq/PipelineConsumerDemo.java index 52540aa..68dc040 100644 --- a/demo/src/main/java/top/limitart/fastmq/PipelineConsumerDemo.java +++ b/demo/src/main/java/top/limitart/demo/fastmq/PipelineConsumerDemo.java @@ -1,13 +1,13 @@ -package top.limitart.fastmq; +package top.limitart.demo.fastmq; import java.nio.charset.StandardCharsets; import java.util.LinkedList; import java.util.List; -import top.limitart.fastmq.consumer.ConsumerBinaryClient; +import top.limitart.fastmq.consumer.MQConsumerBinaryClient; public class PipelineConsumerDemo { - private static ConsumerBinaryClient consumerClient; + private static MQConsumerBinaryClient consumerClient; static { try { @@ -15,7 +15,7 @@ public class PipelineConsumerDemo { tags.add("fuck"); tags.add("shit"); consumerClient = - new ConsumerBinaryClient( + new MQConsumerBinaryClient( "127.0.0.1", 9000, "test_zone", diff --git a/demo/src/main/java/top/limitart/fastmq/PipelineProviderDemo.java b/demo/src/main/java/top/limitart/demo/fastmq/PipelineProviderDemo.java similarity index 78% rename from demo/src/main/java/top/limitart/fastmq/PipelineProviderDemo.java rename to demo/src/main/java/top/limitart/demo/fastmq/PipelineProviderDemo.java index 2f354ef..a56a811 100644 --- a/demo/src/main/java/top/limitart/fastmq/PipelineProviderDemo.java +++ b/demo/src/main/java/top/limitart/demo/fastmq/PipelineProviderDemo.java @@ -1,13 +1,13 @@ -package top.limitart.fastmq; +package top.limitart.demo.fastmq; import java.nio.charset.StandardCharsets; import java.util.LinkedList; import java.util.List; -import top.limitart.fastmq.provider.ProviderBinaryClient; +import top.limitart.fastmq.provider.MQProviderBinaryClient; public class PipelineProviderDemo { - private static ProviderBinaryClient providerClient; + private static MQProviderBinaryClient providerClient; static { try { @@ -15,7 +15,7 @@ public class PipelineProviderDemo { tags.add("fuck"); tags.add("shit"); providerClient = - new ProviderBinaryClient( + new MQProviderBinaryClient( "127.0.0.1", 9000); } catch (Exception e) { diff --git a/demo/src/main/java/top/limitart/fastmq/PipelineServerDemo.java b/demo/src/main/java/top/limitart/demo/fastmq/PipelineServerDemo.java similarity index 60% rename from demo/src/main/java/top/limitart/fastmq/PipelineServerDemo.java rename to demo/src/main/java/top/limitart/demo/fastmq/PipelineServerDemo.java index ff1623d..6e057d3 100644 --- a/demo/src/main/java/top/limitart/fastmq/PipelineServerDemo.java +++ b/demo/src/main/java/top/limitart/demo/fastmq/PipelineServerDemo.java @@ -1,16 +1,16 @@ -package top.limitart.fastmq; +package top.limitart.demo.fastmq; -import top.limitart.fastmq.pipeline.PipelineBinaryServer; +import top.limitart.fastmq.pipeline.MQPipelineBinaryServer; import top.limitart.fastmq.pipeline.core.Pipeline; public class PipelineServerDemo { private static Pipeline pipeline = new Pipeline(); - private static PipelineBinaryServer binaryServer; + private static MQPipelineBinaryServer binaryServer; static { try { - binaryServer = new PipelineBinaryServer(pipeline, 9000); + binaryServer = new MQPipelineBinaryServer(pipeline, 9000); } catch (Exception e) { e.printStackTrace(); } diff --git a/demo/src/main/java/top/limitart/demo/logging/LoggerDemo.java b/demo/src/main/java/top/limitart/demo/logging/LoggerDemo.java new file mode 100644 index 0000000..d265c68 --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/logging/LoggerDemo.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2016-present The Limitart Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package top.limitart.demo.logging; + +import top.limitart.logging.Logger; +import top.limitart.logging.Loggers; + +public class LoggerDemo { + private static final Logger LOGGER = Loggers.create(); + + public static void main(String[] args) { + LOGGER.info("xxxxx"); + } +} diff --git a/demo/src/main/java/top/limitart/demo/mapping/RouterDemo.java b/demo/src/main/java/top/limitart/demo/mapping/RouterDemo.java new file mode 100644 index 0000000..c771eb9 --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/mapping/RouterDemo.java @@ -0,0 +1,19 @@ +package top.limitart.demo.mapping; + +import top.limitart.mapping.Router; + +/** + * @author hank + * @version 2018/10/8 0008 21:25 + */ +public class RouterDemo { + public static void main(String[] args) throws Exception { + Router router = + Router.empty(StringRequest.class, StringQuestParam.class); + router.registerMapperClass(StringMapperClass.class); + StringRequest newRequest = new StringRequest(); + newRequest.setMsg("hank!!!"); + StringQuestParam stringQuestParam = new StringQuestParam(); + router.request(newRequest, stringQuestParam, Router.MethodInvoker::invoke); + } +} diff --git a/demo/src/main/java/top/limitart/demo/mapping/StringMapperClass.java b/demo/src/main/java/top/limitart/demo/mapping/StringMapperClass.java new file mode 100644 index 0000000..ff8fd7f --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/mapping/StringMapperClass.java @@ -0,0 +1,15 @@ +package top.limitart.demo.mapping; + +import top.limitart.mapping.Mapper; +import top.limitart.mapping.Request; + +/** + * @author hank + * @version 2018/10/8 0008 21:23 + */ +@Mapper +public class StringMapperClass { + public void onMsg(@Request StringRequest msg, StringQuestParam param) { + System.out.println(msg.getMsg()); + } +} diff --git a/demo/src/main/java/top/limitart/demo/mapping/StringPoster.java b/demo/src/main/java/top/limitart/demo/mapping/StringPoster.java new file mode 100644 index 0000000..b7985fc --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/mapping/StringPoster.java @@ -0,0 +1,7 @@ +package top.limitart.demo.mapping; + +/** + * @author hank + * @version 2018/10/8 0008 21:22 + */ +public class StringPoster {} diff --git a/demo/src/main/java/top/limitart/demo/mapping/StringQuestParam.java b/demo/src/main/java/top/limitart/demo/mapping/StringQuestParam.java new file mode 100644 index 0000000..85408cf --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/mapping/StringQuestParam.java @@ -0,0 +1,10 @@ +package top.limitart.demo.mapping; + +import top.limitart.mapping.RequestContext; + +/** + * @author hank + * @version 2018/10/8 0008 21:22 + */ +public class StringQuestParam implements RequestContext { +} diff --git a/demo/src/main/java/top/limitart/demo/mapping/StringRequest.java b/demo/src/main/java/top/limitart/demo/mapping/StringRequest.java new file mode 100644 index 0000000..33e662d --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/mapping/StringRequest.java @@ -0,0 +1,17 @@ +package top.limitart.demo.mapping; + +/** + * @author hank + * @version 2018/10/8 0008 21:21 + */ +public class StringRequest { + private String msg; + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } +} diff --git a/demo/src/main/java/top/limitart/net/BinaryClientDemo.java b/demo/src/main/java/top/limitart/demo/net/BinaryClientDemo.java similarity index 89% rename from demo/src/main/java/top/limitart/net/BinaryClientDemo.java rename to demo/src/main/java/top/limitart/demo/net/BinaryClientDemo.java index 858ba61..14ff192 100644 --- a/demo/src/main/java/top/limitart/net/BinaryClientDemo.java +++ b/demo/src/main/java/top/limitart/demo/net/BinaryClientDemo.java @@ -13,9 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package top.limitart.net; +package top.limitart.demo.net; +import top.limitart.mapping.Mapper; import top.limitart.mapping.Router; +import top.limitart.net.AddressPair; import top.limitart.net.binary.BinaryEndPoint; import top.limitart.net.binary.BinaryMessage; import top.limitart.net.binary.BinaryRequestParam; @@ -26,7 +28,7 @@ public class BinaryClientDemo { BinaryEndPoint.builder(false) .router( Router.empty(BinaryMessage.class, BinaryRequestParam.class) - .registerMapperClass(MessageMapper.class)) + .registerMapperClass(Mapper.class)) .onConnected( (s, state) -> { if (state) { diff --git a/demo/src/main/java/top/limitart/net/BinaryMessageDemo.java b/demo/src/main/java/top/limitart/demo/net/BinaryMessageDemo.java similarity index 96% rename from demo/src/main/java/top/limitart/net/BinaryMessageDemo.java rename to demo/src/main/java/top/limitart/demo/net/BinaryMessageDemo.java index 698bec7..3c022b2 100644 --- a/demo/src/main/java/top/limitart/net/BinaryMessageDemo.java +++ b/demo/src/main/java/top/limitart/demo/net/BinaryMessageDemo.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package top.limitart.net; +package top.limitart.demo.net; import top.limitart.net.binary.BinaryMessage; import top.limitart.net.binary.BinaryMessages; diff --git a/demo/src/main/java/top/limitart/net/BinaryMessageDemo2.java b/demo/src/main/java/top/limitart/demo/net/BinaryMessageDemo2.java similarity index 96% rename from demo/src/main/java/top/limitart/net/BinaryMessageDemo2.java rename to demo/src/main/java/top/limitart/demo/net/BinaryMessageDemo2.java index 729b93d..cd74b4e 100644 --- a/demo/src/main/java/top/limitart/net/BinaryMessageDemo2.java +++ b/demo/src/main/java/top/limitart/demo/net/BinaryMessageDemo2.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package top.limitart.net; +package top.limitart.demo.net; import top.limitart.net.binary.BinaryMessage; import top.limitart.net.binary.BinaryMessages; diff --git a/demo/src/main/java/top/limitart/net/BinaryScriptManager.java b/demo/src/main/java/top/limitart/demo/net/BinaryScriptManager.java similarity index 96% rename from demo/src/main/java/top/limitart/net/BinaryScriptManager.java rename to demo/src/main/java/top/limitart/demo/net/BinaryScriptManager.java index e265802..2d02737 100644 --- a/demo/src/main/java/top/limitart/net/BinaryScriptManager.java +++ b/demo/src/main/java/top/limitart/demo/net/BinaryScriptManager.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package top.limitart.net; +package top.limitart.demo.net; import top.limitart.mapping.Mapper; import top.limitart.mapping.Request; diff --git a/demo/src/main/java/top/limitart/net/BinaryScriptManagerImpl.java b/demo/src/main/java/top/limitart/demo/net/BinaryScriptManagerImpl.java similarity index 96% rename from demo/src/main/java/top/limitart/net/BinaryScriptManagerImpl.java rename to demo/src/main/java/top/limitart/demo/net/BinaryScriptManagerImpl.java index e2914f0..545e3e2 100644 --- a/demo/src/main/java/top/limitart/net/BinaryScriptManagerImpl.java +++ b/demo/src/main/java/top/limitart/demo/net/BinaryScriptManagerImpl.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package top.limitart.net; +package top.limitart.demo.net; import top.limitart.net.binary.BinaryRequestParam; diff --git a/demo/src/main/java/top/limitart/net/BinaryServerDemo.java b/demo/src/main/java/top/limitart/demo/net/BinaryServerDemo.java similarity index 94% rename from demo/src/main/java/top/limitart/net/BinaryServerDemo.java rename to demo/src/main/java/top/limitart/demo/net/BinaryServerDemo.java index 8731c00..a897181 100644 --- a/demo/src/main/java/top/limitart/net/BinaryServerDemo.java +++ b/demo/src/main/java/top/limitart/demo/net/BinaryServerDemo.java @@ -13,9 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package top.limitart.net; +package top.limitart.demo.net; import top.limitart.mapping.Router; +import top.limitart.net.AddressPair; +import top.limitart.net.NettySession; import top.limitart.net.binary.BinaryEndPoint; import top.limitart.net.binary.BinaryMessage; import top.limitart.net.binary.BinaryRequestParam; diff --git a/demo/src/main/java/top/limitart/net/BinarySessionRole.java b/demo/src/main/java/top/limitart/demo/net/BinarySessionRole.java similarity index 62% rename from demo/src/main/java/top/limitart/net/BinarySessionRole.java rename to demo/src/main/java/top/limitart/demo/net/BinarySessionRole.java index 357d9fa..bea8b72 100644 --- a/demo/src/main/java/top/limitart/net/BinarySessionRole.java +++ b/demo/src/main/java/top/limitart/demo/net/BinarySessionRole.java @@ -1,6 +1,7 @@ -package top.limitart.net; +package top.limitart.demo.net; +import top.limitart.net.NettySessionActor; import top.limitart.net.binary.BinaryMessage; public class BinarySessionRole extends NettySessionActor {} diff --git a/demo/src/main/java/top/limitart/net/FlashSSLServerDemo.java b/demo/src/main/java/top/limitart/demo/net/FlashSSLServerDemo.java similarity index 80% rename from demo/src/main/java/top/limitart/net/FlashSSLServerDemo.java rename to demo/src/main/java/top/limitart/demo/net/FlashSSLServerDemo.java index 8e46688..ac3c5cc 100644 --- a/demo/src/main/java/top/limitart/net/FlashSSLServerDemo.java +++ b/demo/src/main/java/top/limitart/demo/net/FlashSSLServerDemo.java @@ -1,5 +1,6 @@ -package top.limitart.net; +package top.limitart.demo.net; +import top.limitart.net.AddressPair; import top.limitart.net.flashssl.FlashSSLEndPoint; /** diff --git a/demo/src/main/java/top/limitart/demo/net/HTTPSServerDemo.java b/demo/src/main/java/top/limitart/demo/net/HTTPSServerDemo.java new file mode 100644 index 0000000..725de75 --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/net/HTTPSServerDemo.java @@ -0,0 +1,25 @@ +/* + * + * * Copyright (c) 2016-present The Limitart Project + * * + * * Licensed under the Apache License, Version 2.0 (the "License"); + * * you may not use this file except in compliance with the License. + * * You may obtain a copy of the License at + * * + * * http://www.apache.org/licenses/LICENSE-2.0 + * * + * * Unless required by applicable law or agreed to in writing, software + * * distributed under the License is distributed on an "AS IS" BASIS, + * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * * See the License for the specific language governing permissions and + * * limitations under the License. + * + */ + +package top.limitart.demo.net; + +/** Created by Hank on 2018/10/14 */ +public class HTTPSServerDemo { + // TODO + +} diff --git a/demo/src/main/java/top/limitart/net/HTTPServerDemo.java b/demo/src/main/java/top/limitart/demo/net/HTTPServerDemo.java similarity index 95% rename from demo/src/main/java/top/limitart/net/HTTPServerDemo.java rename to demo/src/main/java/top/limitart/demo/net/HTTPServerDemo.java index 3703e8a..793ec6d 100644 --- a/demo/src/main/java/top/limitart/net/HTTPServerDemo.java +++ b/demo/src/main/java/top/limitart/demo/net/HTTPServerDemo.java @@ -16,8 +16,9 @@ * */ -package top.limitart.net; +package top.limitart.demo.net; +import top.limitart.net.AddressPair; import top.limitart.net.http.HTTPEndPoint; import java.nio.charset.StandardCharsets; diff --git a/demo/src/main/java/top/limitart/net/LocalEndPointDemo.java b/demo/src/main/java/top/limitart/demo/net/LocalEndPointDemo.java similarity index 87% rename from demo/src/main/java/top/limitart/net/LocalEndPointDemo.java rename to demo/src/main/java/top/limitart/demo/net/LocalEndPointDemo.java index bb0e61b..4eeb21e 100644 --- a/demo/src/main/java/top/limitart/net/LocalEndPointDemo.java +++ b/demo/src/main/java/top/limitart/demo/net/LocalEndPointDemo.java @@ -1,6 +1,9 @@ -package top.limitart.net; +package top.limitart.demo.net; +import top.limitart.demo.net.BinaryMessageDemo; import top.limitart.mapping.Router; +import top.limitart.net.AddressPair; +import top.limitart.net.NettyEndPointType; import top.limitart.net.binary.BinaryEndPoint; import top.limitart.net.binary.BinaryMessage; import top.limitart.net.binary.BinaryRequestParam; diff --git a/demo/src/main/java/top/limitart/net/MessageMapper.java b/demo/src/main/java/top/limitart/demo/net/MessageMapper.java similarity index 93% rename from demo/src/main/java/top/limitart/net/MessageMapper.java rename to demo/src/main/java/top/limitart/demo/net/MessageMapper.java index d1ebce6..0629c61 100644 --- a/demo/src/main/java/top/limitart/net/MessageMapper.java +++ b/demo/src/main/java/top/limitart/demo/net/MessageMapper.java @@ -16,12 +16,14 @@ * */ -package top.limitart.net; +package top.limitart.demo.net; import com.google.protobuf.Message; import io.netty.channel.EventLoop; +import top.limitart.demo.net.BinaryMessageDemo; import top.limitart.mapping.Mapper; import top.limitart.mapping.Request; +import top.limitart.net.Session; import top.limitart.net.binary.BinaryMessage; import top.limitart.net.binary.BinaryRequestParam; import top.limitart.net.protobuf.ProtobufRequestParam; diff --git a/demo/src/main/java/top/limitart/net/MessagePackageTest.java b/demo/src/main/java/top/limitart/demo/net/MessagePackageTest.java similarity index 98% rename from demo/src/main/java/top/limitart/net/MessagePackageTest.java rename to demo/src/main/java/top/limitart/demo/net/MessagePackageTest.java index 80b3cf2..a0c9e18 100644 --- a/demo/src/main/java/top/limitart/net/MessagePackageTest.java +++ b/demo/src/main/java/top/limitart/demo/net/MessagePackageTest.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package top.limitart.net; +package top.limitart.demo.net; import top.limitart.base.BinaryMeta; import top.limitart.net.binary.BinaryMessage; diff --git a/demo/src/main/java/top/limitart/net/ProtobufClientDemo.java b/demo/src/main/java/top/limitart/demo/net/ProtobufClientDemo.java similarity index 88% rename from demo/src/main/java/top/limitart/net/ProtobufClientDemo.java rename to demo/src/main/java/top/limitart/demo/net/ProtobufClientDemo.java index 6c4f0b7..4e149e1 100644 --- a/demo/src/main/java/top/limitart/net/ProtobufClientDemo.java +++ b/demo/src/main/java/top/limitart/demo/net/ProtobufClientDemo.java @@ -1,7 +1,9 @@ -package top.limitart.net; +package top.limitart.demo.net; import com.google.protobuf.Message; +import top.limitart.demo.net.MessageMapper; import top.limitart.mapping.Router; +import top.limitart.net.AddressPair; import top.limitart.net.protobuf.ProtobufEndPoint; import top.limitart.net.protobuf.ProtobufRequestParam; diff --git a/demo/src/main/java/top/limitart/demo/net/ProtobufMessageDemo.java b/demo/src/main/java/top/limitart/demo/net/ProtobufMessageDemo.java new file mode 100644 index 0000000..7a08964 --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/net/ProtobufMessageDemo.java @@ -0,0 +1,1334 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: protobuf3.proto + +package top.limitart.demo.net; + +public final class ProtobufMessageDemo { + private ProtobufMessageDemo() {} + + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {} + + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) { + registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); + } + + public interface Demo1OrBuilder + extends + // @@protoc_insertion_point(interface_extends:Demo1) + com.google.protobuf.MessageOrBuilder { + + /** string name = 1; */ + String getName(); + /** string name = 1; */ + com.google.protobuf.ByteString getNameBytes(); + } + /** Protobuf type {@code Demo1} */ + public static final class Demo1 extends com.google.protobuf.GeneratedMessageV3 + implements + // @@protoc_insertion_point(message_implements:Demo1) + Demo1OrBuilder { + private static final long serialVersionUID = 0L; + // Use Demo1.newBuilder() to construct. + private Demo1(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + + private Demo1() { + name_ = ""; + } + + @Override + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { + return this.unknownFields; + } + + private Demo1( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + case 10: + { + String s = input.readStringRequireUtf8(); + + name_ = s; + break; + } + default: + { + if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return ProtobufMessageDemo.internal_static_Demo1_descriptor; + } + + @Override + protected FieldAccessorTable internalGetFieldAccessorTable() { + return ProtobufMessageDemo.internal_static_Demo1_fieldAccessorTable + .ensureFieldAccessorsInitialized(Demo1.class, Builder.class); + } + + public static final int NAME_FIELD_NUMBER = 1; + private volatile Object name_; + /** string name = 1; */ + public String getName() { + Object ref = name_; + if (ref instanceof String) { + return (String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + name_ = s; + return s; + } + } + /** string name = 1; */ + public com.google.protobuf.ByteString getNameBytes() { + Object ref = name_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((String) ref); + name_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + private byte memoizedIsInitialized = -1; + + @Override + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + @Override + public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { + if (!getNameBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_); + } + unknownFields.writeTo(output); + } + + @Override + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + if (!getNameBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @Override + public boolean equals(final Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof Demo1)) { + return super.equals(obj); + } + Demo1 other = (Demo1) obj; + + boolean result = true; + result = result && getName().equals(other.getName()); + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + hash = (37 * hash) + NAME_FIELD_NUMBER; + hash = (53 * hash) + getName().hashCode(); + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static Demo1 parseFrom(java.nio.ByteBuffer data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static Demo1 parseFrom( + java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static Demo1 parseFrom(com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static Demo1 parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static Demo1 parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static Demo1 parseFrom( + byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static Demo1 parseFrom(java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static Demo1 parseFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public static Demo1 parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + } + + public static Demo1 parseDelimitedFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( + PARSER, input, extensionRegistry); + } + + public static Demo1 parseFrom(com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static Demo1 parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + @Override + public Builder newBuilderForType() { + return newBuilder(); + } + + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + + public static Builder newBuilder(Demo1 prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + + @Override + public Builder toBuilder() { + return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + } + + @Override + protected Builder newBuilderForType(BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + /** Protobuf type {@code Demo1} */ + public static final class Builder + extends com.google.protobuf.GeneratedMessageV3.Builder + implements + // @@protoc_insertion_point(builder_implements:Demo1) + Demo1OrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return ProtobufMessageDemo.internal_static_Demo1_descriptor; + } + + @Override + protected FieldAccessorTable internalGetFieldAccessorTable() { + return ProtobufMessageDemo.internal_static_Demo1_fieldAccessorTable + .ensureFieldAccessorsInitialized(Demo1.class, Builder.class); + } + + // Construct using top.limitart.net.ProtobufMessageDemo.Demo1.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} + } + + @Override + public Builder clear() { + super.clear(); + name_ = ""; + + return this; + } + + @Override + public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { + return ProtobufMessageDemo.internal_static_Demo1_descriptor; + } + + @Override + public Demo1 getDefaultInstanceForType() { + return Demo1.getDefaultInstance(); + } + + @Override + public Demo1 build() { + Demo1 result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + @Override + public Demo1 buildPartial() { + Demo1 result = new Demo1(this); + result.name_ = name_; + onBuilt(); + return result; + } + + @Override + public Builder clone() { + return (Builder) super.clone(); + } + + @Override + public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { + return (Builder) super.setField(field, value); + } + + @Override + public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); + } + + @Override + public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); + } + + @Override + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, int index, Object value) { + return (Builder) super.setRepeatedField(field, index, value); + } + + @Override + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { + return (Builder) super.addRepeatedField(field, value); + } + + @Override + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof Demo1) { + return mergeFrom((Demo1) other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(Demo1 other) { + if (other == Demo1.getDefaultInstance()) return this; + if (!other.getName().isEmpty()) { + name_ = other.name_; + onChanged(); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; + } + + @Override + public final boolean isInitialized() { + return true; + } + + @Override + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Demo1 parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (Demo1) e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + + private Object name_ = ""; + /** string name = 1; */ + public String getName() { + Object ref = name_; + if (!(ref instanceof String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + name_ = s; + return s; + } else { + return (String) ref; + } + } + /** string name = 1; */ + public com.google.protobuf.ByteString getNameBytes() { + Object ref = name_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((String) ref); + name_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + /** string name = 1; */ + public Builder setName(String value) { + if (value == null) { + throw new NullPointerException(); + } + + name_ = value; + onChanged(); + return this; + } + /** string name = 1; */ + public Builder clearName() { + + name_ = getDefaultInstance().getName(); + onChanged(); + return this; + } + /** string name = 1; */ + public Builder setNameBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + + name_ = value; + onChanged(); + return this; + } + + @Override + public final Builder setUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFieldsProto3(unknownFields); + } + + @Override + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } + + // @@protoc_insertion_point(builder_scope:Demo1) + } + + // @@protoc_insertion_point(class_scope:Demo1) + private static final Demo1 DEFAULT_INSTANCE; + + static { + DEFAULT_INSTANCE = new Demo1(); + } + + public static Demo1 getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + private static final com.google.protobuf.Parser PARSER = + new com.google.protobuf.AbstractParser() { + @Override + public Demo1 parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new Demo1(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + @Override + public Demo1 getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } + } + + public interface Demo2OrBuilder + extends + // @@protoc_insertion_point(interface_extends:Demo2) + com.google.protobuf.MessageOrBuilder { + + /** repeated .Demo1 demo1 = 1; */ + java.util.List getDemo1List(); + /** repeated .Demo1 demo1 = 1; */ + Demo1 getDemo1(int index); + /** repeated .Demo1 demo1 = 1; */ + int getDemo1Count(); + /** repeated .Demo1 demo1 = 1; */ + java.util.List getDemo1OrBuilderList(); + /** repeated .Demo1 demo1 = 1; */ + Demo1OrBuilder getDemo1OrBuilder(int index); + + /** int32 id = 2; */ + int getId(); + } + /** Protobuf type {@code Demo2} */ + public static final class Demo2 extends com.google.protobuf.GeneratedMessageV3 + implements + // @@protoc_insertion_point(message_implements:Demo2) + Demo2OrBuilder { + private static final long serialVersionUID = 0L; + // Use Demo2.newBuilder() to construct. + private Demo2(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + + private Demo2() { + demo1_ = java.util.Collections.emptyList(); + id_ = 0; + } + + @Override + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { + return this.unknownFields; + } + + private Demo2( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + case 10: + { + if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) { + demo1_ = new java.util.ArrayList(); + mutable_bitField0_ |= 0x00000001; + } + demo1_.add(input.readMessage(Demo1.parser(), extensionRegistry)); + break; + } + case 16: + { + id_ = input.readInt32(); + break; + } + default: + { + if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); + } finally { + if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) { + demo1_ = java.util.Collections.unmodifiableList(demo1_); + } + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return ProtobufMessageDemo.internal_static_Demo2_descriptor; + } + + @Override + protected FieldAccessorTable internalGetFieldAccessorTable() { + return ProtobufMessageDemo.internal_static_Demo2_fieldAccessorTable + .ensureFieldAccessorsInitialized(Demo2.class, Builder.class); + } + + private int bitField0_; + public static final int DEMO1_FIELD_NUMBER = 1; + private java.util.List demo1_; + /** repeated .Demo1 demo1 = 1; */ + public java.util.List getDemo1List() { + return demo1_; + } + /** repeated .Demo1 demo1 = 1; */ + public java.util.List getDemo1OrBuilderList() { + return demo1_; + } + /** repeated .Demo1 demo1 = 1; */ + public int getDemo1Count() { + return demo1_.size(); + } + /** repeated .Demo1 demo1 = 1; */ + public Demo1 getDemo1(int index) { + return demo1_.get(index); + } + /** repeated .Demo1 demo1 = 1; */ + public Demo1OrBuilder getDemo1OrBuilder(int index) { + return demo1_.get(index); + } + + public static final int ID_FIELD_NUMBER = 2; + private int id_; + /** int32 id = 2; */ + public int getId() { + return id_; + } + + private byte memoizedIsInitialized = -1; + + @Override + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + @Override + public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { + for (int i = 0; i < demo1_.size(); i++) { + output.writeMessage(1, demo1_.get(i)); + } + if (id_ != 0) { + output.writeInt32(2, id_); + } + unknownFields.writeTo(output); + } + + @Override + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + for (int i = 0; i < demo1_.size(); i++) { + size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, demo1_.get(i)); + } + if (id_ != 0) { + size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, id_); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @Override + public boolean equals(final Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof Demo2)) { + return super.equals(obj); + } + Demo2 other = (Demo2) obj; + + boolean result = true; + result = result && getDemo1List().equals(other.getDemo1List()); + result = result && (getId() == other.getId()); + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + if (getDemo1Count() > 0) { + hash = (37 * hash) + DEMO1_FIELD_NUMBER; + hash = (53 * hash) + getDemo1List().hashCode(); + } + hash = (37 * hash) + ID_FIELD_NUMBER; + hash = (53 * hash) + getId(); + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static Demo2 parseFrom(java.nio.ByteBuffer data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static Demo2 parseFrom( + java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static Demo2 parseFrom(com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static Demo2 parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static Demo2 parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static Demo2 parseFrom( + byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static Demo2 parseFrom(java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static Demo2 parseFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public static Demo2 parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + } + + public static Demo2 parseDelimitedFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( + PARSER, input, extensionRegistry); + } + + public static Demo2 parseFrom(com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static Demo2 parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + @Override + public Builder newBuilderForType() { + return newBuilder(); + } + + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + + public static Builder newBuilder(Demo2 prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + + @Override + public Builder toBuilder() { + return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + } + + @Override + protected Builder newBuilderForType(BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + /** Protobuf type {@code Demo2} */ + public static final class Builder + extends com.google.protobuf.GeneratedMessageV3.Builder + implements + // @@protoc_insertion_point(builder_implements:Demo2) + Demo2OrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return ProtobufMessageDemo.internal_static_Demo2_descriptor; + } + + @Override + protected FieldAccessorTable internalGetFieldAccessorTable() { + return ProtobufMessageDemo.internal_static_Demo2_fieldAccessorTable + .ensureFieldAccessorsInitialized(Demo2.class, Builder.class); + } + + // Construct using top.limitart.net.ProtobufMessageDemo.Demo2.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { + getDemo1FieldBuilder(); + } + } + + @Override + public Builder clear() { + super.clear(); + if (demo1Builder_ == null) { + demo1_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000001); + } else { + demo1Builder_.clear(); + } + id_ = 0; + + return this; + } + + @Override + public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { + return ProtobufMessageDemo.internal_static_Demo2_descriptor; + } + + @Override + public Demo2 getDefaultInstanceForType() { + return Demo2.getDefaultInstance(); + } + + @Override + public Demo2 build() { + Demo2 result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + @Override + public Demo2 buildPartial() { + Demo2 result = new Demo2(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (demo1Builder_ == null) { + if (((bitField0_ & 0x00000001) == 0x00000001)) { + demo1_ = java.util.Collections.unmodifiableList(demo1_); + bitField0_ = (bitField0_ & ~0x00000001); + } + result.demo1_ = demo1_; + } else { + result.demo1_ = demo1Builder_.build(); + } + result.id_ = id_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + @Override + public Builder clone() { + return (Builder) super.clone(); + } + + @Override + public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { + return (Builder) super.setField(field, value); + } + + @Override + public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); + } + + @Override + public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); + } + + @Override + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, int index, Object value) { + return (Builder) super.setRepeatedField(field, index, value); + } + + @Override + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { + return (Builder) super.addRepeatedField(field, value); + } + + @Override + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof Demo2) { + return mergeFrom((Demo2) other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(Demo2 other) { + if (other == Demo2.getDefaultInstance()) return this; + if (demo1Builder_ == null) { + if (!other.demo1_.isEmpty()) { + if (demo1_.isEmpty()) { + demo1_ = other.demo1_; + bitField0_ = (bitField0_ & ~0x00000001); + } else { + ensureDemo1IsMutable(); + demo1_.addAll(other.demo1_); + } + onChanged(); + } + } else { + if (!other.demo1_.isEmpty()) { + if (demo1Builder_.isEmpty()) { + demo1Builder_.dispose(); + demo1Builder_ = null; + demo1_ = other.demo1_; + bitField0_ = (bitField0_ & ~0x00000001); + demo1Builder_ = + com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders + ? getDemo1FieldBuilder() + : null; + } else { + demo1Builder_.addAllMessages(other.demo1_); + } + } + } + if (other.getId() != 0) { + setId(other.getId()); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; + } + + @Override + public final boolean isInitialized() { + return true; + } + + @Override + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Demo2 parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (Demo2) e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + + private int bitField0_; + + private java.util.List demo1_ = java.util.Collections.emptyList(); + + private void ensureDemo1IsMutable() { + if (!((bitField0_ & 0x00000001) == 0x00000001)) { + demo1_ = new java.util.ArrayList(demo1_); + bitField0_ |= 0x00000001; + } + } + + private com.google.protobuf.RepeatedFieldBuilderV3 + demo1Builder_; + + /** repeated .Demo1 demo1 = 1; */ + public java.util.List getDemo1List() { + if (demo1Builder_ == null) { + return java.util.Collections.unmodifiableList(demo1_); + } else { + return demo1Builder_.getMessageList(); + } + } + /** repeated .Demo1 demo1 = 1; */ + public int getDemo1Count() { + if (demo1Builder_ == null) { + return demo1_.size(); + } else { + return demo1Builder_.getCount(); + } + } + /** repeated .Demo1 demo1 = 1; */ + public Demo1 getDemo1(int index) { + if (demo1Builder_ == null) { + return demo1_.get(index); + } else { + return demo1Builder_.getMessage(index); + } + } + /** repeated .Demo1 demo1 = 1; */ + public Builder setDemo1(int index, Demo1 value) { + if (demo1Builder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureDemo1IsMutable(); + demo1_.set(index, value); + onChanged(); + } else { + demo1Builder_.setMessage(index, value); + } + return this; + } + /** repeated .Demo1 demo1 = 1; */ + public Builder setDemo1(int index, Demo1.Builder builderForValue) { + if (demo1Builder_ == null) { + ensureDemo1IsMutable(); + demo1_.set(index, builderForValue.build()); + onChanged(); + } else { + demo1Builder_.setMessage(index, builderForValue.build()); + } + return this; + } + /** repeated .Demo1 demo1 = 1; */ + public Builder addDemo1(Demo1 value) { + if (demo1Builder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureDemo1IsMutable(); + demo1_.add(value); + onChanged(); + } else { + demo1Builder_.addMessage(value); + } + return this; + } + /** repeated .Demo1 demo1 = 1; */ + public Builder addDemo1(int index, Demo1 value) { + if (demo1Builder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureDemo1IsMutable(); + demo1_.add(index, value); + onChanged(); + } else { + demo1Builder_.addMessage(index, value); + } + return this; + } + /** repeated .Demo1 demo1 = 1; */ + public Builder addDemo1(Demo1.Builder builderForValue) { + if (demo1Builder_ == null) { + ensureDemo1IsMutable(); + demo1_.add(builderForValue.build()); + onChanged(); + } else { + demo1Builder_.addMessage(builderForValue.build()); + } + return this; + } + /** repeated .Demo1 demo1 = 1; */ + public Builder addDemo1(int index, Demo1.Builder builderForValue) { + if (demo1Builder_ == null) { + ensureDemo1IsMutable(); + demo1_.add(index, builderForValue.build()); + onChanged(); + } else { + demo1Builder_.addMessage(index, builderForValue.build()); + } + return this; + } + /** repeated .Demo1 demo1 = 1; */ + public Builder addAllDemo1(Iterable values) { + if (demo1Builder_ == null) { + ensureDemo1IsMutable(); + com.google.protobuf.AbstractMessageLite.Builder.addAll(values, demo1_); + onChanged(); + } else { + demo1Builder_.addAllMessages(values); + } + return this; + } + /** repeated .Demo1 demo1 = 1; */ + public Builder clearDemo1() { + if (demo1Builder_ == null) { + demo1_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000001); + onChanged(); + } else { + demo1Builder_.clear(); + } + return this; + } + /** repeated .Demo1 demo1 = 1; */ + public Builder removeDemo1(int index) { + if (demo1Builder_ == null) { + ensureDemo1IsMutable(); + demo1_.remove(index); + onChanged(); + } else { + demo1Builder_.remove(index); + } + return this; + } + /** repeated .Demo1 demo1 = 1; */ + public Demo1.Builder getDemo1Builder(int index) { + return getDemo1FieldBuilder().getBuilder(index); + } + /** repeated .Demo1 demo1 = 1; */ + public Demo1OrBuilder getDemo1OrBuilder(int index) { + if (demo1Builder_ == null) { + return demo1_.get(index); + } else { + return demo1Builder_.getMessageOrBuilder(index); + } + } + /** repeated .Demo1 demo1 = 1; */ + public java.util.List getDemo1OrBuilderList() { + if (demo1Builder_ != null) { + return demo1Builder_.getMessageOrBuilderList(); + } else { + return java.util.Collections.unmodifiableList(demo1_); + } + } + /** repeated .Demo1 demo1 = 1; */ + public Demo1.Builder addDemo1Builder() { + return getDemo1FieldBuilder().addBuilder(Demo1.getDefaultInstance()); + } + /** repeated .Demo1 demo1 = 1; */ + public Demo1.Builder addDemo1Builder(int index) { + return getDemo1FieldBuilder().addBuilder(index, Demo1.getDefaultInstance()); + } + /** repeated .Demo1 demo1 = 1; */ + public java.util.List getDemo1BuilderList() { + return getDemo1FieldBuilder().getBuilderList(); + } + + private com.google.protobuf.RepeatedFieldBuilderV3 + getDemo1FieldBuilder() { + if (demo1Builder_ == null) { + demo1Builder_ = + new com.google.protobuf.RepeatedFieldBuilderV3( + demo1_, + ((bitField0_ & 0x00000001) == 0x00000001), + getParentForChildren(), + isClean()); + demo1_ = null; + } + return demo1Builder_; + } + + private int id_; + /** int32 id = 2; */ + public int getId() { + return id_; + } + /** int32 id = 2; */ + public Builder setId(int value) { + + id_ = value; + onChanged(); + return this; + } + /** int32 id = 2; */ + public Builder clearId() { + + id_ = 0; + onChanged(); + return this; + } + + @Override + public final Builder setUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFieldsProto3(unknownFields); + } + + @Override + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } + + // @@protoc_insertion_point(builder_scope:Demo2) + } + + // @@protoc_insertion_point(class_scope:Demo2) + private static final Demo2 DEFAULT_INSTANCE; + + static { + DEFAULT_INSTANCE = new Demo2(); + } + + public static Demo2 getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + private static final com.google.protobuf.Parser PARSER = + new com.google.protobuf.AbstractParser() { + @Override + public Demo2 parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new Demo2(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + @Override + public Demo2 getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } + } + + private static final com.google.protobuf.Descriptors.Descriptor internal_static_Demo1_descriptor; + private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_Demo1_fieldAccessorTable; + private static final com.google.protobuf.Descriptors.Descriptor internal_static_Demo2_descriptor; + private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_Demo2_fieldAccessorTable; + + public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { + return descriptor; + } + + private static com.google.protobuf.Descriptors.FileDescriptor descriptor; + + static { + String[] descriptorData = { + "\n\017protobuf3.proto\"\025\n\005Demo1\022\014\n\004name\030\001 \001(\t" + + "\"*\n\005Demo2\022\025\n\005demo1\030\001 \003(\0132\006.Demo1\022\n\n\002id\030\002" + + " \001(\005B\'\n\020top.limitart.netB\023ProtobufMessag" + + "eDemob\006proto3" + }; + com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = + new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { + public com.google.protobuf.ExtensionRegistry assignDescriptors( + com.google.protobuf.Descriptors.FileDescriptor root) { + descriptor = root; + return null; + } + }; + com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom( + descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] {}, assigner); + internal_static_Demo1_descriptor = getDescriptor().getMessageTypes().get(0); + internal_static_Demo1_fieldAccessorTable = + new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_Demo1_descriptor, + new String[] { + "Name", + }); + internal_static_Demo2_descriptor = getDescriptor().getMessageTypes().get(1); + internal_static_Demo2_fieldAccessorTable = + new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_Demo2_descriptor, + new String[] { + "Demo1", "Id", + }); + } + + // @@protoc_insertion_point(outer_class_scope) +} diff --git a/demo/src/main/java/top/limitart/net/ProtobufServerDemo.java b/demo/src/main/java/top/limitart/demo/net/ProtobufServerDemo.java similarity index 93% rename from demo/src/main/java/top/limitart/net/ProtobufServerDemo.java rename to demo/src/main/java/top/limitart/demo/net/ProtobufServerDemo.java index b188f4a..4718c90 100644 --- a/demo/src/main/java/top/limitart/net/ProtobufServerDemo.java +++ b/demo/src/main/java/top/limitart/demo/net/ProtobufServerDemo.java @@ -13,10 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package top.limitart.net; +package top.limitart.demo.net; import com.google.protobuf.Message; +import top.limitart.demo.net.MessageMapper; import top.limitart.mapping.Router; +import top.limitart.net.AddressPair; import top.limitart.net.protobuf.ProtobufEndPoint; import top.limitart.net.protobuf.ProtobufRequestParam; diff --git a/demo/src/main/java/top/limitart/demo/net/ProtobufSessionRole.java b/demo/src/main/java/top/limitart/demo/net/ProtobufSessionRole.java new file mode 100644 index 0000000..9112703 --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/net/ProtobufSessionRole.java @@ -0,0 +1,7 @@ +package top.limitart.demo.net; + + +import com.google.protobuf.Message; +import top.limitart.net.NettySessionActor; + +public class ProtobufSessionRole extends NettySessionActor {} diff --git a/demo/src/main/java/top/limitart/demo/net/WebSocketServerDemo.java b/demo/src/main/java/top/limitart/demo/net/WebSocketServerDemo.java new file mode 100644 index 0000000..7d3a5aa --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/net/WebSocketServerDemo.java @@ -0,0 +1,56 @@ +/* + * + * * Copyright (c) 2016-present The Limitart Project + * * + * * Licensed under the Apache License, Version 2.0 (the "License"); + * * you may not use this file except in compliance with the License. + * * You may obtain a copy of the License at + * * + * * http://www.apache.org/licenses/LICENSE-2.0 + * * + * * Unless required by applicable law or agreed to in writing, software + * * distributed under the License is distributed on an "AS IS" BASIS, + * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * * See the License for the specific language governing permissions and + * * limitations under the License. + * + */ + +package top.limitart.demo.net; + +import io.netty.channel.EventLoop; +import io.netty.handler.codec.http.websocketx.WebSocketFrame; +import top.limitart.net.AddressPair; +import top.limitart.net.NettyEndPointType; +import top.limitart.net.NettySession; +import top.limitart.net.Session; +import top.limitart.net.binary.BinaryMessage; +import top.limitart.net.http.HTTPRequest; +import top.limitart.net.http.HTTPSession; +import top.limitart.net.websocket.WebSocketEndPoint; + +/** Created by Hank on 2019/2/24 */ +public class WebSocketServerDemo { + public static void main(String[] args) throws Exception { + new WebSocketEndPoint("web-socket-server", "/", NettyEndPointType.SERVER_REMOTE, 0, 0) { + @Override + protected void exceptionThrown(NettySession session, Throwable cause) + throws Exception {} + + @Override + protected void sessionActive(NettySession session, boolean activeOrNot) + throws Exception {} + + @Override + protected void onWebSocketFrameReceived( + Session session, WebSocketFrame msg) { + + } + + @Override + protected void onHttpRequestReceived(HTTPSession session, HTTPRequest msg) { + System.out.println(msg); + } + }.start(AddressPair.withPort(8888)); + } +} diff --git a/demo/src/main/java/top/limitart/demo/redefinable/HelloRedefine.java b/demo/src/main/java/top/limitart/demo/redefinable/HelloRedefine.java new file mode 100644 index 0000000..c4677b4 --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/redefinable/HelloRedefine.java @@ -0,0 +1,7 @@ +package top.limitart.demo.redefinable; + +public class HelloRedefine { + public void hello(){ + System.out.println("hello"); + } +} diff --git a/demo/src/main/java/top/limitart/demo/redefinable/RedefinableDemo.java b/demo/src/main/java/top/limitart/demo/redefinable/RedefinableDemo.java new file mode 100644 index 0000000..a20c01d --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/redefinable/RedefinableDemo.java @@ -0,0 +1,11 @@ +package top.limitart.demo.redefinable; + +import java.io.File; +import top.limitart.redefinable.RedefinableApplication; + +public class RedefinableDemo { + public static void main(String[] args) throws Exception { + RedefinableApplication demo = new RedefinableApplication(new File("e://script.jar").toURI(),"top.limitart.redefinable.ScriptEntrance"); + demo.run(args); + } +} diff --git a/demo/src/main/java/top/limitart/demo/redefinable/ScriptEntrance.java b/demo/src/main/java/top/limitart/demo/redefinable/ScriptEntrance.java new file mode 100644 index 0000000..f6187c6 --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/redefinable/ScriptEntrance.java @@ -0,0 +1,24 @@ +package top.limitart.demo.redefinable; + +import top.limitart.redefinable.RedefinableApplicationContext; +import top.limitart.redefinable.RedefinableModule; + +public class ScriptEntrance extends RedefinableModule { + private HelloRedefine helloRedefine = new HelloRedefine(); + @Override + public void onStart(RedefinableApplicationContext context) { + System.out.println("onStart"); + helloRedefine.hello(); + } + + @Override + public void onRedefined(RedefinableApplicationContext context) { + System.out.println("onRedefined"); + helloRedefine.hello(); + } + + @Override + public void onDestroy(RedefinableApplicationContext context) { + System.out.println("onDestroy"); + } +} diff --git a/demo/src/main/java/top/limitart/demo/script/AutoReloadScriptDemo.java b/demo/src/main/java/top/limitart/demo/script/AutoReloadScriptDemo.java new file mode 100644 index 0000000..2db1dfb --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/script/AutoReloadScriptDemo.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2016-present The Limitart Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package top.limitart.demo.script; + +import java.io.IOException; +import top.limitart.script.FileScriptLoader; +import top.limitart.script.ScriptConstructException; +import top.limitart.script.ScriptKeyDuplicatedException; +import top.limitart.script.ScriptNotExistException; + +/** @author hank */ +public class AutoReloadScriptDemo { + public static void main(String[] args) + throws InstantiationException, IllegalAccessException, IOException, ScriptConstructException, + ScriptNotExistException, ScriptKeyDuplicatedException, InterruptedException { + FileScriptLoader loader = new FileScriptLoader<>("./demo/script", 5); + while (true) { + Thread.sleep(1000); + top.limitart.demo.script.HelloScript script = loader.getScript(1); + script.sayHello(); + } + } +} diff --git a/demo/src/main/java/top/limitart/demo/script/HelloScript.java b/demo/src/main/java/top/limitart/demo/script/HelloScript.java new file mode 100644 index 0000000..1dc448d --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/script/HelloScript.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2016-present The Limitart Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package top.limitart.demo.script; + +import top.limitart.script.Script; + +/** + * 脚本引用测试 + * + * @author hank + */ +public interface HelloScript extends Script { + void sayHello(); +} diff --git a/demo/src/main/java/top/limitart/demo/script/ScriptSourceDemo.java b/demo/src/main/java/top/limitart/demo/script/ScriptSourceDemo.java new file mode 100644 index 0000000..fdc07b0 --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/script/ScriptSourceDemo.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2016-present The Limitart Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package top.limitart.demo.script; + +/** + * 脚本编译测试 + * + * @author hank + */ +public class ScriptSourceDemo implements Runnable { + + private class ScriptSourceInnerPrivate { + public void say() { + System.out.println("hello inner"); + } + } + + @Override + public void run() { + System.out.println("hello limitart"); + ((Runnable) () -> System.out.println("inner")).run(); + ScriptSourceInnerPrivate temp = new ScriptSourceInnerPrivate(); + temp.say(); + } + + public class ScriptSourceDemoInnerPublic {} +} + +class ScriptSourceDemoPrivate {} diff --git a/demo/src/main/java/top/limitart/demo/singleton/SingletonA.java b/demo/src/main/java/top/limitart/demo/singleton/SingletonA.java new file mode 100644 index 0000000..4b3935b --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/singleton/SingletonA.java @@ -0,0 +1,14 @@ +package top.limitart.demo.singleton; + +import top.limitart.singleton.Ref; +import top.limitart.singleton.Singleton; + +@Singleton +public class SingletonA { + @Ref + SingletonB singletonB; + + public void say() { + System.out.println(singletonB); + } +} diff --git a/demo/src/main/java/top/limitart/demo/singleton/SingletonB.java b/demo/src/main/java/top/limitart/demo/singleton/SingletonB.java new file mode 100644 index 0000000..989597a --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/singleton/SingletonB.java @@ -0,0 +1,20 @@ +package top.limitart.demo.singleton; + +import top.limitart.singleton.Ref; +import top.limitart.singleton.Singleton; + +@Singleton +public class SingletonB { + @Ref + SingletonA singletonA; + @Ref + SingletonC singletonC; + @Ref + SingletonD singletonD; + + public void say() { + System.out.println(singletonA); + System.out.println(singletonC); + System.out.println(singletonD); + } +} diff --git a/demo/src/main/java/top/limitart/demo/singleton/SingletonC.java b/demo/src/main/java/top/limitart/demo/singleton/SingletonC.java new file mode 100644 index 0000000..a3a106c --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/singleton/SingletonC.java @@ -0,0 +1,34 @@ +/* + * + * * Copyright (c) 2016-present The Limitart Project + * * + * * Licensed under the Apache License, Version 2.0 (the "License"); + * * you may not use this file except in compliance with the License. + * * You may obtain a copy of the License at + * * + * * http://www.apache.org/licenses/LICENSE-2.0 + * * + * * Unless required by applicable law or agreed to in writing, software + * * distributed under the License is distributed on an "AS IS" BASIS, + * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * * See the License for the specific language governing permissions and + * * limitations under the License. + * + */ + +package top.limitart.demo.singleton; + +import top.limitart.singleton.Ref; +import top.limitart.singleton.Singleton; + +/** Created by Hank on 2018/12/11 */ +@Singleton +public class SingletonC { + @Ref + SingletonC singletonC; + + @Ref + public SingletonC(SingletonA singletonA, SingletonB singletonB) { + System.out.println("construct C"); + } +} diff --git a/demo/src/main/java/top/limitart/demo/singleton/SingletonD.java b/demo/src/main/java/top/limitart/demo/singleton/SingletonD.java new file mode 100644 index 0000000..a84dd77 --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/singleton/SingletonD.java @@ -0,0 +1,36 @@ +/* + * + * * Copyright (c) 2016-present The Limitart Project + * * + * * Licensed under the Apache License, Version 2.0 (the "License"); + * * you may not use this file except in compliance with the License. + * * You may obtain a copy of the License at + * * + * * http://www.apache.org/licenses/LICENSE-2.0 + * * + * * Unless required by applicable law or agreed to in writing, software + * * distributed under the License is distributed on an "AS IS" BASIS, + * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * * See the License for the specific language governing permissions and + * * limitations under the License. + * + */ + +package top.limitart.demo.singleton; + +import top.limitart.singleton.Ref; +import top.limitart.singleton.Singleton; + +/** Created by Hank on 2018/12/11 */ +@Singleton +public class SingletonD { + @Ref + public SingletonD(SingletonC singletonC) { + System.out.println("construct D"); + } + + @Ref + public void setSingletonA(SingletonA singletonA) { + System.out.println(singletonA); + } +} diff --git a/demo/src/main/java/top/limitart/demo/singleton/SingletonDemo.java b/demo/src/main/java/top/limitart/demo/singleton/SingletonDemo.java new file mode 100644 index 0000000..8a99eb1 --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/singleton/SingletonDemo.java @@ -0,0 +1,30 @@ +package top.limitart.demo.singleton; + +import top.limitart.demo.singleton.SingletonA; +import top.limitart.demo.singleton.SingletonB; +import top.limitart.demo.singleton.SingletonC; +import top.limitart.singleton.Ref; +import top.limitart.singleton.Singletons; + +public class SingletonDemo { + @Ref + SingletonB singletonB; + @Ref + SingletonA singletonA; + @Ref + SingletonC singletonC; + + public void say() { + singletonB.say(); + singletonA.say(); + } + + public static void main(String[] args) { + new Singletons.Builder() + .withPackage("top.limitart", SingletonDemo.class.getClassLoader()) + .bind(SingletonDemo.class) + .build() + .instance(SingletonDemo.class) + .say(); + } +} diff --git a/fastmq/consumer/src/main/java/top/limitart/fastmq/consumer/ConsumerBinaryClient.java b/fastmq/consumer/src/main/java/top/limitart/fastmq/consumer/MQConsumerBinaryClient.java similarity index 91% rename from fastmq/consumer/src/main/java/top/limitart/fastmq/consumer/ConsumerBinaryClient.java rename to fastmq/consumer/src/main/java/top/limitart/fastmq/consumer/MQConsumerBinaryClient.java index ee5fe59..4b5fe81 100644 --- a/fastmq/consumer/src/main/java/top/limitart/fastmq/consumer/ConsumerBinaryClient.java +++ b/fastmq/consumer/src/main/java/top/limitart/fastmq/consumer/MQConsumerBinaryClient.java @@ -7,7 +7,6 @@ import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import top.limitart.base.ApplicationBootstrap; @@ -37,9 +36,9 @@ import top.limitart.util.FileUtil; import top.limitart.util.StringUtil; import top.limitart.util.TimeUtil; -public class ConsumerBinaryClient extends ApplicationBootstrap { +public class MQConsumerBinaryClient extends ApplicationBootstrap { - private static final Logger LOGGER = LoggerFactory.getLogger(ConsumerBinaryClient.class); + private static final Logger LOGGER = LoggerFactory.getLogger(MQConsumerBinaryClient.class); private static final String TOKEN_FILE = "pipeline-token.tmp"; private static final long PULL_REQUEST_INTERVAL = TimeUnit.SECONDS.toMillis(5); private BinaryEndPoint client; @@ -54,7 +53,7 @@ public class ConsumerBinaryClient extends ApplicationBootstrap { private Session session; private boolean handling = false; - public ConsumerBinaryClient( + public MQConsumerBinaryClient( String remoteIp, int port, String zone, List tags, ConsumerMsgHandler msgHandler) throws Exception { this.remoteAddress = AddressPair.withIP(remoteIp, port); @@ -147,8 +146,8 @@ public class ConsumerBinaryClient extends ApplicationBootstrap { */ private void signOnPipeline(NettySession session) { ReqRegisterZoneMsg msg = new ReqRegisterZoneMsg(); - msg.zone = ConsumerBinaryClient.this.zone; - msg.tags = ConsumerBinaryClient.this.tags; + msg.zone = MQConsumerBinaryClient.this.zone; + msg.tags = MQConsumerBinaryClient.this.tags; session.writeNow( msg, (b, t) -> { @@ -175,12 +174,12 @@ public class ConsumerBinaryClient extends ApplicationBootstrap { LOGGER.error("pipeline {} response a empty token???", request.session()); return; } - ConsumerBinaryClient.this.token = msg.token; + MQConsumerBinaryClient.this.token = msg.token; try { FileUtil.writeNewFile( "." + File.separator, TOKEN_FILE, - ConsumerBinaryClient.this.token.getBytes(StandardCharsets.UTF_8)); + MQConsumerBinaryClient.this.token.getBytes(StandardCharsets.UTF_8)); LOGGER.info("write token {} on {}", msg.token, TOKEN_FILE); } catch (IOException e) { LOGGER.error("write token on disk error", e); @@ -192,8 +191,8 @@ public class ConsumerBinaryClient extends ApplicationBootstrap { private void ready(Session session) { ReqCustomerReadyMsg msg = new ReqCustomerReadyMsg(); - msg.zone = ConsumerBinaryClient.this.zone; - msg.token = ConsumerBinaryClient.this.token; + msg.zone = MQConsumerBinaryClient.this.zone; + msg.token = MQConsumerBinaryClient.this.token; session.writeNow( msg, (b, t) -> { @@ -212,7 +211,7 @@ public class ConsumerBinaryClient extends ApplicationBootstrap { * @param request */ public void onNeedClaim(@Request ReqZoneClaimMsg msg, BinaryRequest request) { - if (StringUtil.empty(ConsumerBinaryClient.this.token)) { + if (StringUtil.empty(MQConsumerBinaryClient.this.token)) { LOGGER.error("no old token to claim pipeline {}", remoteAddress); return; } @@ -226,7 +225,7 @@ public class ConsumerBinaryClient extends ApplicationBootstrap { */ public void onPipelineEstablished( @Request ResPipelineEstablishedMsg msg, BinaryRequest request) { - ConsumerBinaryClient.this.session = request.session(); + MQConsumerBinaryClient.this.session = request.session(); LOGGER.info("pipeline {} established!", remoteAddress); } @@ -240,7 +239,7 @@ public class ConsumerBinaryClient extends ApplicationBootstrap { handling = true; for (byte[] bytes : msg.msgs) { try { - ConsumerBinaryClient.this.msgHandler.onMsg(bytes); + MQConsumerBinaryClient.this.msgHandler.onMsg(bytes); } catch (Exception e) { LOGGER.error("msg handle error", e); } diff --git a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/AbstractBinaryServer.java b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/AbstractBinaryServer.java deleted file mode 100644 index 7ad6fcb..0000000 --- a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/AbstractBinaryServer.java +++ /dev/null @@ -1,7 +0,0 @@ -package top.limitart.fastmq.pipeline; - -import top.limitart.fastmq.pipeline.core.Pipeline; - -public class AbstractBinaryServer { - private Pipeline pipeline; -} diff --git a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/PipelineBinaryServer.java b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/MQPipelineBinaryServer.java similarity index 94% rename from fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/PipelineBinaryServer.java rename to fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/MQPipelineBinaryServer.java index 184fcac..a404566 100644 --- a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/PipelineBinaryServer.java +++ b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/MQPipelineBinaryServer.java @@ -44,16 +44,16 @@ import top.limitart.util.MathUtil; import top.limitart.util.RandomUtil; import top.limitart.util.StringUtil; -public class PipelineBinaryServer extends ApplicationBootstrap { +public class MQPipelineBinaryServer extends ApplicationBootstrap { - private static Logger LOGGER = LoggerFactory.getLogger(PipelineBinaryServer.class); + private static Logger LOGGER = LoggerFactory.getLogger(MQPipelineBinaryServer.class); private Pipeline pipeline; private BinaryEndPoint endPoint; private PipelineBinaryHandler handler; private int port; private Map prs = new ConcurrentHashMap<>(); - public PipelineBinaryServer(Pipeline pipeline, int port) throws Exception { + public MQPipelineBinaryServer(Pipeline pipeline, int port) throws Exception { this.pipeline = pipeline; this.port = port; this.handler = new PipelineBinaryHandler(); @@ -220,7 +220,7 @@ public class PipelineBinaryServer extends ApplicationBootstrap { LOGGER.error("session {} is not validated", session); return; } - PipelineRingBuffer buffer = PipelineBinaryServer.this.pipeline + PipelineRingBuffer buffer = MQPipelineBinaryServer.this.pipeline .getBufferByZone(zone, true); if (buffer == null) { LOGGER.error("session {} , zone {} has no buffer", session, zone); @@ -266,7 +266,7 @@ public class PipelineBinaryServer extends ApplicationBootstrap { request.session().writeNow(ResPushMsgResultMsg.NO_MSG_CONTENT); return; } - States zoneState = PipelineBinaryServer.this.pipeline.getZoneState(msg.zone); + States zoneState = MQPipelineBinaryServer.this.pipeline.getZoneState(msg.zone); if (zoneState == null) { request.session().writeNow(ResPushMsgResultMsg.NO_ZONE); return; @@ -275,7 +275,7 @@ public class PipelineBinaryServer extends ApplicationBootstrap { request.session().writeNow(ResPushMsgResultMsg.ZONE_NOT_ACTIVE); return; } - PipelineRingBuffer buffer = PipelineBinaryServer.this.pipeline + PipelineRingBuffer buffer = MQPipelineBinaryServer.this.pipeline .getBufferByZone(msg.zone, true); if (buffer == null) { request.session().writeNow(ResPushMsgResultMsg.ZONE_HAS_NO_BUFFER); @@ -299,7 +299,7 @@ public class PipelineBinaryServer extends ApplicationBootstrap { request.session().writeNow(ResPushMsgResultMsg.NO_MSG_CONTENT); return; } - List> buffers = PipelineBinaryServer.this.pipeline + List> buffers = MQPipelineBinaryServer.this.pipeline .getBuffersByTags(new HashSet<>(msg.tags), true); if (buffers.isEmpty()) { request.session().writeNow(ResPushMsgResultMsg.CAN_NOT_FIND_ZONE_BY_TAGS); @@ -321,7 +321,7 @@ public class PipelineBinaryServer extends ApplicationBootstrap { request.session().writeNow(ResPushMsgResultMsg.NO_MSG_CONTENT); return; } - List> allBuffers = PipelineBinaryServer.this.pipeline + List> allBuffers = MQPipelineBinaryServer.this.pipeline .getAllBuffers(true); boolean allFail = true; for (PipelineRingBuffer buffer : allBuffers) { @@ -348,7 +348,7 @@ public class PipelineBinaryServer extends ApplicationBootstrap { request.session().writeNow(ResPushMsgResultMsg.NO_MSG_CONTENT); return; } - List> buffers = PipelineBinaryServer.this.pipeline + List> buffers = MQPipelineBinaryServer.this.pipeline .getBuffersByTags(new HashSet<>(msg.tags), true); if (buffers.isEmpty()) { request.session().writeNow(ResPushMsgResultMsg.CAN_NOT_FIND_ZONE_BY_TAGS); @@ -373,7 +373,7 @@ public class PipelineBinaryServer extends ApplicationBootstrap { if (pipelineBinarySession == null) { return; } - PipelineRingBuffer buffer = PipelineBinaryServer.this.pipeline + PipelineRingBuffer buffer = MQPipelineBinaryServer.this.pipeline .getBufferByZone(zone, true); List bytes = buffer.peekAtMost(pipelineBinarySession.requestNum()); if (bytes.isEmpty()) { diff --git a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/PipelineRestServer.java b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/MQPipelineRestServer.java similarity index 53% rename from fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/PipelineRestServer.java rename to fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/MQPipelineRestServer.java index f57964d..589e5a9 100644 --- a/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/PipelineRestServer.java +++ b/fastmq/pipeline/src/main/java/top/limitart/fastmq/pipeline/MQPipelineRestServer.java @@ -1,5 +1,5 @@ package top.limitart.fastmq.pipeline; -public class PipelineRestServer { +public class MQPipelineRestServer { } diff --git a/fastmq/provider/src/main/java/top/limitart/fastmq/provider/ProviderBinaryClient.java b/fastmq/provider/src/main/java/top/limitart/fastmq/provider/MQProviderBinaryClient.java similarity index 95% rename from fastmq/provider/src/main/java/top/limitart/fastmq/provider/ProviderBinaryClient.java rename to fastmq/provider/src/main/java/top/limitart/fastmq/provider/MQProviderBinaryClient.java index 1a82796..c68e30a 100644 --- a/fastmq/provider/src/main/java/top/limitart/fastmq/provider/ProviderBinaryClient.java +++ b/fastmq/provider/src/main/java/top/limitart/fastmq/provider/MQProviderBinaryClient.java @@ -19,14 +19,14 @@ import top.limitart.net.binary.BinaryEndPoint; import top.limitart.net.binary.BinaryMessage; -public class ProviderBinaryClient extends ApplicationBootstrap { +public class MQProviderBinaryClient extends ApplicationBootstrap { private BinaryEndPoint client; private AddressPair remoteAddress; private ProviderBinaryHandler providerBinaryHandler; private NettySession session; - public ProviderBinaryClient(String remoteIp, int port) throws Exception { + public MQProviderBinaryClient(String remoteIp, int port) throws Exception { this.remoteAddress = AddressPair.withIP(remoteIp, port); providerBinaryHandler = new ProviderBinaryHandler(); Router router = diff --git a/game/limitart-game.iml b/game/limitart-game.iml new file mode 100644 index 0000000..64bd157 --- /dev/null +++ b/game/limitart-game.iml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/pom.xml b/pom.xml index 8558416..fdca366 100644 --- a/pom.xml +++ b/pom.xml @@ -26,7 +26,7 @@ demo net hotdep - game + config db project-starter diff --git a/rpc/pom.xml b/rpc/pom.xml index a67dcbd..b23b722 100644 --- a/rpc/pom.xml +++ b/rpc/pom.xml @@ -15,22 +15,6 @@ service-center service-provider service-consumer + service-common - - - ${project.groupId} - limitart-fastmq - ${project.version} - - - org.slf4j - slf4j-api - - - org.slf4j - slf4j-jdk14 - test - - - \ No newline at end of file diff --git a/rpc/service-center/pom.xml b/rpc/service-center/pom.xml index 581f95f..cb55f62 100644 --- a/rpc/service-center/pom.xml +++ b/rpc/service-center/pom.xml @@ -11,5 +11,25 @@ limitart-rpc-service-center - + + + ${project.groupId} + limitart-fastmq-pipeline + ${project.version} + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-jdk14 + test + + + ${project.groupId} + limitart-rpc-common + ${project.version} + + \ No newline at end of file diff --git a/rpc/service-center/src/main/java/top/limitart/rpc/RPCServiceCenter.java b/rpc/service-center/src/main/java/top/limitart/rpc/RPCServiceCenter.java new file mode 100644 index 0000000..646ee7f --- /dev/null +++ b/rpc/service-center/src/main/java/top/limitart/rpc/RPCServiceCenter.java @@ -0,0 +1,28 @@ +package top.limitart.rpc; + +import top.limitart.base.ApplicationBootstrap; +import top.limitart.fastmq.pipeline.MQPipelineBinaryServer; +import top.limitart.fastmq.pipeline.core.Pipeline; + +public class RPCServiceCenter extends ApplicationBootstrap { + + private MQPipelineBinaryServer pipelineServer; + + public RPCServiceCenter(int port) throws Exception { + this.pipelineServer = new MQPipelineBinaryServer(new Pipeline(), port); + } + + public RPCServiceCenter(Pipeline pipeline, int port) throws Exception { + this.pipelineServer = new MQPipelineBinaryServer(pipeline, port); + } + + @Override + protected void onStart(String[] args) throws Exception { + this.pipelineServer.run(args); + } + + @Override + protected void onDestroy(String[] args) { + + } +} diff --git a/rpc/service-common/pom.xml b/rpc/service-common/pom.xml new file mode 100644 index 0000000..f66ff5d --- /dev/null +++ b/rpc/service-common/pom.xml @@ -0,0 +1,21 @@ + + + + limitart-rpc + top.limitart + 3.2.0-SNAPSHOT + + 4.0.0 + + limitart-rpc-common + + + + ${project.groupId} + limitart-core + ${project.version} + + + \ No newline at end of file diff --git a/rpc/service-common/src/main/java/top/limitart/rpc/srvcommon/RPCMeta.java b/rpc/service-common/src/main/java/top/limitart/rpc/srvcommon/RPCMeta.java new file mode 100644 index 0000000..95c9979 --- /dev/null +++ b/rpc/service-common/src/main/java/top/limitart/rpc/srvcommon/RPCMeta.java @@ -0,0 +1,233 @@ +/* + * Copyright (c) 2016-present The Limitart Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package top.limitart.rpc.srvcommon; + +import io.netty.buffer.ByteBuf; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import top.limitart.base.BinaryMeta; +import top.limitart.base.UncatchableException; + +public abstract class RPCMeta extends BinaryMeta { + + public RPCMeta(ByteBuf buffer) { + super(buffer); + } + + public RPCMeta() { + } + + protected final Object decodeObj(Class type) + throws IllegalAccessException { + return decodeObj(type.getName()); + } + + @SuppressWarnings("unchecked") + protected final Object decodeObj(String type) + throws IllegalAccessException { + if (type == null || type.equals("null")) { + return null; + } else if (type.equals(Integer.class.getName()) || type.equals(int.class.getName())) { + return getInt(); + } else if (type.equals(int[].class.getName())) { + return getIntArray(); + } else if (type.equals(Byte.class.getName()) || type.equals(byte.class.getName())) { + return getByte(); + } else if (type.equals(byte[].class.getName())) { + return getByteArray(); + } else if (type.equals(Short.class.getName()) || type.equals(short.class.getName())) { + return getShort(); + } else if (type.equals(short[].class.getName())) { + return getShortArray(); + } else if (type.equals(Long.class.getName()) || type.equals(long.class.getName())) { + return getLong(); + } else if (type.equals(long[].class.getName())) { + return getLongArray(); + } else if (type.equals(Boolean.class.getName()) || type.equals(boolean.class.getName())) { + return getBoolean(); + } else if (type.equals(boolean[].class.getName())) { + return getBooleanArray(); + } else if (type.equals(String.class.getName())) { + return getString(); + } else if (type.equals(String[].class.getName())) { + return getStringArray(); + } else if (type.equals(Float.class.getName()) || type.equals(float.class.getName())) { + return getFloat(); + } else if (type.equals(float[].class.getName())) { + return getFloatArray(); + } else if (type.equals(Double.class.getName()) || type.equals(double.class.getName())) { + return getDouble(); + } else if (type.equals(double[].class.getName())) { + return getDoubleArray(); + } else if (type.equals(Character.class.getName()) || type.equals(char.class.getName())) { + return getChar(); + } else if (type.equals(char[].class.getName())) { + return getCharArray(); + } else if (type.equals(ArrayList.class.getName()) || type.equals(List.class.getName())) { + List objList = new ArrayList<>(); + short length = getShort(); + if (length > 0) { + String listType = getString(); + for (int i = 0; i < length; ++i) { + objList.add(decodeObj(listType)); + } + } + return objList; + } else if (type.equals(HashMap.class.getName()) || type.equals(Map.class.getName())) { + short length = getShort(); + if (length == 0) { + return null; + } + String keyType = getString(); + String valueType = getString(); + Map map = new HashMap<>(); + for (int i = 0; i < length; ++i) { + map.put(decodeObj(keyType), decodeObj(valueType)); + } + return map; + } else if (type.equals(HashSet.class.getName()) || type.equals(Set.class.getName())) { + short length = getShort(); + if (length == 0) { + return null; + } + String setType = getString(); + Set set = new HashSet<>(); + for (int i = 0; i < length; ++i) { + set.add(decodeObj(setType)); + } + return set; + } else if (type.startsWith("[L")) { + @SuppressWarnings("rawtypes") + Class forName = null; + try { + forName = Class.forName(type); + } catch (ClassNotFoundException e) { + throw new UncatchableException(e); + } + return getMessageMetaArray(forName.getComponentType()); + } else { + @SuppressWarnings("rawtypes") + Class forName = null; + try { + forName = Class.forName(type); + } catch (ClassNotFoundException e) { + throw new UncatchableException(e); + } + return getMessageMeta(forName); + } + } + + @SuppressWarnings("unchecked") + protected final void encodeObj(Object object) throws IllegalAccessException { + if (object == null) { + return; + } + Class type = object.getClass(); + if (type.equals(Integer.class) || type.equals(int.class)) { + putInt((int) object); + } else if (type.equals(int[].class)) { + putIntArray((int[]) object); + } else if (type.equals(Byte.class) || type.equals(byte.class)) { + putByte((int) object); + } else if (type.equals(byte[].class)) { + putByteArray((byte[]) object); + } else if (type.equals(Short.class) || type.equals(short.class)) { + putShort((short) object); + } else if (type.equals(short[].class)) { + putShortArray((short[]) object); + } else if (type.equals(Long.class) || type.equals(long.class)) { + putLong((long) object); + } else if (type.equals(long[].class)) { + putLongArray((long[]) object); + } else if (type.equals(Boolean.class) || type.equals(boolean.class)) { + putBoolean((boolean) object); + } else if (type.equals(boolean[].class)) { + putBooleanArray((boolean[]) object); + } else if (type.equals(String.class)) { + putString((String) object); + } else if (type.equals(String[].class)) { + putStringArray((String[]) object); + } else if (type.equals(Float.class) || type.equals(float.class)) { + putFloat((float) object); + } else if (type.equals(float[].class)) { + putFloatArray((float[]) object); + } else if (type.equals(Double.class) || type.equals(double.class)) { + putDouble((double) object); + } else if (type.equals(double[].class)) { + putDoubleArray((double[]) object); + } else if (type.equals(Character.class) || type.equals(char.class)) { + putChar((char) object); + } else if (type.equals(char[].class)) { + putCharArray((char[]) object); + } else if (type.equals(ArrayList.class) || type.equals(List.class)) { + List objs = (List) object; + if (objs.isEmpty()) { + putShort((short) 0); + } else { + putShort((short) objs.size()); + String name = objs.get(0).getClass().getName(); + putString(name); + for (Object obj : objs) { + encodeObj(obj); + } + } + } else if (type.equals(HashMap.class) || type.equals(Map.class)) { + Map map = (Map) object; + if (map.isEmpty()) { + putShort((short) 0); + } else { + putShort((short) map.size()); + boolean f = false; + for (Entry next : map.entrySet()) { + if (!f) { + f = true; + putString(next.getKey().getClass().getName()); + putString(next.getValue().getClass().getName()); + } + encodeObj(next.getKey()); + encodeObj(next.getValue()); + } + } + } else if (type.equals(HashSet.class) || type.equals(Set.class)) { + Set set = (Set) object; + if (set.isEmpty()) { + putShort((short) 0); + } else { + putShort((short) set.size()); + boolean f = false; + for (Object value : set) { + if (!f) { + f = true; + putString(value.getClass().getName()); + } + encodeObj(value); + } + } + } else if (object instanceof BinaryMeta) { + putMessageMeta((BinaryMeta) object); + } else if (object.getClass().isArray() + && object.getClass().getComponentType().getSuperclass() == BinaryMeta.class) { + putMessageMetaArray((BinaryMeta[]) object); + } else { + throw new UncatchableException(object.getClass().getName() + " does not supported yet!"); + } + } +} diff --git a/rpc/service-common/src/main/java/top/limitart/rpc/srvcommon/RPCService.java b/rpc/service-common/src/main/java/top/limitart/rpc/srvcommon/RPCService.java new file mode 100644 index 0000000..2416f8e --- /dev/null +++ b/rpc/service-common/src/main/java/top/limitart/rpc/srvcommon/RPCService.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2016-present The Limitart Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package top.limitart.rpc.srvcommon; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * RPC服务 + * + * @author Hank + * + */ +@Target({ ElementType.TYPE }) +@Retention(RetentionPolicy.RUNTIME) +public @interface RPCService { + String provider(); + + String module() default ""; +} diff --git a/rpc/service-common/src/main/java/top/limitart/rpc/srvcommon/RPCServiceExecuteException.java b/rpc/service-common/src/main/java/top/limitart/rpc/srvcommon/RPCServiceExecuteException.java new file mode 100644 index 0000000..a485b4b --- /dev/null +++ b/rpc/service-common/src/main/java/top/limitart/rpc/srvcommon/RPCServiceExecuteException.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2016-present The Limitart Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package top.limitart.rpc.srvcommon; + + +import top.limitart.base.UncatchableException; + +/** + * 服务执行错误 + * + * @author Hank + * + */ +public class RPCServiceExecuteException extends UncatchableException { + private static final long serialVersionUID = 1L; + + public RPCServiceExecuteException(String info) { + super(info); + } +} diff --git a/rpc/service-common/src/main/java/top/limitart/rpc/srvcommon/RPCServiceIOException.java b/rpc/service-common/src/main/java/top/limitart/rpc/srvcommon/RPCServiceIOException.java new file mode 100644 index 0000000..5d823aa --- /dev/null +++ b/rpc/service-common/src/main/java/top/limitart/rpc/srvcommon/RPCServiceIOException.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2016-present The Limitart Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package top.limitart.rpc.srvcommon; + +import java.io.IOException; + +/** + * 服务IO错误 + * + * @author Hank + * + */ +public class RPCServiceIOException extends IOException { + private static final long serialVersionUID = 1L; + + public RPCServiceIOException(String info) { + super(info); + } + + public RPCServiceIOException(Exception e) { + super(e); + } +} diff --git a/rpc/service-common/src/main/java/top/limitart/rpc/srvcommon/RPCServiceProxyException.java b/rpc/service-common/src/main/java/top/limitart/rpc/srvcommon/RPCServiceProxyException.java new file mode 100644 index 0000000..7d37c3e --- /dev/null +++ b/rpc/service-common/src/main/java/top/limitart/rpc/srvcommon/RPCServiceProxyException.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2016-present The Limitart Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package top.limitart.rpc.srvcommon; + + +import top.limitart.base.CatchableException; + +/** + * 服务代理错误 + * + * @author Hank + * + */ +public class RPCServiceProxyException extends CatchableException { + private static final long serialVersionUID = 1L; + + public RPCServiceProxyException(String info) { + super(info); + } +} diff --git a/rpc/service-common/src/main/java/top/limitart/rpc/srvcommon/RpcExecuteClientMsg.java b/rpc/service-common/src/main/java/top/limitart/rpc/srvcommon/RpcExecuteClientMsg.java new file mode 100644 index 0000000..b91f3f9 --- /dev/null +++ b/rpc/service-common/src/main/java/top/limitart/rpc/srvcommon/RpcExecuteClientMsg.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2016-present The Limitart Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package top.limitart.rpc.srvcommon; + +import io.netty.buffer.ByteBuf; +import java.util.ArrayList; +import java.util.List; + +public class RpcExecuteClientMsg extends RPCMeta { + public String consumerName; + public int requestId; + public String moduleName; + public String methodName; + public List paramTypes = new ArrayList<>(); + public List params = new ArrayList<>(); + + public RpcExecuteClientMsg(ByteBuf buffer) { + super(buffer); + } + + public RpcExecuteClientMsg() { + } + + @Override + public String toString() { + return moduleName + "@" + methodName; + } + + @Override + public void serialize() throws IllegalArgumentException, IllegalAccessException { + putString(this.consumerName); + putInt(this.requestId); + putString(this.moduleName); + putString(this.methodName); + putStringList(this.paramTypes); + if (this.paramTypes != null) { + for (Object object : params) { + encodeObj(object); + } + } + } + + @Override + public void deserialize() throws IllegalArgumentException, IllegalAccessException { + this.consumerName = getString(); + this.requestId = getInt(); + this.moduleName = getString(); + this.methodName = getString(); + this.paramTypes = getStringList(); + // 这里特殊处理,因为服务器要知道参数类型去寻找具体的类 + for (String type : this.paramTypes) { + this.params.add(decodeObj(type)); + } + } +} diff --git a/rpc/service-common/src/main/java/top/limitart/rpc/srvcommon/RpcResultServerMsg.java b/rpc/service-common/src/main/java/top/limitart/rpc/srvcommon/RpcResultServerMsg.java new file mode 100644 index 0000000..a01951a --- /dev/null +++ b/rpc/service-common/src/main/java/top/limitart/rpc/srvcommon/RpcResultServerMsg.java @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2016-present The Limitart Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package top.limitart.rpc.srvcommon; + + +import io.netty.buffer.ByteBuf; + +public class RpcResultServerMsg extends RPCMeta { + + /** + * 成功 + */ + public final static int SUCCESS = 0; + /** + * 没有模块 + */ + public final static int SERVER_HAS_NO_MODULE = 1; + /** + * 没有方法 + */ + public final static int SERVER_HAS_NO_METHOD = 2; + + private int requestId; + private int errorCode; + private String returnType; + private Object returnVal; + + public RpcResultServerMsg(ByteBuf buffer) { + super(buffer); + } + + public RpcResultServerMsg() { + } + + public int getRequestId() { + return requestId; + } + + public void setRequestId(int requestId) { + this.requestId = requestId; + } + + public int getErrorCode() { + return errorCode; + } + + public void setErrorCode(int errorCode) { + this.errorCode = errorCode; + } + + public String getReturnType() { + return returnType; + } + + public void setReturnType(String returnType) { + this.returnType = returnType; + } + + public Object getReturnVal() { + return returnVal; + } + + public void setReturnVal(Object returnVal) { + this.returnVal = returnVal; + } + + @Override + public void serialize() throws IllegalArgumentException, IllegalAccessException { + putInt(this.requestId); + putInt(this.errorCode); + putString(this.returnType); + encodeObj(this.returnVal); + } + + @Override + public void deserialize() throws IllegalArgumentException, IllegalAccessException { + this.requestId = getInt(); + this.errorCode = getInt(); + this.returnType = getString(); + this.returnVal = decodeObj(this.returnType); + } +} diff --git a/rpc/service-common/src/main/java/top/limitart/rpc/srvcommon/RpcUtil.java b/rpc/service-common/src/main/java/top/limitart/rpc/srvcommon/RpcUtil.java new file mode 100644 index 0000000..b35952d --- /dev/null +++ b/rpc/service-common/src/main/java/top/limitart/rpc/srvcommon/RpcUtil.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2016-present The Limitart Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package top.limitart.rpc.srvcommon; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import top.limitart.base.BinaryMeta; +import top.limitart.util.StringUtil; + +public final class RpcUtil { + private RpcUtil() { + } + + /** + * 获取服务名称 + * + * @param providerName + * @param serviceClass + * @return + * @throws RPCServiceProxyException + */ + public static String getServiceName(String providerName, Class serviceClass) + throws RPCServiceProxyException { + RPCService annotation = serviceClass.getAnnotation(RPCService.class); + if (annotation == null) { + throw new RPCServiceProxyException("not a RPCService class(annotation)"); + } + String modole = annotation.module(); + if (StringUtil.empty(modole)) { + modole = serviceClass.getSimpleName(); + } + return providerName + "@" + modole; + } + + /** + * 检查RPC参数类型是否符合标准 + * + * @param type + * @return + * @throws RPCServiceProxyException + */ + public static void checkParamType(Class type) throws RPCServiceProxyException { + if (!type.isPrimitive()) { + if (type.isArray()) { + checkParamType(type.getComponentType()); + } else { + if (!BinaryMeta.class.isAssignableFrom(type) && type != String.class && type != List.class + && type != ArrayList.class && type != HashMap.class && type != Map.class + && type != HashSet.class && type != Set.class) { + throw new RPCServiceProxyException(type.getName() + "必须是基础类型(包括其数组)或" + BinaryMeta.class.getName() + + "的子类,或者为上述类型的java.util.List或java.util.ArrayList"); + } + } + } + } +} diff --git a/rpc/service-consumer/pom.xml b/rpc/service-consumer/pom.xml index dc7e8cf..1865a17 100644 --- a/rpc/service-consumer/pom.xml +++ b/rpc/service-consumer/pom.xml @@ -10,6 +10,31 @@ 4.0.0 limitart-rpc-service-consumer - + + + ${project.groupId} + limitart-fastmq-provider + ${project.version} + + + ${project.groupId} + limitart-fastmq-consumer + ${project.version} + + + ${project.groupId} + limitart-rpc-common + ${project.version} + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-jdk14 + test + + \ No newline at end of file diff --git a/rpc/service-consumer/src/main/java/top/limitart/rpc/srvconsumer/RPCServiceConsumer.java b/rpc/service-consumer/src/main/java/top/limitart/rpc/srvconsumer/RPCServiceConsumer.java new file mode 100644 index 0000000..341e191 --- /dev/null +++ b/rpc/service-consumer/src/main/java/top/limitart/rpc/srvconsumer/RPCServiceConsumer.java @@ -0,0 +1,320 @@ +/* + * Copyright (c) 2016-present The Limitart Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package top.limitart.rpc.srvconsumer; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufAllocator; +import java.io.IOException; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.LongAdder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import top.limitart.base.ApplicationBootstrap; +import top.limitart.fastmq.consumer.ConsumerMsgHandler; +import top.limitart.fastmq.consumer.MQConsumerBinaryClient; +import top.limitart.fastmq.provider.MQProviderBinaryClient; +import top.limitart.rpc.srvcommon.RPCService; +import top.limitart.rpc.srvcommon.RPCServiceExecuteException; +import top.limitart.rpc.srvcommon.RPCServiceIOException; +import top.limitart.rpc.srvcommon.RPCServiceProxyException; +import top.limitart.rpc.srvcommon.RpcExecuteClientMsg; +import top.limitart.rpc.srvcommon.RpcResultServerMsg; +import top.limitart.rpc.srvcommon.RpcUtil; +import top.limitart.util.ReflectionUtil; +import top.limitart.util.StringUtil; + +/** + * RPC客户端 + * + * @author hank + */ +public class RPCServiceConsumer extends ApplicationBootstrap implements ConsumerMsgHandler { + + private static Logger LOGGER = LoggerFactory.getLogger( + RPCServiceConsumer.class); + public static final int MAX_CALL_BACK_LENGTH = 2000; + public static final long EXECUTE_TIMEOUT = 5; + private MQConsumerBinaryClient consumerClient; + private MQProviderBinaryClient providerClient; + // 动态代理集合 + private Map, Object> clientProxys = new HashMap<>(); + // 服务对应的本地代理接口集合 + private Map> serviceProxyClasses = new HashMap<>(); + // RequestId生成器 + private AtomicInteger requestIdCreater = new AtomicInteger(0); + // RPC调用回调集合 + private Map futures = new ConcurrentHashMap<>(); + private LongAdder dropNum = new LongAdder(); + private String customerName; + + public RPCServiceConsumer(String customerName, String serviceCenterIp, int serviceCenterPort, + String... servicePackages) + throws Exception { + this.customerName = customerName; + initRpcProxys(servicePackages); + //初始化请求发送客户端 + providerClient = new MQProviderBinaryClient(serviceCenterIp, serviceCenterPort); + consumerClient = new MQConsumerBinaryClient(serviceCenterIp, serviceCenterPort, customerName, + null, this); + } + + @Override + protected void onStart(String[] args) throws Exception { + providerClient.run(args); + consumerClient.run(args); + } + + @Override + protected void onDestroy(String[] args) { + } + + /** + * 创建RPC同步调用代理 + * + * @param interfaceClss + * @return + * @throws RPCServiceProxyException + */ + @SuppressWarnings("unchecked") + public T createProxy(Class interfaceClss) throws RPCServiceProxyException { + Object proxyObject = this.clientProxys.get(interfaceClss); + if (proxyObject == null) { + throw new RPCServiceProxyException(interfaceClss.getName() + "不是一个RPC服务!"); + } + return (T) proxyObject; + } + + /** + * 初始化本地服务代理 + * + * @throws IOException + * @throws ReflectiveOperationException + * @throws Exception + */ + private void initRpcProxys(String[] interfacePackages) + throws RPCServiceProxyException, IOException, ReflectiveOperationException { + clientProxys.clear(); + List> classesByPackage = new ArrayList<>(); + for (String temp : interfacePackages) { + classesByPackage.addAll(ReflectionUtil.getClassesBySuperClass(temp, Object.class)); + } + for (Class clazz : classesByPackage) { + RPCService annotation = clazz.getAnnotation(RPCService.class); + if (annotation == null) { + continue; + } + if (!clazz.isInterface()) { + throw new RPCServiceProxyException(clazz.getName() + "RPC服务器必须是一个接口!"); + } + // 检查参数是否符合标准 + String provider = annotation.provider(); + if (StringUtil.empty(provider)) { + throw new RPCServiceProxyException("服务:" + clazz.getName() + "的提供商为空!"); + } + String serviceName = RpcUtil.getServiceName(provider, clazz); + // 检查方法 + Method[] methods = clazz.getMethods(); + for (Method method : methods) { + String methodOverloadName = ReflectionUtil.getMethodOverloadName(method); + // 检查参数 + Class[] parameterTypes = method.getParameterTypes(); + for (Class paramsType : parameterTypes) { + RpcUtil.checkParamType(paramsType); + } + // 检查返回参数是否合法 + RpcUtil.checkParamType(method.getReturnType()); + // 异常抛出检查 + Class[] exceptionTypes = method.getExceptionTypes(); + if (exceptionTypes == null || exceptionTypes.length < 1) { + throw new RPCServiceProxyException( + "类" + clazz.getName() + "的方法" + methodOverloadName + "必须要抛出异常:" + + Exception.class.getName()); + } + boolean exOk = false; + for (Class ex : exceptionTypes) { + if (ex == Exception.class) { + exOk = true; + } + } + if (!exOk) { + throw new RPCServiceProxyException( + "类" + clazz.getName() + "的方法" + methodOverloadName + "的异常抛出必须有:" + + Exception.class.getName()); + } + } + // 创建动态代理类 + Object newProxyInstance = ReflectionUtil.newProxy(clazz, + (InvocationHandler) (proxy, method, args) -> proxyExecute(serviceName, proxy, + method.getName(), + ReflectionUtil.getMethodOverloadName(method), args)); + if (serviceProxyClasses.containsKey(serviceName)) { + throw new RPCServiceProxyException("服务名重复:" + serviceName); + } + serviceProxyClasses.put(serviceName, clazz); + clientProxys.put(clazz, newProxyInstance); + LOGGER.info("创建服务动态代理:" + serviceName + ",服务提供商:" + provider + ",代理实例:" + newProxyInstance); + } + } + + /** + * rpc动态代理方法 + * + * @param serviceName + * @param proxy + * @param methodName + * @param methodOverloadName + * @throws InterruptedException + * @throws RPCServiceIOException + */ + private Object proxyExecute(String serviceName, Object proxy, String methodName, + String methodOverloadName, + Object[] args) + throws RPCServiceExecuteException, InterruptedException, RPCServiceIOException { + if (proxy != null) { + if ("equals".equals(methodName)) { + return proxy == args[0]; + } else if ("hashCode".equals(methodName)) { + return System.identityHashCode(proxy); + } else if ("toString".equals(methodName)) { + return proxy.getClass().getName() + "@" + Integer + .toHexString(System.identityHashCode(proxy)); + } + } + if (futures.size() > MAX_CALL_BACK_LENGTH) { + dropNum.increment(); + throw new RPCServiceExecuteException( + "回调列表超过限制:" + MAX_CALL_BACK_LENGTH + + ",不进行任何处理!,已抛弃数量:" + dropNum.longValue()); + } + RemoteFuture future = rpcSend(serviceName, methodOverloadName, args); + if (future.getResponseResult() == null) { + // 无条件线程等待 + boolean await = future.getCountDownLatch() + .await(EXECUTE_TIMEOUT, TimeUnit.MILLISECONDS); + futures.remove(future.getRequestId()); + if (!await) { + throw new RPCServiceExecuteException( + "动态代理方法:" + methodOverloadName + "超时,回调ID:" + future + .getRequestId()); + } + } + // 等待完成设置回调完成,服务器处理完毕后就不用唤醒此线程 + RpcResultServerMsg response = future.getResponseResult(); + int errorCode = response.getErrorCode(); + if (errorCode == RpcResultServerMsg.SUCCESS) { + return response.getReturnVal(); + } else if (errorCode == RpcResultServerMsg.SERVER_HAS_NO_MODULE) { + throw new RPCServiceExecuteException("没有服务名为:" + serviceName); + } else if (errorCode == RpcResultServerMsg.SERVER_HAS_NO_METHOD) { + throw new RPCServiceExecuteException( + "没有服务名为:" + serviceName + "的" + methodOverloadName + "方法!"); + } else { + throw new RPCServiceExecuteException("服务名:" + serviceName + "返回未知错误码!"); + } + } + + /** + * 发送到RPC请求到服务器 + * + * @param serviceName + * @param methodOverloadName + * @param args + * @return + * @throws Exception + */ + private RemoteFuture rpcSend(String serviceName, String methodOverloadName, Object[] args) + throws RPCServiceIOException { + // 开始构造消息 + RpcExecuteClientMsg msg = new RpcExecuteClientMsg(); + msg.consumerName = this.customerName; + msg.requestId = requestIdCreater.incrementAndGet(); + msg.moduleName = serviceName; + msg.methodName = methodOverloadName; + if (args != null && args.length > 0) { + for (Object obj : args) { + if (obj == null) { + msg.paramTypes.add(null); + msg.params.add(null); + } else { + msg.paramTypes.add(obj.getClass().getName()); + msg.params.add(obj); + } + } + } + RemoteFuture future = new RemoteFuture(); + future.setRequestId(msg.requestId); + futures.put(msg.requestId, future); + if (futures.size() > 100) { + LOGGER.error( + "警告!开始动态代理方法:" + methodOverloadName + ",回调列表长度:" + futures.size() + + "(并发量),id:" + msg.requestId); + } + // 发送消息 + ByteBuf buf = ByteBufAllocator.DEFAULT.buffer(); + try { + msg.replaceBuffer(buf); + msg.serialize(); + byte[] c = new byte[buf.readableBytes()]; + buf.readBytes(c); + providerClient.sendMsgWithTags(Collections.singletonList(msg.moduleName), c); + } catch (Exception e) { + LOGGER.error(e.getMessage(), e); + } finally { + buf.release(); + } + return future; + } + + /** + * 当RPC服务器回应RPC服务结果 + */ + private void onRPCResonse(RpcResultServerMsg msg) { + int requestId = msg.getRequestId(); + RemoteFuture rpcFuture = futures.get(requestId); + if (rpcFuture == null) { + LOGGER.error("requestId:" + requestId + "找不到回调!"); + return; + } + rpcFuture.setResponseResult(msg); + // 唤醒线程 + rpcFuture.getCountDownLatch().countDown(); + } + + @Override + public void onMsg(byte[] msg) { + ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer(); + buffer.writeBytes(msg); + RpcResultServerMsg t = new RpcResultServerMsg(buffer); + try { + t.deserialize(); + } catch (IllegalAccessException e) { + LOGGER.error("decode response error", e); + return; + } finally { + buffer.release(); + } + onRPCResonse(t); + } +} diff --git a/rpc/service-consumer/src/main/java/top/limitart/rpc/srvconsumer/RemoteFuture.java b/rpc/service-consumer/src/main/java/top/limitart/rpc/srvconsumer/RemoteFuture.java new file mode 100644 index 0000000..91d805d --- /dev/null +++ b/rpc/service-consumer/src/main/java/top/limitart/rpc/srvconsumer/RemoteFuture.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2016-present The Limitart Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package top.limitart.rpc.srvconsumer; + +import java.util.concurrent.CountDownLatch; +import top.limitart.rpc.srvcommon.RpcResultServerMsg; + +/** + * 远程调用回调 + * + * @author hank + */ +public class RemoteFuture { + + private int requestId; + private volatile RpcResultServerMsg responseResult; + private CountDownLatch countDownLatch = new CountDownLatch(1); + + public int getRequestId() { + return requestId; + } + + public void setRequestId(int requestId) { + this.requestId = requestId; + } + + public RpcResultServerMsg getResponseResult() { + return responseResult; + } + + public void setResponseResult(RpcResultServerMsg responseResult) { + this.responseResult = responseResult; + } + + public CountDownLatch getCountDownLatch() { + return countDownLatch; + } +} diff --git a/rpc/service-provider/pom.xml b/rpc/service-provider/pom.xml index 73d16bb..f4b69af 100644 --- a/rpc/service-provider/pom.xml +++ b/rpc/service-provider/pom.xml @@ -11,5 +11,35 @@ limitart-rpc-service-provider - + + + ${project.groupId} + limitart-fastmq-provider + ${project.version} + + + ${project.groupId} + limitart-fastmq-consumer + ${project.version} + + + ${project.groupId} + limitart-rpc-common + ${project.version} + + + ${project.groupId} + limitart-core + ${project.version} + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-jdk14 + test + + \ No newline at end of file diff --git a/rpc/service-provider/src/main/java/top/limitart/rpc/srvprovider/RPCServiceProvider.java b/rpc/service-provider/src/main/java/top/limitart/rpc/srvprovider/RPCServiceProvider.java new file mode 100644 index 0000000..abd0ead --- /dev/null +++ b/rpc/service-provider/src/main/java/top/limitart/rpc/srvprovider/RPCServiceProvider.java @@ -0,0 +1,296 @@ +/* + * Copyright (c) 2016-present The Limitart Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package top.limitart.rpc.srvprovider; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufAllocator; +import java.io.IOException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import top.limitart.base.ApplicationBootstrap; +import top.limitart.fastmq.consumer.ConsumerMsgHandler; +import top.limitart.fastmq.consumer.MQConsumerBinaryClient; +import top.limitart.fastmq.provider.MQProviderBinaryClient; +import top.limitart.rpc.srvcommon.RPCService; +import top.limitart.rpc.srvcommon.RPCServiceProxyException; +import top.limitart.rpc.srvcommon.RpcExecuteClientMsg; +import top.limitart.rpc.srvcommon.RpcResultServerMsg; +import top.limitart.rpc.srvcommon.RpcUtil; +import top.limitart.util.ReflectionUtil; +import top.limitart.util.StringUtil; + +/** + * RPC服务提供者 + * + * @author hank + */ +public class RPCServiceProvider extends ApplicationBootstrap implements ConsumerMsgHandler { + + private static Logger LOGGER = LoggerFactory.getLogger( + RPCServiceProvider.class); + //发送RPC调用结果 + private MQProviderBinaryClient providerClient; + //接收RPC调用请求 + private MQConsumerBinaryClient consumerClient; + private Map services = new HashMap<>(); + + public RPCServiceProvider(String providerName, String serviceCenterIp, int serviceCenterPort, + String[] interfacePackages, String[] implPackages) + throws Exception { + initAllServices(interfacePackages, implPackages); + this.providerClient = new MQProviderBinaryClient(serviceCenterIp, serviceCenterPort); + this.consumerClient = new MQConsumerBinaryClient(serviceCenterIp, serviceCenterPort, + providerName, new LinkedList<>(services.keySet()), this); + } + + @Override + protected void onStart(String[] args) throws Exception { + this.providerClient.run(args); + this.consumerClient.run(args); + } + + @Override + protected void onDestroy(String[] args) { + + } + + /** + * 扫描本地服务 + * + * @throws RPCServiceProxyException + * @throws IOException + * @throws ReflectiveOperationException + * @throws Exception + */ + private void initAllServices(String[] interfacePackages, String[] implPackages) + throws RPCServiceProxyException, IOException, ReflectiveOperationException { + services.clear(); + List> interfacesByPackage = new ArrayList<>(); + for (String temp : interfacePackages) { + LOGGER.info("开始在包:" + temp + "下查找接口..."); + interfacesByPackage.addAll(ReflectionUtil.getClassesBySuperClass(temp, Object.class)); + } + // RPC接口集合 + Map, Map> rpcInterfaces = new HashMap<>(); + // 查找所有RPC接口 + for (Class clazz : interfacesByPackage) { + // 必须是一个接口 + RPCService annotation = clazz.getAnnotation(RPCService.class); + if (annotation == null) { + continue; + } + if (!clazz.isInterface()) { + throw new RPCServiceProxyException(clazz.getName() + "RPC服务器必须是一个接口!"); + } + // 检查参数是否符合标准 + String provider = annotation.provider(); + if (StringUtil.empty(provider)) { + throw new RPCServiceProxyException("RPC接口提供商不能为空!"); + } + String serviceName = RpcUtil.getServiceName(provider, clazz); + if (services.containsKey(serviceName)) { + throw new RPCServiceProxyException("服务名:" + serviceName + "重复!"); + } + // 检查方法 + Method[] methods = clazz.getMethods(); + Map methodSet = new HashMap<>(); + // 检查方法参数是否合法 + for (Method method : methods) { + String methodOverloadName = ReflectionUtil.getMethodOverloadName(method); + // 检查参数 + Class[] parameterTypes = method.getParameterTypes(); + for (Class paramsType : parameterTypes) { + RpcUtil.checkParamType(paramsType); + + } + // 检查返回参数是否合法 + RpcUtil.checkParamType(method.getReturnType()); + // 异常抛出检查 + Class[] exceptionTypes = method.getExceptionTypes(); + if (exceptionTypes == null || exceptionTypes.length < 1) { + throw new RPCServiceProxyException( + "类" + clazz.getName() + "的方法" + methodOverloadName + "必须要抛出异常:" + + Exception.class.getName()); + } + boolean exOk = false; + for (Class ex : exceptionTypes) { + if (ex == Exception.class) { + exOk = true; + } + } + if (!exOk) { + throw new RPCServiceProxyException( + "类" + clazz.getName() + "的方法" + methodOverloadName + "的异常抛出必须有:" + + Exception.class.getName()); + } + methodSet.put(ReflectionUtil.getMethodOverloadName(method), method); + } + rpcInterfaces.put(clazz, methodSet); + } + // 查找RPC接口的实现类 + List> implsByPackage = new ArrayList<>(); + for (String temp : implPackages) { + LOGGER.info("开始在包:" + temp + "下查找接口..."); + implsByPackage.addAll(ReflectionUtil.getClassesBySuperClass(temp, Object.class)); + } + for (Class clazz : implsByPackage) { + Class[] interfaces = clazz.getInterfaces(); + if (interfaces == null || interfaces.length < 1) { + continue; + } + // 检查实现的接口实例的所有RPC服务 + Map> serviceNames = new HashMap<>(); + Object instance = null; + // 遍历接口(主要处理一个实例,实现了多个RPC接口的情况) + for (Class temp : interfaces) { + Map hashMap = rpcInterfaces.get(temp); + // 没有RPC服务 + if (hashMap == null) { + continue; + } + RPCService annotation = temp.getAnnotation(RPCService.class); + // 此类有实现此RPC接口 + serviceNames.put(RpcUtil.getServiceName(annotation.provider(), temp), temp); + if (instance == null) { + instance = clazz.newInstance(); + } + } + // 如果查找到了实例 + if (instance != null && !serviceNames.isEmpty()) { + for (Entry> entry : serviceNames.entrySet()) { + String serviceName = entry.getKey(); + if (services.containsKey(serviceName)) { + throw new RPCServiceProxyException("服务:" + serviceName + "发现了多个实现类:" + instance); + } + RpcServiceInstance data = new RpcServiceInstance(); + data.setInstance(instance); + Class value = entry.getValue(); + data.getMethods().putAll(rpcInterfaces.get(value)); + services.put(serviceName, data); + LOGGER.info("发现服务:" + serviceName + ",实例名称:" + + (clazz.getName() + "@" + Integer.toHexString(instance.hashCode()))); + } + } + } + } + + /** + * 执行RPC消费者请求的方法 + * + * @param requestId + * @param moduleName + * @param methodName + * @param params + */ + private void executeRPC(String customerName, int requestId, String moduleName, String methodName, + List params) + throws Exception { + RpcResultServerMsg msg = new RpcResultServerMsg(); + msg.setRequestId(requestId); + msg.setErrorCode(RpcResultServerMsg.SUCCESS); + try { + RpcServiceInstance serviceInstanceData = services.get(moduleName); + if (serviceInstanceData == null) { + LOGGER.error("RPC消费者:" + customerName + "发送了未知的服务名:" + moduleName); + msg.setErrorCode(RpcResultServerMsg.SERVER_HAS_NO_MODULE); + return; + } + Method method = serviceInstanceData.getMethods().get(methodName); + if (method == null) { + LOGGER.error("RPC消费者:" + customerName + "发送了未知的方法名:" + methodName + ",服务名为:" + + moduleName); + msg.setErrorCode(RpcResultServerMsg.SERVER_HAS_NO_METHOD); + return; + } + if (msg.getErrorCode() == 0) { + try { + Object result = method.invoke(serviceInstanceData.self(), params.toArray()); + if (result != null) { + msg.setReturnType(result.getClass().getName()); + msg.setReturnVal(result); + } + } catch (Exception e) { + LOGGER.error(e.getMessage(), e); + } + } + } finally { + // 发送消息 + ByteBuf buf = ByteBufAllocator.DEFAULT.buffer(); + try { + msg.replaceBuffer(buf); + msg.serialize(); + byte[] c = new byte[buf.readableBytes()]; + buf.readBytes(c); + providerClient.sendMsg(customerName, c); + } catch (Exception e) { + LOGGER.error("send result error", e); + } finally { + buf.release(); + } + } + } + + /** + * 获取服务实体 + * + * @param providerName + * @param clazz + * @return + * @throws + */ + @SuppressWarnings("unchecked") + public T getServiceInstance(String providerName, Class clazz) + throws RPCServiceProxyException { + RPCService annotation = clazz.getAnnotation(RPCService.class); + if (annotation == null) { + throw new RPCServiceProxyException(clazz.getName() + "is not a RPCService!"); + } + RpcServiceInstance serviceInstanceData = services + .get(RpcUtil.getServiceName(providerName, clazz)); + if (serviceInstanceData == null) { + return null; + } + return (T) serviceInstanceData.self(); + } + + + @Override + public void onMsg(byte[] msg) { + ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer(); + buffer.writeBytes(msg); + RpcExecuteClientMsg t = new RpcExecuteClientMsg(buffer); + try { + t.deserialize(); + } catch (IllegalAccessException e) { + LOGGER.error("decode response error", e); + return; + } finally { + buffer.release(); + } + try { + executeRPC(t.consumerName, t.requestId, t.moduleName, t.methodName, t.params); + } catch (Exception e) { + LOGGER.error("execute error", e); + } + } +} diff --git a/rpc/service-provider/src/main/java/top/limitart/rpc/srvprovider/RpcServiceInstance.java b/rpc/service-provider/src/main/java/top/limitart/rpc/srvprovider/RpcServiceInstance.java new file mode 100644 index 0000000..e6ac8d4 --- /dev/null +++ b/rpc/service-provider/src/main/java/top/limitart/rpc/srvprovider/RpcServiceInstance.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2016-present The Limitart Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package top.limitart.rpc.srvprovider; + +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; + +/** + * RPC服务实现类 + * + * @author ank + * + */ +public class RpcServiceInstance { + private Object instance; + private Map methods = new HashMap<>(); + + public Object self() { + return instance; + } + + public void setInstance(Object instance) { + this.instance = instance; + } + + public Map getMethods() { + return methods; + } + + public void setMethods(HashMap methods) { + this.methods = methods; + } +} -- Gitee From 847d1a976c78169646dd1e16f60bbbdad6557f2d Mon Sep 17 00:00:00 2001 From: hank <104381832> Date: Mon, 3 Feb 2020 21:30:11 +0800 Subject: [PATCH 10/11] 1 --- .../demo/demo/base/EnumBehaviorDemo.java | 11 - .../collections/ConcurrentLRUCacheDemo.java | 57 - .../demo/demo/collections/RankMapDemo.java | 82 - .../demo/concurrent/TaskQueueCronDemo.java | 32 - .../demo/demo/config/ConfigMetaDemo.java | 12 - .../limitart/demo/demo/config/D_ChipRank.java | 42 - .../limitart/demo/demo/config/D_WinRank.java | 54 - .../demo/demo/config/DataTypeDemo.java | 45 - .../demo/demo/config/ExcelModelDemo.java | 31 - .../top/limitart/demo/demo/config/Person.java | 48 - .../demo/demo/config/PersonDataType.java | 52 - .../limitart/demo/demo/event/EventDemo.java | 17 - .../demo/demo/event/EventProviderDemo.java | 31 - .../demo/fastmq/PipelineConsumerDemo.java | 39 - .../demo/fastmq/PipelineProviderDemo.java | 35 - .../demo/demo/fastmq/PipelineServerDemo.java | 22 - .../limitart/demo/demo/game/htb/HTBDemo.java | 63 - .../demo/demo/game/htb/HTBRoleDemo.java | 45 - .../demo/demo/game/htb/HTBTableDemo.java | 29 - .../demo/demo/game/scene8/SceneDemo.java | 81 - .../demo/demo/logging/LoggerDemo.java | 24 - .../demo/demo/mapping/RouterDemo.java | 17 - .../demo/demo/mapping/StringMapperClass.java | 12 - .../demo/demo/mapping/StringPoster.java | 7 - .../demo/demo/mapping/StringQuestParam.java | 8 - .../demo/demo/mapping/StringRequest.java | 17 - .../demo/demo/net/BinaryClientDemo.java | 42 - .../demo/demo/net/BinaryMessageDemo.java | 28 - .../demo/demo/net/BinaryMessageDemo2.java | 29 - .../demo/demo/net/BinaryScriptManager.java | 26 - .../demo/net/BinaryScriptManagerImpl.java | 27 - .../demo/demo/net/BinaryServerDemo.java | 49 - .../demo/demo/net/BinarySessionRole.java | 6 - .../demo/demo/net/FlashSSLServerDemo.java | 13 - .../demo/demo/net/HTTPSServerDemo.java | 25 - .../demo/demo/net/HTTPServerDemo.java | 41 - .../demo/demo/net/LocalEndPointDemo.java | 39 - .../limitart/demo/demo/net/MessageMapper.java | 47 - .../demo/demo/net/MessagePackageTest.java | 96 -- .../demo/demo/net/ProtobufClientDemo.java | 30 - .../demo/demo/net/ProtobufMessageDemo.java | 1334 ----------------- .../demo/demo/net/ProtobufServerDemo.java | 46 - .../demo/demo/net/ProtobufSessionRole.java | 6 - .../demo/demo/net/WebSocketServerDemo.java | 51 - .../demo/demo/redefinable/HelloRedefine.java | 7 - .../demo/redefinable/RedefinableDemo.java | 10 - .../demo/demo/redefinable/ScriptEntrance.java | 21 - .../demo/script/AutoReloadScriptDemo.java | 32 - .../demo/demo/script/HelloScript.java | 25 - .../demo/demo/script/ScriptSourceDemo.java | 42 - .../demo/demo/singleton/SingletonA.java | 10 - .../demo/demo/singleton/SingletonB.java | 14 - .../demo/demo/singleton/SingletonC.java | 30 - .../demo/demo/singleton/SingletonD.java | 33 - .../demo/demo/singleton/SingletonDemo.java | 21 - 55 files changed, 3093 deletions(-) delete mode 100644 demo/src/main/java/top/limitart/demo/demo/base/EnumBehaviorDemo.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/collections/ConcurrentLRUCacheDemo.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/collections/RankMapDemo.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/concurrent/TaskQueueCronDemo.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/config/ConfigMetaDemo.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/config/D_ChipRank.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/config/D_WinRank.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/config/DataTypeDemo.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/config/ExcelModelDemo.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/config/Person.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/config/PersonDataType.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/event/EventDemo.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/event/EventProviderDemo.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/fastmq/PipelineConsumerDemo.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/fastmq/PipelineProviderDemo.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/fastmq/PipelineServerDemo.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/game/htb/HTBDemo.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/game/htb/HTBRoleDemo.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/game/htb/HTBTableDemo.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/game/scene8/SceneDemo.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/logging/LoggerDemo.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/mapping/RouterDemo.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/mapping/StringMapperClass.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/mapping/StringPoster.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/mapping/StringQuestParam.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/mapping/StringRequest.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/net/BinaryClientDemo.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/net/BinaryMessageDemo.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/net/BinaryMessageDemo2.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/net/BinaryScriptManager.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/net/BinaryScriptManagerImpl.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/net/BinaryServerDemo.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/net/BinarySessionRole.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/net/FlashSSLServerDemo.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/net/HTTPSServerDemo.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/net/HTTPServerDemo.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/net/LocalEndPointDemo.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/net/MessageMapper.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/net/MessagePackageTest.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/net/ProtobufClientDemo.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/net/ProtobufMessageDemo.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/net/ProtobufServerDemo.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/net/ProtobufSessionRole.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/net/WebSocketServerDemo.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/redefinable/HelloRedefine.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/redefinable/RedefinableDemo.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/redefinable/ScriptEntrance.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/script/AutoReloadScriptDemo.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/script/HelloScript.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/script/ScriptSourceDemo.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/singleton/SingletonA.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/singleton/SingletonB.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/singleton/SingletonC.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/singleton/SingletonD.java delete mode 100644 demo/src/main/java/top/limitart/demo/demo/singleton/SingletonDemo.java diff --git a/demo/src/main/java/top/limitart/demo/demo/base/EnumBehaviorDemo.java b/demo/src/main/java/top/limitart/demo/demo/base/EnumBehaviorDemo.java deleted file mode 100644 index 880a986..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/base/EnumBehaviorDemo.java +++ /dev/null @@ -1,11 +0,0 @@ -package top.limitart.demo.base; - -/** - * @author hank - * @version 2019/5/30 0030 17:28 - */ -public enum EnumBehaviorDemo implements EnumBehavior { - A, - B, - C, -} diff --git a/demo/src/main/java/top/limitart/demo/demo/collections/ConcurrentLRUCacheDemo.java b/demo/src/main/java/top/limitart/demo/demo/collections/ConcurrentLRUCacheDemo.java deleted file mode 100644 index 0572847..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/collections/ConcurrentLRUCacheDemo.java +++ /dev/null @@ -1,57 +0,0 @@ -package top.limitart.demo.collections; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * @author hank - * @version 2018/11/13 0013 21:31 - */ -public class ConcurrentLRUCacheDemo { - public static void main(String[] args) throws InterruptedException { - ConcurrentLRUCache cache = new ConcurrentLRUCache<>(5, true); - ExecutorService executorService = Executors.newCachedThreadPool(); - AtomicInteger counter = new AtomicInteger(0); - for (; ; ) { - try { - Thread.sleep(50); - } catch (InterruptedException e) { - e.printStackTrace(); - } - executorService.execute( - () -> { - int andIncrement = counter.getAndIncrement(); - cache.put(andIncrement, new CacheObj(andIncrement)); - }); - } - } - - public static class CacheObj extends ConcurrentLRUCache.LRUCacheable { - private int value; - - public CacheObj(int value) { - this.value = value; - } - - @Override - public String toString() { - return "CacheObj{" + "value=" + value + '}'; - } - - @Override - protected long aliveTime() { - return 1000; - } - - @Override - protected boolean removable0() { - return true; - } - - @Override - public void onRemoved(int currentSize) { - System.out.println("removed " + this); - } - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/collections/RankMapDemo.java b/demo/src/main/java/top/limitart/demo/demo/collections/RankMapDemo.java deleted file mode 100644 index 7425a6a..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/collections/RankMapDemo.java +++ /dev/null @@ -1,82 +0,0 @@ -package top.limitart.demo.collections; - -import top.limitart.demo.base.CompareChain; - -import java.util.Comparator; - -public class RankMapDemo { - private static final Comparator COMPARATOR = - CompareChain.build( - (o1, o2) -> CompareChain.start(o2.price * o2.item.getNum(), o1.price * o1.item.num)); - - public static void main(String[] args) { - RankMap rankMap = RankMap.create(COMPARATOR, 100); - Item i1 = new Item(2); - Bean b1 = new Bean(1, i1, 100); - Item i2 = new Item(3); - Bean b2 = new Bean(2, i2, 100); - Item i3 = new Item(3); - Bean b3 = new Bean(3, i3, 500); - Item i4 = new Item(3); - rankMap.putIfAbsent(b1); - rankMap.putIfAbsent(b2); - System.out.println(rankMap.getAll()); - rankMap.update(b1.key(), v -> v.price = 200); - System.out.println(rankMap.getAll()); - rankMap.putIfAbsent(b3); - System.out.println(rankMap.getAll()); - rankMap.updateOrPut(4L, v -> v.price = 1, () -> new Bean(4, i4, 1)); - System.out.println(rankMap.getAll()); - } - - public static class Bean implements RankMap.LongRankObj { - private long id; - private Item item; - private int price; - - public Bean(long id, Item item, int price) { - this.item = item; - this.price = price; - this.id = id; - } - - public Bean copy() { - return new Bean(this.id, this.item.copy(), this.price); - } - - @Override - public Long key() { - return id; - } - - @Override - public String toString() { - return "Bean{" + "id=" + id + ", item=" + item + ", price=" + price + '}'; - } - } - - public static class Item { - private int num; - - public Item copy() { - return new Item(num); - } - - public Item(int num) { - this.num = num; - } - - public int getNum() { - return num; - } - - public void setNum(int num) { - this.num = num; - } - - @Override - public String toString() { - return "Item{" + "num=" + num + '}'; - } - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/concurrent/TaskQueueCronDemo.java b/demo/src/main/java/top/limitart/demo/demo/concurrent/TaskQueueCronDemo.java deleted file mode 100644 index 8437f54..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/concurrent/TaskQueueCronDemo.java +++ /dev/null @@ -1,32 +0,0 @@ -package top.limitart.demo.concurrent; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.text.ParseException; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; - -/** - * @author hank - * @version 2018/12/11 0011 13:55 - */ -public class TaskQueueCronDemo { - private static Logger LOGGER = LoggerFactory.getLogger(TaskQueueCronDemo.class); - - public static void main(String[] args) throws ParseException, ExecutionException, InterruptedException { - TaskQueue queue = TaskQueue.create("test"); - queue.execute(()-> System.out.println("execute")); - queue.submit(()-> System.out.println("submit")).get(); - queue.schedule(()-> System.out.println("schedule"), 1, TimeUnit.SECONDS); - queue.schedule("cron1", "0 22 14 11 12 ? 2018", () -> System.out.println("tick1")); - queue.schedule("cron1", "*/5 * * * * ? *", () -> System.out.println("tick2")); - queue.schedule("cron1", "0 * * * * ? *", () -> System.out.println("tick3")); - - TaskQueueGroup group = new TaskQueueGroup("limitart",5,s->TaskQueue.create(s)); - group.next().execute(()-> System.out.println("execute1")); - group.next().execute(()-> System.out.println("execute2")); - group.next().execute(()-> System.out.println("execute3")); - group.next().execute(()-> System.out.println("execute4")); - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/config/ConfigMetaDemo.java b/demo/src/main/java/top/limitart/demo/demo/config/ConfigMetaDemo.java deleted file mode 100644 index f88a458..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/config/ConfigMetaDemo.java +++ /dev/null @@ -1,12 +0,0 @@ -package top.limitart.demo.config; - -/** - * @author hank - * @version 2018/12/28 0028 11:19 - */ -public class ConfigMetaDemo extends ConfigMeta { - @Override - public Integer primaryKey() { - return null; - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/config/D_ChipRank.java b/demo/src/main/java/top/limitart/demo/demo/config/D_ChipRank.java deleted file mode 100644 index 6165c56..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/config/D_ChipRank.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2016-present The Limitart Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package top.limitart.demo.config; - -/** - * 最高奖金排行奖励 from dat_proto at 2018-12-24T14:33:18.841 - * - * @author limitart - */ -public class D_ChipRank extends ConfigMeta { - /** 起始排名 */ - private int startRank; - /** 奖励数量 */ - private long count; - /** 起始排名 */ - public int getStartRank() { - return this.startRank; - } - /** 奖励数量 */ - public long getCount() { - return this.count; - } - - @Override - public Integer primaryKey() { - return this.startRank; - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/config/D_WinRank.java b/demo/src/main/java/top/limitart/demo/demo/config/D_WinRank.java deleted file mode 100644 index 9026518..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/config/D_WinRank.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2016-present The Limitart Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package top.limitart.demo.config; - -/** - * 胜利场数排行奖励 from dat_proto at 2018-12-24T14:33:18.841 - * - * @author limitart - */ -public class D_WinRank extends ConfigMeta { - /** 起始排名 */ - private int startRank; - /** 奖励数量 */ - private long count; - /** 整型数组测试 */ - private int[] array; - /** 整型二维数组测试 */ - private int[][] array2; - /** 起始排名 */ - public int getStartRank() { - return this.startRank; - } - /** 奖励数量 */ - public long getCount() { - return this.count; - } - /** 整型数组测试 */ - public int[] getArray() { - return this.array; - } - /** 整型二维数组测试 */ - public int[][] getArray2() { - return this.array2; - } - - @Override - public Integer primaryKey() { - return this.startRank; - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/config/DataTypeDemo.java b/demo/src/main/java/top/limitart/demo/demo/config/DataTypeDemo.java deleted file mode 100644 index f1c574a..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/config/DataTypeDemo.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * - * * Copyright (c) 2016-present The Limitart Project - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * - */ - -package top.limitart.demo.config; - -import top.limitart.demo.json.JSON; -import top.limitart.demo.util.CollectionUtil; - -/** Created by Hank on 2018/12/23 */ -public class DataTypeDemo { - public static void main(String[] args) throws Exception { - Person person = new Person(); - person.setName("hank"); - person.setAge(18); - String source = JSON.getDefault().toStr(person); - PersonDataType parser = new PersonDataType(); - Person parse = parser.parse(source); - System.out.println(parse); - - String intArray = "[1,2,3,4,5]"; - IntArrayType intArrayType = new IntArrayType(); - int[] parse1 = intArrayType.parse(intArray); - System.out.println(CollectionUtil.toString(parse1)); - - String intArray2 = "[[1,2,3],[2,3,4]]"; - IntArray2DType intArray2DType = new IntArray2DType(); - int[][] parse2 = intArray2DType.parse(intArray2); - System.out.println(CollectionUtil.toString(parse2)); - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/config/ExcelModelDemo.java b/demo/src/main/java/top/limitart/demo/demo/config/ExcelModelDemo.java deleted file mode 100644 index 0cbf037..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/config/ExcelModelDemo.java +++ /dev/null @@ -1,31 +0,0 @@ -package top.limitart.demo.config; - -import java.util.Collections; -import java.util.Map; - -/** - * @author hank - * @version 2018/12/26 0026 21:20 - */ -public class ExcelModelDemo { - public static void main(String[] args) throws Exception { - DataParser parser = - new DataParser() { - @Override - protected void initDataType() {} - }; - ExcelModel excelModel = - ExcelModel.loadFromExcel( - parser, ExcelModel.class.getClassLoader().getResource("./dat_proto.xlsx").getPath()); - Map stringMap = excelModel.readData(SheetHead.CellHolder.all()); - ConfigContainers configContainers = - ConfigContainers.loadFromExcelModels( - "top.limitart.config", - Collections.singletonList(excelModel), - SheetHead.CellHolder.SERVER); - byte[] bytes = configContainers.toBytes(parser); - ConfigContainers configContainers1 = - ConfigContainers.loadFromBtyes("top.limitart.config", parser, bytes); - excelModel.close(); - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/config/Person.java b/demo/src/main/java/top/limitart/demo/demo/config/Person.java deleted file mode 100644 index 757d7f7..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/config/Person.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * - * * Copyright (c) 2016-present The Limitart Project - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * - */ - -package top.limitart.demo.config; - -import top.limitart.demo.base.BinaryMeta; - -/** Created by Hank on 2018/12/23 */ -public class Person extends BinaryMeta { - private String name; - private int age; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } - - @Override - public String toString() { - return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/config/PersonDataType.java b/demo/src/main/java/top/limitart/demo/demo/config/PersonDataType.java deleted file mode 100644 index 2806f01..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/config/PersonDataType.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * - * * Copyright (c) 2016-present The Limitart Project - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * - */ - -package top.limitart.demo.config; - -import top.limitart.demo.base.BinaryMeta; - -/** Created by Hank on 2018/12/23 */ -public class PersonDataType extends JSONParsingType { - @Override - public String name() { - return "Person"; - } - - @Override - public String alias() { - return "person"; - } - - @Override - public String nameOfR() { - return Person.class.getName(); - } - - @Override - public Class classOfR() { - return Person.class; - } - - @Override - public void serialize(BinaryMeta buf, Person value) {} - - @Override - public Person deserialize(BinaryMeta buf) throws Exception { - return buf.getMessageMeta(Person.class); - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/event/EventDemo.java b/demo/src/main/java/top/limitart/demo/demo/event/EventDemo.java deleted file mode 100644 index c1f6107..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/event/EventDemo.java +++ /dev/null @@ -1,17 +0,0 @@ -package top.limitart.demo.event; - -/** - * @author hank - * @version 2019/3/25 0025 14:48 - */ -public class EventDemo implements Event { - private String name; - - public EventDemo(String name) { - this.name = name; - } - - public String getName() { - return name; - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/event/EventProviderDemo.java b/demo/src/main/java/top/limitart/demo/demo/event/EventProviderDemo.java deleted file mode 100644 index 6829047..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/event/EventProviderDemo.java +++ /dev/null @@ -1,31 +0,0 @@ -package top.limitart.demo.event; - -import top.limitart.demo.concurrent.TaskQueue; - -/** - * @author hank - * @version 2019/3/25 0025 14:49 - */ -public class EventProviderDemo extends AbstractEventProvider { - public static void main(String[] args) { - TaskQueue executor = TaskQueue.create("event demo thread"); - EventProvider demo = new EventProviderDemo(); - int listen = - demo.listen( - EventDemo.class, - null, - e -> System.out.println(Thread.currentThread().getName() + "," + e.getName())); - demo.listen( - EventDemo.class, - executor, - e -> System.out.println(Thread.currentThread().getName() + "," + e.getName())); - demo.notListen(EventDemo.class, listen); - demo.post(new EventDemo("event demo")); - demo.post(new EventDemo("event demo1")); - } - - @Override - protected boolean onPost(Event event) { - return true; - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/fastmq/PipelineConsumerDemo.java b/demo/src/main/java/top/limitart/demo/demo/fastmq/PipelineConsumerDemo.java deleted file mode 100644 index 92cc01f..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/fastmq/PipelineConsumerDemo.java +++ /dev/null @@ -1,39 +0,0 @@ -package top.limitart.demo.fastmq; - -import java.nio.charset.StandardCharsets; -import java.util.LinkedList; -import java.util.List; -import top.limitart.demo.fastmq.consumer.MQConsumerBinaryClient; - -public class PipelineConsumerDemo { - - private static MQConsumerBinaryClient consumerClient; - - static { - try { - List tags = new LinkedList<>(); - tags.add("fuck"); - tags.add("shit"); - consumerClient = - new MQConsumerBinaryClient( - "127.0.0.1", - 9000, - "test_zone", - tags, - msg -> {System.out.println(new String(msg, StandardCharsets.UTF_8)) - ; - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - }); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public static void main(String[] args) throws Exception { - consumerClient.run(args); - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/fastmq/PipelineProviderDemo.java b/demo/src/main/java/top/limitart/demo/demo/fastmq/PipelineProviderDemo.java deleted file mode 100644 index 5f0d572..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/fastmq/PipelineProviderDemo.java +++ /dev/null @@ -1,35 +0,0 @@ -package top.limitart.demo.fastmq; - -import java.nio.charset.StandardCharsets; -import java.util.LinkedList; -import java.util.List; -import top.limitart.demo.fastmq.provider.MQProviderBinaryClient; - -public class PipelineProviderDemo { - - private static MQProviderBinaryClient providerClient; - - static { - try { - List tags = new LinkedList<>(); - tags.add("fuck"); - tags.add("shit"); - providerClient = - new MQProviderBinaryClient( - "127.0.0.1", - 9000); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public static void main(String[] args) throws Exception { - providerClient.run(args); - int count = 0; - while (true) { - providerClient.sendMsg("test_zone", ("hello fastmq !" + count++) - .getBytes(StandardCharsets.UTF_8)); - Thread.sleep(30); - } - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/fastmq/PipelineServerDemo.java b/demo/src/main/java/top/limitart/demo/demo/fastmq/PipelineServerDemo.java deleted file mode 100644 index 6b193e1..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/fastmq/PipelineServerDemo.java +++ /dev/null @@ -1,22 +0,0 @@ -package top.limitart.demo.fastmq; - -import top.limitart.demo.fastmq.pipeline.MQPipelineBinaryServer; -import top.limitart.demo.fastmq.pipeline.core.Pipeline; - -public class PipelineServerDemo { - - private static Pipeline pipeline = new Pipeline(); - private static MQPipelineBinaryServer binaryServer; - - static { - try { - binaryServer = new MQPipelineBinaryServer(pipeline, 9000); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public static void main(String[] args) throws Exception { - binaryServer.run(args); - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/game/htb/HTBDemo.java b/demo/src/main/java/top/limitart/demo/demo/game/htb/HTBDemo.java deleted file mode 100644 index 8118db6..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/game/htb/HTBDemo.java +++ /dev/null @@ -1,63 +0,0 @@ -package top.limitart.demo.game.htb; - -import top.limitart.demo.game.FPSBootstrap; -import top.limitart.demo.game.FPSLimiter; -import top.limitart.demo.game.FPSRunner; -import top.limitart.demo.game.SimpleFPSRunner; -import top.limitart.demo.game.htb.event.RRoleStartHandleEvent; -import top.limitart.demo.game.htb.event.TBattleTurnEndEvent; - -/** - * @author hank - * @version 2019/6/15 0015 16:42 - */ -public class HTBDemo { - public static void main(String[] args) { - FPSBootstrap bootstrap = new FPSBootstrap("htb-room", 4); - HTBTable table = createTable(); - bootstrap.add(table, () -> {}); - FPSLimiter limiter = new FPSLimiter(1000); - bootstrap.add( - new SimpleFPSRunner() { - @Override - public void onUpdate() throws Exception { - limiter.tick( - () -> { - for (FPSRunner fpsRunner : bootstrap) { - if (fpsRunner instanceof HTBTable) { - HTBTable t = (HTBTable) fpsRunner; - if (t.isEnd()) { - t.where().execute(() -> bootstrap.remove(t.uniqueID())); - } - } - } - }); - } - - @Override - public long uniqueID() { - return -1; - } - }, - () -> {}); - } - - private static HTBTable createTable() { - HTBRoleDemo role1 = new HTBRoleDemo(1, 20); - HTBRoleDemo role2 = new HTBRoleDemo(2, 30); - HTBTableDemo table = new HTBTableDemo(1, role1, role2); - table.listen( - RRoleStartHandleEvent.class, - e -> { - System.out.println(e.getRole().uniqueID() + " " + "start!!"); - }); - table.listen( - TBattleTurnEndEvent.class, - e -> { - if (e.currentTurn() >= 4) { - e.table().end(); - } - }); - return table; - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/game/htb/HTBRoleDemo.java b/demo/src/main/java/top/limitart/demo/demo/game/htb/HTBRoleDemo.java deleted file mode 100644 index 2c61242..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/game/htb/HTBRoleDemo.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * - * * Copyright (c) 2016-present The Limitart Project - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * - */ - -package top.limitart.demo.game.htb; - -/** Created by Hank on 2019/6/30 */ -public class HTBRoleDemo extends HTBRole { - private long id; - private int speed; - - public HTBRoleDemo(long id, int speed) { - this.id = id; - this.speed = speed; - } - - @Override - public int speed() { - return this.speed; - } - - @Override - public boolean ready() { - return true; - } - - @Override - public long uniqueID() { - return this.id; - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/game/htb/HTBTableDemo.java b/demo/src/main/java/top/limitart/demo/demo/game/htb/HTBTableDemo.java deleted file mode 100644 index 8d38069..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/game/htb/HTBTableDemo.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * - * * Copyright (c) 2016-present The Limitart Project - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * - */ - -package top.limitart.demo.game.htb; - -/** Created by Hank on 2019/6/30 */ -public class HTBTableDemo extends HTBTable { - public HTBTableDemo(long uniqueID, HTBRoleDemo... roles) { - super(uniqueID); - for (HTBRoleDemo role : roles) { - addRole(role); - } - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/game/scene8/SceneDemo.java b/demo/src/main/java/top/limitart/demo/demo/game/scene8/SceneDemo.java deleted file mode 100644 index 170c097..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/game/scene8/SceneDemo.java +++ /dev/null @@ -1,81 +0,0 @@ -package top.limitart.demo.game.scene8; - -import top.limitart.demo.game.FPSBootstrap; - -/** - * @author hank - * @version 2019/6/1 0001 17:15 - */ -public class SceneDemo { - private static SceneCore core; - - public static void main(String[] args) throws InterruptedException { - core = - new WalkableScene(120, 80, 4, 4, 6, 6) { - @Override - protected void beforeObjAdd(WalkableSceneObj obj) { - super.beforeObjAdd(obj); - System.out.println("beforeObjAdd:" + obj); - } - - @Override - protected void onObjAdd(WalkableSceneObj obj) { - super.onObjAdd(obj); - System.out.println("onObjAdd:" + obj); - for (int i = 0; i < 100; i++) { - obj.changePos(obj.x() + 1, obj.y() + 1); - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - @Override - protected void onObjUpdate(WalkableSceneObj obj) { - // System.out.println("onObjUpdate:" + obj); - } - - @Override - protected void beforeObjRemove(WalkableSceneObj obj) { - System.out.println("beforeObjRemove:" + obj); - } - - @Override - protected void onObjRemove(WalkableSceneObj obj) { - super.onObjRemove(obj); - System.out.println("onObjRemove:" + obj); - } - - @Override - protected void onAddToArea(WalkableScene.Area area, WalkableSceneObj obj) { - System.out.println(String.format("onAddToArea area:%s,obj:%s", area, obj)); - } - - @Override - protected void onRemoveFromArea(WalkableScene.Area area, WalkableSceneObj obj) { - System.out.println(String.format("onRemoveFromArea area:%s,obj:%s", area, obj)); - } - - @Override - public long uniqueID() { - return 1; - } - }; - FPSBootstrap bootstrap = new FPSBootstrap("scene-demo", 4); - bootstrap.add( - core, - () -> { - SceneItem a = new SceneItem(); - a.changePos(20, 40); - core.add(a); - // a.destroy(); - }); - } - - public static class SceneItem extends WalkableSceneObj { - @Override - public void onUpdate() {} - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/logging/LoggerDemo.java b/demo/src/main/java/top/limitart/demo/demo/logging/LoggerDemo.java deleted file mode 100644 index 1f18ccd..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/logging/LoggerDemo.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2016-present The Limitart Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package top.limitart.demo.logging; - -public class LoggerDemo { - private static final Logger LOGGER = Loggers.create(); - - public static void main(String[] args) { - LOGGER.info("xxxxx"); - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/mapping/RouterDemo.java b/demo/src/main/java/top/limitart/demo/demo/mapping/RouterDemo.java deleted file mode 100644 index a6065fe..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/mapping/RouterDemo.java +++ /dev/null @@ -1,17 +0,0 @@ -package top.limitart.demo.mapping; - -/** - * @author hank - * @version 2018/10/8 0008 21:25 - */ -public class RouterDemo { - public static void main(String[] args) throws Exception { - Router router = - Router.empty(StringRequest.class, StringQuestParam.class); - router.registerMapperClass(StringMapperClass.class); - StringRequest newRequest = new StringRequest(); - newRequest.setMsg("hank!!!"); - StringQuestParam stringQuestParam = new StringQuestParam(); - router.request(newRequest, stringQuestParam, Router.MethodInvoker::invoke); - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/mapping/StringMapperClass.java b/demo/src/main/java/top/limitart/demo/demo/mapping/StringMapperClass.java deleted file mode 100644 index 482cc3e..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/mapping/StringMapperClass.java +++ /dev/null @@ -1,12 +0,0 @@ -package top.limitart.demo.mapping; - -/** - * @author hank - * @version 2018/10/8 0008 21:23 - */ -@Mapper -public class StringMapperClass { - public void onMsg(@Request StringRequest msg, StringQuestParam param) { - System.out.println(msg.getMsg()); - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/mapping/StringPoster.java b/demo/src/main/java/top/limitart/demo/demo/mapping/StringPoster.java deleted file mode 100644 index b7985fc..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/mapping/StringPoster.java +++ /dev/null @@ -1,7 +0,0 @@ -package top.limitart.demo.mapping; - -/** - * @author hank - * @version 2018/10/8 0008 21:22 - */ -public class StringPoster {} diff --git a/demo/src/main/java/top/limitart/demo/demo/mapping/StringQuestParam.java b/demo/src/main/java/top/limitart/demo/demo/mapping/StringQuestParam.java deleted file mode 100644 index 36630fd..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/mapping/StringQuestParam.java +++ /dev/null @@ -1,8 +0,0 @@ -package top.limitart.demo.mapping; - -/** - * @author hank - * @version 2018/10/8 0008 21:22 - */ -public class StringQuestParam implements RequestContext { -} diff --git a/demo/src/main/java/top/limitart/demo/demo/mapping/StringRequest.java b/demo/src/main/java/top/limitart/demo/demo/mapping/StringRequest.java deleted file mode 100644 index 33e662d..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/mapping/StringRequest.java +++ /dev/null @@ -1,17 +0,0 @@ -package top.limitart.demo.mapping; - -/** - * @author hank - * @version 2018/10/8 0008 21:21 - */ -public class StringRequest { - private String msg; - - public String getMsg() { - return msg; - } - - public void setMsg(String msg) { - this.msg = msg; - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/net/BinaryClientDemo.java b/demo/src/main/java/top/limitart/demo/demo/net/BinaryClientDemo.java deleted file mode 100644 index dab5e3e..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/net/BinaryClientDemo.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2016-present The Limitart Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package top.limitart.demo.net; - -import top.limitart.demo.mapping.Router; -import top.limitart.demo.net.binary.BinaryEndPoint; -import top.limitart.demo.net.binary.BinaryMessage; -import top.limitart.demo.net.binary.BinaryRequestParam; - -/** @author hank */ -public class BinaryClientDemo { - public static void main(String[] args) throws Exception { - BinaryEndPoint.builder(false) - .router( - Router.empty(BinaryMessage.class, BinaryRequestParam.class) - .registerMapperClass(MessageMapper.class)) - .onConnected( - (s, state) -> { - if (state) { - try { - s.writeNow(new BinaryMessageDemo()); - } catch (Exception ignored) { - } - } - }) - .build() - .start(AddressPair.withIP("127.0.0.1", 7878)); - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/net/BinaryMessageDemo.java b/demo/src/main/java/top/limitart/demo/demo/net/BinaryMessageDemo.java deleted file mode 100644 index 2e3aeb5..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/net/BinaryMessageDemo.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2016-present The Limitart Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package top.limitart.demo.net; - -import top.limitart.demo.net.binary.BinaryMessage; -import top.limitart.demo.net.binary.BinaryMessages; - -public class BinaryMessageDemo extends BinaryMessage { - public final String content = "hello limitart!"; - - @Override - public short id() { - return BinaryMessages.createID(0X00, 0X01); - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/net/BinaryMessageDemo2.java b/demo/src/main/java/top/limitart/demo/demo/net/BinaryMessageDemo2.java deleted file mode 100644 index f58677f..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/net/BinaryMessageDemo2.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2016-present The Limitart Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package top.limitart.demo.net; - -import top.limitart.demo.net.binary.BinaryMessage; -import top.limitart.demo.net.binary.BinaryMessages; - -/** @author hank */ -public class BinaryMessageDemo2 extends BinaryMessage { - public final String content = "hello script manager"; - - @Override - public short id() { - return BinaryMessages.createID(0X00, 0X02); - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/net/BinaryScriptManager.java b/demo/src/main/java/top/limitart/demo/demo/net/BinaryScriptManager.java deleted file mode 100644 index c5108d4..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/net/BinaryScriptManager.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) 2016-present The Limitart Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package top.limitart.demo.net; - -import top.limitart.demo.mapping.Mapper; -import top.limitart.demo.mapping.Request; -import top.limitart.demo.net.binary.BinaryRequestParam; - -/** @author hank */ -@Mapper -public abstract class BinaryScriptManager { - public abstract void helloScriptManager(@Request BinaryMessageDemo2 msg, BinaryRequestParam param); -} diff --git a/demo/src/main/java/top/limitart/demo/demo/net/BinaryScriptManagerImpl.java b/demo/src/main/java/top/limitart/demo/demo/net/BinaryScriptManagerImpl.java deleted file mode 100644 index a72f731..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/net/BinaryScriptManagerImpl.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2016-present The Limitart Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package top.limitart.demo.net; - -import top.limitart.demo.net.binary.BinaryRequestParam; - -/** @author hank */ -public class BinaryScriptManagerImpl extends BinaryScriptManager { - - @Override - public void helloScriptManager(BinaryMessageDemo2 msg, BinaryRequestParam param) { - System.out.println(msg.content); - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/net/BinaryServerDemo.java b/demo/src/main/java/top/limitart/demo/demo/net/BinaryServerDemo.java deleted file mode 100644 index d53ef43..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/net/BinaryServerDemo.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2016-present The Limitart Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package top.limitart.demo.net; - -import top.limitart.demo.mapping.Router; -import top.limitart.demo.net.binary.BinaryEndPoint; -import top.limitart.demo.net.binary.BinaryMessage; -import top.limitart.demo.net.binary.BinaryRequestParam; - -/** @author hank */ -public class BinaryServerDemo { - static final BinarySessionRole role = new BinarySessionRole(); - - public static void main(String[] args) throws Exception { - BinaryEndPoint.builder(true) - .router( - Router.empty(BinaryMessage.class, BinaryRequestParam.class) - .registerMapperClass(MessageMapper.class)) - .onConnected( - (s, b) -> { - if (b) { - role.joinWhenFree( - s, - () -> {System.out.println("join session success!"); - NettySession where = role.where(); - }, - Throwable::printStackTrace); - } else { - role.leave(s); - System.out.println("leave session success"); - } - }) - .build() - .start(AddressPair.withPort(7878)); - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/net/BinarySessionRole.java b/demo/src/main/java/top/limitart/demo/demo/net/BinarySessionRole.java deleted file mode 100644 index cee0285..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/net/BinarySessionRole.java +++ /dev/null @@ -1,6 +0,0 @@ -package top.limitart.demo.net; - - -import top.limitart.demo.net.binary.BinaryMessage; - -public class BinarySessionRole extends NettySessionActor {} diff --git a/demo/src/main/java/top/limitart/demo/demo/net/FlashSSLServerDemo.java b/demo/src/main/java/top/limitart/demo/demo/net/FlashSSLServerDemo.java deleted file mode 100644 index 3d6bbbf..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/net/FlashSSLServerDemo.java +++ /dev/null @@ -1,13 +0,0 @@ -package top.limitart.demo.net; - -import top.limitart.demo.net.flashssl.FlashSSLEndPoint; - -/** - * @author hank - * @version 2018/10/15 0015 21:23 - */ -public class FlashSSLServerDemo { - public static void main(String[] args) throws Exception { - FlashSSLEndPoint.builder().build().start(AddressPair.withPort(843)); - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/net/HTTPSServerDemo.java b/demo/src/main/java/top/limitart/demo/demo/net/HTTPSServerDemo.java deleted file mode 100644 index 725de75..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/net/HTTPSServerDemo.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * - * * Copyright (c) 2016-present The Limitart Project - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * - */ - -package top.limitart.demo.net; - -/** Created by Hank on 2018/10/14 */ -public class HTTPSServerDemo { - // TODO - -} diff --git a/demo/src/main/java/top/limitart/demo/demo/net/HTTPServerDemo.java b/demo/src/main/java/top/limitart/demo/demo/net/HTTPServerDemo.java deleted file mode 100644 index 1a3b9eb..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/net/HTTPServerDemo.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * - * * Copyright (c) 2016-present The Limitart Project - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * - */ - -package top.limitart.demo.net; - -import top.limitart.demo.net.http.HTTPEndPoint; - -import java.nio.charset.StandardCharsets; -import java.util.concurrent.Executors; - -/** Created by Hank on 2018/10/14 */ -public class HTTPServerDemo { - public static void main(String[] args) throws Exception { - HTTPEndPoint.builder() - .onMessageIn( - (s, i) -> { - if (i.getUrl().equals("/limitart")) { - return "hello limitart!".getBytes(StandardCharsets.UTF_8); - } - return null; - }, - () -> Executors.newSingleThreadScheduledExecutor()) - .build() - .start(AddressPair.withPort(8080)); - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/net/LocalEndPointDemo.java b/demo/src/main/java/top/limitart/demo/demo/net/LocalEndPointDemo.java deleted file mode 100644 index 94b926e..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/net/LocalEndPointDemo.java +++ /dev/null @@ -1,39 +0,0 @@ -package top.limitart.demo.net; - -import top.limitart.demo.mapping.Router; -import top.limitart.demo.net.binary.BinaryEndPoint; -import top.limitart.demo.net.binary.BinaryMessage; -import top.limitart.demo.net.binary.BinaryRequestParam; - -/** - * @author hank - * @version 2018/10/15 0015 14:14 - */ -public class LocalEndPointDemo { - - public static void main(String[] args) throws Exception { - // server - BinaryEndPoint.builder(NettyEndPointType.SERVER_LOCAL) - .router( - Router.empty(BinaryMessage.class, BinaryRequestParam.class) - .registerMapperClass(MessageMapper.class)) - .build() - .start(AddressPair.withLocalHost(1)); - // client - BinaryEndPoint.builder(NettyEndPointType.CLIENT_LOCAL) - .router( - Router.empty(BinaryMessage.class, BinaryRequestParam.class) - .registerMapperClass(MessageMapper.class)) - .onConnected( - (s, state) -> { - if (state) { - try { - s.writeNow(new BinaryMessageDemo()); - } catch (Exception ignored) { - } - } - }) - .build() - .start(AddressPair.withLocalHost(1)); - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/net/MessageMapper.java b/demo/src/main/java/top/limitart/demo/demo/net/MessageMapper.java deleted file mode 100644 index d660d67..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/net/MessageMapper.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * - * * Copyright (c) 2016-present The Limitart Project - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * - */ - -package top.limitart.demo.net; - -import com.google.protobuf.Message; -import io.netty.channel.EventLoop; -import top.limitart.demo.mapping.Mapper; -import top.limitart.demo.mapping.Request; -import top.limitart.demo.net.binary.BinaryMessage; -import top.limitart.demo.net.binary.BinaryRequestParam; -import top.limitart.demo.net.protobuf.ProtobufRequestParam; - -/** Created by Hank on 2018/10/13 */ -@Mapper -public class MessageMapper { - public void doMessageDemo(@Request BinaryMessageDemo msg, BinaryRequestParam param) { - Session session = param.session(); - System.out.println(msg.content); - session.writeNow(msg); - } - - public void doMessageDemo2(@Request ProtobufMessageDemo.Demo2 msg, ProtobufRequestParam param) { - Session session = param.session(); - System.out.println("demo2:" + msg.getId()); - } - - public void doMessageDemo1(@Request ProtobufMessageDemo.Demo1 msg, ProtobufRequestParam param) { - Session session = param.session(); - System.out.println("demo1:" + msg.getName()); - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/net/MessagePackageTest.java b/demo/src/main/java/top/limitart/demo/demo/net/MessagePackageTest.java deleted file mode 100644 index ba19297..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/net/MessagePackageTest.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (c) 2016-present The Limitart Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package top.limitart.demo.net; - -import top.limitart.demo.base.BinaryMeta; -import top.limitart.demo.net.binary.BinaryByteMessage; -import top.limitart.demo.net.binary.BinaryMessage; -import top.limitart.demo.net.binary.BinaryMessages; - -/** - * 消息生成测试 - * - * @author limitart - */ -public class MessagePackageTest { - private static final byte PACKAGE_ID = 1; - - /** - * 消息Bean测试 - * - * @author limitart - */ - public static class MetaInfo extends BinaryMeta { - /** 测试ID */ - public int ID; - /** 测试名字 */ - public String str; - /** 测试列表 */ - public java.util.List list = new java.util.ArrayList<>(); - } - - /** - * 消息测试 - * - * @author limitart - */ - public static class MessageTest extends BinaryMessage { - /** ID */ - public int ID; - /** 名称 */ - public String name; - /** bean列表 */ - public java.util.List metas = new java.util.ArrayList<>(); - - @Override - public short id() { - return BinaryMessages.createID(PACKAGE_ID, 1); - } - } - - /** - * 消息测试1 - * - * @author limitart - */ - public static class MessageTest1 extends BinaryMessage { - /** ID */ - public int ID; - /** 名称 */ - public String name; - /** bean列表 */ - public java.util.List metas = new java.util.ArrayList<>(); - - @Override - public short id() { - return BinaryMessages.createID(PACKAGE_ID, 2); - } - } - - public static class MessageEnumTest extends BinaryByteMessage { - /** */ - public static MessageEnumTest XXX1 = new MessageEnumTest((byte) 1); - - public MessageEnumTest(byte code) { - super(code); - } - - @Override - public short id() { - return BinaryMessages.createID(PACKAGE_ID, 3); - } - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/net/ProtobufClientDemo.java b/demo/src/main/java/top/limitart/demo/demo/net/ProtobufClientDemo.java deleted file mode 100644 index 68e1366..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/net/ProtobufClientDemo.java +++ /dev/null @@ -1,30 +0,0 @@ -package top.limitart.demo.net; - -import com.google.protobuf.Message; -import top.limitart.demo.mapping.Router; -import top.limitart.demo.net.protobuf.ProtobufEndPoint; -import top.limitart.demo.net.protobuf.ProtobufRequestParam; - -/** - * @author hank - * @version 2018/10/12 0012 21:29 - */ -public class ProtobufClientDemo { - public static void main(String[] args) throws Exception { - ProtobufEndPoint.builder(false) - .router( - Router.empty(Message.class, ProtobufRequestParam.class) - .registerMapperClass(MessageMapper.class)) - .onConnected( - (s, state) -> { - if (state) { - try { - s.writeNow(ProtobufMessageDemo.Demo2.newBuilder().setId(1111).build()); - } catch (Exception ignored) { - } - } - }) - .build() - .start(AddressPair.withIP("127.0.0.1", 7878)); - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/net/ProtobufMessageDemo.java b/demo/src/main/java/top/limitart/demo/demo/net/ProtobufMessageDemo.java deleted file mode 100644 index 7a08964..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/net/ProtobufMessageDemo.java +++ /dev/null @@ -1,1334 +0,0 @@ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: protobuf3.proto - -package top.limitart.demo.net; - -public final class ProtobufMessageDemo { - private ProtobufMessageDemo() {} - - public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {} - - public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) { - registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); - } - - public interface Demo1OrBuilder - extends - // @@protoc_insertion_point(interface_extends:Demo1) - com.google.protobuf.MessageOrBuilder { - - /** string name = 1; */ - String getName(); - /** string name = 1; */ - com.google.protobuf.ByteString getNameBytes(); - } - /** Protobuf type {@code Demo1} */ - public static final class Demo1 extends com.google.protobuf.GeneratedMessageV3 - implements - // @@protoc_insertion_point(message_implements:Demo1) - Demo1OrBuilder { - private static final long serialVersionUID = 0L; - // Use Demo1.newBuilder() to construct. - private Demo1(com.google.protobuf.GeneratedMessageV3.Builder builder) { - super(builder); - } - - private Demo1() { - name_ = ""; - } - - @Override - public final com.google.protobuf.UnknownFieldSet getUnknownFields() { - return this.unknownFields; - } - - private Demo1( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - this(); - if (extensionRegistry == null) { - throw new NullPointerException(); - } - int mutable_bitField0_ = 0; - com.google.protobuf.UnknownFieldSet.Builder unknownFields = - com.google.protobuf.UnknownFieldSet.newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - case 10: - { - String s = input.readStringRequireUtf8(); - - name_ = s; - break; - } - default: - { - if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { - done = true; - } - break; - } - } - } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); - } finally { - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); - } - } - - public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return ProtobufMessageDemo.internal_static_Demo1_descriptor; - } - - @Override - protected FieldAccessorTable internalGetFieldAccessorTable() { - return ProtobufMessageDemo.internal_static_Demo1_fieldAccessorTable - .ensureFieldAccessorsInitialized(Demo1.class, Builder.class); - } - - public static final int NAME_FIELD_NUMBER = 1; - private volatile Object name_; - /** string name = 1; */ - public String getName() { - Object ref = name_; - if (ref instanceof String) { - return (String) ref; - } else { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - String s = bs.toStringUtf8(); - name_ = s; - return s; - } - } - /** string name = 1; */ - public com.google.protobuf.ByteString getNameBytes() { - Object ref = name_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8((String) ref); - name_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - - private byte memoizedIsInitialized = -1; - - @Override - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) return true; - if (isInitialized == 0) return false; - - memoizedIsInitialized = 1; - return true; - } - - @Override - public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { - if (!getNameBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_); - } - unknownFields.writeTo(output); - } - - @Override - public int getSerializedSize() { - int size = memoizedSize; - if (size != -1) return size; - - size = 0; - if (!getNameBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_); - } - size += unknownFields.getSerializedSize(); - memoizedSize = size; - return size; - } - - @Override - public boolean equals(final Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof Demo1)) { - return super.equals(obj); - } - Demo1 other = (Demo1) obj; - - boolean result = true; - result = result && getName().equals(other.getName()); - result = result && unknownFields.equals(other.unknownFields); - return result; - } - - @Override - public int hashCode() { - if (memoizedHashCode != 0) { - return memoizedHashCode; - } - int hash = 41; - hash = (19 * hash) + getDescriptor().hashCode(); - hash = (37 * hash) + NAME_FIELD_NUMBER; - hash = (53 * hash) + getName().hashCode(); - hash = (29 * hash) + unknownFields.hashCode(); - memoizedHashCode = hash; - return hash; - } - - public static Demo1 parseFrom(java.nio.ByteBuffer data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - - public static Demo1 parseFrom( - java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - - public static Demo1 parseFrom(com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - - public static Demo1 parseFrom( - com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - - public static Demo1 parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - - public static Demo1 parseFrom( - byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - - public static Demo1 parseFrom(java.io.InputStream input) throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); - } - - public static Demo1 parseFrom( - java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException( - PARSER, input, extensionRegistry); - } - - public static Demo1 parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); - } - - public static Demo1 parseDelimitedFrom( - java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( - PARSER, input, extensionRegistry); - } - - public static Demo1 parseFrom(com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); - } - - public static Demo1 parseFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException( - PARSER, input, extensionRegistry); - } - - @Override - public Builder newBuilderForType() { - return newBuilder(); - } - - public static Builder newBuilder() { - return DEFAULT_INSTANCE.toBuilder(); - } - - public static Builder newBuilder(Demo1 prototype) { - return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); - } - - @Override - public Builder toBuilder() { - return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); - } - - @Override - protected Builder newBuilderForType(BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; - } - /** Protobuf type {@code Demo1} */ - public static final class Builder - extends com.google.protobuf.GeneratedMessageV3.Builder - implements - // @@protoc_insertion_point(builder_implements:Demo1) - Demo1OrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return ProtobufMessageDemo.internal_static_Demo1_descriptor; - } - - @Override - protected FieldAccessorTable internalGetFieldAccessorTable() { - return ProtobufMessageDemo.internal_static_Demo1_fieldAccessorTable - .ensureFieldAccessorsInitialized(Demo1.class, Builder.class); - } - - // Construct using top.limitart.net.ProtobufMessageDemo.Demo1.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder(BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} - } - - @Override - public Builder clear() { - super.clear(); - name_ = ""; - - return this; - } - - @Override - public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { - return ProtobufMessageDemo.internal_static_Demo1_descriptor; - } - - @Override - public Demo1 getDefaultInstanceForType() { - return Demo1.getDefaultInstance(); - } - - @Override - public Demo1 build() { - Demo1 result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); - } - return result; - } - - @Override - public Demo1 buildPartial() { - Demo1 result = new Demo1(this); - result.name_ = name_; - onBuilt(); - return result; - } - - @Override - public Builder clone() { - return (Builder) super.clone(); - } - - @Override - public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { - return (Builder) super.setField(field, value); - } - - @Override - public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { - return (Builder) super.clearField(field); - } - - @Override - public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { - return (Builder) super.clearOneof(oneof); - } - - @Override - public Builder setRepeatedField( - com.google.protobuf.Descriptors.FieldDescriptor field, int index, Object value) { - return (Builder) super.setRepeatedField(field, index, value); - } - - @Override - public Builder addRepeatedField( - com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { - return (Builder) super.addRepeatedField(field, value); - } - - @Override - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof Demo1) { - return mergeFrom((Demo1) other); - } else { - super.mergeFrom(other); - return this; - } - } - - public Builder mergeFrom(Demo1 other) { - if (other == Demo1.getDefaultInstance()) return this; - if (!other.getName().isEmpty()) { - name_ = other.name_; - onChanged(); - } - this.mergeUnknownFields(other.unknownFields); - onChanged(); - return this; - } - - @Override - public final boolean isInitialized() { - return true; - } - - @Override - public Builder mergeFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - Demo1 parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (Demo1) e.getUnfinishedMessage(); - throw e.unwrapIOException(); - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } - - private Object name_ = ""; - /** string name = 1; */ - public String getName() { - Object ref = name_; - if (!(ref instanceof String)) { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - String s = bs.toStringUtf8(); - name_ = s; - return s; - } else { - return (String) ref; - } - } - /** string name = 1; */ - public com.google.protobuf.ByteString getNameBytes() { - Object ref = name_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8((String) ref); - name_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - /** string name = 1; */ - public Builder setName(String value) { - if (value == null) { - throw new NullPointerException(); - } - - name_ = value; - onChanged(); - return this; - } - /** string name = 1; */ - public Builder clearName() { - - name_ = getDefaultInstance().getName(); - onChanged(); - return this; - } - /** string name = 1; */ - public Builder setNameBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); - - name_ = value; - onChanged(); - return this; - } - - @Override - public final Builder setUnknownFields( - final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.setUnknownFieldsProto3(unknownFields); - } - - @Override - public final Builder mergeUnknownFields( - final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.mergeUnknownFields(unknownFields); - } - - // @@protoc_insertion_point(builder_scope:Demo1) - } - - // @@protoc_insertion_point(class_scope:Demo1) - private static final Demo1 DEFAULT_INSTANCE; - - static { - DEFAULT_INSTANCE = new Demo1(); - } - - public static Demo1 getDefaultInstance() { - return DEFAULT_INSTANCE; - } - - private static final com.google.protobuf.Parser PARSER = - new com.google.protobuf.AbstractParser() { - @Override - public Demo1 parsePartialFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new Demo1(input, extensionRegistry); - } - }; - - public static com.google.protobuf.Parser parser() { - return PARSER; - } - - @Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } - - @Override - public Demo1 getDefaultInstanceForType() { - return DEFAULT_INSTANCE; - } - } - - public interface Demo2OrBuilder - extends - // @@protoc_insertion_point(interface_extends:Demo2) - com.google.protobuf.MessageOrBuilder { - - /** repeated .Demo1 demo1 = 1; */ - java.util.List getDemo1List(); - /** repeated .Demo1 demo1 = 1; */ - Demo1 getDemo1(int index); - /** repeated .Demo1 demo1 = 1; */ - int getDemo1Count(); - /** repeated .Demo1 demo1 = 1; */ - java.util.List getDemo1OrBuilderList(); - /** repeated .Demo1 demo1 = 1; */ - Demo1OrBuilder getDemo1OrBuilder(int index); - - /** int32 id = 2; */ - int getId(); - } - /** Protobuf type {@code Demo2} */ - public static final class Demo2 extends com.google.protobuf.GeneratedMessageV3 - implements - // @@protoc_insertion_point(message_implements:Demo2) - Demo2OrBuilder { - private static final long serialVersionUID = 0L; - // Use Demo2.newBuilder() to construct. - private Demo2(com.google.protobuf.GeneratedMessageV3.Builder builder) { - super(builder); - } - - private Demo2() { - demo1_ = java.util.Collections.emptyList(); - id_ = 0; - } - - @Override - public final com.google.protobuf.UnknownFieldSet getUnknownFields() { - return this.unknownFields; - } - - private Demo2( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - this(); - if (extensionRegistry == null) { - throw new NullPointerException(); - } - int mutable_bitField0_ = 0; - com.google.protobuf.UnknownFieldSet.Builder unknownFields = - com.google.protobuf.UnknownFieldSet.newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - case 10: - { - if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) { - demo1_ = new java.util.ArrayList(); - mutable_bitField0_ |= 0x00000001; - } - demo1_.add(input.readMessage(Demo1.parser(), extensionRegistry)); - break; - } - case 16: - { - id_ = input.readInt32(); - break; - } - default: - { - if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { - done = true; - } - break; - } - } - } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); - } finally { - if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) { - demo1_ = java.util.Collections.unmodifiableList(demo1_); - } - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); - } - } - - public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return ProtobufMessageDemo.internal_static_Demo2_descriptor; - } - - @Override - protected FieldAccessorTable internalGetFieldAccessorTable() { - return ProtobufMessageDemo.internal_static_Demo2_fieldAccessorTable - .ensureFieldAccessorsInitialized(Demo2.class, Builder.class); - } - - private int bitField0_; - public static final int DEMO1_FIELD_NUMBER = 1; - private java.util.List demo1_; - /** repeated .Demo1 demo1 = 1; */ - public java.util.List getDemo1List() { - return demo1_; - } - /** repeated .Demo1 demo1 = 1; */ - public java.util.List getDemo1OrBuilderList() { - return demo1_; - } - /** repeated .Demo1 demo1 = 1; */ - public int getDemo1Count() { - return demo1_.size(); - } - /** repeated .Demo1 demo1 = 1; */ - public Demo1 getDemo1(int index) { - return demo1_.get(index); - } - /** repeated .Demo1 demo1 = 1; */ - public Demo1OrBuilder getDemo1OrBuilder(int index) { - return demo1_.get(index); - } - - public static final int ID_FIELD_NUMBER = 2; - private int id_; - /** int32 id = 2; */ - public int getId() { - return id_; - } - - private byte memoizedIsInitialized = -1; - - @Override - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) return true; - if (isInitialized == 0) return false; - - memoizedIsInitialized = 1; - return true; - } - - @Override - public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { - for (int i = 0; i < demo1_.size(); i++) { - output.writeMessage(1, demo1_.get(i)); - } - if (id_ != 0) { - output.writeInt32(2, id_); - } - unknownFields.writeTo(output); - } - - @Override - public int getSerializedSize() { - int size = memoizedSize; - if (size != -1) return size; - - size = 0; - for (int i = 0; i < demo1_.size(); i++) { - size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, demo1_.get(i)); - } - if (id_ != 0) { - size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, id_); - } - size += unknownFields.getSerializedSize(); - memoizedSize = size; - return size; - } - - @Override - public boolean equals(final Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof Demo2)) { - return super.equals(obj); - } - Demo2 other = (Demo2) obj; - - boolean result = true; - result = result && getDemo1List().equals(other.getDemo1List()); - result = result && (getId() == other.getId()); - result = result && unknownFields.equals(other.unknownFields); - return result; - } - - @Override - public int hashCode() { - if (memoizedHashCode != 0) { - return memoizedHashCode; - } - int hash = 41; - hash = (19 * hash) + getDescriptor().hashCode(); - if (getDemo1Count() > 0) { - hash = (37 * hash) + DEMO1_FIELD_NUMBER; - hash = (53 * hash) + getDemo1List().hashCode(); - } - hash = (37 * hash) + ID_FIELD_NUMBER; - hash = (53 * hash) + getId(); - hash = (29 * hash) + unknownFields.hashCode(); - memoizedHashCode = hash; - return hash; - } - - public static Demo2 parseFrom(java.nio.ByteBuffer data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - - public static Demo2 parseFrom( - java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - - public static Demo2 parseFrom(com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - - public static Demo2 parseFrom( - com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - - public static Demo2 parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - - public static Demo2 parseFrom( - byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - - public static Demo2 parseFrom(java.io.InputStream input) throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); - } - - public static Demo2 parseFrom( - java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException( - PARSER, input, extensionRegistry); - } - - public static Demo2 parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); - } - - public static Demo2 parseDelimitedFrom( - java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( - PARSER, input, extensionRegistry); - } - - public static Demo2 parseFrom(com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); - } - - public static Demo2 parseFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException( - PARSER, input, extensionRegistry); - } - - @Override - public Builder newBuilderForType() { - return newBuilder(); - } - - public static Builder newBuilder() { - return DEFAULT_INSTANCE.toBuilder(); - } - - public static Builder newBuilder(Demo2 prototype) { - return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); - } - - @Override - public Builder toBuilder() { - return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); - } - - @Override - protected Builder newBuilderForType(BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; - } - /** Protobuf type {@code Demo2} */ - public static final class Builder - extends com.google.protobuf.GeneratedMessageV3.Builder - implements - // @@protoc_insertion_point(builder_implements:Demo2) - Demo2OrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return ProtobufMessageDemo.internal_static_Demo2_descriptor; - } - - @Override - protected FieldAccessorTable internalGetFieldAccessorTable() { - return ProtobufMessageDemo.internal_static_Demo2_fieldAccessorTable - .ensureFieldAccessorsInitialized(Demo2.class, Builder.class); - } - - // Construct using top.limitart.net.ProtobufMessageDemo.Demo2.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder(BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { - getDemo1FieldBuilder(); - } - } - - @Override - public Builder clear() { - super.clear(); - if (demo1Builder_ == null) { - demo1_ = java.util.Collections.emptyList(); - bitField0_ = (bitField0_ & ~0x00000001); - } else { - demo1Builder_.clear(); - } - id_ = 0; - - return this; - } - - @Override - public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { - return ProtobufMessageDemo.internal_static_Demo2_descriptor; - } - - @Override - public Demo2 getDefaultInstanceForType() { - return Demo2.getDefaultInstance(); - } - - @Override - public Demo2 build() { - Demo2 result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); - } - return result; - } - - @Override - public Demo2 buildPartial() { - Demo2 result = new Demo2(this); - int from_bitField0_ = bitField0_; - int to_bitField0_ = 0; - if (demo1Builder_ == null) { - if (((bitField0_ & 0x00000001) == 0x00000001)) { - demo1_ = java.util.Collections.unmodifiableList(demo1_); - bitField0_ = (bitField0_ & ~0x00000001); - } - result.demo1_ = demo1_; - } else { - result.demo1_ = demo1Builder_.build(); - } - result.id_ = id_; - result.bitField0_ = to_bitField0_; - onBuilt(); - return result; - } - - @Override - public Builder clone() { - return (Builder) super.clone(); - } - - @Override - public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { - return (Builder) super.setField(field, value); - } - - @Override - public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { - return (Builder) super.clearField(field); - } - - @Override - public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { - return (Builder) super.clearOneof(oneof); - } - - @Override - public Builder setRepeatedField( - com.google.protobuf.Descriptors.FieldDescriptor field, int index, Object value) { - return (Builder) super.setRepeatedField(field, index, value); - } - - @Override - public Builder addRepeatedField( - com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { - return (Builder) super.addRepeatedField(field, value); - } - - @Override - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof Demo2) { - return mergeFrom((Demo2) other); - } else { - super.mergeFrom(other); - return this; - } - } - - public Builder mergeFrom(Demo2 other) { - if (other == Demo2.getDefaultInstance()) return this; - if (demo1Builder_ == null) { - if (!other.demo1_.isEmpty()) { - if (demo1_.isEmpty()) { - demo1_ = other.demo1_; - bitField0_ = (bitField0_ & ~0x00000001); - } else { - ensureDemo1IsMutable(); - demo1_.addAll(other.demo1_); - } - onChanged(); - } - } else { - if (!other.demo1_.isEmpty()) { - if (demo1Builder_.isEmpty()) { - demo1Builder_.dispose(); - demo1Builder_ = null; - demo1_ = other.demo1_; - bitField0_ = (bitField0_ & ~0x00000001); - demo1Builder_ = - com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders - ? getDemo1FieldBuilder() - : null; - } else { - demo1Builder_.addAllMessages(other.demo1_); - } - } - } - if (other.getId() != 0) { - setId(other.getId()); - } - this.mergeUnknownFields(other.unknownFields); - onChanged(); - return this; - } - - @Override - public final boolean isInitialized() { - return true; - } - - @Override - public Builder mergeFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - Demo2 parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (Demo2) e.getUnfinishedMessage(); - throw e.unwrapIOException(); - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } - - private int bitField0_; - - private java.util.List demo1_ = java.util.Collections.emptyList(); - - private void ensureDemo1IsMutable() { - if (!((bitField0_ & 0x00000001) == 0x00000001)) { - demo1_ = new java.util.ArrayList(demo1_); - bitField0_ |= 0x00000001; - } - } - - private com.google.protobuf.RepeatedFieldBuilderV3 - demo1Builder_; - - /** repeated .Demo1 demo1 = 1; */ - public java.util.List getDemo1List() { - if (demo1Builder_ == null) { - return java.util.Collections.unmodifiableList(demo1_); - } else { - return demo1Builder_.getMessageList(); - } - } - /** repeated .Demo1 demo1 = 1; */ - public int getDemo1Count() { - if (demo1Builder_ == null) { - return demo1_.size(); - } else { - return demo1Builder_.getCount(); - } - } - /** repeated .Demo1 demo1 = 1; */ - public Demo1 getDemo1(int index) { - if (demo1Builder_ == null) { - return demo1_.get(index); - } else { - return demo1Builder_.getMessage(index); - } - } - /** repeated .Demo1 demo1 = 1; */ - public Builder setDemo1(int index, Demo1 value) { - if (demo1Builder_ == null) { - if (value == null) { - throw new NullPointerException(); - } - ensureDemo1IsMutable(); - demo1_.set(index, value); - onChanged(); - } else { - demo1Builder_.setMessage(index, value); - } - return this; - } - /** repeated .Demo1 demo1 = 1; */ - public Builder setDemo1(int index, Demo1.Builder builderForValue) { - if (demo1Builder_ == null) { - ensureDemo1IsMutable(); - demo1_.set(index, builderForValue.build()); - onChanged(); - } else { - demo1Builder_.setMessage(index, builderForValue.build()); - } - return this; - } - /** repeated .Demo1 demo1 = 1; */ - public Builder addDemo1(Demo1 value) { - if (demo1Builder_ == null) { - if (value == null) { - throw new NullPointerException(); - } - ensureDemo1IsMutable(); - demo1_.add(value); - onChanged(); - } else { - demo1Builder_.addMessage(value); - } - return this; - } - /** repeated .Demo1 demo1 = 1; */ - public Builder addDemo1(int index, Demo1 value) { - if (demo1Builder_ == null) { - if (value == null) { - throw new NullPointerException(); - } - ensureDemo1IsMutable(); - demo1_.add(index, value); - onChanged(); - } else { - demo1Builder_.addMessage(index, value); - } - return this; - } - /** repeated .Demo1 demo1 = 1; */ - public Builder addDemo1(Demo1.Builder builderForValue) { - if (demo1Builder_ == null) { - ensureDemo1IsMutable(); - demo1_.add(builderForValue.build()); - onChanged(); - } else { - demo1Builder_.addMessage(builderForValue.build()); - } - return this; - } - /** repeated .Demo1 demo1 = 1; */ - public Builder addDemo1(int index, Demo1.Builder builderForValue) { - if (demo1Builder_ == null) { - ensureDemo1IsMutable(); - demo1_.add(index, builderForValue.build()); - onChanged(); - } else { - demo1Builder_.addMessage(index, builderForValue.build()); - } - return this; - } - /** repeated .Demo1 demo1 = 1; */ - public Builder addAllDemo1(Iterable values) { - if (demo1Builder_ == null) { - ensureDemo1IsMutable(); - com.google.protobuf.AbstractMessageLite.Builder.addAll(values, demo1_); - onChanged(); - } else { - demo1Builder_.addAllMessages(values); - } - return this; - } - /** repeated .Demo1 demo1 = 1; */ - public Builder clearDemo1() { - if (demo1Builder_ == null) { - demo1_ = java.util.Collections.emptyList(); - bitField0_ = (bitField0_ & ~0x00000001); - onChanged(); - } else { - demo1Builder_.clear(); - } - return this; - } - /** repeated .Demo1 demo1 = 1; */ - public Builder removeDemo1(int index) { - if (demo1Builder_ == null) { - ensureDemo1IsMutable(); - demo1_.remove(index); - onChanged(); - } else { - demo1Builder_.remove(index); - } - return this; - } - /** repeated .Demo1 demo1 = 1; */ - public Demo1.Builder getDemo1Builder(int index) { - return getDemo1FieldBuilder().getBuilder(index); - } - /** repeated .Demo1 demo1 = 1; */ - public Demo1OrBuilder getDemo1OrBuilder(int index) { - if (demo1Builder_ == null) { - return demo1_.get(index); - } else { - return demo1Builder_.getMessageOrBuilder(index); - } - } - /** repeated .Demo1 demo1 = 1; */ - public java.util.List getDemo1OrBuilderList() { - if (demo1Builder_ != null) { - return demo1Builder_.getMessageOrBuilderList(); - } else { - return java.util.Collections.unmodifiableList(demo1_); - } - } - /** repeated .Demo1 demo1 = 1; */ - public Demo1.Builder addDemo1Builder() { - return getDemo1FieldBuilder().addBuilder(Demo1.getDefaultInstance()); - } - /** repeated .Demo1 demo1 = 1; */ - public Demo1.Builder addDemo1Builder(int index) { - return getDemo1FieldBuilder().addBuilder(index, Demo1.getDefaultInstance()); - } - /** repeated .Demo1 demo1 = 1; */ - public java.util.List getDemo1BuilderList() { - return getDemo1FieldBuilder().getBuilderList(); - } - - private com.google.protobuf.RepeatedFieldBuilderV3 - getDemo1FieldBuilder() { - if (demo1Builder_ == null) { - demo1Builder_ = - new com.google.protobuf.RepeatedFieldBuilderV3( - demo1_, - ((bitField0_ & 0x00000001) == 0x00000001), - getParentForChildren(), - isClean()); - demo1_ = null; - } - return demo1Builder_; - } - - private int id_; - /** int32 id = 2; */ - public int getId() { - return id_; - } - /** int32 id = 2; */ - public Builder setId(int value) { - - id_ = value; - onChanged(); - return this; - } - /** int32 id = 2; */ - public Builder clearId() { - - id_ = 0; - onChanged(); - return this; - } - - @Override - public final Builder setUnknownFields( - final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.setUnknownFieldsProto3(unknownFields); - } - - @Override - public final Builder mergeUnknownFields( - final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.mergeUnknownFields(unknownFields); - } - - // @@protoc_insertion_point(builder_scope:Demo2) - } - - // @@protoc_insertion_point(class_scope:Demo2) - private static final Demo2 DEFAULT_INSTANCE; - - static { - DEFAULT_INSTANCE = new Demo2(); - } - - public static Demo2 getDefaultInstance() { - return DEFAULT_INSTANCE; - } - - private static final com.google.protobuf.Parser PARSER = - new com.google.protobuf.AbstractParser() { - @Override - public Demo2 parsePartialFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new Demo2(input, extensionRegistry); - } - }; - - public static com.google.protobuf.Parser parser() { - return PARSER; - } - - @Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } - - @Override - public Demo2 getDefaultInstanceForType() { - return DEFAULT_INSTANCE; - } - } - - private static final com.google.protobuf.Descriptors.Descriptor internal_static_Demo1_descriptor; - private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable - internal_static_Demo1_fieldAccessorTable; - private static final com.google.protobuf.Descriptors.Descriptor internal_static_Demo2_descriptor; - private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable - internal_static_Demo2_fieldAccessorTable; - - public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { - return descriptor; - } - - private static com.google.protobuf.Descriptors.FileDescriptor descriptor; - - static { - String[] descriptorData = { - "\n\017protobuf3.proto\"\025\n\005Demo1\022\014\n\004name\030\001 \001(\t" - + "\"*\n\005Demo2\022\025\n\005demo1\030\001 \003(\0132\006.Demo1\022\n\n\002id\030\002" - + " \001(\005B\'\n\020top.limitart.netB\023ProtobufMessag" - + "eDemob\006proto3" - }; - com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = - new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { - public com.google.protobuf.ExtensionRegistry assignDescriptors( - com.google.protobuf.Descriptors.FileDescriptor root) { - descriptor = root; - return null; - } - }; - com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom( - descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] {}, assigner); - internal_static_Demo1_descriptor = getDescriptor().getMessageTypes().get(0); - internal_static_Demo1_fieldAccessorTable = - new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_Demo1_descriptor, - new String[] { - "Name", - }); - internal_static_Demo2_descriptor = getDescriptor().getMessageTypes().get(1); - internal_static_Demo2_fieldAccessorTable = - new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_Demo2_descriptor, - new String[] { - "Demo1", "Id", - }); - } - - // @@protoc_insertion_point(outer_class_scope) -} diff --git a/demo/src/main/java/top/limitart/demo/demo/net/ProtobufServerDemo.java b/demo/src/main/java/top/limitart/demo/demo/net/ProtobufServerDemo.java deleted file mode 100644 index bb9a52d..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/net/ProtobufServerDemo.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 2016-present The Limitart Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package top.limitart.demo.net; - -import com.google.protobuf.Message; -import top.limitart.demo.mapping.Router; -import top.limitart.demo.net.protobuf.ProtobufEndPoint; -import top.limitart.demo.net.protobuf.ProtobufRequestParam; - -/** @author hank */ -public class ProtobufServerDemo { - static final ProtobufSessionRole role = new ProtobufSessionRole(); - - public static void main(String[] args) throws Exception { - ProtobufEndPoint.builder(true) - .router( - Router.empty(Message.class, ProtobufRequestParam.class) - .registerMapperClass(MessageMapper.class)) - .onConnected( - (s, b) -> { - if (b) { - role.joinWhenFree( - s, - () -> System.out.println("join session success!"),e->{}); - } else { - role.leave(s); - System.out.println("leave session success"); - } - }) - .build() - .start(AddressPair.withPort(7878)); - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/net/ProtobufSessionRole.java b/demo/src/main/java/top/limitart/demo/demo/net/ProtobufSessionRole.java deleted file mode 100644 index 2140594..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/net/ProtobufSessionRole.java +++ /dev/null @@ -1,6 +0,0 @@ -package top.limitart.demo.net; - - -import com.google.protobuf.Message; - -public class ProtobufSessionRole extends NettySessionActor {} diff --git a/demo/src/main/java/top/limitart/demo/demo/net/WebSocketServerDemo.java b/demo/src/main/java/top/limitart/demo/demo/net/WebSocketServerDemo.java deleted file mode 100644 index 5ddf1d9..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/net/WebSocketServerDemo.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * - * * Copyright (c) 2016-present The Limitart Project - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * - */ - -package top.limitart.demo.net; - -import io.netty.channel.EventLoop; -import io.netty.handler.codec.http.websocketx.WebSocketFrame; -import top.limitart.demo.net.http.HTTPRequest; -import top.limitart.demo.net.http.HTTPSession; -import top.limitart.demo.net.websocket.WebSocketEndPoint; - -/** Created by Hank on 2019/2/24 */ -public class WebSocketServerDemo { - public static void main(String[] args) throws Exception { - new WebSocketEndPoint("web-socket-server", "/",NettyEndPointType.SERVER_REMOTE, 0, 0) { - @Override - protected void exceptionThrown(NettySession session, Throwable cause) - throws Exception {} - - @Override - protected void sessionActive(NettySession session, boolean activeOrNot) - throws Exception {} - - @Override - protected void onWebSocketFrameReceived( - Session session, WebSocketFrame msg) { - - } - - @Override - protected void onHttpRequestReceived(HTTPSession session, HTTPRequest msg) { - System.out.println(msg); - } - }.start(AddressPair.withPort(8888)); - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/redefinable/HelloRedefine.java b/demo/src/main/java/top/limitart/demo/demo/redefinable/HelloRedefine.java deleted file mode 100644 index c4677b4..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/redefinable/HelloRedefine.java +++ /dev/null @@ -1,7 +0,0 @@ -package top.limitart.demo.redefinable; - -public class HelloRedefine { - public void hello(){ - System.out.println("hello"); - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/redefinable/RedefinableDemo.java b/demo/src/main/java/top/limitart/demo/demo/redefinable/RedefinableDemo.java deleted file mode 100644 index 19b651a..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/redefinable/RedefinableDemo.java +++ /dev/null @@ -1,10 +0,0 @@ -package top.limitart.demo.redefinable; - -import java.io.File; - -public class RedefinableDemo { - public static void main(String[] args) throws Exception { - RedefinableApplication demo = new RedefinableApplication(new File("e://script.jar").toURI(),"top.limitart.redefinable.ScriptEntrance"); - demo.run(args); - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/redefinable/ScriptEntrance.java b/demo/src/main/java/top/limitart/demo/demo/redefinable/ScriptEntrance.java deleted file mode 100644 index 6f37cec..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/redefinable/ScriptEntrance.java +++ /dev/null @@ -1,21 +0,0 @@ -package top.limitart.demo.redefinable; - -public class ScriptEntrance extends RedefinableModule { - private HelloRedefine helloRedefine = new HelloRedefine(); - @Override - public void onStart(RedefinableApplicationContext context) { - System.out.println("onStart"); - helloRedefine.hello(); - } - - @Override - public void onRedefined(RedefinableApplicationContext context) { - System.out.println("onRedefined"); - helloRedefine.hello(); - } - - @Override - public void onDestroy(RedefinableApplicationContext context) { - System.out.println("onDestroy"); - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/script/AutoReloadScriptDemo.java b/demo/src/main/java/top/limitart/demo/demo/script/AutoReloadScriptDemo.java deleted file mode 100644 index b1ba048..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/script/AutoReloadScriptDemo.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2016-present The Limitart Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package top.limitart.demo.script; - -import java.io.IOException; - -/** @author hank */ -public class AutoReloadScriptDemo { - public static void main(String[] args) - throws InstantiationException, IllegalAccessException, IOException, ScriptConstructException, - ScriptNotExistException, ScriptKeyDuplicatedException, InterruptedException { - FileScriptLoader loader = new FileScriptLoader<>("./demo/script", 5); - while (true) { - Thread.sleep(1000); - HelloScript script = loader.getScript(1); - script.sayHello(); - } - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/script/HelloScript.java b/demo/src/main/java/top/limitart/demo/demo/script/HelloScript.java deleted file mode 100644 index 6969197..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/script/HelloScript.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2016-present The Limitart Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package top.limitart.demo.script; - -/** - * 脚本引用测试 - * - * @author hank - */ -public interface HelloScript extends Script { - void sayHello(); -} diff --git a/demo/src/main/java/top/limitart/demo/demo/script/ScriptSourceDemo.java b/demo/src/main/java/top/limitart/demo/demo/script/ScriptSourceDemo.java deleted file mode 100644 index fdc07b0..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/script/ScriptSourceDemo.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2016-present The Limitart Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package top.limitart.demo.script; - -/** - * 脚本编译测试 - * - * @author hank - */ -public class ScriptSourceDemo implements Runnable { - - private class ScriptSourceInnerPrivate { - public void say() { - System.out.println("hello inner"); - } - } - - @Override - public void run() { - System.out.println("hello limitart"); - ((Runnable) () -> System.out.println("inner")).run(); - ScriptSourceInnerPrivate temp = new ScriptSourceInnerPrivate(); - temp.say(); - } - - public class ScriptSourceDemoInnerPublic {} -} - -class ScriptSourceDemoPrivate {} diff --git a/demo/src/main/java/top/limitart/demo/demo/singleton/SingletonA.java b/demo/src/main/java/top/limitart/demo/demo/singleton/SingletonA.java deleted file mode 100644 index cfe150f..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/singleton/SingletonA.java +++ /dev/null @@ -1,10 +0,0 @@ -package top.limitart.demo.singleton; - -@Singleton -public class SingletonA { - @Ref SingletonB singletonB; - - public void say() { - System.out.println(singletonB); - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/singleton/SingletonB.java b/demo/src/main/java/top/limitart/demo/demo/singleton/SingletonB.java deleted file mode 100644 index d144bc2..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/singleton/SingletonB.java +++ /dev/null @@ -1,14 +0,0 @@ -package top.limitart.demo.singleton; - -@Singleton -public class SingletonB { - @Ref SingletonA singletonA; - @Ref SingletonC singletonC; - @Ref SingletonD singletonD; - - public void say() { - System.out.println(singletonA); - System.out.println(singletonC); - System.out.println(singletonD); - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/singleton/SingletonC.java b/demo/src/main/java/top/limitart/demo/demo/singleton/SingletonC.java deleted file mode 100644 index 1887203..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/singleton/SingletonC.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * - * * Copyright (c) 2016-present The Limitart Project - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * - */ - -package top.limitart.demo.singleton; - -/** Created by Hank on 2018/12/11 */ -@Singleton -public class SingletonC { - @Ref SingletonC singletonC; - - @Ref - public SingletonC(SingletonA singletonA, SingletonB singletonB) { - System.out.println("construct C"); - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/singleton/SingletonD.java b/demo/src/main/java/top/limitart/demo/demo/singleton/SingletonD.java deleted file mode 100644 index 583294c..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/singleton/SingletonD.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * - * * Copyright (c) 2016-present The Limitart Project - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * - */ - -package top.limitart.demo.singleton; - -/** Created by Hank on 2018/12/11 */ -@Singleton -public class SingletonD { - @Ref - public SingletonD(SingletonC singletonC) { - System.out.println("construct D"); - } - - @Ref - public void setSingletonA(SingletonA singletonA) { - System.out.println(singletonA); - } -} diff --git a/demo/src/main/java/top/limitart/demo/demo/singleton/SingletonDemo.java b/demo/src/main/java/top/limitart/demo/demo/singleton/SingletonDemo.java deleted file mode 100644 index 9f0e25e..0000000 --- a/demo/src/main/java/top/limitart/demo/demo/singleton/SingletonDemo.java +++ /dev/null @@ -1,21 +0,0 @@ -package top.limitart.demo.singleton; - -public class SingletonDemo { - @Ref SingletonB singletonB; - @Ref SingletonA singletonA; - @Ref SingletonC singletonC; - - public void say() { - singletonB.say(); - singletonA.say(); - } - - public static void main(String[] args) { - new Singletons.Builder() - .withPackage("top.limitart", SingletonDemo.class.getClassLoader()) - .bind(SingletonDemo.class) - .build() - .instance(SingletonDemo.class) - .say(); - } -} -- Gitee From 1c1e786982b7e043283c16a08489bb45dadece4a Mon Sep 17 00:00:00 2001 From: hank <104381832> Date: Mon, 3 Feb 2020 21:57:48 +0800 Subject: [PATCH 11/11] 1 --- demo/pom.xml | 15 +++++++++++++ .../java/top/limitart/demo/rpc/HelloRpc.java | 9 ++++++++ .../top/limitart/demo/rpc/HelloRpcImpl.java | 9 ++++++++ .../demo/rpc/RPCServiceCenterDemo.java | 11 ++++++++++ .../demo/rpc/RPCServiceConsumerDemo.java | 22 +++++++++++++++++++ .../demo/rpc/RPCServiceProviderDemo.java | 12 ++++++++++ .../provider/MQProviderBinaryClient.java | 19 ++++++++++++---- pipeline-token.tmp | 2 +- .../rpc/srvconsumer/RPCServiceConsumer.java | 2 +- .../rpc/srvprovider/RPCServiceProvider.java | 2 +- 10 files changed, 96 insertions(+), 7 deletions(-) create mode 100644 demo/src/main/java/top/limitart/demo/rpc/HelloRpc.java create mode 100644 demo/src/main/java/top/limitart/demo/rpc/HelloRpcImpl.java create mode 100644 demo/src/main/java/top/limitart/demo/rpc/RPCServiceCenterDemo.java create mode 100644 demo/src/main/java/top/limitart/demo/rpc/RPCServiceConsumerDemo.java create mode 100644 demo/src/main/java/top/limitart/demo/rpc/RPCServiceProviderDemo.java diff --git a/demo/pom.xml b/demo/pom.xml index be93c80..78dd4f5 100644 --- a/demo/pom.xml +++ b/demo/pom.xml @@ -53,6 +53,21 @@ limitart-fastmq-provider ${project.version} + + ${project.groupId} + limitart-rpc-service-center + ${project.version} + + + ${project.groupId} + limitart-rpc-service-provider + ${project.version} + + + ${project.groupId} + limitart-rpc-service-consumer + ${project.version} + org.apache.logging.log4j diff --git a/demo/src/main/java/top/limitart/demo/rpc/HelloRpc.java b/demo/src/main/java/top/limitart/demo/rpc/HelloRpc.java new file mode 100644 index 0000000..bcc2119 --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/rpc/HelloRpc.java @@ -0,0 +1,9 @@ +package top.limitart.demo.rpc; + +import top.limitart.rpc.srvcommon.RPCService; + +@RPCService(provider = "limitart") +public interface HelloRpc { + + int plus(int a, int b) throws Exception; +} diff --git a/demo/src/main/java/top/limitart/demo/rpc/HelloRpcImpl.java b/demo/src/main/java/top/limitart/demo/rpc/HelloRpcImpl.java new file mode 100644 index 0000000..8596d2d --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/rpc/HelloRpcImpl.java @@ -0,0 +1,9 @@ +package top.limitart.demo.rpc; + +public class HelloRpcImpl implements HelloRpc { + + @Override + public int plus(int a, int b) { + return a + b; + } +} diff --git a/demo/src/main/java/top/limitart/demo/rpc/RPCServiceCenterDemo.java b/demo/src/main/java/top/limitart/demo/rpc/RPCServiceCenterDemo.java new file mode 100644 index 0000000..babb37f --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/rpc/RPCServiceCenterDemo.java @@ -0,0 +1,11 @@ +package top.limitart.demo.rpc; + +import top.limitart.rpc.RPCServiceCenter; + +public class RPCServiceCenterDemo { + + public static void main(String[] args) throws Exception { + RPCServiceCenter center = new RPCServiceCenter(9999); + center.run(args); + } +} diff --git a/demo/src/main/java/top/limitart/demo/rpc/RPCServiceConsumerDemo.java b/demo/src/main/java/top/limitart/demo/rpc/RPCServiceConsumerDemo.java new file mode 100644 index 0000000..d82e677 --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/rpc/RPCServiceConsumerDemo.java @@ -0,0 +1,22 @@ +package top.limitart.demo.rpc; + +import top.limitart.rpc.srvconsumer.RPCServiceConsumer; + +public class RPCServiceConsumerDemo { + + public static void main(String[] args) throws Exception { + RPCServiceConsumer consumer = new RPCServiceConsumer("test_consumer", "127.0.0.1", 9999, + "top.limitart.demo.rpc"); + consumer.run(args); + HelloRpc proxy = consumer.createProxy(HelloRpc.class); + int count = 0; + while (true) { + try{ + int plus = proxy.plus(++count, 1); + System.out.println("rpc result:" + plus); + }catch (Exception e){ + e.printStackTrace(); + } + } + } +} diff --git a/demo/src/main/java/top/limitart/demo/rpc/RPCServiceProviderDemo.java b/demo/src/main/java/top/limitart/demo/rpc/RPCServiceProviderDemo.java new file mode 100644 index 0000000..9e75ae0 --- /dev/null +++ b/demo/src/main/java/top/limitart/demo/rpc/RPCServiceProviderDemo.java @@ -0,0 +1,12 @@ +package top.limitart.demo.rpc; + +import top.limitart.rpc.srvprovider.RPCServiceProvider; + +public class RPCServiceProviderDemo { + + public static void main(String[] args) throws Exception { + RPCServiceProvider provider = new RPCServiceProvider("test_provider", "127.0.0.1", 9999, + new String[]{"top.limitart.demo.rpc"}, new String[]{"top.limitart.demo.rpc"}); + provider.run(args); + } +} diff --git a/fastmq/provider/src/main/java/top/limitart/fastmq/provider/MQProviderBinaryClient.java b/fastmq/provider/src/main/java/top/limitart/fastmq/provider/MQProviderBinaryClient.java index c68e30a..a6bc224 100644 --- a/fastmq/provider/src/main/java/top/limitart/fastmq/provider/MQProviderBinaryClient.java +++ b/fastmq/provider/src/main/java/top/limitart/fastmq/provider/MQProviderBinaryClient.java @@ -1,7 +1,10 @@ package top.limitart.fastmq.provider; import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import top.limitart.base.ApplicationBootstrap; +import top.limitart.base.BinaryMeta; import top.limitart.base.Conditions; import top.limitart.fastmq.common.binary.BinaryRequest; import top.limitart.fastmq.common.binary.ReqBroadcastMsgToPipelineMsg; @@ -10,6 +13,7 @@ import top.limitart.fastmq.common.binary.ReqHeartBeatMsg; import top.limitart.fastmq.common.binary.ReqPushMsgToPipelineMsg; import top.limitart.fastmq.common.binary.ReqPushMsgToPipelineWithTagsMsg; import top.limitart.fastmq.common.binary.ResHeartBeatMsg; +import top.limitart.fastmq.common.binary.ResPushMsgResultMsg; import top.limitart.mapping.Mapper; import top.limitart.mapping.Request; import top.limitart.mapping.Router; @@ -21,6 +25,7 @@ import top.limitart.net.binary.BinaryMessage; public class MQProviderBinaryClient extends ApplicationBootstrap { + private static final Logger LOGGER = LoggerFactory.getLogger(MQProviderBinaryClient.class); private BinaryEndPoint client; private AddressPair remoteAddress; private ProviderBinaryHandler providerBinaryHandler; @@ -41,7 +46,7 @@ public class MQProviderBinaryClient extends ApplicationBootstrap { } public void sendMsgWithTags(List tags, byte[] bytes) { - if(this.session == null || !this.session.writable()){ + if (this.session == null || !this.session.writable()) { //todo return; } @@ -52,7 +57,7 @@ public class MQProviderBinaryClient extends ApplicationBootstrap { } public void sendMsg(String zone, byte[] bytes) { - if(this.session == null || !this.session.writable()){ + if (this.session == null || !this.session.writable()) { //todo return; } @@ -63,7 +68,7 @@ public class MQProviderBinaryClient extends ApplicationBootstrap { } public void broadcastMsgWithTags(List tags, byte[] bytes) { - if(this.session == null || !this.session.writable()){ + if (this.session == null || !this.session.writable()) { //todo return; } @@ -74,7 +79,7 @@ public class MQProviderBinaryClient extends ApplicationBootstrap { } public void broadcastMsg(byte[] bytes) { - if(this.session == null || !this.session.writable()){ + if (this.session == null || !this.session.writable()) { //todo return; } @@ -108,5 +113,11 @@ public class MQProviderBinaryClient extends ApplicationBootstrap { public void onHeartBeat(@Request ReqHeartBeatMsg msg, BinaryRequest request) { request.session().writeNow(ResHeartBeatMsg.INSTANCE); } + + public void onPushMsgResult(@Request ResPushMsgResultMsg msg, BinaryRequest request) { + if (msg.getCode() != ResPushMsgResultMsg.SUCCESS.getCode()) { + MQProviderBinaryClient.LOGGER.error("push msg error {}", msg.getCode()); + } + } } } diff --git a/pipeline-token.tmp b/pipeline-token.tmp index 7c1f7b1..b98b9ea 100644 --- a/pipeline-token.tmp +++ b/pipeline-token.tmp @@ -1 +1 @@ -68785719AFEF4B4CB46093088F03DFBD \ No newline at end of file +E8FC3DBBBED24D6EB5675DBA3E1C0F48 \ No newline at end of file diff --git a/rpc/service-consumer/src/main/java/top/limitart/rpc/srvconsumer/RPCServiceConsumer.java b/rpc/service-consumer/src/main/java/top/limitart/rpc/srvconsumer/RPCServiceConsumer.java index 341e191..1ef8c6a 100644 --- a/rpc/service-consumer/src/main/java/top/limitart/rpc/srvconsumer/RPCServiceConsumer.java +++ b/rpc/service-consumer/src/main/java/top/limitart/rpc/srvconsumer/RPCServiceConsumer.java @@ -212,7 +212,7 @@ public class RPCServiceConsumer extends ApplicationBootstrap implements Consumer if (future.getResponseResult() == null) { // 无条件线程等待 boolean await = future.getCountDownLatch() - .await(EXECUTE_TIMEOUT, TimeUnit.MILLISECONDS); + .await(EXECUTE_TIMEOUT, TimeUnit.SECONDS); futures.remove(future.getRequestId()); if (!await) { throw new RPCServiceExecuteException( diff --git a/rpc/service-provider/src/main/java/top/limitart/rpc/srvprovider/RPCServiceProvider.java b/rpc/service-provider/src/main/java/top/limitart/rpc/srvprovider/RPCServiceProvider.java index abd0ead..c6dbfe2 100644 --- a/rpc/service-provider/src/main/java/top/limitart/rpc/srvprovider/RPCServiceProvider.java +++ b/rpc/service-provider/src/main/java/top/limitart/rpc/srvprovider/RPCServiceProvider.java @@ -150,7 +150,7 @@ public class RPCServiceProvider extends ApplicationBootstrap implements Consumer // 查找RPC接口的实现类 List> implsByPackage = new ArrayList<>(); for (String temp : implPackages) { - LOGGER.info("开始在包:" + temp + "下查找接口..."); + LOGGER.info("开始在包:" + temp + "下查找接口实现..."); implsByPackage.addAll(ReflectionUtil.getClassesBySuperClass(temp, Object.class)); } for (Class clazz : implsByPackage) { -- Gitee