From 367c6a16d3c9bfcbf1c7475c39483e50bd435b5f Mon Sep 17 00:00:00 2001 From: Wenjun Ruan Date: Sun, 21 Nov 2021 23:45:36 +0800 Subject: [PATCH] Add protocol producer in java sdk (#600) * Add protocol producer in sdk * Refactor callback handler * Add tcp protocol client --- docs/cn/features/https.md | 6 +- docs/en/features/https.md | 6 +- eventmesh-common/build.gradle | 27 +- .../eventmesh/common/EventMeshMessage.java | 70 +++++ .../apache/eventmesh/common/LiteMessage.java | 131 -------- .../eventmesh/common/ThreadPoolFactory.java | 30 +- .../common/config/CommonConfiguration.java | 4 +- .../{ => exception}/EventMeshException.java | 8 +- .../WeightRandomLoadBalanceSelector.java | 2 +- .../ProtocolTransportObject.java | 6 +- .../http}/HttpCommand.java | 33 +- .../body/message/SendMessageResponseBody.java | 35 +-- .../common/protocol/tcp/Package.java | 2 +- .../common/protocol/tcp/UserAgent.java | 180 +---------- .../{IPUtil.java => utils/IPUtils.java} | 4 +- .../RandomStringUtils.java} | 10 +- .../ThreadUtils.java} | 26 +- ...ageTest.java => EventMeshMessageTest.java} | 36 +-- .../http}/HttpCommandTest.java | 25 +- .../IPUtilsTest.java} | 8 +- .../ThreadUtilsTest.java} | 8 +- .../eventmesh-connector-api/build.gradle | 7 - .../producer/RocketMQProducerImpl.java | 6 + .../consumer/PushConsumerImplTest.java | 10 +- .../build.gradle | 2 - .../standalone/broker/task/SubScribeTask.java | 7 +- eventmesh-examples/build.gradle | 71 +---- .../http/demo/AsyncPublishInstance.java | 87 +++-- .../http/demo/AsyncSyncRequestInstance.java | 82 ++--- .../http/demo/SyncRequestInstance.java | 39 +-- .../http/demo/sub/service/SubService.java | 90 +++--- .../eventmesh/tcp/demo/AsyncPublish.java | 8 +- .../tcp/demo/AsyncPublishBroadcast.java | 8 +- .../eventmesh/tcp/demo/AsyncSubscribe.java | 36 +-- .../tcp/demo/AsyncSubscribeBroadcast.java | 36 +-- .../eventmesh/tcp/demo/SyncRequest.java | 9 +- .../eventmesh/tcp/demo/SyncResponse.java | 30 +- .../java/org/apache/eventmesh/util/Utils.java | 21 +- .../protocol/api/ProtocolAdaptor.java | 4 +- .../protocol/api/ProtocolPluginFactory.java | 2 +- .../CloudEventsProtocolAdaptor.java | 5 +- .../CloudEventsProtocolAdaptorTest.java | 3 +- .../MeshMessageProtocolAdaptor.java | 18 +- .../OpenMessageProtocolAdaptor.java | 4 +- .../OpenMessageProtocolAdaptorTest.java | 3 +- eventmesh-runtime/build.gradle | 14 - .../runtime/boot/AbstractHTTPServer.java | 11 +- .../runtime/boot/AbstractRemotingServer.java | 4 +- .../runtime/boot/EventMeshTCPServer.java | 6 +- .../http/processor/AdminMetricsProcessor.java | 2 +- .../processor/AdminShutdownProcessor.java | 6 +- .../processor/BatchSendMessageProcessor.java | 12 +- .../BatchSendMessageV2Processor.java | 10 +- .../http/processor/HeartBeatProcessor.java | 8 +- .../http/processor/ReplyMessageProcessor.java | 14 +- .../processor/SendAsyncMessageProcessor.java | 15 +- .../processor/SendSyncMessageProcessor.java | 12 +- .../http/processor/SubscribeProcessor.java | 8 +- .../http/processor/UnSubscribeProcessor.java | 8 +- .../processor/inf/HttpRequestProcessor.java | 2 +- .../http/push/AsyncHTTPPushRequest.java | 14 +- .../group/ClientSessionGroupMapping.java | 7 +- .../tcp/client/task/MessageTransferTask.java | 4 +- .../eventmesh/runtime/util/EventMeshUtil.java | 10 +- .../runtime/demo/AsyncPubClient.java | 4 +- .../runtime/demo/BroadCastPubClient.java | 4 +- eventmesh-sdk-java/build.gradle | 13 +- .../client/http/AbstractHttpClient.java | 97 ++++++ .../client/http/AbstractLiteClient.java | 75 ----- .../http/conf/EventMeshHttpClientConfig.java | 74 +++++ .../client/http/conf/LiteClientConfig.java | 207 ------------ .../http/consumer/EventMeshHttpConsumer.java | 199 ++++++++++++ .../client/http/consumer/LiteConsumer.java | 297 ------------------ .../listener/LiteMessageListener.java | 4 +- .../http/{http => model}/RequestParam.java | 17 +- .../http/producer/CloudEventProducer.java | 114 +++++++ .../http/producer/EventMeshHttpProducer.java | 89 ++++++ .../producer/EventMeshMessageProducer.java | 128 ++++++++ .../producer/EventMeshProtocolProducer.java | 22 ++ .../client/http/producer/LiteProducer.java | 245 --------------- .../http/producer/OpenMessageProducer.java | 111 +++++++ .../client/http/producer/RRCallback.java | 15 +- .../RRCallbackResponseHandlerAdapter.java | 79 ++--- .../http/util/HttpLoadBalanceUtils.java | 32 +- .../HttpUtil.java => util/HttpUtils.java} | 87 ++--- ...eshClient.java => EventMeshTCPClient.java} | 44 +-- ...Client.java => EventMeshTCPPubClient.java} | 32 +- ...Client.java => EventMeshTCPSubClient.java} | 28 +- .../client/tcp/common/ReceiveMsgHook.java | 20 +- .../client/tcp/common/TcpClient.java | 81 +++-- .../tcp/conf/EventMeshTcpClientConfig.java | 14 + ...nt.java => DefaultEventMeshTCPClient.java} | 75 +++-- ...pl.java => EventMeshTCPPubClientImpl.java} | 60 ++-- ...pl.java => EventMeshTCPSubClientImpl.java} | 14 +- .../cloudevent/CloudEventTCPPubClient.java | 78 +++++ .../cloudevent/CloudEventTCPSubClient.java | 64 ++++ .../EventMeshMessageTCPPubClient.java | 210 +++++++++++++ .../EventMeshMessageTCPSubClient.java | 191 +++++++++++ .../openmessage/OpenMessageTCPPubClient.java | 75 +++++ .../openmessage/OpenMessageTCPSubClient.java | 60 ++++ .../http/demo/AsyncPublishInstance.java | 86 ++--- .../http/demo/AsyncSyncRequestInstance.java | 61 ++-- .../client/http/demo/SyncRequestInstance.java | 39 +-- .../http/util/HttpLoadBalanceUtilsTest.java | 16 +- .../client/tcp/demo/AsyncPublish.java | 8 +- .../tcp/demo/AsyncPublishBroadcast.java | 8 +- .../client/tcp/demo/AsyncSubscribe.java | 12 +- .../tcp/demo/AsyncSubscribeBroadcast.java | 37 +-- .../client/tcp/demo/SyncRequest.java | 8 +- .../client/tcp/demo/SyncResponse.java | 34 +- eventmesh-spi/build.gradle | 1 - eventmesh-starter/build.gradle | 2 - 112 files changed, 2491 insertions(+), 2192 deletions(-) create mode 100644 eventmesh-common/src/main/java/org/apache/eventmesh/common/EventMeshMessage.java delete mode 100644 eventmesh-common/src/main/java/org/apache/eventmesh/common/LiteMessage.java rename eventmesh-common/src/main/java/org/apache/eventmesh/common/{ => exception}/EventMeshException.java (89%) rename eventmesh-common/src/main/java/org/apache/eventmesh/common/{ => protocol}/ProtocolTransportObject.java (56%) rename eventmesh-common/src/main/java/org/apache/eventmesh/common/{command => protocol/http}/HttpCommand.java (85%) rename eventmesh-common/src/main/java/org/apache/eventmesh/common/{IPUtil.java => utils/IPUtils.java} (98%) rename eventmesh-common/src/main/java/org/apache/eventmesh/common/{RandomStringUtil.java => utils/RandomStringUtils.java} (76%) rename eventmesh-common/src/main/java/org/apache/eventmesh/common/{ThreadUtil.java => utils/ThreadUtils.java} (70%) rename eventmesh-common/src/test/java/org/apache/eventmesh/common/{LiteMessageTest.java => EventMeshMessageTest.java} (69%) rename eventmesh-common/src/test/java/org/apache/eventmesh/common/{command => protocol/http}/HttpCommandTest.java (86%) rename eventmesh-common/src/test/java/org/apache/eventmesh/common/{IPUtilTest.java => utils/IPUtilsTest.java} (85%) rename eventmesh-common/src/test/java/org/apache/eventmesh/common/{ThreadUtilTest.java => utils/ThreadUtilsTest.java} (90%) create mode 100644 eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/AbstractHttpClient.java delete mode 100644 eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/AbstractLiteClient.java create mode 100644 eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/conf/EventMeshHttpClientConfig.java delete mode 100644 eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/conf/LiteClientConfig.java create mode 100644 eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/consumer/EventMeshHttpConsumer.java delete mode 100644 eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/consumer/LiteConsumer.java rename eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/{http => model}/RequestParam.java (90%) create mode 100644 eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/producer/CloudEventProducer.java create mode 100644 eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/producer/EventMeshHttpProducer.java create mode 100644 eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/producer/EventMeshMessageProducer.java create mode 100644 eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/producer/EventMeshProtocolProducer.java delete mode 100644 eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/producer/LiteProducer.java create mode 100644 eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/producer/OpenMessageProducer.java rename eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/{http/HttpUtil.java => util/HttpUtils.java} (82%) rename eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/{EventMeshClient.java => EventMeshTCPClient.java} (55%) rename eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/{SimplePubClient.java => EventMeshTCPPubClient.java} (57%) rename eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/{SimpleSubClient.java => EventMeshTCPSubClient.java} (65%) create mode 100644 eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/conf/EventMeshTcpClientConfig.java rename eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/{DefaultEventMeshClient.java => DefaultEventMeshTCPClient.java} (64%) rename eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/{SimplePubClientImpl.java => EventMeshTCPPubClientImpl.java} (79%) rename eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/{SimpleSubClientImpl.java => EventMeshTCPSubClientImpl.java} (92%) create mode 100644 eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/cloudevent/CloudEventTCPPubClient.java create mode 100644 eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/cloudevent/CloudEventTCPSubClient.java create mode 100644 eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/eventmeshmessage/EventMeshMessageTCPPubClient.java create mode 100644 eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/eventmeshmessage/EventMeshMessageTCPSubClient.java create mode 100644 eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/openmessage/OpenMessageTCPPubClient.java create mode 100644 eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/openmessage/OpenMessageTCPSubClient.java diff --git a/docs/cn/features/https.md b/docs/cn/features/https.md index 4c30527469..a100ba3977 100644 --- a/docs/cn/features/https.md +++ b/docs/cn/features/https.md @@ -17,12 +17,12 @@ config env varible ``` //创建producer -LiteClientConfig liteClientConfig = new liteClientConfig(); +LiteClientConfig eventMeshHttpClientConfig = new eventMeshHttpClientConfig(); ... //设置开启TLS -liteClientConfig.setUseTls(true); -LiteProducer producer = new LiteProducer(liteClientConfig); +eventMeshHttpClientConfig.setUseTls(true); +LiteProducer producer = new LiteProducer(eventMeshHttpClientConfig); //配置环境变量 diff --git a/docs/en/features/https.md b/docs/en/features/https.md index 8f928c135c..0ef6b5aa97 100644 --- a/docs/en/features/https.md +++ b/docs/en/features/https.md @@ -18,11 +18,11 @@ config env varible ``` // create producer -LiteClientConfig liteClientConfig = new liteClientConfig(); +LiteClientConfig eventMeshHttpClientConfig = new eventMeshHttpClientConfig(); ... // enable TLS -liteClientConfig.setUseTls(true); -LiteProducer producer = new LiteProducer(liteClientConfig); +eventMeshHttpClientConfig.setUseTls(true); +LiteProducer producer = new LiteProducer(eventMeshHttpClientConfig); config env varible diff --git a/eventmesh-common/build.gradle b/eventmesh-common/build.gradle index b552781545..84a03a5d39 100644 --- a/eventmesh-common/build.gradle +++ b/eventmesh-common/build.gradle @@ -44,32 +44,13 @@ dependencies { implementation "com.github.stefanbirkner:system-rules" - testImplementation "org.apache.commons:commons-lang3" - testImplementation "org.apache.commons:commons-collections4" - testImplementation "commons-io:commons-io" - testImplementation "org.apache.commons:commons-text" + compileOnly 'org.projectlombok:lombok:1.18.22' + annotationProcessor 'org.projectlombok:lombok:1.18.22' - testImplementation "com.google.guava:guava" - - testImplementation "org.slf4j:slf4j-api" - testImplementation "org.apache.logging.log4j:log4j-api" - testImplementation "org.apache.logging.log4j:log4j-core" - testImplementation "org.apache.logging.log4j:log4j-core" - testImplementation "org.apache.logging.log4j:log4j-slf4j-impl" - testImplementation "org.apache.logging.log4j:log4j-web" - - testImplementation "com.lmax:disruptor" - - testImplementation "com.fasterxml.jackson.core:jackson-databind" - testImplementation "com.fasterxml.jackson.core:jackson-core" - testImplementation "com.fasterxml.jackson.core:jackson-annotations" - - testImplementation "org.apache.httpcomponents:httpclient" - - testImplementation "io.netty:netty-all" + testCompileOnly 'org.projectlombok:lombok:1.18.22' + testAnnotationProcessor 'org.projectlombok:lombok:1.18.22' testImplementation "junit:junit" - testImplementation "com.github.stefanbirkner:system-rules" testImplementation "org.assertj:assertj-core" testImplementation "org.mockito:mockito-core" diff --git a/eventmesh-common/src/main/java/org/apache/eventmesh/common/EventMeshMessage.java b/eventmesh-common/src/main/java/org/apache/eventmesh/common/EventMeshMessage.java new file mode 100644 index 0000000000..8fecc700fe --- /dev/null +++ b/eventmesh-common/src/main/java/org/apache/eventmesh/common/EventMeshMessage.java @@ -0,0 +1,70 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.apache.eventmesh.common; + +import java.util.HashMap; +import java.util.Map; + +import lombok.Builder; +import lombok.Data; + +/** + * EventMesh message. + */ +@Builder +@Data +public class EventMeshMessage { + + private String bizSeqNo; + + private String uniqueId; + + private String topic; + + private String content; + + private Map prop; + + @Builder.Default + private final long createTime = System.currentTimeMillis(); + + public EventMeshMessage addProp(String key, String val) { + if (prop == null) { + prop = new HashMap<>(); + } + prop.put(key, val); + return this; + } + + public String getProp(String key) { + if (prop == null) { + return null; + } + return prop.get(key); + } + + public EventMeshMessage removePropIfPresent(String key) { + if (prop == null) { + + return this; + } + prop.remove(key); + return this; + } + +} diff --git a/eventmesh-common/src/main/java/org/apache/eventmesh/common/LiteMessage.java b/eventmesh-common/src/main/java/org/apache/eventmesh/common/LiteMessage.java deleted file mode 100644 index 455dfc65d0..0000000000 --- a/eventmesh-common/src/main/java/org/apache/eventmesh/common/LiteMessage.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.apache.eventmesh.common; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.lang3.time.DateFormatUtils; - -public class LiteMessage { - - private String bizSeqNo; - - private String uniqueId; - - private String topic; - - private String content; - - private Map prop; - - private long createTime = System.currentTimeMillis(); - - public LiteMessage() { - } - - public LiteMessage(String bizSeqno, String uniqueId, String topic, - String content) { - this.bizSeqNo = bizSeqno; - this.uniqueId = uniqueId; - this.topic = topic; - this.content = content; - } - - public Map getProp() { - return prop; - } - - public LiteMessage setProp(Map prop) { - this.prop = prop; - return this; - } - - public LiteMessage addProp(String key, String val) { - if (prop == null) { - prop = new HashMap(); - } - prop.put(key, val); - return this; - } - - public String getPropKey(String key) { - if (prop == null) { - return null; - } - return prop.get(key); - } - - public LiteMessage removeProp(String key) { - if (prop == null) { - return this; - } - prop.remove(key); - return this; - } - - public String getBizSeqNo() { - return bizSeqNo; - } - - public LiteMessage setBizSeqNo(String bizSeqNo) { - this.bizSeqNo = bizSeqNo; - return this; - } - - public String getUniqueId() { - return uniqueId; - } - - public LiteMessage setUniqueId(String uniqueId) { - this.uniqueId = uniqueId; - return this; - } - - public String getTopic() { - return topic; - } - - public LiteMessage setTopic(String topic) { - this.topic = topic; - return this; - } - - public String getContent() { - return content; - } - - public LiteMessage setContent(String content) { - this.content = content; - return this; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("liteMessage={") - .append("bizSeqNo=").append(bizSeqNo).append(",") - .append("uniqueId=").append(uniqueId).append(",") - .append("topic=").append(topic).append(",") - .append("content=").append(content).append(",") - .append("prop=").append(prop).append(",") - .append("createTime=").append(DateFormatUtils.format(createTime, Constants.DATE_FORMAT)) - .append("}"); - return sb.toString(); - } -} diff --git a/eventmesh-common/src/main/java/org/apache/eventmesh/common/ThreadPoolFactory.java b/eventmesh-common/src/main/java/org/apache/eventmesh/common/ThreadPoolFactory.java index 5be65297b3..319673d247 100644 --- a/eventmesh-common/src/main/java/org/apache/eventmesh/common/ThreadPoolFactory.java +++ b/eventmesh-common/src/main/java/org/apache/eventmesh/common/ThreadPoolFactory.java @@ -26,37 +26,32 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import com.google.common.util.concurrent.ThreadFactoryBuilder; + public class ThreadPoolFactory { public static ThreadPoolExecutor createThreadPoolExecutor(int core, int max, final String threadName) { return createThreadPoolExecutor(core, max, threadName, true); } - public static ThreadPoolExecutor createThreadPoolExecutor(int core, int max, final String threadName, final boolean isDaemon) { + public static ThreadPoolExecutor createThreadPoolExecutor(int core, int max, final String threadName, + final boolean isDaemon) { return createThreadPoolExecutor(core, max, new LinkedBlockingQueue(1000), threadName, isDaemon); } - public static ThreadPoolExecutor createThreadPoolExecutor(int core, int max, BlockingQueue blockingQueue, final String threadName, final boolean isDaemon) { - return new ThreadPoolExecutor(core, max, - 10 * 1000, TimeUnit.MILLISECONDS, blockingQueue, new ThreadFactory() { - - private AtomicInteger seq = new AtomicInteger(0); - - @Override - public Thread newThread(Runnable r) { - seq.incrementAndGet(); - Thread t = new Thread(r, threadName + seq.get()); - t.setDaemon(isDaemon); - return t; - } - }); + public static ThreadPoolExecutor createThreadPoolExecutor(int core, int max, BlockingQueue blockingQueue, + final String threadName, final boolean isDaemon) { + return new ThreadPoolExecutor(core, max, 10 * 1000, TimeUnit.MILLISECONDS, blockingQueue, + new ThreadFactoryBuilder().setNameFormat(threadName).setDaemon(isDaemon).build() + ); } public static ThreadPoolExecutor createThreadPoolExecutor(int core, int max, ThreadFactory threadFactory) { return createThreadPoolExecutor(core, max, new LinkedBlockingQueue(1000), threadFactory); } - public static ThreadPoolExecutor createThreadPoolExecutor(int core, int max, BlockingQueue blockingQueue, ThreadFactory threadFactory) { + public static ThreadPoolExecutor createThreadPoolExecutor(int core, int max, BlockingQueue blockingQueue, + ThreadFactory threadFactory) { return new ThreadPoolExecutor(core, max, 10 * 1000, TimeUnit.MILLISECONDS, blockingQueue, threadFactory); } @@ -77,7 +72,8 @@ public static ScheduledExecutorService createScheduledExecutor(int core, final S return createScheduledExecutor(core, threadName, true); } - public static ScheduledExecutorService createScheduledExecutor(int core, final String threadName, final boolean isDaemon) { + public static ScheduledExecutorService createScheduledExecutor(int core, final String threadName, + final boolean isDaemon) { return Executors.newScheduledThreadPool(core, new ThreadFactory() { private AtomicInteger ai = new AtomicInteger(0); diff --git a/eventmesh-common/src/main/java/org/apache/eventmesh/common/config/CommonConfiguration.java b/eventmesh-common/src/main/java/org/apache/eventmesh/common/config/CommonConfiguration.java index 2c6b37d63c..3e4ade1df4 100644 --- a/eventmesh-common/src/main/java/org/apache/eventmesh/common/config/CommonConfiguration.java +++ b/eventmesh-common/src/main/java/org/apache/eventmesh/common/config/CommonConfiguration.java @@ -20,7 +20,7 @@ import com.google.common.base.Preconditions; import org.apache.commons.lang3.StringUtils; -import org.apache.eventmesh.common.IPUtil; +import org.apache.eventmesh.common.utils.IPUtils; public class CommonConfiguration { public String eventMeshEnv = "P"; @@ -75,7 +75,7 @@ public void init() { eventMeshServerIp = configurationWrapper.getProp(ConfKeys.KEYS_EVENTMESH_SERVER_HOST_IP); if (StringUtils.isBlank(eventMeshServerIp)) { - eventMeshServerIp = IPUtil.getLocalAddress(); + eventMeshServerIp = IPUtils.getLocalAddress(); } eventMeshConnectorPluginType = configurationWrapper.getProp(ConfKeys.KEYS_ENENTMESH_CONNECTOR_PLUGIN_TYPE); diff --git a/eventmesh-common/src/main/java/org/apache/eventmesh/common/EventMeshException.java b/eventmesh-common/src/main/java/org/apache/eventmesh/common/exception/EventMeshException.java similarity index 89% rename from eventmesh-common/src/main/java/org/apache/eventmesh/common/EventMeshException.java rename to eventmesh-common/src/main/java/org/apache/eventmesh/common/exception/EventMeshException.java index 620bdf9fc5..9dc45c29f9 100644 --- a/eventmesh-common/src/main/java/org/apache/eventmesh/common/EventMeshException.java +++ b/eventmesh-common/src/main/java/org/apache/eventmesh/common/exception/EventMeshException.java @@ -15,13 +15,10 @@ * limitations under the License. */ -package org.apache.eventmesh.common; +package org.apache.eventmesh.common.exception; public class EventMeshException extends Exception { - public EventMeshException() { - } - public EventMeshException(String message) { super(message); } @@ -34,8 +31,7 @@ public EventMeshException(Throwable cause) { super(cause); } - public EventMeshException(String message, Throwable cause, boolean enableSuppression, - boolean writableStackTrace) { + public EventMeshException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } diff --git a/eventmesh-common/src/main/java/org/apache/eventmesh/common/loadbalance/WeightRandomLoadBalanceSelector.java b/eventmesh-common/src/main/java/org/apache/eventmesh/common/loadbalance/WeightRandomLoadBalanceSelector.java index 1fc239d608..835bc48382 100644 --- a/eventmesh-common/src/main/java/org/apache/eventmesh/common/loadbalance/WeightRandomLoadBalanceSelector.java +++ b/eventmesh-common/src/main/java/org/apache/eventmesh/common/loadbalance/WeightRandomLoadBalanceSelector.java @@ -19,7 +19,7 @@ import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.RandomUtils; -import org.apache.eventmesh.common.EventMeshException; +import org.apache.eventmesh.common.exception.EventMeshException; import java.util.List; diff --git a/eventmesh-common/src/main/java/org/apache/eventmesh/common/ProtocolTransportObject.java b/eventmesh-common/src/main/java/org/apache/eventmesh/common/protocol/ProtocolTransportObject.java similarity index 56% rename from eventmesh-common/src/main/java/org/apache/eventmesh/common/ProtocolTransportObject.java rename to eventmesh-common/src/main/java/org/apache/eventmesh/common/protocol/ProtocolTransportObject.java index cf660a35cb..f54bf76250 100644 --- a/eventmesh-common/src/main/java/org/apache/eventmesh/common/ProtocolTransportObject.java +++ b/eventmesh-common/src/main/java/org/apache/eventmesh/common/protocol/ProtocolTransportObject.java @@ -1,11 +1,13 @@ -package org.apache.eventmesh.common; +package org.apache.eventmesh.common.protocol; + +import org.apache.eventmesh.common.protocol.http.HttpCommand; import java.io.Serializable; /** *
    *
  • Tcp transport object{@link org.apache.eventmesh.common.protocol.tcp.Package}
  • - *
  • Http transport object{@link org.apache.eventmesh.common.command.HttpCommand}
  • + *
  • Http transport object{@link HttpCommand}
  • *
*/ public interface ProtocolTransportObject extends Serializable { diff --git a/eventmesh-common/src/main/java/org/apache/eventmesh/common/command/HttpCommand.java b/eventmesh-common/src/main/java/org/apache/eventmesh/common/protocol/http/HttpCommand.java similarity index 85% rename from eventmesh-common/src/main/java/org/apache/eventmesh/common/command/HttpCommand.java rename to eventmesh-common/src/main/java/org/apache/eventmesh/common/protocol/http/HttpCommand.java index 031b993cd7..4b2d7b5816 100644 --- a/eventmesh-common/src/main/java/org/apache/eventmesh/common/command/HttpCommand.java +++ b/eventmesh-common/src/main/java/org/apache/eventmesh/common/protocol/http/HttpCommand.java @@ -15,10 +15,10 @@ * limitations under the License. */ -package org.apache.eventmesh.common.command; +package org.apache.eventmesh.common.protocol.http; import org.apache.eventmesh.common.Constants; -import org.apache.eventmesh.common.ProtocolTransportObject; +import org.apache.eventmesh.common.protocol.ProtocolTransportObject; import org.apache.eventmesh.common.protocol.http.body.BaseResponseBody; import org.apache.eventmesh.common.protocol.http.body.Body; import org.apache.eventmesh.common.protocol.http.common.EventMeshRetCode; @@ -26,10 +26,9 @@ import org.apache.eventmesh.common.protocol.http.header.Header; import org.apache.eventmesh.common.utils.JsonUtils; -import org.apache.commons.collections4.MapUtils; import org.apache.commons.lang3.StringUtils; -import java.util.Map; +import java.util.Optional; import java.util.concurrent.atomic.AtomicLong; import io.netty.buffer.Unpooled; @@ -76,8 +75,7 @@ public HttpCommand(String httpMethod, String httpVersion, String requestCode) { this.opaque = requestId.incrementAndGet(); } - public HttpCommand createHttpCommandResponse(Header header, - Body body) { + public HttpCommand createHttpCommandResponse(Header header, Body body) { if (StringUtils.isBlank(requestCode)) { return null; } @@ -234,22 +232,13 @@ public DefaultFullHttpResponse httpResponse() throws Exception { if (cmdType == CmdType.REQ) { return null; } - - DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, - HttpResponseStatus.OK, - Unpooled.wrappedBuffer( - JsonUtils.serialize(this.getBody()).getBytes(Constants.DEFAULT_CHARSET))); - response.headers().add(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.TEXT_PLAIN + - "; charset=" + Constants.DEFAULT_CHARSET); - response.headers().add(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); - response.headers().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); - Map customHeader = this.getHeader().toMap(); - if (MapUtils.isNotEmpty(customHeader)) { - HttpHeaders heads = response.headers(); - for (String key : customHeader.keySet()) { - heads.add(key, (customHeader.get(key) == null) ? "" : customHeader.get(key)); - } - } + DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, + Unpooled.wrappedBuffer(JsonUtils.serialize(this.getBody()).getBytes(Constants.DEFAULT_CHARSET))); + HttpHeaders headers = response.headers(); + headers.add(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=" + Constants.DEFAULT_CHARSET); + headers.add(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); + headers.add(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); + Optional.of(this.getHeader().toMap()).ifPresent(customerHeader -> customerHeader.forEach(headers::add)); return response; } diff --git a/eventmesh-common/src/main/java/org/apache/eventmesh/common/protocol/http/body/message/SendMessageResponseBody.java b/eventmesh-common/src/main/java/org/apache/eventmesh/common/protocol/http/body/message/SendMessageResponseBody.java index 9086e3d897..7a5f40dabd 100644 --- a/eventmesh-common/src/main/java/org/apache/eventmesh/common/protocol/http/body/message/SendMessageResponseBody.java +++ b/eventmesh-common/src/main/java/org/apache/eventmesh/common/protocol/http/body/message/SendMessageResponseBody.java @@ -17,14 +17,18 @@ package org.apache.eventmesh.common.protocol.http.body.message; -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.lang3.time.DateFormatUtils; import org.apache.eventmesh.common.Constants; import org.apache.eventmesh.common.protocol.http.body.Body; import org.apache.eventmesh.common.protocol.http.common.ProtocolKey; +import org.apache.commons.lang3.time.DateFormatUtils; + +import java.util.HashMap; +import java.util.Map; + +import lombok.Builder; +import lombok.Data; + public class SendMessageResponseBody extends Body { private Integer retCode; @@ -69,9 +73,9 @@ public static SendMessageResponseBody buildBody(Integer retCode, String retMsg) public String toString() { StringBuilder sb = new StringBuilder(); sb.append("sendMessageResponseBody={") - .append("retCode=").append(retCode).append(",") - .append("retMsg=").append(retMsg).append(",") - .append("resTime=").append(DateFormatUtils.format(resTime, Constants.DATE_FORMAT)).append("}"); + .append("retCode=").append(retCode).append(",") + .append("retMsg=").append(retMsg).append(",") + .append("resTime=").append(DateFormatUtils.format(resTime, Constants.DATE_FORMAT)).append("}"); return sb.toString(); } @@ -84,20 +88,11 @@ public Map toMap() { return map; } + @Data + @Builder public static class ReplyMessage { - public String topic; - public String body; + public String topic; + public String body; public Map properties; - - public ReplyMessage(String topic, String body){ - this.topic = topic; - this.body = body; - } - - public ReplyMessage(String topic, String body, Map properties) { - this.topic = topic; - this.body = body; - this.properties = properties; - } } } diff --git a/eventmesh-common/src/main/java/org/apache/eventmesh/common/protocol/tcp/Package.java b/eventmesh-common/src/main/java/org/apache/eventmesh/common/protocol/tcp/Package.java index d10881716b..82557a5710 100644 --- a/eventmesh-common/src/main/java/org/apache/eventmesh/common/protocol/tcp/Package.java +++ b/eventmesh-common/src/main/java/org/apache/eventmesh/common/protocol/tcp/Package.java @@ -17,7 +17,7 @@ package org.apache.eventmesh.common.protocol.tcp; -import org.apache.eventmesh.common.ProtocolTransportObject; +import org.apache.eventmesh.common.protocol.ProtocolTransportObject; public class Package implements ProtocolTransportObject { diff --git a/eventmesh-common/src/main/java/org/apache/eventmesh/common/protocol/tcp/UserAgent.java b/eventmesh-common/src/main/java/org/apache/eventmesh/common/protocol/tcp/UserAgent.java index 14b5058e69..701cd6260e 100644 --- a/eventmesh-common/src/main/java/org/apache/eventmesh/common/protocol/tcp/UserAgent.java +++ b/eventmesh-common/src/main/java/org/apache/eventmesh/common/protocol/tcp/UserAgent.java @@ -17,14 +17,19 @@ package org.apache.eventmesh.common.protocol.tcp; +import lombok.Builder; +import lombok.Data; + +@Data +@Builder public class UserAgent { private String env; private String subsystem; private String path; - private int pid; + private int pid; private String host; - private int port; + private int port; private String version; private String username; private String password; @@ -32,174 +37,7 @@ public class UserAgent { private String producerGroup; private String consumerGroup; private String purpose; - private int unack = 0; - - public UserAgent() { - } - - public String getProducerGroup() { - return producerGroup; - } - - public void setProducerGroup(String producerGroup) { - this.producerGroup = producerGroup; - } - - public String getConsumerGroup() { - return consumerGroup; - } - - public void setConsumerGroup(String consumerGroup) { - this.consumerGroup = consumerGroup; - } - - public String getEnv() { - return env; - } - - public void setEnv(String env) { - this.env = env; - } - - public String getPurpose() { - return purpose; - } - - public void setPurpose(String purpose) { - this.purpose = purpose; - } - - public String getSubsystem() { - return subsystem; - } - - public void setSubsystem(String subsystem) { - this.subsystem = subsystem; - } - - public String getPath() { - return path; - } - - public void setPath(String path) { - this.path = path; - } - - public int getPid() { - return pid; - } - - public void setPid(int pid) { - this.pid = pid; - } - - public String getHost() { - return host; - } - - public void setHost(String host) { - this.host = host; - } - - public int getPort() { - return port; - } - - public void setPort(int port) { - this.port = port; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public String getIdc() { - return idc; - } - - public void setIdc(String idc) { - this.idc = idc; - } - - public int getUnack() { - return unack; - } - - public void setUnack(int unack) { - this.unack = unack; - } - - @Override - public String toString() { - return "UserAgent{" + - "env='" + env + '\'' + - "subsystem='" + subsystem + '\'' + - ", path='" + path + '\'' + - ", pid=" + pid + - ", host='" + host + '\'' + - ", port=" + port + - ", version='" + version + '\'' + - ", idc='" + idc + '\'' + - ", purpose='" + purpose + '\'' + - ", unack='" + unack + '\'' + - '}'; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - UserAgent userAgent = (UserAgent) o; - - if (pid != userAgent.pid) return false; - if (port != userAgent.port) return false; - if (unack != userAgent.unack) return false; - if (subsystem != null ? !subsystem.equals(userAgent.subsystem) : userAgent.subsystem != null) return false; - if (path != null ? !path.equals(userAgent.path) : userAgent.path != null) return false; - if (host != null ? !host.equals(userAgent.host) : userAgent.host != null) return false; - if (purpose != null ? !purpose.equals(userAgent.purpose) : userAgent.purpose != null) return false; - if (version != null ? !version.equals(userAgent.version) : userAgent.version != null) return false; - if (username != null ? !username.equals(userAgent.username) : userAgent.username != null) return false; - if (password != null ? !password.equals(userAgent.password) : userAgent.password != null) return false; - if (env != null ? !env.equals(userAgent.env) : userAgent.env != null) return false; - return idc != null ? idc.equals(userAgent.idc) : userAgent.idc == null; - } + @Builder.Default + private int unack = 0; - @Override - public int hashCode() { - int result = subsystem != null ? subsystem.hashCode() : 0; - result = 31 * result + (path != null ? path.hashCode() : 0); - result = 31 * result + pid; - result = 31 * result + (host != null ? host.hashCode() : 0); - result = 31 * result + (purpose != null ? purpose.hashCode() : 0); - result = 31 * result + port; - result = 31 * result + (version != null ? version.hashCode() : 0); - result = 31 * result + (username != null ? username.hashCode() : 0); - result = 31 * result + (password != null ? password.hashCode() : 0); - result = 31 * result + (idc != null ? idc.hashCode() : 0); - result = 31 * result + (env != null ? env.hashCode() : 0); - result = 31 * result + unack; - return result; - } } diff --git a/eventmesh-common/src/main/java/org/apache/eventmesh/common/IPUtil.java b/eventmesh-common/src/main/java/org/apache/eventmesh/common/utils/IPUtils.java similarity index 98% rename from eventmesh-common/src/main/java/org/apache/eventmesh/common/IPUtil.java rename to eventmesh-common/src/main/java/org/apache/eventmesh/common/utils/IPUtils.java index 5165deb8af..434f5a580e 100644 --- a/eventmesh-common/src/main/java/org/apache/eventmesh/common/IPUtil.java +++ b/eventmesh-common/src/main/java/org/apache/eventmesh/common/utils/IPUtils.java @@ -15,7 +15,7 @@ * limitations under the License. */ -package org.apache.eventmesh.common; +package org.apache.eventmesh.common.utils; import java.net.Inet6Address; import java.net.InetAddress; @@ -30,7 +30,7 @@ import io.netty.channel.Channel; -public class IPUtil { +public class IPUtils { public static String getLocalAddress() { // if the progress works under docker environment diff --git a/eventmesh-common/src/main/java/org/apache/eventmesh/common/RandomStringUtil.java b/eventmesh-common/src/main/java/org/apache/eventmesh/common/utils/RandomStringUtils.java similarity index 76% rename from eventmesh-common/src/main/java/org/apache/eventmesh/common/RandomStringUtil.java rename to eventmesh-common/src/main/java/org/apache/eventmesh/common/utils/RandomStringUtils.java index 802c3a6ccd..aaeaec84a6 100644 --- a/eventmesh-common/src/main/java/org/apache/eventmesh/common/RandomStringUtil.java +++ b/eventmesh-common/src/main/java/org/apache/eventmesh/common/utils/RandomStringUtils.java @@ -15,17 +15,17 @@ * limitations under the License. */ -package org.apache.eventmesh.common; +package org.apache.eventmesh.common.utils; import org.apache.commons.text.RandomStringGenerator; -public class RandomStringUtil { +public class RandomStringUtils { - private final static RandomStringGenerator randomNumGenerator = new RandomStringGenerator.Builder() - .withinRange('0', '9').build(); + private static final RandomStringGenerator RANDOM_NUM_GENERATOR = new RandomStringGenerator.Builder() + .withinRange('0', '9').build(); public static String generateNum(int length) { - return randomNumGenerator.generate(length); + return RANDOM_NUM_GENERATOR.generate(length); } } diff --git a/eventmesh-common/src/main/java/org/apache/eventmesh/common/ThreadUtil.java b/eventmesh-common/src/main/java/org/apache/eventmesh/common/utils/ThreadUtils.java similarity index 70% rename from eventmesh-common/src/main/java/org/apache/eventmesh/common/ThreadUtil.java rename to eventmesh-common/src/main/java/org/apache/eventmesh/common/utils/ThreadUtils.java index 895215d0da..af69f08508 100644 --- a/eventmesh-common/src/main/java/org/apache/eventmesh/common/ThreadUtil.java +++ b/eventmesh-common/src/main/java/org/apache/eventmesh/common/utils/ThreadUtils.java @@ -15,13 +15,15 @@ * limitations under the License. */ -package org.apache.eventmesh.common; +package org.apache.eventmesh.common.utils; + +import org.apache.logging.log4j.util.ProcessIdUtil; import java.util.concurrent.ThreadLocalRandom; -public class ThreadUtil { +public class ThreadUtils { - private static long currentPID = -1; + private static volatile long currentPID = -1; public static void randomSleep(int min, int max) throws Exception { // nextInt is normally exclusive of the top value, so add 1 to make it inclusive @@ -35,22 +37,18 @@ public static void randomSleep(int max) throws Exception { } /** - * get current process id only once. + * get current process id. * * @return process id */ public static long getPID() { - if (currentPID >= 0) { - return currentPID; - } - String processName = java.lang.management.ManagementFactory.getRuntimeMXBean().getName(); - if (processName != null && processName.length() > 0) { - try { - currentPID = Long.parseLong(processName.split("@")[0]); - } catch (Exception e) { - return 0; + if (currentPID == -1) { + synchronized (ThreadUtils.class) { + if (currentPID == -1) { + currentPID = Long.parseLong(ProcessIdUtil.getProcessId()); + } } } - return 0; + return currentPID; } } diff --git a/eventmesh-common/src/test/java/org/apache/eventmesh/common/LiteMessageTest.java b/eventmesh-common/src/test/java/org/apache/eventmesh/common/EventMeshMessageTest.java similarity index 69% rename from eventmesh-common/src/test/java/org/apache/eventmesh/common/LiteMessageTest.java rename to eventmesh-common/src/test/java/org/apache/eventmesh/common/EventMeshMessageTest.java index 2f206a8d82..006a1d1cb3 100644 --- a/eventmesh-common/src/test/java/org/apache/eventmesh/common/LiteMessageTest.java +++ b/eventmesh-common/src/test/java/org/apache/eventmesh/common/EventMeshMessageTest.java @@ -17,58 +17,58 @@ package org.apache.eventmesh.common; -import org.junit.Assert; -import org.junit.Test; - import java.util.HashMap; import java.util.Map; -public class LiteMessageTest { +import org.junit.Assert; +import org.junit.Test; + +public class EventMeshMessageTest { @Test public void testGetProp() { - LiteMessage message = createLiteMessage(); + EventMeshMessage message = createLiteMessage(); Assert.assertEquals(2L, message.getProp().size()); } @Test public void testSetProp() { - LiteMessage message = createLiteMessage(); + EventMeshMessage message = createLiteMessage(); Map prop = new HashMap<>(); prop.put("key3", "value3"); message.setProp(prop); Assert.assertEquals(1L, message.getProp().size()); - Assert.assertEquals("value3", message.getPropKey("key3")); + Assert.assertEquals("value3", message.getProp("key3")); } @Test public void testAddProp() { - LiteMessage message = createLiteMessage(); + EventMeshMessage message = createLiteMessage(); message.addProp("key3", "value3"); Assert.assertEquals(3L, message.getProp().size()); - Assert.assertEquals("value1", message.getPropKey("key1")); + Assert.assertEquals("value1", message.getProp("key1")); } @Test public void testGetPropKey() { - LiteMessage message = createLiteMessage(); - Assert.assertEquals("value1", message.getPropKey("key1")); + EventMeshMessage message = createLiteMessage(); + Assert.assertEquals("value1", message.getProp("key1")); } @Test public void testRemoveProp() { - LiteMessage message = createLiteMessage(); - message.removeProp("key1"); + EventMeshMessage message = createLiteMessage(); + message.removePropIfPresent("key1"); Assert.assertEquals(1L, message.getProp().size()); - Assert.assertNull(message.getPropKey("key1")); + Assert.assertNull(message.getProp("key1")); } - private LiteMessage createLiteMessage() { - LiteMessage result = new LiteMessage(); + private EventMeshMessage createLiteMessage() { Map prop = new HashMap<>(); prop.put("key1", "value1"); prop.put("key2", "value2"); - result.setProp(prop); - return result; + return EventMeshMessage.builder() + .prop(prop) + .build(); } } diff --git a/eventmesh-common/src/test/java/org/apache/eventmesh/common/command/HttpCommandTest.java b/eventmesh-common/src/test/java/org/apache/eventmesh/common/protocol/http/HttpCommandTest.java similarity index 86% rename from eventmesh-common/src/test/java/org/apache/eventmesh/common/command/HttpCommandTest.java rename to eventmesh-common/src/test/java/org/apache/eventmesh/common/protocol/http/HttpCommandTest.java index ce5ac0c80b..962d6c7a79 100644 --- a/eventmesh-common/src/test/java/org/apache/eventmesh/common/command/HttpCommandTest.java +++ b/eventmesh-common/src/test/java/org/apache/eventmesh/common/protocol/http/HttpCommandTest.java @@ -15,13 +15,16 @@ * limitations under the License. */ -package org.apache.eventmesh.common.command; +package org.apache.eventmesh.common.protocol.http; + +import static org.mockito.Mockito.when; -import io.netty.handler.codec.http.DefaultFullHttpResponse; -import io.netty.handler.codec.http.HttpHeaderNames; -import org.apache.eventmesh.common.protocol.http.body.BaseResponseBody; import org.apache.eventmesh.common.protocol.http.body.Body; import org.apache.eventmesh.common.protocol.http.header.Header; + +import java.util.HashMap; +import java.util.Map; + import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -29,11 +32,8 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; -import java.util.HashMap; -import java.util.Map; - -import static org.hamcrest.CoreMatchers.is; -import static org.mockito.Mockito.when; +import io.netty.handler.codec.http.DefaultFullHttpResponse; +import io.netty.handler.codec.http.HttpHeaderNames; @RunWith(MockitoJUnitRunner.class) public class HttpCommandTest { @@ -63,13 +63,6 @@ public void testCreateHttpCommandResponseWithHeaderAndBody() { Assert.assertEquals("value1", command.getHeader().toMap().get("key1")); } - @Test - public void testCreateHttpCommandResponseWithRetCodeAndRetMsg() { - HttpCommand command = httpCommand.createHttpCommandResponse(200, "SUCCESS"); - Assert.assertThat(((BaseResponseBody) command.getBody()).getRetCode(), is(200)); - Assert.assertEquals("SUCCESS", ((BaseResponseBody) command.getBody()).getRetMsg()); - } - @Test public void testAbstractDesc() { HttpCommand command = httpCommand.createHttpCommandResponse(header, body); diff --git a/eventmesh-common/src/test/java/org/apache/eventmesh/common/IPUtilTest.java b/eventmesh-common/src/test/java/org/apache/eventmesh/common/utils/IPUtilsTest.java similarity index 85% rename from eventmesh-common/src/test/java/org/apache/eventmesh/common/IPUtilTest.java rename to eventmesh-common/src/test/java/org/apache/eventmesh/common/utils/IPUtilsTest.java index d4f4f97139..4adff4475d 100644 --- a/eventmesh-common/src/test/java/org/apache/eventmesh/common/IPUtilTest.java +++ b/eventmesh-common/src/test/java/org/apache/eventmesh/common/utils/IPUtilsTest.java @@ -15,24 +15,24 @@ * limitations under the License. */ -package org.apache.eventmesh.common; +package org.apache.eventmesh.common.utils; import org.junit.Assert; import org.junit.Test; import org.junit.contrib.java.lang.system.EnvironmentVariables; -public class IPUtilTest { +public class IPUtilsTest { @Test public void testDockerIP() { EnvironmentVariables environmentVariables = new EnvironmentVariables(); environmentVariables.set("docker_host_ip", "dockHostIP"); - Assert.assertEquals("dockHostIP", IPUtil.getLocalAddress()); + Assert.assertEquals("dockHostIP", IPUtils.getLocalAddress()); } @Test public void testLocalhostIP() { - Assert.assertNotNull(IPUtil.getLocalAddress()); + Assert.assertNotNull(IPUtils.getLocalAddress()); } } diff --git a/eventmesh-common/src/test/java/org/apache/eventmesh/common/ThreadUtilTest.java b/eventmesh-common/src/test/java/org/apache/eventmesh/common/utils/ThreadUtilsTest.java similarity index 90% rename from eventmesh-common/src/test/java/org/apache/eventmesh/common/ThreadUtilTest.java rename to eventmesh-common/src/test/java/org/apache/eventmesh/common/utils/ThreadUtilsTest.java index b888fde1e8..a9aeb0e38e 100644 --- a/eventmesh-common/src/test/java/org/apache/eventmesh/common/ThreadUtilTest.java +++ b/eventmesh-common/src/test/java/org/apache/eventmesh/common/utils/ThreadUtilsTest.java @@ -15,12 +15,12 @@ * limitations under the License. */ -package org.apache.eventmesh.common; +package org.apache.eventmesh.common.utils; import org.junit.Assert; import org.junit.Test; -public class ThreadUtilTest { +public class ThreadUtilsTest { @Test public void testRandomSleep() throws InterruptedException { @@ -33,7 +33,7 @@ public void testRandomSleep() throws InterruptedException { @Test public void testPID() { - Assert.assertNotEquals(-1, ThreadUtil.getPID()); + Assert.assertNotEquals(-1, ThreadUtils.getPID()); } class TestThread extends Thread { @@ -47,7 +47,7 @@ public long getSleepTime() { public void run() { long startTime = System.currentTimeMillis(); try { - ThreadUtil.randomSleep(50); + ThreadUtils.randomSleep(50); } catch (Exception ignore) { } sleepTime = System.currentTimeMillis() - startTime; diff --git a/eventmesh-connector-plugin/eventmesh-connector-api/build.gradle b/eventmesh-connector-plugin/eventmesh-connector-api/build.gradle index a7211893e1..81d1568ec0 100644 --- a/eventmesh-connector-plugin/eventmesh-connector-api/build.gradle +++ b/eventmesh-connector-plugin/eventmesh-connector-api/build.gradle @@ -25,11 +25,4 @@ dependencies { api "io.dropwizard.metrics:metrics-annotation" api "io.dropwizard.metrics:metrics-json" - testImplementation project(":eventmesh-spi") - testImplementation project(":eventmesh-common") - testImplementation 'io.openmessaging:openmessaging-api' - testImplementation 'io.dropwizard.metrics:metrics-core' - testImplementation "io.dropwizard.metrics:metrics-healthchecks" - testImplementation "io.dropwizard.metrics:metrics-annotation" - testImplementation "io.dropwizard.metrics:metrics-json" } diff --git a/eventmesh-connector-plugin/eventmesh-connector-rocketmq/src/main/java/org/apache/eventmesh/connector/rocketmq/producer/RocketMQProducerImpl.java b/eventmesh-connector-plugin/eventmesh-connector-rocketmq/src/main/java/org/apache/eventmesh/connector/rocketmq/producer/RocketMQProducerImpl.java index 52af730271..54d06a0bf9 100644 --- a/eventmesh-connector-plugin/eventmesh-connector-rocketmq/src/main/java/org/apache/eventmesh/connector/rocketmq/producer/RocketMQProducerImpl.java +++ b/eventmesh-connector-plugin/eventmesh-connector-rocketmq/src/main/java/org/apache/eventmesh/connector/rocketmq/producer/RocketMQProducerImpl.java @@ -18,6 +18,7 @@ package org.apache.eventmesh.connector.rocketmq.producer; import org.apache.eventmesh.api.RRCallback; +import org.apache.eventmesh.api.RequestReplyCallback; import org.apache.eventmesh.api.SendCallback; import org.apache.eventmesh.api.SendResult; import org.apache.eventmesh.api.producer.Producer; @@ -98,6 +99,11 @@ public void request(CloudEvent message, RRCallback rrCallback, long timeout) producer.request(message, rrCallback, timeout); } + @Override + public void request(CloudEvent cloudEvent, RequestReplyCallback rrCallback, long timeout) throws Exception { + + } + @Override public boolean reply(final CloudEvent message, final SendCallback sendCallback) throws Exception { producer.reply(message, sendCallback); diff --git a/eventmesh-connector-plugin/eventmesh-connector-rocketmq/src/test/java/org/apache/rocketmq/consumer/PushConsumerImplTest.java b/eventmesh-connector-plugin/eventmesh-connector-rocketmq/src/test/java/org/apache/rocketmq/consumer/PushConsumerImplTest.java index 1a77792118..5e34777196 100644 --- a/eventmesh-connector-plugin/eventmesh-connector-rocketmq/src/test/java/org/apache/rocketmq/consumer/PushConsumerImplTest.java +++ b/eventmesh-connector-plugin/eventmesh-connector-rocketmq/src/test/java/org/apache/rocketmq/consumer/PushConsumerImplTest.java @@ -53,7 +53,8 @@ public class PushConsumerImplTest { @Before public void before() throws Exception { Properties consumerProp = new Properties(); - consumerProp.setProperty(OMSBuiltinKeys.DRIVER_IMPL, "org.apache.eventmesh.connector.rocketmq.MessagingAccessPointImpl"); + consumerProp.setProperty(OMSBuiltinKeys.DRIVER_IMPL, + "org.apache.eventmesh.connector.rocketmq.MessagingAccessPointImpl"); consumerProp.setProperty("access_points", "IP1:9876,IP2:9876"); //final MessagingAccessPoint messagingAccessPoint = OMS.builder().build(consumerProp);//.endpoint("oms:rocketmq://IP1:9876,IP2:9876/namespace").build(config); @@ -81,7 +82,7 @@ public void after() throws Exception { @Test public void testConsumeMessage() { - final byte[] testBody = new byte[]{'a', 'b'}; + final byte[] testBody = new byte[] {'a', 'b'}; MessageExt consumedMsg = new MessageExt(); consumedMsg.setMsgId("NewMsgId"); @@ -91,15 +92,14 @@ public void testConsumeMessage() { consumer.subscribe("HELLO_QUEUE", "*", new EventListener() { @Override - public void consume(CloudEvent cloudEvent, - org.apache.eventmesh.api.AsyncConsumeContext context) { + public void consume(CloudEvent cloudEvent, org.apache.eventmesh.api.AsyncConsumeContext context) { assertThat(cloudEvent.getExtension("MESSAGE_ID")).isEqualTo("NewMsgId"); assertThat(cloudEvent.getData()).isEqualTo(testBody); context.commit(EventMeshAction.CommitMessage); } }); ((MessageListenerConcurrently) rocketmqPushConsumer - .getMessageListener()).consumeMessage(Collections.singletonList(consumedMsg), null); + .getMessageListener()).consumeMessage(Collections.singletonList(consumedMsg), null); } diff --git a/eventmesh-connector-plugin/eventmesh-connector-standalone/build.gradle b/eventmesh-connector-plugin/eventmesh-connector-standalone/build.gradle index 6152c89028..32b1372c13 100644 --- a/eventmesh-connector-plugin/eventmesh-connector-standalone/build.gradle +++ b/eventmesh-connector-plugin/eventmesh-connector-standalone/build.gradle @@ -19,6 +19,4 @@ dependencies { compileOnly project(":eventmesh-common") compileOnly project(":eventmesh-connector-plugin:eventmesh-connector-api") - testImplementation project(":eventmesh-connector-plugin:eventmesh-connector-api") - testImplementation project(":eventmesh-common") } \ No newline at end of file diff --git a/eventmesh-connector-plugin/eventmesh-connector-standalone/src/main/java/org/apache/eventmesh/connector/standalone/broker/task/SubScribeTask.java b/eventmesh-connector-plugin/eventmesh-connector-standalone/src/main/java/org/apache/eventmesh/connector/standalone/broker/task/SubScribeTask.java index 15e8cf6aa7..430e4aa5b9 100644 --- a/eventmesh-connector-plugin/eventmesh-connector-standalone/src/main/java/org/apache/eventmesh/connector/standalone/broker/task/SubScribeTask.java +++ b/eventmesh-connector-plugin/eventmesh-connector-standalone/src/main/java/org/apache/eventmesh/connector/standalone/broker/task/SubScribeTask.java @@ -21,12 +21,13 @@ import org.apache.eventmesh.api.EventMeshAction; import org.apache.eventmesh.api.EventMeshAsyncConsumeContext; import org.apache.eventmesh.connector.standalone.broker.StandaloneBroker; + +import java.util.concurrent.atomic.AtomicInteger; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; +import io.openmessaging.api.Message; public class SubScribeTask implements Runnable { diff --git a/eventmesh-examples/build.gradle b/eventmesh-examples/build.gradle index 771cbdd442..b7b1f654a3 100644 --- a/eventmesh-examples/build.gradle +++ b/eventmesh-examples/build.gradle @@ -15,80 +15,17 @@ * limitations under the License. */ -//group 'org.apache.eventmesh' -//version '1.2.0-SNAPSHOT' - dependencies { -// compile log4j2, sl4j -// testCompile log4j2, sl4j implementation project(":eventmesh-sdk-java") implementation project(":eventmesh-common") implementation project(":eventmesh-connector-plugin:eventmesh-connector-api") implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'io.netty:netty-all' implementation "io.cloudevents:cloudevents-core" - testImplementation project(":eventmesh-sdk-java") - testImplementation project(":eventmesh-common") - testImplementation project(":eventmesh-connector-plugin:eventmesh-connector-api") - testImplementation 'org.springframework.boot:spring-boot-starter-web' - testImplementation 'io.netty:netty-all' - -} - -configurations.all { - exclude group: "ch.qos.logback" - exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging' -} - -task testdist(dependsOn: ['jar']) { - - doFirst { - BasicTest - new File(projectDir.getPath(), 'dist/bin').mkdirs() - new File(projectDir.getPath(), 'dist/apps').mkdirs() - new File(projectDir.getPath(), 'dist/conf').mkdirs() - new File(projectDir.getPath(), 'dist/lib').mkdirs() - } - - doLast { - copy { - into('dist/apps/') - from project.jar.getArchivePath() - } - copy { - into 'dist/lib' - from project.configurations.runtime - } - - copy { - into 'dist/bin' - from '../eventmesh-test/bin' - } - - copy { - into 'dist/conf' - from 'conf' - } - } -} - -task testtar(type: Tar) { - extension = 'tar.gz' - compression = Compression.GZIP - archiveName = project.name + '_' + project.version + '.' + extension - destinationDir = new File(projectDir.getPath(), 'build') - into('/') { - from 'dist' - } -} -task packageTestSources(type: Jar) { - from project.sourceSets.main.allSource - classifier = 'sources' // either here or in artifacts block -} + compileOnly 'org.projectlombok:lombok:1.18.22' + annotationProcessor 'org.projectlombok:lombok:1.18.22' -artifacts { - archives jar - archives packageJavadoc - archives packageSources + testCompileOnly 'org.projectlombok:lombok:1.18.22' + testAnnotationProcessor 'org.projectlombok:lombok:1.18.22' } \ No newline at end of file diff --git a/eventmesh-examples/src/main/java/org/apache/eventmesh/http/demo/AsyncPublishInstance.java b/eventmesh-examples/src/main/java/org/apache/eventmesh/http/demo/AsyncPublishInstance.java index b867885ce6..1af175dd9b 100644 --- a/eventmesh-examples/src/main/java/org/apache/eventmesh/http/demo/AsyncPublishInstance.java +++ b/eventmesh-examples/src/main/java/org/apache/eventmesh/http/demo/AsyncPublishInstance.java @@ -17,17 +17,19 @@ package org.apache.eventmesh.http.demo; -import java.util.Properties; - -import org.apache.commons.lang3.StringUtils; -import org.apache.eventmesh.client.http.conf.LiteClientConfig; -import org.apache.eventmesh.client.http.producer.LiteProducer; +import org.apache.eventmesh.client.http.conf.EventMeshHttpClientConfig; +import org.apache.eventmesh.client.http.producer.EventMeshHttpProducer; import org.apache.eventmesh.common.Constants; -import org.apache.eventmesh.common.IPUtil; -import org.apache.eventmesh.common.LiteMessage; -import org.apache.eventmesh.common.RandomStringUtil; -import org.apache.eventmesh.common.ThreadUtil; +import org.apache.eventmesh.common.EventMeshMessage; +import org.apache.eventmesh.common.utils.IPUtils; +import org.apache.eventmesh.common.utils.RandomStringUtils; +import org.apache.eventmesh.common.utils.ThreadUtils; import org.apache.eventmesh.util.Utils; + +import org.apache.commons.lang3.StringUtils; + +import java.util.Properties; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -43,52 +45,37 @@ public static void main(String[] args) throws Exception { final String eventMeshIp = properties.getProperty("eventmesh.ip"); final String eventMeshHttpPort = properties.getProperty("eventmesh.http.port"); - LiteProducer liteProducer = null; - try { -// String eventMeshIPPort = args[0]; - String eventMeshIPPort = eventMeshIp + ":" + eventMeshHttpPort; -// final String topic = args[1]; - final String topic = "TEST-TOPIC-HTTP-ASYNC"; - if (StringUtils.isBlank(eventMeshIPPort)) { - // if has multi value, can config as: 127.0.0.1:10105;127.0.0.2:10105 - eventMeshIPPort = "127.0.0.1:10105"; - } + String eventMeshIPPort; + if (StringUtils.isBlank(eventMeshIp) || StringUtils.isBlank(eventMeshHttpPort)) { + // if has multi value, can config as: 127.0.0.1:10105;127.0.0.2:10105 + eventMeshIPPort = "127.0.0.1:10105"; + } else { + eventMeshIPPort = eventMeshIp + ":" + eventMeshHttpPort; + } - LiteClientConfig eventMeshClientConfig = new LiteClientConfig(); - eventMeshClientConfig.setLiteEventMeshAddr(eventMeshIPPort) - .setProducerGroup("EventMeshTest-producerGroup") - .setEnv("env") - .setIdc("idc") - .setIp(IPUtil.getLocalAddress()) - .setSys("1234") - .setPid(String.valueOf(ThreadUtil.getPID())); + final String topic = "TEST-TOPIC-HTTP-ASYNC"; - liteProducer = new LiteProducer(eventMeshClientConfig); - liteProducer.start(); - for (int i = 0; i < messageSize; i++) { - LiteMessage liteMessage = new LiteMessage(); - liteMessage.setBizSeqNo(RandomStringUtil.generateNum(30)) -// .setContent("contentStr with special protocal") - .setContent("testPublishMessage") - .setTopic(topic) - .setUniqueId(RandomStringUtil.generateNum(30)) - .addProp(Constants.EVENTMESH_MESSAGE_CONST_TTL, String.valueOf(4 * 1000)); + EventMeshHttpClientConfig eventMeshClientConfig = EventMeshHttpClientConfig.builder() + .liteEventMeshAddr(eventMeshIPPort) + .producerGroup("EventMeshTest-producerGroup") + .env("env") + .idc("idc") + .ip(IPUtils.getLocalAddress()) + .sys("1234") + .pid(String.valueOf(ThreadUtils.getPID())).build(); - boolean flag = liteProducer.publish(liteMessage); - Thread.sleep(1000); - logger.info("publish result , {}", flag); + try (EventMeshHttpProducer eventMeshHttpProducer = new EventMeshHttpProducer(eventMeshClientConfig);) { + for (int i = 0; i < messageSize; i++) { + EventMeshMessage eventMeshMessage = EventMeshMessage.builder() + .bizSeqNo(RandomStringUtils.generateNum(30)) + .content("testPublishMessage") + .topic(topic) + .uniqueId(RandomStringUtils.generateNum(30)) + .build() + .addProp(Constants.EVENTMESH_MESSAGE_CONST_TTL, String.valueOf(4 * 1000)); + eventMeshHttpProducer.publish(eventMeshMessage); } - } catch (Exception e) { - logger.warn("publish msg failed", e); - } - - try { Thread.sleep(30000); - if (liteProducer != null) { - liteProducer.shutdown(); - } - } catch (Exception e1) { - logger.warn("producer shutdown exception", e1); } } } diff --git a/eventmesh-examples/src/main/java/org/apache/eventmesh/http/demo/AsyncSyncRequestInstance.java b/eventmesh-examples/src/main/java/org/apache/eventmesh/http/demo/AsyncSyncRequestInstance.java index ba2d99ccd2..a007ed1459 100644 --- a/eventmesh-examples/src/main/java/org/apache/eventmesh/http/demo/AsyncSyncRequestInstance.java +++ b/eventmesh-examples/src/main/java/org/apache/eventmesh/http/demo/AsyncSyncRequestInstance.java @@ -17,83 +17,83 @@ package org.apache.eventmesh.http.demo; -import java.util.Properties; - -import org.apache.commons.lang3.StringUtils; -import org.apache.eventmesh.client.http.conf.LiteClientConfig; -import org.apache.eventmesh.client.http.producer.LiteProducer; +import org.apache.eventmesh.client.http.conf.EventMeshHttpClientConfig; +import org.apache.eventmesh.client.http.producer.EventMeshHttpProducer; import org.apache.eventmesh.client.http.producer.RRCallback; -import org.apache.eventmesh.common.IPUtil; -import org.apache.eventmesh.common.LiteMessage; -import org.apache.eventmesh.common.RandomStringUtil; -import org.apache.eventmesh.common.ThreadUtil; +import org.apache.eventmesh.common.EventMeshMessage; +import org.apache.eventmesh.common.utils.IPUtils; +import org.apache.eventmesh.common.utils.RandomStringUtils; +import org.apache.eventmesh.common.utils.ThreadUtils; import org.apache.eventmesh.util.Utils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -public class AsyncSyncRequestInstance { +import org.apache.commons.lang3.StringUtils; + +import java.util.Properties; + +import com.google.common.base.Preconditions; + +import lombok.extern.slf4j.Slf4j; - public static Logger logger = LoggerFactory.getLogger(AsyncSyncRequestInstance.class); +@Slf4j +public class AsyncSyncRequestInstance { public static void main(String[] args) throws Exception { Properties properties = Utils.readPropertiesFile("application.properties"); + Preconditions.checkNotNull(properties, "application.properties"); final String eventMeshIp = properties.getProperty("eventmesh.ip"); final String eventMeshHttpPort = properties.getProperty("eventmesh.http.port"); - LiteProducer liteProducer = null; + EventMeshHttpProducer eventMeshHttpProducer = null; try { -// String eventMeshIPPort = args[0]; String eventMeshIPPort = eventMeshIp + ":" + eventMeshHttpPort; -// final String topic = args[1]; final String topic = "TEST-TOPIC-TCP-ASYNC"; if (StringUtils.isBlank(eventMeshIPPort)) { // if has multi value, can config as: 127.0.0.1:10105;127.0.0.2:10105 eventMeshIPPort = "127.0.0.1:10105"; } - LiteClientConfig eventMeshClientConfig = new LiteClientConfig(); - eventMeshClientConfig.setLiteEventMeshAddr(eventMeshIPPort) - .setProducerGroup("EventMeshTest-producerGroup") - .setEnv("env") - .setIdc("idc") - .setIp(IPUtil.getLocalAddress()) - .setSys("1234") - .setPid(String.valueOf(ThreadUtil.getPID())); + EventMeshHttpClientConfig eventMeshClientConfig = EventMeshHttpClientConfig.builder() + .liteEventMeshAddr(eventMeshIPPort) + .producerGroup("EventMeshTest-producerGroup") + .env("env") + .idc("idc") + .ip(IPUtils.getLocalAddress()) + .sys("1234") + .pid(String.valueOf(ThreadUtils.getPID())).build(); - liteProducer = new LiteProducer(eventMeshClientConfig); + eventMeshHttpProducer = new EventMeshHttpProducer(eventMeshClientConfig); final long startTime = System.currentTimeMillis(); - final LiteMessage liteMessage = new LiteMessage(); - liteMessage.setBizSeqNo(RandomStringUtil.generateNum(30)) - .setContent("testAsyncMessage") - .setTopic(topic) - .setUniqueId(RandomStringUtil.generateNum(30)); + final EventMeshMessage eventMeshMessage = EventMeshMessage.builder() + .bizSeqNo(RandomStringUtils.generateNum(30)) + .content("testAsyncMessage") + .topic(topic) + .uniqueId(RandomStringUtils.generateNum(30)).build(); - liteProducer.request(liteMessage, new RRCallback() { + eventMeshHttpProducer.request(eventMeshMessage, new RRCallback() { @Override - public void onSuccess(LiteMessage o) { - logger.debug("sendmsg : {}, return : {}, cost:{}ms", liteMessage.getContent(), o.getContent(), System.currentTimeMillis() - startTime); + public void onSuccess(EventMeshMessage o) { + log.debug("sendmsg : {}, return : {}, cost:{}ms", eventMeshMessage.getContent(), o.getContent(), + System.currentTimeMillis() - startTime); } @Override public void onException(Throwable e) { - logger.debug("sendmsg failed", e); + log.debug("send msg failed", e); } }, 3000); Thread.sleep(2000); } catch (Exception e) { - logger.warn("async send msg failed", e); + log.warn("async send msg failed", e); } - try { - Thread.sleep(30000); - if (liteProducer != null) { - liteProducer.shutdown(); - } + Thread.sleep(30000); + try (final EventMeshHttpProducer ignore = eventMeshHttpProducer) { + // close producer } catch (Exception e1) { - logger.warn("producer shutdown exception", e1); + log.warn("producer shutdown exception", e1); } } } diff --git a/eventmesh-examples/src/main/java/org/apache/eventmesh/http/demo/SyncRequestInstance.java b/eventmesh-examples/src/main/java/org/apache/eventmesh/http/demo/SyncRequestInstance.java index a88396bedf..58d287dd32 100644 --- a/eventmesh-examples/src/main/java/org/apache/eventmesh/http/demo/SyncRequestInstance.java +++ b/eventmesh-examples/src/main/java/org/apache/eventmesh/http/demo/SyncRequestInstance.java @@ -18,12 +18,13 @@ package org.apache.eventmesh.http.demo; import org.apache.commons.lang3.StringUtils; -import org.apache.eventmesh.client.http.conf.LiteClientConfig; -import org.apache.eventmesh.client.http.producer.LiteProducer; -import org.apache.eventmesh.common.IPUtil; -import org.apache.eventmesh.common.LiteMessage; -import org.apache.eventmesh.common.RandomStringUtil; -import org.apache.eventmesh.common.ThreadUtil; + +import org.apache.eventmesh.client.http.conf.EventMeshHttpClientConfig; +import org.apache.eventmesh.client.http.producer.EventMeshHttpProducer; +import org.apache.eventmesh.common.utils.IPUtils; +import org.apache.eventmesh.common.EventMeshMessage; +import org.apache.eventmesh.common.utils.RandomStringUtils; +import org.apache.eventmesh.common.utils.ThreadUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -33,7 +34,7 @@ public class SyncRequestInstance { public static void main(String[] args) throws Exception { - LiteProducer liteProducer = null; + EventMeshHttpProducer eventMeshHttpProducer = null; String eventMeshIPPort = "127.0.0.1:10105"; String topic = "EventMesh.SyncRequestInstance"; try { @@ -49,28 +50,28 @@ public static void main(String[] args) throws Exception { eventMeshIPPort = "127.0.0.1:10105"; } - LiteClientConfig eventMeshClientConfig = new LiteClientConfig(); + EventMeshHttpClientConfig eventMeshClientConfig = new EventMeshHttpClientConfig(); eventMeshClientConfig.setLiteEventMeshAddr(eventMeshIPPort) .setProducerGroup("EventMeshTest-producerGroup") .setEnv("env") .setIdc("idc") - .setIp(IPUtil.getLocalAddress()) + .setIp(IPUtils.getLocalAddress()) .setSys("1234") - .setPid(String.valueOf(ThreadUtil.getPID())); + .setPid(String.valueOf(ThreadUtils.getPID())); - liteProducer = new LiteProducer(eventMeshClientConfig); - liteProducer.start(); + eventMeshHttpProducer = new EventMeshHttpProducer(eventMeshClientConfig); + eventMeshHttpProducer.start(); long startTime = System.currentTimeMillis(); - LiteMessage liteMessage = new LiteMessage(); - liteMessage.setBizSeqNo(RandomStringUtil.generateNum(30)) + EventMeshMessage eventMeshMessage = new EventMeshMessage(); + eventMeshMessage.setBizSeqNo(RandomStringUtils.generateNum(30)) .setContent("contentStr with special protocal") .setTopic(topic) - .setUniqueId(RandomStringUtil.generateNum(30)); + .setUniqueId(RandomStringUtils.generateNum(30)); - LiteMessage rsp = liteProducer.request(liteMessage, 10000); + EventMeshMessage rsp = eventMeshHttpProducer.request(eventMeshMessage, 10000); if (logger.isDebugEnabled()) { - logger.debug("sendmsg : {}, return : {}, cost:{}ms", liteMessage.getContent(), rsp.getContent(), System.currentTimeMillis() - startTime); + logger.debug("sendmsg : {}, return : {}, cost:{}ms", eventMeshMessage.getContent(), rsp.getContent(), System.currentTimeMillis() - startTime); } } catch (Exception e) { logger.warn("send msg failed", e); @@ -78,8 +79,8 @@ public static void main(String[] args) throws Exception { try { Thread.sleep(30000); - if (liteProducer != null) { - liteProducer.shutdown(); + if (eventMeshHttpProducer != null) { + eventMeshHttpProducer.shutdown(); } } catch (Exception e1) { logger.warn("producer shutdown exception", e1); diff --git a/eventmesh-examples/src/main/java/org/apache/eventmesh/http/demo/sub/service/SubService.java b/eventmesh-examples/src/main/java/org/apache/eventmesh/http/demo/sub/service/SubService.java index 0772fca952..6470c770df 100644 --- a/eventmesh-examples/src/main/java/org/apache/eventmesh/http/demo/sub/service/SubService.java +++ b/eventmesh-examples/src/main/java/org/apache/eventmesh/http/demo/sub/service/SubService.java @@ -19,48 +19,50 @@ package org.apache.eventmesh.http.demo.sub.service; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Properties; -import java.util.concurrent.CountDownLatch; -import org.apache.commons.lang3.StringUtils; -import org.apache.eventmesh.client.http.conf.LiteClientConfig; -import org.apache.eventmesh.client.http.consumer.LiteConsumer; -import org.apache.eventmesh.common.EventMeshException; -import org.apache.eventmesh.common.IPUtil; -import org.apache.eventmesh.common.ThreadUtil; -import org.apache.eventmesh.common.protocol.SubscriptionType; +import org.apache.eventmesh.client.http.conf.EventMeshHttpClientConfig; +import org.apache.eventmesh.client.http.consumer.EventMeshHttpConsumer; import org.apache.eventmesh.common.protocol.SubscriptionItem; import org.apache.eventmesh.common.protocol.SubscriptionMode; +import org.apache.eventmesh.common.protocol.SubscriptionType; +import org.apache.eventmesh.common.utils.IPUtils; +import org.apache.eventmesh.common.utils.ThreadUtils; import org.apache.eventmesh.http.demo.AsyncPublishInstance; import org.apache.eventmesh.util.Utils; + +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; +import java.util.concurrent.CountDownLatch; + +import javax.annotation.PreDestroy; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.stereotype.Component; -import javax.annotation.PreDestroy; + +import com.google.common.collect.Lists; @Component public class SubService implements InitializingBean { public static Logger logger = LoggerFactory.getLogger(SubService.class); - private LiteConsumer liteConsumer; - - private String eventMeshIPPort = ""; + private EventMeshHttpConsumer eventMeshHttpConsumer; final Properties properties = Utils.readPropertiesFile("application.properties"); - final List topicList = Arrays.asList(new SubscriptionItem("TEST-TOPIC-HTTP-ASYNC", SubscriptionMode.CLUSTERING, SubscriptionType.ASYNC)); - final String localIp = IPUtil.getLocalAddress(); - final String localPort = properties.getProperty("server.port"); - final String eventMeshIp = properties.getProperty("eventmesh.ip"); - final String eventMeshHttpPort = properties.getProperty("eventmesh.http.port"); - final String url = "http://" + localIp + ":" + localPort + "/sub/test"; - final String env = "P"; - final String idc = "FT"; - final String subsys = "1234"; + final List topicList = Lists.newArrayList( + new SubscriptionItem("TEST-TOPIC-HTTP-ASYNC", SubscriptionMode.CLUSTERING, SubscriptionType.ASYNC) + ); + final String localIp = IPUtils.getLocalAddress(); + final String localPort = properties.getProperty("server.port"); + final String eventMeshIp = properties.getProperty("eventmesh.ip"); + final String eventMeshHttpPort = properties.getProperty("eventmesh.http.port"); + final String url = "http://" + localIp + ":" + localPort + "/sub/test"; + final String env = "P"; + final String idc = "FT"; + final String subsys = "1234"; // CountDownLatch size is the same as messageSize in AsyncPublishInstance.java (Publisher) private CountDownLatch countDownLatch = new CountDownLatch(AsyncPublishInstance.messageSize); @@ -68,23 +70,19 @@ public class SubService implements InitializingBean { @Override public void afterPropertiesSet() throws Exception { - if (StringUtils.isBlank(eventMeshIPPort)) { - // if has multi value, can config as: 127.0.0.1:10105;127.0.0.2:10105 - eventMeshIPPort = eventMeshIp + ":" + eventMeshHttpPort; - } - LiteClientConfig eventMeshClientConfig = new LiteClientConfig(); - eventMeshClientConfig.setLiteEventMeshAddr(eventMeshIPPort) - .setConsumerGroup("EventMeshTest-consumerGroup") - .setEnv(env) - .setIdc(idc) - .setIp(IPUtil.getLocalAddress()) - .setSys(subsys) - .setPid(String.valueOf(ThreadUtil.getPID())); - - liteConsumer = new LiteConsumer(eventMeshClientConfig); - liteConsumer.start(); - liteConsumer.heartBeat(topicList, url); - liteConsumer.subscribe(topicList, url); + final String eventMeshIPPort = eventMeshIp + ":" + eventMeshHttpPort; + EventMeshHttpClientConfig eventMeshClientConfig = EventMeshHttpClientConfig.builder() + .liteEventMeshAddr(eventMeshIPPort) + .consumerGroup("EventMeshTest-consumerGroup") + .env(env) + .idc(idc) + .ip(IPUtils.getLocalAddress()) + .sys(subsys) + .pid(String.valueOf(ThreadUtils.getPID())).build(); + + eventMeshHttpConsumer = new EventMeshHttpConsumer(eventMeshClientConfig); + eventMeshHttpConsumer.heartBeat(topicList, url); + eventMeshHttpConsumer.subscribe(topicList, url); // Wait for all messaged to be consumed Thread stopThread = new Thread(() -> { @@ -104,15 +102,15 @@ public void cleanup() { logger.info("start destory ...."); try { List unSubList = new ArrayList<>(); - for (SubscriptionItem item:topicList) { + for (SubscriptionItem item : topicList) { unSubList.add(item.getTopic()); } - liteConsumer.unsubscribe(unSubList, url); + eventMeshHttpConsumer.unsubscribe(unSubList, url); } catch (Exception e) { e.printStackTrace(); } - try { - liteConsumer.shutdown(); + try (final EventMeshHttpConsumer ignore = eventMeshHttpConsumer) { + // close consumer } catch (Exception e) { e.printStackTrace(); } diff --git a/eventmesh-examples/src/main/java/org/apache/eventmesh/tcp/demo/AsyncPublish.java b/eventmesh-examples/src/main/java/org/apache/eventmesh/tcp/demo/AsyncPublish.java index 4cbac1923a..90bd4c794a 100644 --- a/eventmesh-examples/src/main/java/org/apache/eventmesh/tcp/demo/AsyncPublish.java +++ b/eventmesh-examples/src/main/java/org/apache/eventmesh/tcp/demo/AsyncPublish.java @@ -19,9 +19,9 @@ import java.util.Properties; -import org.apache.eventmesh.client.tcp.EventMeshClient; +import org.apache.eventmesh.client.tcp.EventMeshTCPClient; import org.apache.eventmesh.client.tcp.common.EventMeshCommon; -import org.apache.eventmesh.client.tcp.impl.DefaultEventMeshClient; +import org.apache.eventmesh.client.tcp.impl.DefaultEventMeshTCPClient; import org.apache.eventmesh.common.protocol.tcp.Package; import org.apache.eventmesh.common.protocol.tcp.UserAgent; import org.apache.eventmesh.tcp.common.EventMeshTestUtils; @@ -33,7 +33,7 @@ public class AsyncPublish { public static Logger logger = LoggerFactory.getLogger(AsyncPublish.class); - private static EventMeshClient client; + private static EventMeshTCPClient client; public static AsyncPublish handler = new AsyncPublish(); @@ -43,7 +43,7 @@ public static void main(String[] agrs) throws Exception { final int eventMeshTcpPort = Integer.parseInt(properties.getProperty("eventmesh.tcp.port")); try { UserAgent userAgent = EventMeshTestUtils.generateClient1(); - client = new DefaultEventMeshClient(eventMeshIp, eventMeshTcpPort, userAgent); + client = new DefaultEventMeshTCPClient(eventMeshIp, eventMeshTcpPort, userAgent); client.init(); client.heartbeat(); diff --git a/eventmesh-examples/src/main/java/org/apache/eventmesh/tcp/demo/AsyncPublishBroadcast.java b/eventmesh-examples/src/main/java/org/apache/eventmesh/tcp/demo/AsyncPublishBroadcast.java index 4803daec19..f1dadef505 100644 --- a/eventmesh-examples/src/main/java/org/apache/eventmesh/tcp/demo/AsyncPublishBroadcast.java +++ b/eventmesh-examples/src/main/java/org/apache/eventmesh/tcp/demo/AsyncPublishBroadcast.java @@ -19,9 +19,9 @@ import java.util.Properties; -import org.apache.eventmesh.client.tcp.EventMeshClient; +import org.apache.eventmesh.client.tcp.EventMeshTCPClient; import org.apache.eventmesh.client.tcp.common.EventMeshCommon; -import org.apache.eventmesh.client.tcp.impl.DefaultEventMeshClient; +import org.apache.eventmesh.client.tcp.impl.DefaultEventMeshTCPClient; import org.apache.eventmesh.common.protocol.tcp.Package; import org.apache.eventmesh.common.protocol.tcp.UserAgent; import org.apache.eventmesh.tcp.common.EventMeshTestUtils; @@ -33,7 +33,7 @@ public class AsyncPublishBroadcast { public static Logger logger = LoggerFactory.getLogger(AsyncPublishBroadcast.class); - private static EventMeshClient client; + private static EventMeshTCPClient client; public static void main(String[] agrs) throws Exception { Properties properties = Utils.readPropertiesFile("application.properties"); @@ -41,7 +41,7 @@ public static void main(String[] agrs) throws Exception { final int eventMeshTcpPort = Integer.parseInt(properties.getProperty("eventmesh.tcp.port")); try { UserAgent userAgent = EventMeshTestUtils.generateClient1(); - client = new DefaultEventMeshClient(eventMeshIp, eventMeshTcpPort, userAgent); + client = new DefaultEventMeshTCPClient(eventMeshIp, eventMeshTcpPort, userAgent); client.init(); client.heartbeat(); diff --git a/eventmesh-examples/src/main/java/org/apache/eventmesh/tcp/demo/AsyncSubscribe.java b/eventmesh-examples/src/main/java/org/apache/eventmesh/tcp/demo/AsyncSubscribe.java index f9b910857b..18d607a84b 100644 --- a/eventmesh-examples/src/main/java/org/apache/eventmesh/tcp/demo/AsyncSubscribe.java +++ b/eventmesh-examples/src/main/java/org/apache/eventmesh/tcp/demo/AsyncSubscribe.java @@ -17,28 +17,26 @@ package org.apache.eventmesh.tcp.demo; -import java.util.Properties; - -import io.netty.channel.ChannelHandlerContext; - -import org.apache.eventmesh.client.tcp.EventMeshClient; +import org.apache.eventmesh.client.tcp.EventMeshTCPClient; import org.apache.eventmesh.client.tcp.common.ReceiveMsgHook; -import org.apache.eventmesh.client.tcp.impl.DefaultEventMeshClient; +import org.apache.eventmesh.client.tcp.impl.DefaultEventMeshTCPClient; +import org.apache.eventmesh.common.protocol.SubscriptionMode; import org.apache.eventmesh.common.protocol.SubscriptionType; import org.apache.eventmesh.common.protocol.tcp.EventMeshMessage; import org.apache.eventmesh.common.protocol.tcp.Package; -import org.apache.eventmesh.common.protocol.SubscriptionMode; import org.apache.eventmesh.common.protocol.tcp.UserAgent; import org.apache.eventmesh.tcp.common.EventMeshTestUtils; import org.apache.eventmesh.util.Utils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -public class AsyncSubscribe implements ReceiveMsgHook { +import java.util.Properties; + +import io.netty.channel.ChannelHandlerContext; +import lombok.extern.slf4j.Slf4j; - public static Logger logger = LoggerFactory.getLogger(AsyncSubscribe.class); +@Slf4j +public class AsyncSubscribe implements ReceiveMsgHook { - private static EventMeshClient client; + private static EventMeshTCPClient client; public static AsyncSubscribe handler = new AsyncSubscribe(); @@ -48,7 +46,7 @@ public static void main(String[] agrs) throws Exception { final int eventMeshTcpPort = Integer.parseInt(properties.getProperty("eventmesh.tcp.port")); try { UserAgent userAgent = EventMeshTestUtils.generateClient2(); - client = new DefaultEventMeshClient(eventMeshIp, eventMeshTcpPort, userAgent); + client = new DefaultEventMeshTCPClient(eventMeshIp, eventMeshTcpPort, userAgent); client.init(); client.heartbeat(); @@ -57,23 +55,19 @@ public static void main(String[] agrs) throws Exception { client.listen(); - //client.unsubscribe(); - - // release resource and close client - // client.close(); } catch (Exception e) { - logger.warn("AsyncSubscribe failed", e); + log.warn("AsyncSubscribe failed", e); } } @Override public void handle(Package msg, ChannelHandlerContext ctx) { - EventMeshMessage eventMeshMessage = convert(msg); - logger.info("receive async msg====================={}", eventMeshMessage); + EventMeshMessage eventMeshMessage = convertToProtocolMessage(msg); + log.info("receive async msg====================={}", eventMeshMessage); } @Override - public EventMeshMessage convert(Package pkg) { + public EventMeshMessage convertToProtocolMessage(Package pkg) { return (EventMeshMessage) pkg.getBody(); } } diff --git a/eventmesh-examples/src/main/java/org/apache/eventmesh/tcp/demo/AsyncSubscribeBroadcast.java b/eventmesh-examples/src/main/java/org/apache/eventmesh/tcp/demo/AsyncSubscribeBroadcast.java index 5381c8ff5f..1d6c6d107c 100644 --- a/eventmesh-examples/src/main/java/org/apache/eventmesh/tcp/demo/AsyncSubscribeBroadcast.java +++ b/eventmesh-examples/src/main/java/org/apache/eventmesh/tcp/demo/AsyncSubscribeBroadcast.java @@ -17,28 +17,26 @@ package org.apache.eventmesh.tcp.demo; -import java.util.Properties; - -import io.netty.channel.ChannelHandlerContext; - -import org.apache.eventmesh.client.tcp.EventMeshClient; +import org.apache.eventmesh.client.tcp.EventMeshTCPClient; import org.apache.eventmesh.client.tcp.common.ReceiveMsgHook; -import org.apache.eventmesh.client.tcp.impl.DefaultEventMeshClient; +import org.apache.eventmesh.client.tcp.impl.DefaultEventMeshTCPClient; +import org.apache.eventmesh.common.protocol.SubscriptionMode; import org.apache.eventmesh.common.protocol.SubscriptionType; import org.apache.eventmesh.common.protocol.tcp.EventMeshMessage; import org.apache.eventmesh.common.protocol.tcp.Package; -import org.apache.eventmesh.common.protocol.SubscriptionMode; import org.apache.eventmesh.common.protocol.tcp.UserAgent; import org.apache.eventmesh.tcp.common.EventMeshTestUtils; import org.apache.eventmesh.util.Utils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -public class AsyncSubscribeBroadcast implements ReceiveMsgHook { +import java.util.Properties; + +import io.netty.channel.ChannelHandlerContext; +import lombok.extern.slf4j.Slf4j; - public static Logger logger = LoggerFactory.getLogger(AsyncSubscribeBroadcast.class); +@Slf4j +public class AsyncSubscribeBroadcast implements ReceiveMsgHook { - private static EventMeshClient client; + private static EventMeshTCPClient client; public static AsyncSubscribeBroadcast handler = new AsyncSubscribeBroadcast(); @@ -48,7 +46,7 @@ public static void main(String[] agrs) throws Exception { final int eventMeshTcpPort = Integer.parseInt(properties.getProperty("eventmesh.tcp.port")); try { UserAgent userAgent = EventMeshTestUtils.generateClient2(); - client = new DefaultEventMeshClient(eventMeshIp, eventMeshTcpPort, userAgent); + client = new DefaultEventMeshTCPClient(eventMeshIp, eventMeshTcpPort, userAgent); client.init(); client.heartbeat(); @@ -57,23 +55,19 @@ public static void main(String[] agrs) throws Exception { client.listen(); - //client.unsubscribe(); - - // release resource and close client - // client.close(); } catch (Exception e) { - logger.warn("AsyncSubscribeBroadcast failed", e); + log.warn("AsyncSubscribeBroadcast failed", e); } } @Override public void handle(Package msg, ChannelHandlerContext ctx) { - EventMeshMessage eventMeshMessage = convert(msg); - logger.info("receive broadcast msg==============={}", eventMeshMessage); + EventMeshMessage eventMeshMessage = convertToProtocolMessage(msg); + log.info("receive broadcast msg==============={}", eventMeshMessage); } @Override - public EventMeshMessage convert(Package pkg) { + public EventMeshMessage convertToProtocolMessage(Package pkg) { return (EventMeshMessage) pkg.getBody(); } } diff --git a/eventmesh-examples/src/main/java/org/apache/eventmesh/tcp/demo/SyncRequest.java b/eventmesh-examples/src/main/java/org/apache/eventmesh/tcp/demo/SyncRequest.java index 15f01e155e..65339de3a9 100644 --- a/eventmesh-examples/src/main/java/org/apache/eventmesh/tcp/demo/SyncRequest.java +++ b/eventmesh-examples/src/main/java/org/apache/eventmesh/tcp/demo/SyncRequest.java @@ -17,13 +17,12 @@ package org.apache.eventmesh.tcp.demo; -import org.apache.eventmesh.client.tcp.EventMeshClient; +import org.apache.eventmesh.client.tcp.EventMeshTCPClient; import org.apache.eventmesh.client.tcp.common.EventMeshCommon; -import org.apache.eventmesh.client.tcp.impl.DefaultEventMeshClient; +import org.apache.eventmesh.client.tcp.impl.DefaultEventMeshTCPClient; import org.apache.eventmesh.common.protocol.tcp.Package; import org.apache.eventmesh.common.protocol.tcp.UserAgent; import org.apache.eventmesh.tcp.common.EventMeshTestUtils; -import org.apache.eventmesh.common.protocol.tcp.Package; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -32,12 +31,12 @@ public class SyncRequest { public static Logger logger = LoggerFactory.getLogger(SyncRequest.class); - private static EventMeshClient client; + private static EventMeshTCPClient client; public static void main(String[] agrs) throws Exception { try { UserAgent userAgent = EventMeshTestUtils.generateClient1(); - client = new DefaultEventMeshClient("127.0.0.1", 10000, userAgent); + client = new DefaultEventMeshTCPClient("127.0.0.1", 10000, userAgent); client.init(); client.heartbeat(); diff --git a/eventmesh-examples/src/main/java/org/apache/eventmesh/tcp/demo/SyncResponse.java b/eventmesh-examples/src/main/java/org/apache/eventmesh/tcp/demo/SyncResponse.java index 0eb4f77d30..026fa11d80 100644 --- a/eventmesh-examples/src/main/java/org/apache/eventmesh/tcp/demo/SyncResponse.java +++ b/eventmesh-examples/src/main/java/org/apache/eventmesh/tcp/demo/SyncResponse.java @@ -17,32 +17,28 @@ package org.apache.eventmesh.tcp.demo; -import io.netty.channel.ChannelHandlerContext; - -import org.apache.eventmesh.client.tcp.EventMeshClient; +import org.apache.eventmesh.client.tcp.EventMeshTCPClient; import org.apache.eventmesh.client.tcp.common.ReceiveMsgHook; -import org.apache.eventmesh.client.tcp.impl.DefaultEventMeshClient; +import org.apache.eventmesh.client.tcp.impl.DefaultEventMeshTCPClient; +import org.apache.eventmesh.common.protocol.SubscriptionMode; import org.apache.eventmesh.common.protocol.SubscriptionType; import org.apache.eventmesh.common.protocol.tcp.EventMeshMessage; import org.apache.eventmesh.common.protocol.tcp.Package; -import org.apache.eventmesh.common.protocol.SubscriptionMode; import org.apache.eventmesh.common.protocol.tcp.UserAgent; import org.apache.eventmesh.tcp.common.EventMeshTestUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -public class SyncResponse implements ReceiveMsgHook { - - public static Logger logger = LoggerFactory.getLogger(SyncResponse.class); +import io.netty.channel.ChannelHandlerContext; +import lombok.extern.slf4j.Slf4j; - private static EventMeshClient client; +@Slf4j +public class SyncResponse implements ReceiveMsgHook { public static SyncResponse handler = new SyncResponse(); public static void main(String[] agrs) throws Exception { try { UserAgent userAgent = EventMeshTestUtils.generateClient2(); - client = new DefaultEventMeshClient("127.0.0.1", 10000, userAgent); + EventMeshTCPClient client = new DefaultEventMeshTCPClient("127.0.0.1", 10000, userAgent); client.init(); client.heartbeat(); @@ -52,24 +48,20 @@ public static void main(String[] agrs) throws Exception { client.listen(); - //client.unsubscribe(); - - // release resource and close client - // client.close(); } catch (Exception e) { - logger.warn("SyncResponse failed", e); + log.warn("SyncResponse failed", e); } } @Override public void handle(Package msg, ChannelHandlerContext ctx) { - logger.info("receive sync rr msg================{}", msg); + log.info("receive sync rr msg================{}", msg); Package pkg = EventMeshTestUtils.rrResponse(msg); ctx.writeAndFlush(pkg); } @Override - public EventMeshMessage convert(Package pkg) { + public EventMeshMessage convertToProtocolMessage(Package pkg) { return null; } } diff --git a/eventmesh-examples/src/main/java/org/apache/eventmesh/util/Utils.java b/eventmesh-examples/src/main/java/org/apache/eventmesh/util/Utils.java index 6911a4388b..a20e1dcedc 100644 --- a/eventmesh-examples/src/main/java/org/apache/eventmesh/util/Utils.java +++ b/eventmesh-examples/src/main/java/org/apache/eventmesh/util/Utils.java @@ -17,6 +17,7 @@ package org.apache.eventmesh.util; +import java.io.InputStream; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; @@ -24,10 +25,6 @@ import java.util.Enumeration; import java.util.Properties; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; -import org.springframework.core.io.support.PropertiesLoaderUtils; - public class Utils { /** @@ -71,12 +68,13 @@ private static String getLinuxLocalIp() throws SocketException { NetworkInterface intf = en.nextElement(); String name = intf.getName(); if (!name.contains("docker") && !name.contains("lo")) { - for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) { + for (Enumeration enumIpAddr = intf.getInetAddresses(); + enumIpAddr.hasMoreElements(); ) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { String ipaddress = inetAddress.getHostAddress().toString(); if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") - && !ipaddress.contains("fe80")) { + && !ipaddress.contains("fe80")) { ip = ipaddress; } } @@ -95,14 +93,13 @@ private static String getLinuxLocalIp() throws SocketException { * @return */ public static Properties readPropertiesFile(String fileName) { - try { - Resource resource = new ClassPathResource(fileName); - Properties props = PropertiesLoaderUtils.loadProperties(resource); - return props; + try (final InputStream inputStream = Utils.class.getClassLoader().getResourceAsStream(fileName)) { + Properties properties = new Properties(); + properties.load(inputStream); + return properties; } catch (Exception e) { - e.printStackTrace(); + throw new IllegalArgumentException(String.format("File: %s is not exist", fileName)); } - return null; } } diff --git a/eventmesh-protocol-plugin/eventmesh-protocol-api/src/main/java/org/apache/eventmesh/protocol/api/ProtocolAdaptor.java b/eventmesh-protocol-plugin/eventmesh-protocol-api/src/main/java/org/apache/eventmesh/protocol/api/ProtocolAdaptor.java index e8b854effd..43ba72401b 100644 --- a/eventmesh-protocol-plugin/eventmesh-protocol-api/src/main/java/org/apache/eventmesh/protocol/api/ProtocolAdaptor.java +++ b/eventmesh-protocol-plugin/eventmesh-protocol-api/src/main/java/org/apache/eventmesh/protocol/api/ProtocolAdaptor.java @@ -17,14 +17,12 @@ package org.apache.eventmesh.protocol.api; -import org.apache.eventmesh.common.ProtocolTransportObject; -import org.apache.eventmesh.common.protocol.tcp.Package; +import org.apache.eventmesh.common.protocol.ProtocolTransportObject; import org.apache.eventmesh.protocol.api.exception.ProtocolHandleException; import org.apache.eventmesh.spi.EventMeshExtensionType; import org.apache.eventmesh.spi.EventMeshSPI; import io.cloudevents.CloudEvent; -import io.cloudevents.core.v1.CloudEventV1; import java.util.List; diff --git a/eventmesh-protocol-plugin/eventmesh-protocol-api/src/main/java/org/apache/eventmesh/protocol/api/ProtocolPluginFactory.java b/eventmesh-protocol-plugin/eventmesh-protocol-api/src/main/java/org/apache/eventmesh/protocol/api/ProtocolPluginFactory.java index fd0de78707..2d6f7bd559 100644 --- a/eventmesh-protocol-plugin/eventmesh-protocol-api/src/main/java/org/apache/eventmesh/protocol/api/ProtocolPluginFactory.java +++ b/eventmesh-protocol-plugin/eventmesh-protocol-api/src/main/java/org/apache/eventmesh/protocol/api/ProtocolPluginFactory.java @@ -17,7 +17,7 @@ package org.apache.eventmesh.protocol.api; -import org.apache.eventmesh.common.ProtocolTransportObject; +import org.apache.eventmesh.common.protocol.ProtocolTransportObject; import org.apache.eventmesh.spi.EventMeshExtensionFactory; import java.util.Map; diff --git a/eventmesh-protocol-plugin/eventmesh-protocol-cloudevents/src/main/java/org/apache/eventmesh/protocol/cloudevents/CloudEventsProtocolAdaptor.java b/eventmesh-protocol-plugin/eventmesh-protocol-cloudevents/src/main/java/org/apache/eventmesh/protocol/cloudevents/CloudEventsProtocolAdaptor.java index b9bb8e20b9..56fe0534a9 100644 --- a/eventmesh-protocol-plugin/eventmesh-protocol-cloudevents/src/main/java/org/apache/eventmesh/protocol/cloudevents/CloudEventsProtocolAdaptor.java +++ b/eventmesh-protocol-plugin/eventmesh-protocol-cloudevents/src/main/java/org/apache/eventmesh/protocol/cloudevents/CloudEventsProtocolAdaptor.java @@ -20,8 +20,8 @@ import io.cloudevents.CloudEvent; import org.apache.commons.lang3.StringUtils; import org.apache.eventmesh.common.Constants; -import org.apache.eventmesh.common.ProtocolTransportObject; -import org.apache.eventmesh.common.command.HttpCommand; +import org.apache.eventmesh.common.protocol.ProtocolTransportObject; +import org.apache.eventmesh.common.protocol.http.HttpCommand; import org.apache.eventmesh.common.protocol.http.body.Body; import org.apache.eventmesh.common.protocol.http.common.RequestCode; import org.apache.eventmesh.common.protocol.tcp.Header; @@ -33,7 +33,6 @@ import org.apache.eventmesh.protocol.cloudevents.resolver.http.SendMessageRequestProtocolResolver; import org.apache.eventmesh.protocol.cloudevents.resolver.tcp.TcpMessageProtocolResolver; -import java.nio.charset.StandardCharsets; import java.util.List; /** diff --git a/eventmesh-protocol-plugin/eventmesh-protocol-cloudevents/src/test/java/org/apache/eventmesh/protocol/cloudevents/CloudEventsProtocolAdaptorTest.java b/eventmesh-protocol-plugin/eventmesh-protocol-cloudevents/src/test/java/org/apache/eventmesh/protocol/cloudevents/CloudEventsProtocolAdaptorTest.java index 7cbb9ab481..5155cf6e84 100644 --- a/eventmesh-protocol-plugin/eventmesh-protocol-cloudevents/src/test/java/org/apache/eventmesh/protocol/cloudevents/CloudEventsProtocolAdaptorTest.java +++ b/eventmesh-protocol-plugin/eventmesh-protocol-cloudevents/src/test/java/org/apache/eventmesh/protocol/cloudevents/CloudEventsProtocolAdaptorTest.java @@ -17,6 +17,7 @@ package org.apache.eventmesh.protocol.cloudevents; +import org.apache.eventmesh.common.protocol.ProtocolTransportObject; import org.apache.eventmesh.protocol.api.ProtocolAdaptor; import org.apache.eventmesh.protocol.api.ProtocolPluginFactory; @@ -27,7 +28,7 @@ public class CloudEventsProtocolAdaptorTest { @Test public void loadPlugin() { - ProtocolAdaptor protocolAdaptor = + ProtocolAdaptor protocolAdaptor = ProtocolPluginFactory.getProtocolAdaptor(CloudEventsProtocolConstant.PROTOCOL_NAME); Assert.assertNotNull(protocolAdaptor); diff --git a/eventmesh-protocol-plugin/eventmesh-protocol-meshmessage/src/main/java/org/apache/eventmesh/protocol/meshmessage/MeshMessageProtocolAdaptor.java b/eventmesh-protocol-plugin/eventmesh-protocol-meshmessage/src/main/java/org/apache/eventmesh/protocol/meshmessage/MeshMessageProtocolAdaptor.java index 378114715c..c1e636e734 100644 --- a/eventmesh-protocol-plugin/eventmesh-protocol-meshmessage/src/main/java/org/apache/eventmesh/protocol/meshmessage/MeshMessageProtocolAdaptor.java +++ b/eventmesh-protocol-plugin/eventmesh-protocol-meshmessage/src/main/java/org/apache/eventmesh/protocol/meshmessage/MeshMessageProtocolAdaptor.java @@ -17,11 +17,9 @@ package org.apache.eventmesh.protocol.meshmessage; -import io.cloudevents.CloudEvent; -import org.apache.commons.lang3.StringUtils; import org.apache.eventmesh.common.Constants; -import org.apache.eventmesh.common.ProtocolTransportObject; -import org.apache.eventmesh.common.command.HttpCommand; +import org.apache.eventmesh.common.protocol.ProtocolTransportObject; +import org.apache.eventmesh.common.protocol.http.HttpCommand; import org.apache.eventmesh.common.protocol.http.body.Body; import org.apache.eventmesh.common.protocol.http.common.RequestCode; import org.apache.eventmesh.common.protocol.tcp.Header; @@ -33,11 +31,13 @@ import org.apache.eventmesh.protocol.meshmessage.resolver.http.SendMessageRequestProtocolResolver; import org.apache.eventmesh.protocol.meshmessage.resolver.tcp.TcpMessageProtocolResolver; -import java.nio.charset.StandardCharsets; +import org.apache.commons.lang3.StringUtils; + import java.util.List; -public class MeshMessageProtocolAdaptor - implements ProtocolAdaptor { +import io.cloudevents.CloudEvent; + +public class MeshMessageProtocolAdaptor implements ProtocolAdaptor { @Override public CloudEvent toCloudEvent(ProtocolTransportObject protocol) throws ProtocolHandleException { @@ -62,7 +62,9 @@ private CloudEvent deserializeTcpProtocol(Header header, Object body) throws Pro return TcpMessageProtocolResolver.buildEvent(header, body); } - private CloudEvent deserializeHttpProtocol(String requestCode, org.apache.eventmesh.common.protocol.http.header.Header header, Body body) throws ProtocolHandleException { + private CloudEvent deserializeHttpProtocol(String requestCode, + org.apache.eventmesh.common.protocol.http.header.Header header, + Body body) throws ProtocolHandleException { if (String.valueOf(RequestCode.MSG_BATCH_SEND.getRequestCode()).equals(requestCode)) { return SendMessageBatchProtocolResolver.buildEvent(header, body); diff --git a/eventmesh-protocol-plugin/eventmesh-protocol-openmessage/src/main/java/org/apache/eventmesh/protocol/openmessage/OpenMessageProtocolAdaptor.java b/eventmesh-protocol-plugin/eventmesh-protocol-openmessage/src/main/java/org/apache/eventmesh/protocol/openmessage/OpenMessageProtocolAdaptor.java index 1492a28453..00a48b19a8 100644 --- a/eventmesh-protocol-plugin/eventmesh-protocol-openmessage/src/main/java/org/apache/eventmesh/protocol/openmessage/OpenMessageProtocolAdaptor.java +++ b/eventmesh-protocol-plugin/eventmesh-protocol-openmessage/src/main/java/org/apache/eventmesh/protocol/openmessage/OpenMessageProtocolAdaptor.java @@ -17,12 +17,10 @@ package org.apache.eventmesh.protocol.openmessage; -import org.apache.eventmesh.common.ProtocolTransportObject; -import org.apache.eventmesh.common.protocol.tcp.Package; +import org.apache.eventmesh.common.protocol.ProtocolTransportObject; import org.apache.eventmesh.protocol.api.ProtocolAdaptor; import io.cloudevents.CloudEvent; -import io.cloudevents.core.v1.CloudEventV1; import io.openmessaging.api.Message; import org.apache.eventmesh.protocol.api.exception.ProtocolHandleException; diff --git a/eventmesh-protocol-plugin/eventmesh-protocol-openmessage/src/test/java/org/apache/eventmesh/protocol/openmessage/OpenMessageProtocolAdaptorTest.java b/eventmesh-protocol-plugin/eventmesh-protocol-openmessage/src/test/java/org/apache/eventmesh/protocol/openmessage/OpenMessageProtocolAdaptorTest.java index 60c2eb6613..5d833ec580 100644 --- a/eventmesh-protocol-plugin/eventmesh-protocol-openmessage/src/test/java/org/apache/eventmesh/protocol/openmessage/OpenMessageProtocolAdaptorTest.java +++ b/eventmesh-protocol-plugin/eventmesh-protocol-openmessage/src/test/java/org/apache/eventmesh/protocol/openmessage/OpenMessageProtocolAdaptorTest.java @@ -17,6 +17,7 @@ package org.apache.eventmesh.protocol.openmessage; +import org.apache.eventmesh.common.protocol.ProtocolTransportObject; import org.apache.eventmesh.protocol.api.ProtocolAdaptor; import org.apache.eventmesh.protocol.api.ProtocolPluginFactory; @@ -27,7 +28,7 @@ public class OpenMessageProtocolAdaptorTest { @Test public void loadPlugin() { - ProtocolAdaptor protocolAdaptor = + ProtocolAdaptor protocolAdaptor = ProtocolPluginFactory.getProtocolAdaptor(OpenMessageProtocolConstant.PROTOCOL_NAME); Assert.assertNotNull(protocolAdaptor); diff --git a/eventmesh-runtime/build.gradle b/eventmesh-runtime/build.gradle index ebf498049f..2678f7ccfb 100644 --- a/eventmesh-runtime/build.gradle +++ b/eventmesh-runtime/build.gradle @@ -38,20 +38,6 @@ dependencies { implementation project(":eventmesh-protocol-plugin:eventmesh-protocol-api") - testImplementation project(":eventmesh-common") - testImplementation project(":eventmesh-spi") - testImplementation project(":eventmesh-connector-plugin:eventmesh-connector-api") - testImplementation project(":eventmesh-connector-plugin:eventmesh-connector-standalone") - testImplementation project(":eventmesh-security-plugin:eventmesh-security-api") - testImplementation project(":eventmesh-security-plugin:eventmesh-security-acl") - testImplementation project(":eventmesh-registry-plugin:eventmesh-registry-api") - testImplementation project(":eventmesh-registry-plugin:eventmesh-registry-namesrv") - - testImplementation project(":eventmesh-protocol-plugin:eventmesh-protocol-api") - - testImplementation "org.apache.httpcomponents:httpclient" - testImplementation "io.netty:netty-all" - testImplementation "org.mockito:mockito-core" testImplementation "org.powermock:powermock-module-junit4" testImplementation "org.powermock:powermock-api-mockito2" diff --git a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/boot/AbstractHTTPServer.java b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/boot/AbstractHTTPServer.java index 9b08724daa..e64882b7d7 100644 --- a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/boot/AbstractHTTPServer.java +++ b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/boot/AbstractHTTPServer.java @@ -18,7 +18,7 @@ package org.apache.eventmesh.runtime.boot; import org.apache.eventmesh.common.ThreadPoolFactory; -import org.apache.eventmesh.common.command.HttpCommand; +import org.apache.eventmesh.common.protocol.http.HttpCommand; import org.apache.eventmesh.common.protocol.http.body.Body; import org.apache.eventmesh.common.protocol.http.common.EventMeshRetCode; import org.apache.eventmesh.common.protocol.http.common.ProtocolKey; @@ -258,7 +258,8 @@ public void processEventMeshRequest(final ChannelHandlerContext ctx, try { choosed.getObject2().submit(() -> { try { - if (choosed.getObject1().rejectRequest()) { + HttpRequestProcessor processor = choosed.getObject1(); + if (processor.rejectRequest()) { HttpCommand responseCommand = request.createHttpCommandResponse(EventMeshRetCode.EVENTMESH_REJECT_BY_PROCESSOR_ERROR); asyncContext.onComplete(responseCommand); @@ -271,13 +272,13 @@ public void processEventMeshRequest(final ChannelHandlerContext ctx, return; } - choosed.getObject1().processRequest(ctx, asyncContext); + processor.processRequest(ctx, asyncContext); if (!asyncContext.isComplete()) { return; } - metrics.summaryMetrics.recordHTTPReqResTimeCost( - System.currentTimeMillis() - request.getReqTime()); + metrics.summaryMetrics + .recordHTTPReqResTimeCost(System.currentTimeMillis() - request.getReqTime()); if (httpLogger.isDebugEnabled()) { httpLogger.debug("{}", asyncContext.getResponse()); diff --git a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/boot/AbstractRemotingServer.java b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/boot/AbstractRemotingServer.java index 02f537dacf..bcf31bfd0b 100644 --- a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/boot/AbstractRemotingServer.java +++ b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/boot/AbstractRemotingServer.java @@ -23,7 +23,7 @@ import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; -import org.apache.eventmesh.common.ThreadUtil; +import org.apache.eventmesh.common.utils.ThreadUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -92,7 +92,7 @@ public void shutdown() throws Exception { logger.info("shutdown bossGroup"); } - ThreadUtil.randomSleep(30); + ThreadUtils.randomSleep(30); if (ioGroup != null) { ioGroup.shutdownGracefully(); diff --git a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/boot/EventMeshTCPServer.java b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/boot/EventMeshTCPServer.java index 6cbb130caf..9c624421f8 100644 --- a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/boot/EventMeshTCPServer.java +++ b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/boot/EventMeshTCPServer.java @@ -31,8 +31,8 @@ import org.apache.eventmesh.api.registry.dto.EventMeshRegisterInfo; import org.apache.eventmesh.api.registry.dto.EventMeshUnRegisterInfo; -import org.apache.eventmesh.common.EventMeshException; -import org.apache.eventmesh.common.IPUtil; +import org.apache.eventmesh.common.exception.EventMeshException; +import org.apache.eventmesh.common.utils.IPUtils; import org.apache.eventmesh.common.ThreadPoolFactory; import org.apache.eventmesh.common.protocol.tcp.codec.Codec; import org.apache.eventmesh.runtime.admin.controller.ClientManageController; @@ -287,7 +287,7 @@ private void selfRegisterToRegistry() throws Exception { public boolean registerToRegistry() { boolean registerResult = false; try{ - String endPoints = IPUtil.getLocalAddress() + String endPoints = IPUtils.getLocalAddress() + EventMeshConstants.IP_PORT_SEPARATOR + eventMeshTCPConfiguration.eventMeshTcpServerPort; EventMeshRegisterInfo self = new EventMeshRegisterInfo(); self.setEventMeshClusterName(eventMeshTCPConfiguration.eventMeshCluster); diff --git a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/AdminMetricsProcessor.java b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/AdminMetricsProcessor.java index 6feaf9ae22..a8153c60a6 100644 --- a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/AdminMetricsProcessor.java +++ b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/AdminMetricsProcessor.java @@ -19,7 +19,7 @@ import io.netty.channel.ChannelHandlerContext; -import org.apache.eventmesh.common.command.HttpCommand; +import org.apache.eventmesh.common.protocol.http.HttpCommand; import org.apache.eventmesh.runtime.boot.EventMeshHTTPServer; import org.apache.eventmesh.runtime.core.protocol.http.async.AsyncContext; import org.apache.eventmesh.runtime.core.protocol.http.processor.inf.HttpRequestProcessor; diff --git a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/AdminShutdownProcessor.java b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/AdminShutdownProcessor.java index ca6212afb0..97db4bba44 100644 --- a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/AdminShutdownProcessor.java +++ b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/AdminShutdownProcessor.java @@ -17,8 +17,8 @@ package org.apache.eventmesh.runtime.core.protocol.http.processor; -import org.apache.eventmesh.common.IPUtil; -import org.apache.eventmesh.common.command.HttpCommand; +import org.apache.eventmesh.common.utils.IPUtils; +import org.apache.eventmesh.common.protocol.http.HttpCommand; import org.apache.eventmesh.common.protocol.http.common.EventMeshRetCode; import org.apache.eventmesh.common.protocol.http.common.RequestCode; import org.apache.eventmesh.runtime.boot.EventMeshServer; @@ -49,7 +49,7 @@ public void processRequest(ChannelHandlerContext ctx, AsyncContext cmdLogger.info("cmd={}|{}|client2eventMesh|from={}|to={}", RequestCode.get(Integer.valueOf(asyncContext.getRequest().getRequestCode())), EventMeshConstants.PROTOCOL_HTTP, - RemotingHelper.parseChannelRemoteAddr(ctx.channel()), IPUtil.getLocalAddress()); + RemotingHelper.parseChannelRemoteAddr(ctx.channel()), IPUtils.getLocalAddress()); eventMeshServer.shutdown(); diff --git a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/BatchSendMessageProcessor.java b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/BatchSendMessageProcessor.java index fe18a31532..595df2b52c 100644 --- a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/BatchSendMessageProcessor.java +++ b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/BatchSendMessageProcessor.java @@ -26,9 +26,9 @@ import org.apache.eventmesh.api.SendCallback; import org.apache.eventmesh.api.SendResult; import org.apache.eventmesh.api.exception.OnExceptionContext; -import org.apache.eventmesh.common.Constants; -import org.apache.eventmesh.common.IPUtil; -import org.apache.eventmesh.common.command.HttpCommand; +import org.apache.eventmesh.common.protocol.ProtocolTransportObject; +import org.apache.eventmesh.common.utils.IPUtils; +import org.apache.eventmesh.common.protocol.http.HttpCommand; import org.apache.eventmesh.common.protocol.http.body.message.SendMessageBatchRequestBody; import org.apache.eventmesh.common.protocol.http.body.message.SendMessageBatchResponseBody; import org.apache.eventmesh.common.protocol.http.body.message.SendMessageRequestBody; @@ -79,17 +79,17 @@ public void processRequest(ChannelHandlerContext ctx, AsyncContext cmdLogger.info("cmd={}|{}|client2eventMesh|from={}|to={}", RequestCode.get(Integer.valueOf(asyncContext.getRequest().getRequestCode())), EventMeshConstants.PROTOCOL_HTTP, - RemotingHelper.parseChannelRemoteAddr(ctx.channel()), IPUtil.getLocalAddress()); + RemotingHelper.parseChannelRemoteAddr(ctx.channel()), IPUtils.getLocalAddress()); SendMessageBatchRequestHeader sendMessageBatchRequestHeader = (SendMessageBatchRequestHeader) asyncContext.getRequest().getHeader(); SendMessageBatchResponseHeader sendMessageBatchResponseHeader = SendMessageBatchResponseHeader.buildHeader(Integer.valueOf(asyncContext.getRequest().getRequestCode()), eventMeshHTTPServer.getEventMeshHttpConfiguration().eventMeshCluster, - IPUtil.getLocalAddress(), eventMeshHTTPServer.getEventMeshHttpConfiguration().eventMeshEnv, + IPUtils.getLocalAddress(), eventMeshHTTPServer.getEventMeshHttpConfiguration().eventMeshEnv, eventMeshHTTPServer.getEventMeshHttpConfiguration().eventMeshIDC); String protocolType = sendMessageBatchRequestHeader.getProtocolType(); - ProtocolAdaptor httpCommandProtocolAdaptor = ProtocolPluginFactory.getProtocolAdaptor(protocolType); + ProtocolAdaptor httpCommandProtocolAdaptor = ProtocolPluginFactory.getProtocolAdaptor(protocolType); List eventList = httpCommandProtocolAdaptor.toBatchCloudEvent(asyncContext.getRequest()); if (CollectionUtils.isEmpty(eventList)) { diff --git a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/BatchSendMessageV2Processor.java b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/BatchSendMessageV2Processor.java index 2787142e7d..d568fce77c 100644 --- a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/BatchSendMessageV2Processor.java +++ b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/BatchSendMessageV2Processor.java @@ -20,9 +20,9 @@ import org.apache.eventmesh.api.SendCallback; import org.apache.eventmesh.api.SendResult; import org.apache.eventmesh.api.exception.OnExceptionContext; -import org.apache.eventmesh.common.IPUtil; -import org.apache.eventmesh.common.ProtocolTransportObject; -import org.apache.eventmesh.common.command.HttpCommand; +import org.apache.eventmesh.common.utils.IPUtils; +import org.apache.eventmesh.common.protocol.ProtocolTransportObject; +import org.apache.eventmesh.common.protocol.http.HttpCommand; import org.apache.eventmesh.common.protocol.http.body.message.SendMessageBatchV2RequestBody; import org.apache.eventmesh.common.protocol.http.body.message.SendMessageBatchV2ResponseBody; import org.apache.eventmesh.common.protocol.http.body.message.SendMessageRequestBody; @@ -81,7 +81,7 @@ public void processRequest(ChannelHandlerContext ctx, AsyncContext cmdLogger.info("cmd={}|{}|client2eventMesh|from={}|to={}", RequestCode.get(requestCode), EventMeshConstants.PROTOCOL_HTTP, - RemotingHelper.parseChannelRemoteAddr(ctx.channel()), IPUtil.getLocalAddress()); + RemotingHelper.parseChannelRemoteAddr(ctx.channel()), IPUtils.getLocalAddress()); SendMessageBatchV2RequestHeader sendMessageBatchV2RequestHeader = (SendMessageBatchV2RequestHeader) asyncContext.getRequest().getHeader(); @@ -95,7 +95,7 @@ public void processRequest(ChannelHandlerContext ctx, AsyncContext SendMessageBatchV2ResponseHeader.buildHeader( requestCode, eventMeshHTTPServer.getEventMeshHttpConfiguration().eventMeshCluster, - IPUtil.getLocalAddress(), + IPUtils.getLocalAddress(), eventMeshHTTPServer.getEventMeshHttpConfiguration().eventMeshEnv, eventMeshHTTPServer.getEventMeshHttpConfiguration().eventMeshIDC ); diff --git a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/HeartBeatProcessor.java b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/HeartBeatProcessor.java index 3fefd5157b..45e21dae42 100644 --- a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/HeartBeatProcessor.java +++ b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/HeartBeatProcessor.java @@ -17,8 +17,8 @@ package org.apache.eventmesh.runtime.core.protocol.http.processor; -import org.apache.eventmesh.common.IPUtil; -import org.apache.eventmesh.common.command.HttpCommand; +import org.apache.eventmesh.common.utils.IPUtils; +import org.apache.eventmesh.common.protocol.http.HttpCommand; import org.apache.eventmesh.common.protocol.http.body.client.HeartbeatRequestBody; import org.apache.eventmesh.common.protocol.http.body.client.HeartbeatResponseBody; import org.apache.eventmesh.common.protocol.http.body.message.SendMessageResponseBody; @@ -68,14 +68,14 @@ public void processRequest(ChannelHandlerContext ctx, AsyncContext httpLogger.info("cmd={}|{}|client2eventMesh|from={}|to={}", RequestCode.get(Integer.valueOf(asyncContext.getRequest().getRequestCode())), EventMeshConstants.PROTOCOL_HTTP, - RemotingHelper.parseChannelRemoteAddr(ctx.channel()), IPUtil.getLocalAddress()); + RemotingHelper.parseChannelRemoteAddr(ctx.channel()), IPUtils.getLocalAddress()); HeartbeatRequestHeader heartbeatRequestHeader = (HeartbeatRequestHeader) asyncContext.getRequest().getHeader(); HeartbeatRequestBody heartbeatRequestBody = (HeartbeatRequestBody) asyncContext.getRequest().getBody(); HeartbeatResponseHeader heartbeatResponseHeader = HeartbeatResponseHeader.buildHeader(Integer.valueOf(asyncContext.getRequest().getRequestCode()), eventMeshHTTPServer.getEventMeshHttpConfiguration().eventMeshCluster, - IPUtil.getLocalAddress(), eventMeshHTTPServer.getEventMeshHttpConfiguration().eventMeshEnv, + IPUtils.getLocalAddress(), eventMeshHTTPServer.getEventMeshHttpConfiguration().eventMeshEnv, eventMeshHTTPServer.getEventMeshHttpConfiguration().eventMeshIDC); diff --git a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/ReplyMessageProcessor.java b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/ReplyMessageProcessor.java index 5b2914d6d6..ca6890bc90 100644 --- a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/ReplyMessageProcessor.java +++ b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/ReplyMessageProcessor.java @@ -20,16 +20,15 @@ import io.cloudevents.CloudEvent; import io.cloudevents.core.builder.CloudEventBuilder; import io.netty.channel.ChannelHandlerContext; -import org.apache.commons.collections4.MapUtils; + import org.apache.commons.lang3.StringUtils; import org.apache.eventmesh.api.SendCallback; import org.apache.eventmesh.api.SendResult; import org.apache.eventmesh.api.exception.OnExceptionContext; import org.apache.eventmesh.common.Constants; -import org.apache.eventmesh.common.IPUtil; -import org.apache.eventmesh.common.ProtocolTransportObject; -import org.apache.eventmesh.common.command.HttpCommand; -import org.apache.eventmesh.common.protocol.http.body.message.ReplyMessageRequestBody; +import org.apache.eventmesh.common.utils.IPUtils; +import org.apache.eventmesh.common.protocol.ProtocolTransportObject; +import org.apache.eventmesh.common.protocol.http.HttpCommand; import org.apache.eventmesh.common.protocol.http.body.message.ReplyMessageResponseBody; import org.apache.eventmesh.common.protocol.http.body.message.SendMessageRequestBody; import org.apache.eventmesh.common.protocol.http.body.message.SendMessageResponseBody; @@ -52,7 +51,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Map; import java.util.Objects; import java.util.concurrent.TimeUnit; @@ -76,7 +74,7 @@ public void processRequest(ChannelHandlerContext ctx, AsyncContext cmdLogger.info("cmd={}|{}|client2eventMesh|from={}|to={}", RequestCode.get(Integer.valueOf(asyncContext.getRequest().getRequestCode())), EventMeshConstants.PROTOCOL_HTTP, - RemotingHelper.parseChannelRemoteAddr(ctx.channel()), IPUtil.getLocalAddress()); + RemotingHelper.parseChannelRemoteAddr(ctx.channel()), IPUtils.getLocalAddress()); ReplyMessageRequestHeader replyMessageRequestHeader = (ReplyMessageRequestHeader) asyncContext.getRequest().getHeader(); // ReplyMessageRequestBody replyMessageRequestBody = (ReplyMessageRequestBody) asyncContext.getRequest().getBody(); @@ -87,7 +85,7 @@ public void processRequest(ChannelHandlerContext ctx, AsyncContext ReplyMessageResponseHeader replyMessageResponseHeader = ReplyMessageResponseHeader.buildHeader(Integer.valueOf(asyncContext.getRequest().getRequestCode()), eventMeshHTTPServer.getEventMeshHttpConfiguration().eventMeshCluster, - IPUtil.getLocalAddress(), eventMeshHTTPServer.getEventMeshHttpConfiguration().eventMeshEnv, + IPUtils.getLocalAddress(), eventMeshHTTPServer.getEventMeshHttpConfiguration().eventMeshEnv, eventMeshHTTPServer.getEventMeshHttpConfiguration().eventMeshIDC); //validate event diff --git a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/SendAsyncMessageProcessor.java b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/SendAsyncMessageProcessor.java index d3e05d1cd8..6b078c8b1a 100644 --- a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/SendAsyncMessageProcessor.java +++ b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/SendAsyncMessageProcessor.java @@ -18,16 +18,14 @@ package org.apache.eventmesh.runtime.core.protocol.http.processor; import io.cloudevents.core.builder.CloudEventBuilder; -import jdk.nashorn.internal.runtime.URIUtils; + import org.apache.commons.lang3.StringUtils; import org.apache.eventmesh.api.SendCallback; import org.apache.eventmesh.api.SendResult; import org.apache.eventmesh.api.exception.OnExceptionContext; -import org.apache.eventmesh.common.Constants; -import org.apache.eventmesh.common.IPUtil; -import org.apache.eventmesh.common.LiteMessage; -import org.apache.eventmesh.common.ProtocolTransportObject; -import org.apache.eventmesh.common.command.HttpCommand; +import org.apache.eventmesh.common.utils.IPUtils; +import org.apache.eventmesh.common.protocol.ProtocolTransportObject; +import org.apache.eventmesh.common.protocol.http.HttpCommand; import org.apache.eventmesh.common.protocol.http.body.message.SendMessageRequestBody; import org.apache.eventmesh.common.protocol.http.body.message.SendMessageResponseBody; import org.apache.eventmesh.common.protocol.http.common.EventMeshRetCode; @@ -35,7 +33,6 @@ import org.apache.eventmesh.common.protocol.http.common.RequestCode; import org.apache.eventmesh.common.protocol.http.header.message.SendMessageRequestHeader; import org.apache.eventmesh.common.protocol.http.header.message.SendMessageResponseHeader; -import org.apache.eventmesh.common.protocol.tcp.Package; import org.apache.eventmesh.protocol.api.ProtocolAdaptor; import org.apache.eventmesh.protocol.api.ProtocolPluginFactory; import org.apache.eventmesh.runtime.acl.Acl; @@ -80,14 +77,14 @@ public void processRequest(ChannelHandlerContext ctx, AsyncContext cmdLogger.info("cmd={}|{}|client2eventMesh|from={}|to={}", RequestCode.get(Integer.valueOf(asyncContext.getRequest().getRequestCode())), EventMeshConstants.PROTOCOL_HTTP, - RemotingHelper.parseChannelRemoteAddr(ctx.channel()), IPUtil.getLocalAddress()); + RemotingHelper.parseChannelRemoteAddr(ctx.channel()), IPUtils.getLocalAddress()); SendMessageRequestHeader sendMessageRequestHeader = (SendMessageRequestHeader) asyncContext.getRequest().getHeader(); // SendMessageRequestBody sendMessageRequestBody = (SendMessageRequestBody) asyncContext.getRequest().getBody(); SendMessageResponseHeader sendMessageResponseHeader = SendMessageResponseHeader.buildHeader(Integer.valueOf(asyncContext.getRequest().getRequestCode()), eventMeshHTTPServer.getEventMeshHttpConfiguration().eventMeshCluster, - IPUtil.getLocalAddress(), eventMeshHTTPServer.getEventMeshHttpConfiguration().eventMeshEnv, + IPUtils.getLocalAddress(), eventMeshHTTPServer.getEventMeshHttpConfiguration().eventMeshEnv, eventMeshHTTPServer.getEventMeshHttpConfiguration().eventMeshIDC); String protocolType = sendMessageRequestHeader.getProtocolType(); diff --git a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/SendSyncMessageProcessor.java b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/SendSyncMessageProcessor.java index bdae55e770..ef025a007a 100644 --- a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/SendSyncMessageProcessor.java +++ b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/SendSyncMessageProcessor.java @@ -19,11 +19,11 @@ import io.cloudevents.CloudEvent; import io.cloudevents.core.builder.CloudEventBuilder; -import org.apache.eventmesh.api.RRCallback; + import org.apache.eventmesh.api.RequestReplyCallback; -import org.apache.eventmesh.common.IPUtil; -import org.apache.eventmesh.common.ProtocolTransportObject; -import org.apache.eventmesh.common.command.HttpCommand; +import org.apache.eventmesh.common.utils.IPUtils; +import org.apache.eventmesh.common.protocol.ProtocolTransportObject; +import org.apache.eventmesh.common.protocol.http.HttpCommand; import org.apache.eventmesh.common.protocol.http.body.message.SendMessageRequestBody; import org.apache.eventmesh.common.protocol.http.body.message.SendMessageResponseBody; import org.apache.eventmesh.common.protocol.http.common.EventMeshRetCode; @@ -79,7 +79,7 @@ public void processRequest(ChannelHandlerContext ctx, AsyncContext cmdLogger.info("cmd={}|{}|client2eventMesh|from={}|to={}", RequestCode.get(Integer.valueOf(asyncContext.getRequest().getRequestCode())), EventMeshConstants.PROTOCOL_HTTP, - RemotingHelper.parseChannelRemoteAddr(ctx.channel()), IPUtil.getLocalAddress()); + RemotingHelper.parseChannelRemoteAddr(ctx.channel()), IPUtils.getLocalAddress()); ProtocolAdaptor httpCommandProtocolAdaptor = ProtocolPluginFactory.getProtocolAdaptor("cloudevents"); CloudEvent event = httpCommandProtocolAdaptor.toCloudEvent(asyncContext.getRequest()); @@ -88,7 +88,7 @@ public void processRequest(ChannelHandlerContext ctx, AsyncContext SendMessageResponseHeader .buildHeader(Integer.valueOf(asyncContext.getRequest().getRequestCode()), eventMeshHTTPServer.getEventMeshHttpConfiguration().eventMeshCluster, - IPUtil.getLocalAddress(), + IPUtils.getLocalAddress(), eventMeshHTTPServer.getEventMeshHttpConfiguration().eventMeshEnv, eventMeshHTTPServer.getEventMeshHttpConfiguration().eventMeshIDC); diff --git a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/SubscribeProcessor.java b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/SubscribeProcessor.java index 32ddee17b8..02e1c1ec69 100644 --- a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/SubscribeProcessor.java +++ b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/SubscribeProcessor.java @@ -17,8 +17,8 @@ package org.apache.eventmesh.runtime.core.protocol.http.processor; -import org.apache.eventmesh.common.IPUtil; -import org.apache.eventmesh.common.command.HttpCommand; +import org.apache.eventmesh.common.utils.IPUtils; +import org.apache.eventmesh.common.protocol.http.HttpCommand; import org.apache.eventmesh.common.protocol.SubscriptionItem; import org.apache.eventmesh.common.protocol.http.body.client.SubscribeRequestBody; import org.apache.eventmesh.common.protocol.http.body.client.SubscribeResponseBody; @@ -78,7 +78,7 @@ public void processRequest(ChannelHandlerContext ctx, AsyncContext httpLogger.info("cmd={}|{}|client2eventMesh|from={}|to={}", RequestCode.get(requestCode), EventMeshConstants.PROTOCOL_HTTP, - RemotingHelper.parseChannelRemoteAddr(ctx.channel()), IPUtil.getLocalAddress() + RemotingHelper.parseChannelRemoteAddr(ctx.channel()), IPUtils.getLocalAddress() ); SubscribeRequestHeader subscribeRequestHeader = (SubscribeRequestHeader) request.getHeader(); SubscribeRequestBody subscribeRequestBody = (SubscribeRequestBody) request.getBody(); @@ -87,7 +87,7 @@ public void processRequest(ChannelHandlerContext ctx, AsyncContext SubscribeResponseHeader .buildHeader(requestCode, eventMeshHTTPServer.getEventMeshHttpConfiguration().eventMeshCluster, - IPUtil.getLocalAddress(), + IPUtils.getLocalAddress(), eventMeshHTTPServer.getEventMeshHttpConfiguration().eventMeshEnv, eventMeshHTTPServer.getEventMeshHttpConfiguration().eventMeshIDC); diff --git a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/UnSubscribeProcessor.java b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/UnSubscribeProcessor.java index 45b567db0a..7d9eb87e1a 100644 --- a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/UnSubscribeProcessor.java +++ b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/UnSubscribeProcessor.java @@ -17,8 +17,8 @@ package org.apache.eventmesh.runtime.core.protocol.http.processor; -import org.apache.eventmesh.common.IPUtil; -import org.apache.eventmesh.common.command.HttpCommand; +import org.apache.eventmesh.common.utils.IPUtils; +import org.apache.eventmesh.common.protocol.http.HttpCommand; import org.apache.eventmesh.common.protocol.http.body.client.UnSubscribeRequestBody; import org.apache.eventmesh.common.protocol.http.body.client.UnSubscribeResponseBody; import org.apache.eventmesh.common.protocol.http.common.EventMeshRetCode; @@ -71,7 +71,7 @@ public void processRequest(ChannelHandlerContext ctx, AsyncContext httpLogger.info("cmd={}|{}|client2eventMesh|from={}|to={}", RequestCode.get(Integer.valueOf(asyncContext.getRequest().getRequestCode())), EventMeshConstants.PROTOCOL_HTTP, - RemotingHelper.parseChannelRemoteAddr(ctx.channel()), IPUtil.getLocalAddress()); + RemotingHelper.parseChannelRemoteAddr(ctx.channel()), IPUtils.getLocalAddress()); UnSubscribeRequestHeader unSubscribeRequestHeader = (UnSubscribeRequestHeader) asyncContext.getRequest().getHeader(); UnSubscribeRequestBody unSubscribeRequestBody = @@ -81,7 +81,7 @@ public void processRequest(ChannelHandlerContext ctx, AsyncContext UnSubscribeResponseHeader .buildHeader(Integer.valueOf(asyncContext.getRequest().getRequestCode()), eventMeshHTTPServer.getEventMeshHttpConfiguration().eventMeshCluster, - IPUtil.getLocalAddress(), + IPUtils.getLocalAddress(), eventMeshHTTPServer.getEventMeshHttpConfiguration().eventMeshEnv, eventMeshHTTPServer.getEventMeshHttpConfiguration().eventMeshIDC); diff --git a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/inf/HttpRequestProcessor.java b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/inf/HttpRequestProcessor.java index cafddac0ff..4f256d66e5 100644 --- a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/inf/HttpRequestProcessor.java +++ b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/processor/inf/HttpRequestProcessor.java @@ -19,7 +19,7 @@ import io.netty.channel.ChannelHandlerContext; -import org.apache.eventmesh.common.command.HttpCommand; +import org.apache.eventmesh.common.protocol.http.HttpCommand; import org.apache.eventmesh.runtime.core.protocol.http.async.AsyncContext; public interface HttpRequestProcessor { diff --git a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/push/AsyncHTTPPushRequest.java b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/push/AsyncHTTPPushRequest.java index 5f31355cb8..67253d624e 100644 --- a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/push/AsyncHTTPPushRequest.java +++ b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/http/push/AsyncHTTPPushRequest.java @@ -20,9 +20,9 @@ import io.cloudevents.CloudEvent; import io.cloudevents.core.builder.CloudEventBuilder; import org.apache.eventmesh.common.Constants; -import org.apache.eventmesh.common.IPUtil; -import org.apache.eventmesh.common.ProtocolTransportObject; -import org.apache.eventmesh.common.RandomStringUtil; +import org.apache.eventmesh.common.utils.IPUtils; +import org.apache.eventmesh.common.protocol.ProtocolTransportObject; +import org.apache.eventmesh.common.utils.RandomStringUtils; import org.apache.eventmesh.common.exception.JsonException; import org.apache.eventmesh.common.protocol.SubscriptionType; import org.apache.eventmesh.common.protocol.http.body.message.PushMessageRequestBody; @@ -102,7 +102,7 @@ public void tryHTTPRequest() { builder.addHeader(ProtocolKey.EventMeshInstanceKey.EVENTMESHCLUSTER, handleMsgContext.getEventMeshHTTPServer() .getEventMeshHttpConfiguration().eventMeshCluster); - builder.addHeader(ProtocolKey.EventMeshInstanceKey.EVENTMESHIP, IPUtil.getLocalAddress()); + builder.addHeader(ProtocolKey.EventMeshInstanceKey.EVENTMESHIP, IPUtils.getLocalAddress()); builder.addHeader(ProtocolKey.EventMeshInstanceKey.EVENTMESHENV, handleMsgContext.getEventMeshHTTPServer().getEventMeshHttpConfiguration().eventMeshEnv); builder.addHeader(ProtocolKey.EventMeshInstanceKey.EVENTMESHIDC, @@ -134,14 +134,14 @@ public void tryHTTPRequest() { body.add(new BasicNameValuePair(PushMessageRequestBody.CONTENT, content)); if (StringUtils.isBlank(handleMsgContext.getBizSeqNo())) { body.add(new BasicNameValuePair(PushMessageRequestBody.BIZSEQNO, - RandomStringUtil.generateNum(20))); + RandomStringUtils.generateNum(20))); } else { body.add(new BasicNameValuePair(PushMessageRequestBody.BIZSEQNO, handleMsgContext.getBizSeqNo())); } if (StringUtils.isBlank(handleMsgContext.getUniqueId())) { body.add(new BasicNameValuePair(PushMessageRequestBody.UNIQUEID, - RandomStringUtil.generateNum(20))); + RandomStringUtils.generateNum(20))); } else { body.add(new BasicNameValuePair(PushMessageRequestBody.UNIQUEID, handleMsgContext.getUniqueId())); @@ -167,7 +167,7 @@ public void tryHTTPRequest() { addToWaitingMap(this); cmdLogger.info("cmd={}|eventMesh2client|from={}|to={}", requestCode, - IPUtil.getLocalAddress(), currPushUrl); + IPUtils.getLocalAddress(), currPushUrl); try { httpClientPool.getClient().execute(builder, new ResponseHandler() { diff --git a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/tcp/client/group/ClientSessionGroupMapping.java b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/tcp/client/group/ClientSessionGroupMapping.java index 1c6b3ed7fa..674fb18e83 100644 --- a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/tcp/client/group/ClientSessionGroupMapping.java +++ b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/tcp/client/group/ClientSessionGroupMapping.java @@ -31,9 +31,8 @@ import io.netty.channel.ChannelHandlerContext; import org.apache.commons.collections4.MapUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.eventmesh.common.Constants; -import org.apache.eventmesh.common.ThreadUtil; + +import org.apache.eventmesh.common.utils.ThreadUtils; import org.apache.eventmesh.common.protocol.SubscriptionItem; import org.apache.eventmesh.common.protocol.SubscriptionMode; import org.apache.eventmesh.common.protocol.tcp.UserAgent; @@ -443,7 +442,7 @@ public void shutdown() throws Exception { logger.error("say goodbye to session error! {}", itr, e); } }); - ThreadUtil.randomSleep(50); + ThreadUtils.randomSleep(50); logger.info("ClientSessionGroupMapping shutdown......"); } diff --git a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/tcp/client/task/MessageTransferTask.java b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/tcp/client/task/MessageTransferTask.java index 4c595e1b77..588d9bc0d2 100644 --- a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/tcp/client/task/MessageTransferTask.java +++ b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/core/protocol/tcp/client/task/MessageTransferTask.java @@ -27,19 +27,17 @@ import org.apache.eventmesh.api.SendResult; import org.apache.eventmesh.api.exception.OnExceptionContext; import org.apache.eventmesh.common.Constants; -import org.apache.eventmesh.common.ProtocolTransportObject; +import org.apache.eventmesh.common.protocol.ProtocolTransportObject; import org.apache.eventmesh.common.protocol.tcp.Package; import org.apache.eventmesh.common.protocol.tcp.*; import org.apache.eventmesh.protocol.api.ProtocolAdaptor; import org.apache.eventmesh.protocol.api.ProtocolPluginFactory; -import org.apache.eventmesh.protocol.api.exception.ProtocolHandleException; import org.apache.eventmesh.runtime.acl.Acl; import org.apache.eventmesh.runtime.boot.EventMeshTCPServer; import org.apache.eventmesh.runtime.constants.EventMeshConstants; import org.apache.eventmesh.runtime.core.protocol.tcp.client.session.send.EventMeshTcpSendResult; import org.apache.eventmesh.runtime.core.protocol.tcp.client.session.send.EventMeshTcpSendStatus; import org.apache.eventmesh.runtime.core.protocol.tcp.client.session.send.UpStreamMsgContext; -import org.apache.eventmesh.runtime.util.EventMeshUtil; import org.apache.eventmesh.runtime.util.RemotingHelper; import org.apache.eventmesh.runtime.util.Utils; import org.slf4j.Logger; diff --git a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/util/EventMeshUtil.java b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/util/EventMeshUtil.java index c8dfd10514..58e05e0d65 100644 --- a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/util/EventMeshUtil.java +++ b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/util/EventMeshUtil.java @@ -44,8 +44,8 @@ import org.apache.commons.lang3.StringUtils; import org.apache.eventmesh.common.Constants; -import org.apache.eventmesh.common.RandomStringUtil; -import org.apache.eventmesh.common.ThreadUtil; +import org.apache.eventmesh.common.utils.RandomStringUtils; +import org.apache.eventmesh.common.utils.ThreadUtils; import org.apache.eventmesh.common.protocol.tcp.EventMeshMessage; import org.apache.eventmesh.common.protocol.tcp.UserAgent; import org.apache.eventmesh.runtime.constants.EventMeshConstants; @@ -60,14 +60,14 @@ public class EventMeshUtil { private final static Logger tcpLogger = LoggerFactory.getLogger("tcpMonitor"); public static String buildPushMsgSeqNo() { - return StringUtils.rightPad(String.valueOf(System.currentTimeMillis()), 6) + RandomStringUtil.generateNum(4); + return StringUtils.rightPad(String.valueOf(System.currentTimeMillis()), 6) + RandomStringUtils.generateNum(4); } public static String buildMeshClientID(String clientGroup, String meshCluster) { return StringUtils.trim(clientGroup) + "(" + StringUtils.trim(meshCluster) + ")" + "-" + EventMeshVersion.getCurrentVersionDesc() - + "-" + ThreadUtil.getPID(); + + "-" + ThreadUtils.getPID(); } public static String buildMeshTcpClientID(String clientSysId, String purpose, String meshCluster) { @@ -75,7 +75,7 @@ public static String buildMeshTcpClientID(String clientSysId, String purpose, St + "-" + StringUtils.trim(purpose) + "-" + StringUtils.trim(meshCluster) + "-" + EventMeshVersion.getCurrentVersionDesc() - + "-" + ThreadUtil.getPID(); + + "-" + ThreadUtils.getPID(); } public static String buildClientGroup(String systemId) { diff --git a/eventmesh-runtime/src/test/java/org/apache/eventmesh/runtime/demo/AsyncPubClient.java b/eventmesh-runtime/src/test/java/org/apache/eventmesh/runtime/demo/AsyncPubClient.java index 5fdea19614..14ee1ddbc7 100644 --- a/eventmesh-runtime/src/test/java/org/apache/eventmesh/runtime/demo/AsyncPubClient.java +++ b/eventmesh-runtime/src/test/java/org/apache/eventmesh/runtime/demo/AsyncPubClient.java @@ -19,7 +19,7 @@ import io.netty.channel.ChannelHandlerContext; -import org.apache.eventmesh.common.ThreadUtil; +import org.apache.eventmesh.common.utils.ThreadUtils; import org.apache.eventmesh.common.protocol.tcp.Package; import org.apache.eventmesh.runtime.client.common.ClientConstants; @@ -46,7 +46,7 @@ public void handle(Package msg, ChannelHandlerContext ctx) { }); for (int i = 0; i < 1; i++) { - ThreadUtil.randomSleep(0, 500); + ThreadUtils.randomSleep(0, 500); pubClient.broadcast(MessageUtils.asyncMessage(ClientConstants.ASYNC_TOPIC, i), 5000); } } diff --git a/eventmesh-runtime/src/test/java/org/apache/eventmesh/runtime/demo/BroadCastPubClient.java b/eventmesh-runtime/src/test/java/org/apache/eventmesh/runtime/demo/BroadCastPubClient.java index 5594e900a7..d85e8c364f 100644 --- a/eventmesh-runtime/src/test/java/org/apache/eventmesh/runtime/demo/BroadCastPubClient.java +++ b/eventmesh-runtime/src/test/java/org/apache/eventmesh/runtime/demo/BroadCastPubClient.java @@ -17,7 +17,7 @@ package org.apache.eventmesh.runtime.demo; -import org.apache.eventmesh.common.ThreadUtil; +import org.apache.eventmesh.common.utils.ThreadUtils; import org.apache.eventmesh.runtime.client.common.ClientConstants; import org.apache.eventmesh.runtime.client.common.MessageUtils; @@ -30,7 +30,7 @@ public static void main(String[] args) throws Exception { pubClient.init(); pubClient.heartbeat(); for (int i = 0; i < 10000; i++) { - ThreadUtil.randomSleep(0, 500); + ThreadUtils.randomSleep(0, 500); pubClient.broadcast(MessageUtils.broadcastMessage(ClientConstants.BROADCAST_TOPIC, i), 5000); } } diff --git a/eventmesh-sdk-java/build.gradle b/eventmesh-sdk-java/build.gradle index f62840dfe5..108e418652 100644 --- a/eventmesh-sdk-java/build.gradle +++ b/eventmesh-sdk-java/build.gradle @@ -17,7 +17,6 @@ dependencies { implementation project(":eventmesh-common") - implementation project(":eventmesh-common") implementation "com.fasterxml.jackson.core:jackson-databind" implementation "com.fasterxml.jackson.core:jackson-core" @@ -26,17 +25,9 @@ dependencies { implementation "io.netty:netty-all" implementation "org.apache.httpcomponents:httpclient" + // protocol implementation "io.cloudevents:cloudevents-core" - - testImplementation project(":eventmesh-common") - testImplementation project(":eventmesh-common") - - testImplementation "com.fasterxml.jackson.core:jackson-databind" - testImplementation "com.fasterxml.jackson.core:jackson-core" - testImplementation "com.fasterxml.jackson.core:jackson-annotations" - - testImplementation "io.netty:netty-all" - testImplementation "org.apache.httpcomponents:httpclient" + implementation "io.openmessaging:openmessaging-api" compileOnly 'org.projectlombok:lombok:1.18.22' annotationProcessor 'org.projectlombok:lombok:1.18.22' diff --git a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/AbstractHttpClient.java b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/AbstractHttpClient.java new file mode 100644 index 0000000000..057f2805b7 --- /dev/null +++ b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/AbstractHttpClient.java @@ -0,0 +1,97 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.apache.eventmesh.client.http; + +import org.apache.eventmesh.client.http.conf.EventMeshHttpClientConfig; +import org.apache.eventmesh.client.http.ssl.MyX509TrustManager; +import org.apache.eventmesh.client.http.util.HttpLoadBalanceUtils; +import org.apache.eventmesh.common.Constants; +import org.apache.eventmesh.common.exception.EventMeshException; +import org.apache.eventmesh.common.loadbalance.LoadBalanceSelector; + +import org.apache.http.conn.ssl.DefaultHostnameVerifier; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; + +import java.io.IOException; +import java.security.SecureRandom; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; + +import com.google.common.base.Preconditions; + +import lombok.extern.slf4j.Slf4j; + +@Slf4j +public abstract class AbstractHttpClient implements AutoCloseable { + + protected EventMeshHttpClientConfig eventMeshHttpClientConfig; + + protected LoadBalanceSelector eventMeshServerSelector; + + protected final CloseableHttpClient httpClient; + + public AbstractHttpClient(EventMeshHttpClientConfig eventMeshHttpClientConfig) throws EventMeshException { + Preconditions.checkNotNull(eventMeshHttpClientConfig, "liteClientConfig can't be null"); + Preconditions.checkNotNull(eventMeshHttpClientConfig.getLiteEventMeshAddr(), "liteServerAddr can't be null"); + + this.eventMeshHttpClientConfig = eventMeshHttpClientConfig; + this.eventMeshServerSelector = HttpLoadBalanceUtils.createEventMeshServerLoadBalanceSelector( + eventMeshHttpClientConfig); + this.httpClient = setHttpClient(); + } + + public void close() throws EventMeshException { + try (final CloseableHttpClient ignore = this.httpClient) { + // ignore + } catch (IOException e) { + throw new EventMeshException("Close http client error", e); + } + } + + private CloseableHttpClient setHttpClient() throws EventMeshException { + if (!eventMeshHttpClientConfig.isUseTls()) { + return HttpClients.createDefault(); + } + SSLContext sslContext; + try { + // todo: config in properties file? + String protocol = System.getProperty("ssl.client.protocol", "TLSv1.2"); + TrustManager[] tm = new TrustManager[] {new MyX509TrustManager()}; + sslContext = SSLContext.getInstance(protocol); + sslContext.init(null, tm, new SecureRandom()); + // todo: custom client pool + return HttpClients.custom() + .setSSLContext(sslContext) + .setSSLHostnameVerifier(new DefaultHostnameVerifier()) + .build(); + } catch (Exception e) { + log.error("Error in creating HttpClient.", e); + throw new EventMeshException(e); + } + } + + protected String selectEventMesh() { + if (eventMeshHttpClientConfig.isUseTls()) { + return Constants.HTTPS_PROTOCOL_PREFIX + eventMeshServerSelector.select(); + } else { + return Constants.HTTP_PROTOCOL_PREFIX + eventMeshServerSelector.select(); + } + } +} diff --git a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/AbstractLiteClient.java b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/AbstractLiteClient.java deleted file mode 100644 index df72fac7e7..0000000000 --- a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/AbstractLiteClient.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.apache.eventmesh.client.http; - -import lombok.extern.slf4j.Slf4j; - -import org.apache.eventmesh.client.http.conf.LiteClientConfig; -import org.apache.eventmesh.client.http.ssl.MyX509TrustManager; -import org.apache.eventmesh.client.http.util.HttpLoadBalanceUtils; -import org.apache.eventmesh.common.loadbalance.LoadBalanceSelector; -import org.apache.http.conn.ssl.DefaultHostnameVerifier; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import java.security.SecureRandom; - -@Slf4j -public abstract class AbstractLiteClient { - - protected LiteClientConfig liteClientConfig; - - protected LoadBalanceSelector eventMeshServerSelector; - - public AbstractLiteClient(LiteClientConfig liteClientConfig) { - this.liteClientConfig = liteClientConfig; - } - - public void start() throws Exception { - eventMeshServerSelector = HttpLoadBalanceUtils.createEventMeshServerLoadBalanceSelector(liteClientConfig); - } - - public LiteClientConfig getLiteClientConfig() { - return liteClientConfig; - } - - public void shutdown() throws Exception { - log.info("AbstractLiteClient shutdown"); - } - - public CloseableHttpClient setHttpClient() throws Exception { - if (!liteClientConfig.isUseTls()) { - return HttpClients.createDefault(); - } - SSLContext sslContext = null; - try { - String protocol = System.getProperty("ssl.client.protocol", "TLSv1.2"); - TrustManager[] tm = new TrustManager[]{new MyX509TrustManager()}; - sslContext = SSLContext.getInstance(protocol); - sslContext.init(null, tm, new SecureRandom()); - return HttpClients.custom().setSSLContext(sslContext) - .setSSLHostnameVerifier(new DefaultHostnameVerifier()).build(); - } catch (Exception e) { - log.error("Error in creating HttpClient.", e); - throw e; - } - } -} diff --git a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/conf/EventMeshHttpClientConfig.java b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/conf/EventMeshHttpClientConfig.java new file mode 100644 index 0000000000..062b2e1b76 --- /dev/null +++ b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/conf/EventMeshHttpClientConfig.java @@ -0,0 +1,74 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.apache.eventmesh.client.http.conf; + +import org.apache.eventmesh.common.loadbalance.LoadBalanceType; + +import lombok.Builder; +import lombok.Data; + +@Data +@Builder +public class EventMeshHttpClientConfig { + + /** + * The event server address list + *

+ * If it's a cluster, please use ; to split, and the address format is related to loadBalanceType. + *

+ * E.g. + *

If you use Random strategy, the format like: 127.0.0.1:10105;127.0.0.2:10105 + *

If you use weighted round robin or weighted random strategy, the format like: 127.0.0.1:10105:1;127.0.0.2:10105:2 + */ + @Builder.Default + private String liteEventMeshAddr = "127.0.0.1:10105"; + + @Builder.Default + private LoadBalanceType loadBalanceType = LoadBalanceType.RANDOM; + + @Builder.Default + private int consumeThreadCore = 2; + + @Builder.Default + private int consumeThreadMax = 5; + + private String env; + + @Builder.Default + private String consumerGroup = "DefaultConsumerGroup"; + + @Builder.Default + private String producerGroup = "DefaultProducerGroup"; + + private String idc; + + @Builder.Default + private String ip = "127.0.0.1"; + + private String pid; + + private String sys; + + private String userName; + + private String password; + + @Builder.Default + private boolean useTls = false; + +} diff --git a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/conf/LiteClientConfig.java b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/conf/LiteClientConfig.java deleted file mode 100644 index c302523fa6..0000000000 --- a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/conf/LiteClientConfig.java +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.apache.eventmesh.client.http.conf; - -import org.apache.eventmesh.common.loadbalance.LoadBalanceType; - -public class LiteClientConfig { - - /** - * The event server address list - *

- * If it's a cluster, please use ; to split, and the address format is related to loadBalanceType. - *

- * E.g. - *

If you use Random strategy, the format like: 127.0.0.1:10105;127.0.0.2:10105 - *

If you use weighted round robin or weighted random strategy, the format like: 127.0.0.1:10105:1;127.0.0.2:10105:2 - */ - private String liteEventMeshAddr = "127.0.0.1:10105"; - - private LoadBalanceType loadBalanceType = LoadBalanceType.RANDOM; - - private int consumeThreadCore = 2; - - private int consumeThreadMax = 5; - - private String env; - - private String consumerGroup = "DefaultConsumerGroup"; - - private String producerGroup = "DefaultProducerGroup"; - - private String idc; - - private String ip = "127.0.0.1"; - - private String pid; - - private String sys; - - private String userName; - - private String password; - - private boolean useTls = false; - - public String getLiteEventMeshAddr() { - return liteEventMeshAddr; - } - - public LiteClientConfig setLiteEventMeshAddr(String liteEventMeshAddr) { - this.liteEventMeshAddr = liteEventMeshAddr; - return this; - } - - public LoadBalanceType getLoadBalanceType() { - return loadBalanceType; - } - - public LiteClientConfig setLoadBalanceType(LoadBalanceType loadBalanceType) { - this.loadBalanceType = loadBalanceType; - return this; - } - - public int getConsumeThreadCore() { - return consumeThreadCore; - } - - public LiteClientConfig setConsumeThreadCore(int consumeThreadCore) { - this.consumeThreadCore = consumeThreadCore; - return this; - } - - public int getConsumeThreadMax() { - return consumeThreadMax; - } - - public LiteClientConfig setConsumeThreadMax(int consumeThreadMax) { - this.consumeThreadMax = consumeThreadMax; - return this; - } - - public String getEnv() { - return env; - } - - public LiteClientConfig setEnv(String env) { - this.env = env; - return this; - } - - public String getIdc() { - return idc; - } - - public LiteClientConfig setIdc(String idc) { - this.idc = idc; - return this; - } - - public String getIp() { - return ip; - } - - public LiteClientConfig setIp(String ip) { - this.ip = ip; - return this; - } - - public String getPid() { - return pid; - } - - public LiteClientConfig setPid(String pid) { - this.pid = pid; - return this; - } - - public String getSys() { - return sys; - } - - public LiteClientConfig setSys(String sys) { - this.sys = sys; - return this; - } - - public String getUserName() { - return userName; - } - - public LiteClientConfig setUserName(String userName) { - this.userName = userName; - return this; - } - - public String getPassword() { - return password; - } - - public LiteClientConfig setPassword(String password) { - this.password = password; - return this; - } - - public boolean isUseTls() { - return useTls; - } - - public LiteClientConfig setUseTls(boolean useTls) { - this.useTls = useTls; - return this; - } - - public String getConsumerGroup() { - return consumerGroup; - } - - public LiteClientConfig setConsumerGroup(String consumerGroup) { - this.consumerGroup = consumerGroup; - return this; - } - - public String getProducerGroup() { - return producerGroup; - } - - public LiteClientConfig setProducerGroup(String producerGroup) { - this.producerGroup = producerGroup; - return this; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("liteClientConfig={") - .append("liteEventMeshAddr=").append(liteEventMeshAddr).append(",") - .append("loadBalanceType=").append(loadBalanceType).append(",") - .append("consumeThreadCore=").append(consumeThreadCore).append(",") - .append("consumeThreadMax=").append(consumeThreadMax).append(",") - .append("env=").append(env).append(",") - .append("idc=").append(idc).append(",") - .append("producerGroup=").append(producerGroup).append(",") - .append("consumerGroup=").append(consumerGroup).append(",") - .append("ip=").append(ip).append(",") - .append("pid=").append(pid).append(",") - .append("sys=").append(sys).append(",") - .append("userName=").append(userName).append(",") - .append("password=").append(password).append(",") - .append("useTls=").append(useTls).append("}"); - return sb.toString(); - } -} diff --git a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/consumer/EventMeshHttpConsumer.java b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/consumer/EventMeshHttpConsumer.java new file mode 100644 index 0000000000..7b3081e468 --- /dev/null +++ b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/consumer/EventMeshHttpConsumer.java @@ -0,0 +1,199 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.apache.eventmesh.client.http.consumer; + +import org.apache.eventmesh.client.http.AbstractHttpClient; +import org.apache.eventmesh.client.http.EventMeshRetObj; +import org.apache.eventmesh.client.http.conf.EventMeshHttpClientConfig; +import org.apache.eventmesh.client.http.model.RequestParam; +import org.apache.eventmesh.client.http.util.HttpUtils; +import org.apache.eventmesh.client.tcp.common.EventMeshCommon; +import org.apache.eventmesh.common.Constants; +import org.apache.eventmesh.common.ThreadPoolFactory; +import org.apache.eventmesh.common.exception.EventMeshException; +import org.apache.eventmesh.common.protocol.SubscriptionItem; +import org.apache.eventmesh.common.protocol.http.body.client.HeartbeatRequestBody; +import org.apache.eventmesh.common.protocol.http.body.client.SubscribeRequestBody; +import org.apache.eventmesh.common.protocol.http.body.client.UnSubscribeRequestBody; +import org.apache.eventmesh.common.protocol.http.common.ClientType; +import org.apache.eventmesh.common.protocol.http.common.EventMeshRetCode; +import org.apache.eventmesh.common.protocol.http.common.ProtocolKey; +import org.apache.eventmesh.common.protocol.http.common.ProtocolVersion; +import org.apache.eventmesh.common.protocol.http.common.RequestCode; +import org.apache.eventmesh.common.utils.JsonUtils; + +import java.util.List; +import java.util.Optional; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +import com.google.common.base.Preconditions; +import com.google.common.collect.Lists; +import com.google.common.util.concurrent.ThreadFactoryBuilder; + +import io.netty.handler.codec.http.HttpMethod; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +public class EventMeshHttpConsumer extends AbstractHttpClient implements AutoCloseable { + + private final ThreadPoolExecutor consumeExecutor; + + private static final List subscription = Lists.newArrayList(); + + private final ScheduledThreadPoolExecutor scheduler; + + public EventMeshHttpConsumer(EventMeshHttpClientConfig eventMeshHttpClientConfig) throws EventMeshException { + this(eventMeshHttpClientConfig, null); + } + + public EventMeshHttpConsumer(EventMeshHttpClientConfig eventMeshHttpClientConfig, ThreadPoolExecutor customExecutor) + throws EventMeshException { + super(eventMeshHttpClientConfig); + this.consumeExecutor = Optional.ofNullable(customExecutor).orElseGet( + () -> ThreadPoolFactory.createThreadPoolExecutor(eventMeshHttpClientConfig.getConsumeThreadCore(), + eventMeshHttpClientConfig.getConsumeThreadMax(), "EventMesh-client-consume-") + ); + this.scheduler = new ScheduledThreadPoolExecutor( + Runtime.getRuntime().availableProcessors(), + new ThreadFactoryBuilder().setNameFormat("HTTPClientScheduler").setDaemon(true).build() + ); + } + + /** + * When receive message will callback the url. + * + * @param topicList topic that be subscribed + * @param subscribeUrl url will be trigger + * @throws EventMeshException if subscribe failed + */ + public void subscribe(List topicList, String subscribeUrl) throws EventMeshException { + Preconditions.checkNotNull(topicList, "Subscribe item cannot be null"); + Preconditions.checkNotNull(subscribeUrl, "SubscribeUrl cannot be null"); + RequestParam subscribeParam = buildCommonRequestParam() + .addHeader(ProtocolKey.REQUEST_CODE, RequestCode.SUBSCRIBE.getRequestCode()) + .addBody(SubscribeRequestBody.TOPIC, JsonUtils.serialize(topicList)) + .addBody(SubscribeRequestBody.CONSUMERGROUP, eventMeshHttpClientConfig.getConsumerGroup()) + .addBody(SubscribeRequestBody.URL, subscribeUrl); + + String target = selectEventMesh(); + try { + String subRes = HttpUtils.post(httpClient, target, subscribeParam); + EventMeshRetObj ret = JsonUtils.deserialize(subRes, EventMeshRetObj.class); + if (ret.getRetCode() != EventMeshRetCode.SUCCESS.getRetCode()) { + throw new EventMeshException(ret.getRetCode(), ret.getRetMsg()); + } + subscription.addAll(topicList); + } catch (Exception ex) { + throw new EventMeshException(String.format("Subscribe topic error, target:%s", target), ex); + } + } + + // todo: remove http heartBeat? + public void heartBeat(List topicList, String subscribeUrl) { + Preconditions.checkNotNull(topicList, "Subscribe item cannot be null"); + Preconditions.checkNotNull(subscribeUrl, "SubscribeUrl cannot be null"); + scheduler.scheduleAtFixedRate(() -> { + try { + List heartbeatEntities = topicList.stream().map(subscriptionItem + -> { + HeartbeatRequestBody.HeartbeatEntity heartbeatEntity = new HeartbeatRequestBody.HeartbeatEntity(); + heartbeatEntity.topic = subscriptionItem.getTopic(); + heartbeatEntity.url = subscribeUrl; + return heartbeatEntity; + }).collect(Collectors.toList()); + RequestParam requestParam = buildCommonRequestParam() + .addHeader(ProtocolKey.REQUEST_CODE, RequestCode.HEARTBEAT.getRequestCode()) + .addBody(HeartbeatRequestBody.CLIENTTYPE, ClientType.SUB.name()) + .addBody(HeartbeatRequestBody.HEARTBEATENTITIES, JsonUtils.serialize(heartbeatEntities)); + String target = selectEventMesh(); + String res = HttpUtils.post(httpClient, target, requestParam); + EventMeshRetObj ret = JsonUtils.deserialize(res, EventMeshRetObj.class); + if (ret.getRetCode() != EventMeshRetCode.SUCCESS.getRetCode()) { + throw new EventMeshException(ret.getRetCode(), ret.getRetMsg()); + } + } catch (Exception e) { + log.error("send heartBeat error", e); + } + }, EventMeshCommon.HEARTBEAT, EventMeshCommon.HEARTBEAT, TimeUnit.MILLISECONDS); + } + + /** + * @param topicList subscribe topic + * @param unSubscribeUrl subscribeUrl + * @throws EventMeshException if unsubscribe failed + */ + public void unsubscribe(List topicList, String unSubscribeUrl) throws EventMeshException { + Preconditions.checkNotNull(topicList, "Topics cannot be null"); + Preconditions.checkNotNull(unSubscribeUrl, "unSubscribeUrl cannot be null"); + RequestParam unSubscribeParam = buildCommonRequestParam() + .addHeader(ProtocolKey.REQUEST_CODE, RequestCode.UNSUBSCRIBE.getRequestCode()) + .addBody(UnSubscribeRequestBody.TOPIC, JsonUtils.serialize(topicList)) + .addBody(UnSubscribeRequestBody.URL, unSubscribeUrl); + String target = selectEventMesh(); + try { + String unSubRes = HttpUtils.post(httpClient, target, unSubscribeParam); + EventMeshRetObj ret = JsonUtils.deserialize(unSubRes, EventMeshRetObj.class); + + if (ret.getRetCode() != EventMeshRetCode.SUCCESS.getRetCode()) { + throw new EventMeshException(ret.getRetCode(), ret.getRetMsg()); + } + // todo: avoid concurrentModifiedException + subscription.removeIf(item -> topicList.contains(item.getTopic())); + } catch (Exception ex) { + throw new EventMeshException(String.format("Unsubscribe topic error, target:%s", target), ex); + } + } + + @Override + public void close() throws EventMeshException { + log.info("LiteConsumer shutting down"); + super.close(); + if (consumeExecutor != null) { + consumeExecutor.shutdown(); + } + scheduler.shutdown(); + log.info("LiteConsumer shutdown"); + } + + private String selectEventMesh() { + // todo: target endpoint maybe destroy, should remove the bad endpoint + if (eventMeshHttpClientConfig.isUseTls()) { + return Constants.HTTPS_PROTOCOL_PREFIX + eventMeshServerSelector.select(); + } else { + return Constants.HTTP_PROTOCOL_PREFIX + eventMeshServerSelector.select(); + } + } + + private RequestParam buildCommonRequestParam() { + return new RequestParam(HttpMethod.POST) + .addHeader(ProtocolKey.ClientInstanceKey.ENV, eventMeshHttpClientConfig.getEnv()) + .addHeader(ProtocolKey.ClientInstanceKey.IDC, eventMeshHttpClientConfig.getIdc()) + .addHeader(ProtocolKey.ClientInstanceKey.IP, eventMeshHttpClientConfig.getIp()) + .addHeader(ProtocolKey.ClientInstanceKey.PID, eventMeshHttpClientConfig.getPid()) + .addHeader(ProtocolKey.ClientInstanceKey.SYS, eventMeshHttpClientConfig.getSys()) + .addHeader(ProtocolKey.ClientInstanceKey.USERNAME, eventMeshHttpClientConfig.getUserName()) + .addHeader(ProtocolKey.ClientInstanceKey.PASSWD, eventMeshHttpClientConfig.getPassword()) + .addHeader(ProtocolKey.VERSION, ProtocolVersion.V1.getVersion()) + .addHeader(ProtocolKey.LANGUAGE, Constants.LANGUAGE_JAVA) + .setTimeout(Constants.DEFAULT_HTTP_TIME_OUT) + .addBody(HeartbeatRequestBody.CONSUMERGROUP, eventMeshHttpClientConfig.getConsumerGroup()); + } +} diff --git a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/consumer/LiteConsumer.java b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/consumer/LiteConsumer.java deleted file mode 100644 index 2dad1c6da6..0000000000 --- a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/consumer/LiteConsumer.java +++ /dev/null @@ -1,297 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.apache.eventmesh.client.http.consumer; - -import org.apache.eventmesh.client.http.AbstractLiteClient; -import org.apache.eventmesh.client.http.EventMeshRetObj; -import org.apache.eventmesh.client.http.conf.LiteClientConfig; -import org.apache.eventmesh.client.http.http.HttpUtil; -import org.apache.eventmesh.client.http.http.RequestParam; -import org.apache.eventmesh.client.tcp.common.EventMeshCommon; -import org.apache.eventmesh.common.Constants; -import org.apache.eventmesh.common.EventMeshException; -import org.apache.eventmesh.common.ThreadPoolFactory; -import org.apache.eventmesh.common.protocol.SubscriptionItem; -import org.apache.eventmesh.common.protocol.http.body.client.HeartbeatRequestBody; -import org.apache.eventmesh.common.protocol.http.body.client.SubscribeRequestBody; -import org.apache.eventmesh.common.protocol.http.body.client.UnSubscribeRequestBody; -import org.apache.eventmesh.common.protocol.http.common.ClientType; -import org.apache.eventmesh.common.protocol.http.common.EventMeshRetCode; -import org.apache.eventmesh.common.protocol.http.common.ProtocolKey; -import org.apache.eventmesh.common.protocol.http.common.ProtocolVersion; -import org.apache.eventmesh.common.protocol.http.common.RequestCode; -import org.apache.eventmesh.common.utils.JsonUtils; - -import org.apache.http.impl.client.CloseableHttpClient; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -import com.google.common.base.Preconditions; -import com.google.common.collect.Lists; -import com.google.common.util.concurrent.ThreadFactoryBuilder; - -import io.netty.handler.codec.http.HttpMethod; -import lombok.extern.slf4j.Slf4j; - -@Slf4j -public class LiteConsumer extends AbstractLiteClient { - - private ThreadPoolExecutor consumeExecutor; - - protected LiteClientConfig eventMeshClientConfig; - - private static final List subscription = Lists.newArrayList(); - - private static final AtomicBoolean started = new AtomicBoolean(Boolean.FALSE); - - protected final ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor( - Runtime.getRuntime().availableProcessors(), - new ThreadFactoryBuilder().setNameFormat("TCPClientScheduler").setDaemon(true).build() - ); - - public LiteConsumer(LiteClientConfig liteClientConfig) { - this(liteClientConfig, - ThreadPoolFactory.createThreadPoolExecutor(liteClientConfig.getConsumeThreadCore(), - liteClientConfig.getConsumeThreadMax(), "EventMesh-client-consume-") - ); - } - - public LiteConsumer(LiteClientConfig liteClientConfig, - ThreadPoolExecutor customExecutor) { - super(liteClientConfig); - this.consumeExecutor = customExecutor; - this.eventMeshClientConfig = liteClientConfig; - } - - @Override - public void start() throws Exception { - Preconditions.checkNotNull(eventMeshClientConfig, - "EventMeshClientConfig can't be null"); - Preconditions.checkNotNull(consumeExecutor, "consumeExecutor can't be null"); - log.info("LiteConsumer starting"); - super.start(); - started.compareAndSet(false, true); - log.info("LiteConsumer started"); - } - - @Override - public void shutdown() throws Exception { - log.info("LiteConsumer shutting down"); - super.shutdown(); - if (consumeExecutor != null) { - consumeExecutor.shutdown(); - } - scheduler.shutdown(); - started.compareAndSet(true, false); - log.info("LiteConsumer shutdown"); - } - - /** - * When receive message will callback the url. - * - * @param topicList topic that be subscribed - * @param url url will be trigger - * @return true if subscribe success - * @throws Exception - */ - public boolean subscribe(List topicList, String url) throws Exception { - subscription.addAll(topicList); - if (!started.get()) { - start(); - } - - RequestParam subscribeParam = generateSubscribeRequestParam(topicList, url); - - long startTime = System.nanoTime(); - String target = selectEventMesh(); - String subRes = ""; - - try (CloseableHttpClient httpClient = setHttpClient()) { - subRes = HttpUtil.post(httpClient, target, subscribeParam); - } - - if (log.isDebugEnabled()) { - log.debug( - "subscribe message by await, targetEventMesh:{}, cost:{}ms, subscribeParam:{}, " - + "rtn:{}", target, (System.nanoTime() - startTime) / 1000000, - JsonUtils.serialize(subscribeParam), subRes); - } - - EventMeshRetObj ret = JsonUtils.deserialize(subRes, EventMeshRetObj.class); - - if (ret.getRetCode() == EventMeshRetCode.SUCCESS.getRetCode()) { - // todo: remove return result - return true; - } else { - throw new EventMeshException(ret.getRetCode(), ret.getRetMsg()); - } - - } - - private RequestParam generateSubscribeRequestParam(List topicList, - String url) { - RequestParam requestParam = new RequestParam(HttpMethod.POST); - requestParam - .addHeader(ProtocolKey.REQUEST_CODE, RequestCode.SUBSCRIBE.getRequestCode()) - .addHeader(ProtocolKey.ClientInstanceKey.ENV, eventMeshClientConfig.getEnv()) - .addHeader(ProtocolKey.ClientInstanceKey.IDC, eventMeshClientConfig.getIdc()) - .addHeader(ProtocolKey.ClientInstanceKey.IP, eventMeshClientConfig.getIp()) - .addHeader(ProtocolKey.ClientInstanceKey.PID, eventMeshClientConfig.getPid()) - .addHeader(ProtocolKey.ClientInstanceKey.SYS, eventMeshClientConfig.getSys()) - .addHeader(ProtocolKey.ClientInstanceKey.USERNAME, eventMeshClientConfig.getUserName()) - .addHeader(ProtocolKey.ClientInstanceKey.PASSWD, eventMeshClientConfig.getPassword()) - .addHeader(ProtocolKey.VERSION, ProtocolVersion.V1.getVersion()) - .addHeader(ProtocolKey.LANGUAGE, Constants.LANGUAGE_JAVA) - .setTimeout(Constants.DEFAULT_HTTP_TIME_OUT) - .addBody(SubscribeRequestBody.TOPIC, JsonUtils.serialize(topicList)) - .addBody(SubscribeRequestBody.CONSUMERGROUP, eventMeshClientConfig.getConsumerGroup()) - .addBody(SubscribeRequestBody.URL, url); - return requestParam; - } - - private RequestParam generateHeartBeatRequestParam(List topics, String url) { - List heartbeatEntities = new ArrayList<>(); - for (SubscriptionItem item : topics) { - HeartbeatRequestBody.HeartbeatEntity heartbeatEntity = - new HeartbeatRequestBody.HeartbeatEntity(); - heartbeatEntity.topic = item.getTopic(); - heartbeatEntity.url = url; - heartbeatEntities.add(heartbeatEntity); - } - - RequestParam requestParam = new RequestParam(HttpMethod.POST); - requestParam - .addHeader(ProtocolKey.REQUEST_CODE, RequestCode.HEARTBEAT.getRequestCode()) - .addHeader(ProtocolKey.ClientInstanceKey.ENV, eventMeshClientConfig.getEnv()) - .addHeader(ProtocolKey.ClientInstanceKey.IDC, eventMeshClientConfig.getIdc()) - .addHeader(ProtocolKey.ClientInstanceKey.IP, eventMeshClientConfig.getIp()) - .addHeader(ProtocolKey.ClientInstanceKey.PID, eventMeshClientConfig.getPid()) - .addHeader(ProtocolKey.ClientInstanceKey.SYS, eventMeshClientConfig.getSys()) - .addHeader(ProtocolKey.ClientInstanceKey.USERNAME, eventMeshClientConfig.getUserName()) - .addHeader(ProtocolKey.ClientInstanceKey.PASSWD, eventMeshClientConfig.getPassword()) - .addHeader(ProtocolKey.VERSION, ProtocolVersion.V1.getVersion()) - .addHeader(ProtocolKey.LANGUAGE, Constants.LANGUAGE_JAVA) - .setTimeout(Constants.DEFAULT_HTTP_TIME_OUT) - .addBody(HeartbeatRequestBody.CLIENTTYPE, ClientType.SUB.name()) - .addBody(HeartbeatRequestBody.CONSUMERGROUP, eventMeshClientConfig.getConsumerGroup()) - .addBody(HeartbeatRequestBody.HEARTBEATENTITIES, - JsonUtils.serialize(heartbeatEntities)); - return requestParam; - } - - public void heartBeat(List topicList, String url) throws Exception { - scheduler.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - try { - if (!started.get()) { - start(); - } - RequestParam requestParam = generateHeartBeatRequestParam(topicList, url); - - long startTime = System.nanoTime(); - String target = selectEventMesh(); - String res = ""; - - try (CloseableHttpClient httpClient = setHttpClient()) { - res = HttpUtil.post(httpClient, target, requestParam); - } - - if (log.isDebugEnabled()) { - log.debug( - "heartBeat message by await, targetEventMesh:{}, cost:{}ms, rtn:{}", - target, (System.nanoTime() - startTime) / 1000000, res); - } - - EventMeshRetObj ret = JsonUtils.deserialize(res, EventMeshRetObj.class); - - if (ret.getRetCode() != EventMeshRetCode.SUCCESS.getRetCode()) { - throw new EventMeshException(ret.getRetCode(), ret.getRetMsg()); - } - } catch (Exception e) { - log.error("send heartBeat error", e); - } - } - }, EventMeshCommon.HEARTBEAT, EventMeshCommon.HEARTBEAT, TimeUnit.MILLISECONDS); - } - - public boolean unsubscribe(List topicList, String url) throws Exception { - Set unSub = new HashSet<>(topicList); - subscription.removeIf(item -> unSub.contains(item.getTopic())); - - RequestParam unSubscribeParam = generateUnSubscribeRequestParam(topicList, url); - - long startTime = System.nanoTime(); - String target = selectEventMesh(); - String unSubRes = ""; - - try (CloseableHttpClient httpClient = setHttpClient()) { - unSubRes = HttpUtil.post(httpClient, target, unSubscribeParam); - } - - if (log.isDebugEnabled()) { - log.debug( - "unSubscribe message by await, targetEventMesh:{}, cost:{}ms, unSubscribeParam:{}, " - + "rtn:{}", target, (System.nanoTime() - startTime) / 1000000, - JsonUtils.serialize(unSubscribeParam), unSubRes); - } - - EventMeshRetObj ret = JsonUtils.deserialize(unSubRes, EventMeshRetObj.class); - - if (ret.getRetCode() == EventMeshRetCode.SUCCESS.getRetCode()) { - return true; - } else { - throw new EventMeshException(ret.getRetCode(), ret.getRetMsg()); - } - } - - private RequestParam generateUnSubscribeRequestParam(List topicList, String url) { - RequestParam requestParam = new RequestParam(HttpMethod.POST); - requestParam - .addHeader(ProtocolKey.REQUEST_CODE, RequestCode.UNSUBSCRIBE.getRequestCode()) - .addHeader(ProtocolKey.ClientInstanceKey.ENV, eventMeshClientConfig.getEnv()) - .addHeader(ProtocolKey.ClientInstanceKey.IDC, eventMeshClientConfig.getIdc()) - .addHeader(ProtocolKey.ClientInstanceKey.IP, eventMeshClientConfig.getIp()) - .addHeader(ProtocolKey.ClientInstanceKey.PID, eventMeshClientConfig.getPid()) - .addHeader(ProtocolKey.ClientInstanceKey.SYS, eventMeshClientConfig.getSys()) - .addHeader(ProtocolKey.ClientInstanceKey.USERNAME, eventMeshClientConfig.getUserName()) - .addHeader(ProtocolKey.ClientInstanceKey.PASSWD, eventMeshClientConfig.getPassword()) - .addHeader(ProtocolKey.VERSION, ProtocolVersion.V1.getVersion()) - .addHeader(ProtocolKey.LANGUAGE, Constants.LANGUAGE_JAVA) - .setTimeout(Constants.DEFAULT_HTTP_TIME_OUT) - .addBody(UnSubscribeRequestBody.TOPIC, JsonUtils.serialize(topicList)) - .addBody(UnSubscribeRequestBody.CONSUMERGROUP, eventMeshClientConfig.getConsumerGroup()) - .addBody(UnSubscribeRequestBody.URL, url); - return requestParam; - } - - public String selectEventMesh() { - if (liteClientConfig.isUseTls()) { - return Constants.HTTPS_PROTOCOL_PREFIX + eventMeshServerSelector.select(); - } else { - return Constants.HTTP_PROTOCOL_PREFIX + eventMeshServerSelector.select(); - } - } -} diff --git a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/consumer/listener/LiteMessageListener.java b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/consumer/listener/LiteMessageListener.java index c7f5ac99af..38ac5b2705 100644 --- a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/consumer/listener/LiteMessageListener.java +++ b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/consumer/listener/LiteMessageListener.java @@ -20,11 +20,11 @@ import org.apache.eventmesh.client.http.consumer.HandleResult; import org.apache.eventmesh.client.http.consumer.context.LiteConsumeContext; -import org.apache.eventmesh.common.LiteMessage; +import org.apache.eventmesh.common.EventMeshMessage; public interface LiteMessageListener { - HandleResult handle(LiteMessage liteMessage, LiteConsumeContext liteConsumeContext); + HandleResult handle(EventMeshMessage eventMeshMessage, LiteConsumeContext liteConsumeContext); boolean reject(); diff --git a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/http/RequestParam.java b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/model/RequestParam.java similarity index 90% rename from eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/http/RequestParam.java rename to eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/model/RequestParam.java index de8c82f1ac..2e33444285 100644 --- a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/http/RequestParam.java +++ b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/model/RequestParam.java @@ -15,7 +15,9 @@ * limitations under the License. */ -package org.apache.eventmesh.client.http.http; +package org.apache.eventmesh.client.http.model; + +import org.apache.eventmesh.common.Constants; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; @@ -26,21 +28,18 @@ import io.netty.handler.codec.http.HttpMethod; import lombok.extern.slf4j.Slf4j; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - @Slf4j public class RequestParam { private Map queryParams; - private HttpMethod httpMethod; + private final HttpMethod httpMethod; private Map body; private Map headers; - private long timeout; + private long timeout = Constants.DEFAULT_HTTP_TIME_OUT; public RequestParam(HttpMethod httpMethod) { this.httpMethod = httpMethod; @@ -81,11 +80,11 @@ public String getQueryParams() { for (Map.Entry query : queryParams.entrySet()) { for (String val : query.getValue()) { stringBuilder.append("&") - .append(URLEncoder.encode(query.getKey(), "UTF-8")); + .append(URLEncoder.encode(query.getKey(), "UTF-8")); if (val != null && !val.isEmpty()) { stringBuilder.append("=") - .append(URLEncoder.encode(val, "UTF-8")); + .append(URLEncoder.encode(val, "UTF-8")); } } } @@ -106,7 +105,7 @@ public RequestParam addQueryParam(String key, String value) { queryParams = new HashMap<>(); } if (!queryParams.containsKey(key)) { - queryParams.put(key, new String[]{value}); + queryParams.put(key, new String[] {value}); } else { queryParams.put(key, (String[]) Arrays.asList(queryParams.get(key), value).toArray()); } diff --git a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/producer/CloudEventProducer.java b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/producer/CloudEventProducer.java new file mode 100644 index 0000000000..9fd83aa101 --- /dev/null +++ b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/producer/CloudEventProducer.java @@ -0,0 +1,114 @@ +package org.apache.eventmesh.client.http.producer; + +import org.apache.eventmesh.client.http.AbstractHttpClient; +import org.apache.eventmesh.client.http.EventMeshRetObj; +import org.apache.eventmesh.client.http.conf.EventMeshHttpClientConfig; +import org.apache.eventmesh.client.http.model.RequestParam; +import org.apache.eventmesh.client.http.util.HttpUtils; +import org.apache.eventmesh.common.Constants; +import org.apache.eventmesh.common.exception.EventMeshException; +import org.apache.eventmesh.common.protocol.http.body.message.SendMessageRequestBody; +import org.apache.eventmesh.common.protocol.http.body.message.SendMessageResponseBody; +import org.apache.eventmesh.common.protocol.http.common.EventMeshRetCode; +import org.apache.eventmesh.common.protocol.http.common.ProtocolKey; +import org.apache.eventmesh.common.protocol.http.common.ProtocolVersion; +import org.apache.eventmesh.common.protocol.http.common.RequestCode; +import org.apache.eventmesh.common.utils.JsonUtils; + +import java.io.IOException; + +import com.google.common.base.Preconditions; + +import io.cloudevents.CloudEvent; +import io.netty.handler.codec.http.HttpMethod; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +class CloudEventProducer extends AbstractHttpClient implements EventMeshProtocolProducer { + + public CloudEventProducer(EventMeshHttpClientConfig eventMeshHttpClientConfig) throws EventMeshException { + super(eventMeshHttpClientConfig); + } + + @Override + public void publish(CloudEvent cloudEvent) throws EventMeshException { + validateCloudEvent(cloudEvent); + // todo: Can put to abstract class, all protocol use the same send method? This can be a template method + RequestParam requestParam = buildCommonPostParam(cloudEvent) + .addHeader(ProtocolKey.REQUEST_CODE, RequestCode.MSG_SEND_ASYNC.getRequestCode()); + String target = selectEventMesh(); + try { + String response = HttpUtils.post(httpClient, target, requestParam); + EventMeshRetObj ret = JsonUtils.deserialize(response, EventMeshRetObj.class); + + if (ret.getRetCode() != EventMeshRetCode.SUCCESS.getRetCode()) { + throw new EventMeshException(ret.getRetCode(), ret.getRetMsg()); + } + } catch (Exception exception) { + throw new EventMeshException(String.format("Publish message error, target:%s", target), exception); + } + + } + + @Override + public CloudEvent request(CloudEvent cloudEvent, long timeout) throws EventMeshException { + validateCloudEvent(cloudEvent); + RequestParam requestParam = buildCommonPostParam(cloudEvent) + .addHeader(ProtocolKey.REQUEST_CODE, RequestCode.MSG_SEND_SYNC.getRequestCode()) + .setTimeout(timeout); + String target = selectEventMesh(); + + try { + String response = HttpUtils.post(httpClient, target, requestParam); + EventMeshRetObj ret = JsonUtils.deserialize(response, EventMeshRetObj.class); + if (ret.getRetCode() == EventMeshRetCode.SUCCESS.getRetCode()) { + return transformMessage(ret); + } + throw new EventMeshException(ret.getRetCode(), ret.getRetMsg()); + } catch (Exception e) { + throw new EventMeshException(String.format("Request message error, target:%s", target), e); + } + } + + @Override + public void request(CloudEvent cloudEvent, RRCallback rrCallback, long timeout) + throws EventMeshException { + validateCloudEvent(cloudEvent); + RequestParam requestParam = buildCommonPostParam(cloudEvent) + .addHeader(ProtocolKey.REQUEST_CODE, RequestCode.MSG_SEND_SYNC.getRequestCode()) + .setTimeout(timeout); + String target = selectEventMesh(); + RRCallbackResponseHandlerAdapter adapter = + new RRCallbackResponseHandlerAdapter<>(cloudEvent, rrCallback, timeout); + try { + HttpUtils.post(httpClient, null, target, requestParam, adapter); + } catch (IOException e) { + throw new EventMeshException(String.format("Request message error, target:%s", target), e); + } + + } + + private void validateCloudEvent(CloudEvent cloudEvent) { + Preconditions.checkNotNull(cloudEvent, "CloudEvent cannot be null"); + } + + private RequestParam buildCommonPostParam(CloudEvent cloudEvent) { + RequestParam requestParam = new RequestParam(HttpMethod.POST); + requestParam + .addHeader(ProtocolKey.ClientInstanceKey.USERNAME, eventMeshHttpClientConfig.getUserName()) + .addHeader(ProtocolKey.ClientInstanceKey.PASSWD, eventMeshHttpClientConfig.getPassword()) + .addHeader(ProtocolKey.VERSION, ProtocolVersion.V1.getVersion()) + .addHeader(ProtocolKey.LANGUAGE, Constants.LANGUAGE_JAVA) + // todo: add producerGroup to header, set protocol type, protocol version + .addBody(SendMessageRequestBody.PRODUCERGROUP, eventMeshHttpClientConfig.getProducerGroup()) + .addBody(SendMessageRequestBody.CONTENT, JsonUtils.serialize(cloudEvent)); + return requestParam; + } + + private CloudEvent transformMessage(EventMeshRetObj retObj) { + SendMessageResponseBody.ReplyMessage replyMessage = JsonUtils.deserialize(retObj.getRetMsg(), + SendMessageResponseBody.ReplyMessage.class); + // todo: deserialize message + return null; + } +} diff --git a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/producer/EventMeshHttpProducer.java b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/producer/EventMeshHttpProducer.java new file mode 100644 index 0000000000..1077427535 --- /dev/null +++ b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/producer/EventMeshHttpProducer.java @@ -0,0 +1,89 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.apache.eventmesh.client.http.producer; + +import org.apache.eventmesh.client.http.conf.EventMeshHttpClientConfig; +import org.apache.eventmesh.common.EventMeshMessage; +import org.apache.eventmesh.common.exception.EventMeshException; + +import io.cloudevents.CloudEvent; +import io.openmessaging.api.Message; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +public class EventMeshHttpProducer implements AutoCloseable { + + private final EventMeshMessageProducer eventMeshMessageProducer; + private final CloudEventProducer cloudEventProducer; + private final OpenMessageProducer openMessageProducer; + + public EventMeshHttpProducer(final EventMeshHttpClientConfig eventMeshHttpClientConfig) throws EventMeshException { + this.cloudEventProducer = new CloudEventProducer(eventMeshHttpClientConfig); + this.eventMeshMessageProducer = new EventMeshMessageProducer(eventMeshHttpClientConfig); + this.openMessageProducer = new OpenMessageProducer(eventMeshHttpClientConfig); + } + + public void publish(final EventMeshMessage message) throws EventMeshException { + eventMeshMessageProducer.publish(message); + } + + public void publish(final CloudEvent cloudEvent) throws EventMeshException { + cloudEventProducer.publish(cloudEvent); + } + + public void publish(final Message openMessage) throws EventMeshException { + openMessageProducer.publish(openMessage); + } + + public EventMeshMessage request(final EventMeshMessage message, final long timeout) throws EventMeshException { + return eventMeshMessageProducer.request(message, timeout); + } + + public CloudEvent request(final CloudEvent cloudEvent, final long timeout) throws EventMeshException { + return cloudEventProducer.request(cloudEvent, timeout); + } + + public Message request(final Message openMessage, final long timeout) throws EventMeshException { + return openMessageProducer.request(openMessage, timeout); + } + + public void request(final EventMeshMessage message, final RRCallback rrCallback, final long timeout) + throws EventMeshException { + eventMeshMessageProducer.request(message, rrCallback, timeout); + } + + public void request(final CloudEvent cloudEvent, final RRCallback rrCallback, final long timeout) + throws EventMeshException { + cloudEventProducer.request(cloudEvent, rrCallback, timeout); + } + + public void request(final Message openMessage, final RRCallback rrCallback, final long timeout) + throws EventMeshException { + openMessageProducer.request(openMessage, rrCallback, timeout); + } + + @Override + public void close() throws EventMeshException { + try ( + final EventMeshMessageProducer ignored = eventMeshMessageProducer; + final OpenMessageProducer ignored1 = openMessageProducer; + final CloudEventProducer ignored2 = cloudEventProducer) { + log.info("Close producer"); + } + } +} diff --git a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/producer/EventMeshMessageProducer.java b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/producer/EventMeshMessageProducer.java new file mode 100644 index 0000000000..85f6153953 --- /dev/null +++ b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/producer/EventMeshMessageProducer.java @@ -0,0 +1,128 @@ +package org.apache.eventmesh.client.http.producer; + +import org.apache.eventmesh.client.http.AbstractHttpClient; +import org.apache.eventmesh.client.http.EventMeshRetObj; +import org.apache.eventmesh.client.http.conf.EventMeshHttpClientConfig; +import org.apache.eventmesh.client.http.model.RequestParam; +import org.apache.eventmesh.client.http.util.HttpUtils; +import org.apache.eventmesh.common.Constants; +import org.apache.eventmesh.common.EventMeshMessage; +import org.apache.eventmesh.common.exception.EventMeshException; +import org.apache.eventmesh.common.protocol.http.body.message.SendMessageRequestBody; +import org.apache.eventmesh.common.protocol.http.body.message.SendMessageResponseBody; +import org.apache.eventmesh.common.protocol.http.common.EventMeshRetCode; +import org.apache.eventmesh.common.protocol.http.common.ProtocolKey; +import org.apache.eventmesh.common.protocol.http.common.ProtocolVersion; +import org.apache.eventmesh.common.protocol.http.common.RequestCode; +import org.apache.eventmesh.common.utils.JsonUtils; + +import java.io.IOException; + +import com.google.common.base.Preconditions; + +import io.netty.handler.codec.http.HttpMethod; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +class EventMeshMessageProducer extends AbstractHttpClient implements EventMeshProtocolProducer { + + public EventMeshMessageProducer(EventMeshHttpClientConfig eventMeshHttpClientConfig) throws EventMeshException { + super(eventMeshHttpClientConfig); + } + + @Override + public void publish(EventMeshMessage message) throws EventMeshException { + validateEventMeshMessage(message); + RequestParam requestParam = buildCommonPostParam(message) + .addHeader(ProtocolKey.REQUEST_CODE, RequestCode.MSG_SEND_ASYNC.getRequestCode()); + + String target = selectEventMesh(); + try { + String response = HttpUtils.post(httpClient, target, requestParam); + EventMeshRetObj ret = JsonUtils.deserialize(response, EventMeshRetObj.class); + + if (ret.getRetCode() != EventMeshRetCode.SUCCESS.getRetCode()) { + throw new EventMeshException(ret.getRetCode(), ret.getRetMsg()); + } + } catch (Exception exception) { + throw new EventMeshException(String.format("Publish message error, target:%s", target), exception); + } + } + + @Override + public EventMeshMessage request(EventMeshMessage message, long timeout) throws EventMeshException { + validateEventMeshMessage(message); + RequestParam requestParam = buildCommonPostParam(message) + .addHeader(ProtocolKey.REQUEST_CODE, RequestCode.MSG_SEND_SYNC.getRequestCode()) + .setTimeout(timeout); + + String target = selectEventMesh(); + + try { + String response = HttpUtils.post(httpClient, target, requestParam); + EventMeshRetObj ret = JsonUtils.deserialize(response, EventMeshRetObj.class); + if (ret.getRetCode() == EventMeshRetCode.SUCCESS.getRetCode()) { + return transformMessage(ret); + } + throw new EventMeshException(ret.getRetCode(), ret.getRetMsg()); + } catch (Exception e) { + throw new EventMeshException(String.format("Request message error, target:%s", target), e); + } + } + + @Override + public void request(EventMeshMessage message, RRCallback rrCallback, long timeout) + throws EventMeshException { + validateEventMeshMessage(message); + + RequestParam requestParam = buildCommonPostParam(message) + .addHeader(ProtocolKey.REQUEST_CODE, RequestCode.MSG_SEND_SYNC.getRequestCode()) + .setTimeout(timeout); + + String target = selectEventMesh(); + RRCallbackResponseHandlerAdapter adapter = + new RRCallbackResponseHandlerAdapter<>(message, rrCallback, timeout); + try { + HttpUtils.post(httpClient, null, target, requestParam, adapter); + } catch (IOException e) { + throw new EventMeshException(String.format("Request message error, target:%s", target), e); + } + } + + private void validateEventMeshMessage(EventMeshMessage message) { + Preconditions.checkNotNull(message, "eventMeshMessage invalid"); + Preconditions.checkNotNull(message.getTopic(), "eventMeshMessage[topic] invalid"); + Preconditions.checkNotNull(message.getContent(), "eventMeshMessage[content] invalid"); + } + + private RequestParam buildCommonPostParam(EventMeshMessage message) { + RequestParam requestParam = new RequestParam(HttpMethod.POST); + requestParam + .addHeader(ProtocolKey.ClientInstanceKey.ENV, eventMeshHttpClientConfig.getEnv()) + .addHeader(ProtocolKey.ClientInstanceKey.IDC, eventMeshHttpClientConfig.getIdc()) + .addHeader(ProtocolKey.ClientInstanceKey.IP, eventMeshHttpClientConfig.getIp()) + .addHeader(ProtocolKey.ClientInstanceKey.PID, eventMeshHttpClientConfig.getPid()) + .addHeader(ProtocolKey.ClientInstanceKey.SYS, eventMeshHttpClientConfig.getSys()) + .addHeader(ProtocolKey.ClientInstanceKey.USERNAME, eventMeshHttpClientConfig.getUserName()) + .addHeader(ProtocolKey.ClientInstanceKey.PASSWD, eventMeshHttpClientConfig.getPassword()) + .addHeader(ProtocolKey.VERSION, ProtocolVersion.V1.getVersion()) + .addHeader(ProtocolKey.LANGUAGE, Constants.LANGUAGE_JAVA) + .addBody(SendMessageRequestBody.PRODUCERGROUP, eventMeshHttpClientConfig.getProducerGroup()) + // todo: set message to content is better + .addBody(SendMessageRequestBody.TOPIC, message.getTopic()) + .addBody(SendMessageRequestBody.CONTENT, message.getContent()) + .addBody(SendMessageRequestBody.TTL, message.getProp(Constants.EVENTMESH_MESSAGE_CONST_TTL)) + .addBody(SendMessageRequestBody.BIZSEQNO, message.getBizSeqNo()) + .addBody(SendMessageRequestBody.UNIQUEID, message.getUniqueId()); + return requestParam; + } + + private EventMeshMessage transformMessage(EventMeshRetObj retObj) { + SendMessageResponseBody.ReplyMessage replyMessage = JsonUtils.deserialize(retObj.getRetMsg(), + SendMessageResponseBody.ReplyMessage.class); + return EventMeshMessage.builder() + .content(replyMessage.body) + .prop(replyMessage.properties) + .topic(replyMessage.topic).build(); + } +} diff --git a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/producer/EventMeshProtocolProducer.java b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/producer/EventMeshProtocolProducer.java new file mode 100644 index 0000000000..349406f162 --- /dev/null +++ b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/producer/EventMeshProtocolProducer.java @@ -0,0 +1,22 @@ +package org.apache.eventmesh.client.http.producer; + +import org.apache.eventmesh.common.exception.EventMeshException; + +/** + * EventMeshProducer, SDK should implement this interface. + *

    + *
  • {@link EventMeshProtocolProducer}
  • + *
  • {@link OpenMessageProducer}
  • + *
  • {@link CloudEventProducer}
  • + *
+ */ +public interface EventMeshProtocolProducer extends AutoCloseable { + + void publish(ProtocolMessage eventMeshMessage) throws EventMeshException; + + ProtocolMessage request(ProtocolMessage message, long timeout) throws EventMeshException; + + void request(ProtocolMessage message, RRCallback rrCallback, long timeout) + throws EventMeshException; + +} diff --git a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/producer/LiteProducer.java b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/producer/LiteProducer.java deleted file mode 100644 index 0fadad6222..0000000000 --- a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/producer/LiteProducer.java +++ /dev/null @@ -1,245 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.apache.eventmesh.client.http.producer; - -import org.apache.eventmesh.client.http.AbstractLiteClient; -import org.apache.eventmesh.client.http.EventMeshRetObj; -import org.apache.eventmesh.client.http.conf.LiteClientConfig; -import org.apache.eventmesh.client.http.http.HttpUtil; -import org.apache.eventmesh.client.http.http.RequestParam; -import org.apache.eventmesh.common.Constants; -import org.apache.eventmesh.common.EventMeshException; -import org.apache.eventmesh.common.LiteMessage; -import org.apache.eventmesh.common.protocol.http.body.message.SendMessageRequestBody; -import org.apache.eventmesh.common.protocol.http.body.message.SendMessageResponseBody; -import org.apache.eventmesh.common.protocol.http.common.EventMeshRetCode; -import org.apache.eventmesh.common.protocol.http.common.ProtocolKey; -import org.apache.eventmesh.common.protocol.http.common.ProtocolVersion; -import org.apache.eventmesh.common.protocol.http.common.RequestCode; -import org.apache.eventmesh.common.utils.JsonUtils; - -import org.apache.commons.lang3.ObjectUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.http.impl.client.CloseableHttpClient; - -import java.util.concurrent.atomic.AtomicBoolean; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.base.Preconditions; - -import io.netty.handler.codec.http.HttpMethod; -import lombok.extern.slf4j.Slf4j; - -@Slf4j -public class LiteProducer extends AbstractLiteClient { - - public LiteProducer(LiteClientConfig liteClientConfig) { - super(liteClientConfig); - } - - private static final AtomicBoolean started = new AtomicBoolean(Boolean.FALSE); - - @Override - public void start() throws Exception { - Preconditions.checkNotNull(liteClientConfig, "liteClientConfig can't be null"); - Preconditions.checkNotNull( - liteClientConfig.getLiteEventMeshAddr(), "liteClientConfig.liteServerAddr can't be null" - ); - if (started.get()) { - return; - } - log.info("LiteProducer starting"); - super.start(); - started.compareAndSet(false, true); - log.info("LiteProducer started"); - } - - @Override - public void shutdown() throws Exception { - if (!started.get()) { - return; - } - log.info("LiteProducer shutting down"); - super.shutdown(); - started.compareAndSet(true, false); - log.info("LiteProducer shutdown"); - } - - public AtomicBoolean getStarted() { - return started; - } - - public boolean publish(LiteMessage message) throws Exception { - if (!started.get()) { - start(); - } - Preconditions.checkState(StringUtils.isNotBlank(message.getTopic()), - "eventMeshMessage[topic] invalid"); - Preconditions.checkState(StringUtils.isNotBlank(message.getContent()), - "eventMeshMessage[content] invalid"); - RequestParam requestParam = new RequestParam(HttpMethod.POST); - requestParam - .addHeader(ProtocolKey.REQUEST_CODE, RequestCode.MSG_SEND_ASYNC.getRequestCode()) - .addHeader(ProtocolKey.ClientInstanceKey.ENV, liteClientConfig.getEnv()) - .addHeader(ProtocolKey.ClientInstanceKey.IDC, liteClientConfig.getIdc()) - .addHeader(ProtocolKey.ClientInstanceKey.IP, liteClientConfig.getIp()) - .addHeader(ProtocolKey.ClientInstanceKey.PID, liteClientConfig.getPid()) - .addHeader(ProtocolKey.ClientInstanceKey.SYS, liteClientConfig.getSys()) - .addHeader(ProtocolKey.ClientInstanceKey.USERNAME, liteClientConfig.getUserName()) - .addHeader(ProtocolKey.ClientInstanceKey.PASSWD, liteClientConfig.getPassword()) - .addHeader(ProtocolKey.VERSION, ProtocolVersion.V1.getVersion()) - .addHeader(ProtocolKey.LANGUAGE, Constants.LANGUAGE_JAVA) - .setTimeout(Constants.DEFAULT_HTTP_TIME_OUT) - .addBody(SendMessageRequestBody.PRODUCERGROUP, liteClientConfig.getProducerGroup()) - .addBody(SendMessageRequestBody.TOPIC, message.getTopic()) - .addBody(SendMessageRequestBody.CONTENT, message.getContent()) - .addBody(SendMessageRequestBody.TTL, message.getPropKey(Constants.EVENTMESH_MESSAGE_CONST_TTL)) - .addBody(SendMessageRequestBody.BIZSEQNO, message.getBizSeqNo()) - .addBody(SendMessageRequestBody.UNIQUEID, message.getUniqueId()); - - long startTime = System.nanoTime(); - String target = selectEventMesh(); - String res = ""; - - try (CloseableHttpClient httpClient = setHttpClient()) { - res = HttpUtil.post(httpClient, target, requestParam); - } - - if (log.isDebugEnabled()) { - log.debug("publish async message, targetEventMesh:{}, cost:{}ms, message:{}, rtn:{}", - target, (System.nanoTime() - startTime) / 1000000, message, res); - } - - EventMeshRetObj ret = JsonUtils.deserialize(res, EventMeshRetObj.class); - - if (ret.getRetCode() == EventMeshRetCode.SUCCESS.getRetCode()) { - return true; - } else { - throw new EventMeshException(ret.getRetCode(), ret.getRetMsg()); - } - } - - public String selectEventMesh() { - if (liteClientConfig.isUseTls()) { - return Constants.HTTPS_PROTOCOL_PREFIX + eventMeshServerSelector.select(); - } else { - return Constants.HTTP_PROTOCOL_PREFIX + eventMeshServerSelector.select(); - } - } - - public LiteMessage request(LiteMessage message, long timeout) throws Exception { - if (!started.get()) { - start(); - } - Preconditions.checkState(StringUtils.isNotBlank(message.getTopic()), - "eventMeshMessage[topic] invalid"); - Preconditions.checkState(StringUtils.isNotBlank(message.getContent()), - "eventMeshMessage[content] invalid"); - RequestParam requestParam = new RequestParam(HttpMethod.POST); - requestParam - .addHeader(ProtocolKey.REQUEST_CODE, RequestCode.MSG_SEND_SYNC.getRequestCode()) - .addHeader(ProtocolKey.ClientInstanceKey.ENV, liteClientConfig.getEnv()) - .addHeader(ProtocolKey.ClientInstanceKey.IDC, liteClientConfig.getIdc()) - .addHeader(ProtocolKey.ClientInstanceKey.IP, liteClientConfig.getIp()) - .addHeader(ProtocolKey.ClientInstanceKey.PID, liteClientConfig.getPid()) - .addHeader(ProtocolKey.ClientInstanceKey.SYS, liteClientConfig.getSys()) - .addHeader(ProtocolKey.ClientInstanceKey.USERNAME, liteClientConfig.getUserName()) - .addHeader(ProtocolKey.ClientInstanceKey.PASSWD, liteClientConfig.getPassword()) - .addHeader(ProtocolKey.VERSION, ProtocolVersion.V1.getVersion()) - .addHeader(ProtocolKey.LANGUAGE, Constants.LANGUAGE_JAVA) - .setTimeout(timeout) - .addBody(SendMessageRequestBody.PRODUCERGROUP, liteClientConfig.getProducerGroup()) - .addBody(SendMessageRequestBody.TOPIC, message.getTopic()) - .addBody(SendMessageRequestBody.CONTENT, message.getContent()) - .addBody(SendMessageRequestBody.TTL, String.valueOf(timeout)) - .addBody(SendMessageRequestBody.BIZSEQNO, message.getBizSeqNo()) - .addBody(SendMessageRequestBody.UNIQUEID, message.getUniqueId()); - - long startTime = System.nanoTime(); - String target = selectEventMesh(); - String res = ""; - - try (CloseableHttpClient httpClient = setHttpClient()) { - res = HttpUtil.post(httpClient, target, requestParam); - } - - if (log.isDebugEnabled()) { - log.debug( - "publish sync message by await, targetEventMesh:{}, cost:{}ms, message:{}, rtn:{}", - target, (System.nanoTime() - startTime) / 1000000, message, res); - } - - EventMeshRetObj ret = JsonUtils.deserialize(res, EventMeshRetObj.class); - if (ret.getRetCode() == EventMeshRetCode.SUCCESS.getRetCode()) { - LiteMessage eventMeshMessage = new LiteMessage(); - SendMessageResponseBody.ReplyMessage replyMessage = - JsonUtils.deserialize(ret.getRetMsg(), SendMessageResponseBody.ReplyMessage.class); - eventMeshMessage.setContent(replyMessage.body).setProp(replyMessage.properties) - .setTopic(replyMessage.topic); - return eventMeshMessage; - } - // todo: return msg - return null; - } - - public void request(LiteMessage message, RRCallback rrCallback, long timeout) throws Exception { - if (!started.get()) { - start(); - } - Preconditions.checkState(StringUtils.isNotBlank(message.getTopic()), - "eventMeshMessage[topic] invalid"); - Preconditions.checkState(StringUtils.isNotBlank(message.getContent()), - "eventMeshMessage[content] invalid"); - Preconditions.checkState(ObjectUtils.allNotNull(rrCallback), - "rrCallback invalid"); - RequestParam requestParam = new RequestParam(HttpMethod.POST); - requestParam - .addHeader(ProtocolKey.REQUEST_CODE, RequestCode.MSG_SEND_SYNC.getRequestCode()) - .addHeader(ProtocolKey.ClientInstanceKey.ENV, liteClientConfig.getEnv()) - .addHeader(ProtocolKey.ClientInstanceKey.IDC, liteClientConfig.getIdc()) - .addHeader(ProtocolKey.ClientInstanceKey.IP, liteClientConfig.getIp()) - .addHeader(ProtocolKey.ClientInstanceKey.PID, liteClientConfig.getPid()) - .addHeader(ProtocolKey.ClientInstanceKey.SYS, liteClientConfig.getSys()) - .addHeader(ProtocolKey.ClientInstanceKey.USERNAME, liteClientConfig.getUserName()) - .addHeader(ProtocolKey.ClientInstanceKey.PASSWD, liteClientConfig.getPassword()) - .addHeader(ProtocolKey.VERSION, ProtocolVersion.V1.getVersion()) - .addHeader(ProtocolKey.LANGUAGE, Constants.LANGUAGE_JAVA) - .setTimeout(timeout) - .addBody(SendMessageRequestBody.PRODUCERGROUP, liteClientConfig.getProducerGroup()) - .addBody(SendMessageRequestBody.TOPIC, message.getTopic()) - .addBody(SendMessageRequestBody.CONTENT, message.getContent()) - .addBody(SendMessageRequestBody.TTL, String.valueOf(timeout)) - .addBody(SendMessageRequestBody.BIZSEQNO, message.getBizSeqNo()) - .addBody(SendMessageRequestBody.UNIQUEID, message.getUniqueId()); - - long startTime = System.nanoTime(); - String target = selectEventMesh(); - - try (CloseableHttpClient httpClient = setHttpClient()) { - HttpUtil.post(httpClient, null, target, requestParam, - new RRCallbackResponseHandlerAdapter(message, rrCallback, timeout)); - } - - if (log.isDebugEnabled()) { - log.debug("publish sync message by async, target:{}, cost:{}, message:{}", target, - (System.nanoTime() - startTime) / 1000000, message); - } - } -} diff --git a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/producer/OpenMessageProducer.java b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/producer/OpenMessageProducer.java new file mode 100644 index 0000000000..b3cadccf19 --- /dev/null +++ b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/producer/OpenMessageProducer.java @@ -0,0 +1,111 @@ +package org.apache.eventmesh.client.http.producer; + +import org.apache.eventmesh.client.http.AbstractHttpClient; +import org.apache.eventmesh.client.http.EventMeshRetObj; +import org.apache.eventmesh.client.http.conf.EventMeshHttpClientConfig; +import org.apache.eventmesh.client.http.model.RequestParam; +import org.apache.eventmesh.client.http.util.HttpUtils; +import org.apache.eventmesh.common.Constants; +import org.apache.eventmesh.common.exception.EventMeshException; +import org.apache.eventmesh.common.protocol.http.body.message.SendMessageRequestBody; +import org.apache.eventmesh.common.protocol.http.body.message.SendMessageResponseBody; +import org.apache.eventmesh.common.protocol.http.common.EventMeshRetCode; +import org.apache.eventmesh.common.protocol.http.common.ProtocolKey; +import org.apache.eventmesh.common.protocol.http.common.ProtocolVersion; +import org.apache.eventmesh.common.protocol.http.common.RequestCode; +import org.apache.eventmesh.common.utils.JsonUtils; + +import java.io.IOException; + +import com.google.common.base.Preconditions; + +import io.netty.handler.codec.http.HttpMethod; +import io.openmessaging.api.Message; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +class OpenMessageProducer extends AbstractHttpClient implements EventMeshProtocolProducer { + + public OpenMessageProducer(EventMeshHttpClientConfig eventMeshHttpClientConfig) + throws EventMeshException { + super(eventMeshHttpClientConfig); + } + + @Override + public void publish(Message openMessage) throws EventMeshException { + validateOpenMessage(openMessage); + RequestParam requestParam = buildCommonPostParam(openMessage) + .addHeader(ProtocolKey.REQUEST_CODE, RequestCode.MSG_SEND_ASYNC.getRequestCode()); + String target = selectEventMesh(); + try { + String response = HttpUtils.post(httpClient, target, requestParam); + EventMeshRetObj ret = JsonUtils.deserialize(response, EventMeshRetObj.class); + + if (ret.getRetCode() != EventMeshRetCode.SUCCESS.getRetCode()) { + throw new EventMeshException(ret.getRetCode(), ret.getRetMsg()); + } + } catch (Exception exception) { + throw new EventMeshException(String.format("Publish message error, target:%s", target), exception); + } + } + + @Override + public Message request(Message message, long timeout) throws EventMeshException { + validateOpenMessage(message); + RequestParam requestParam = buildCommonPostParam(message) + .addHeader(ProtocolKey.REQUEST_CODE, RequestCode.MSG_SEND_SYNC.getRequestCode()) + .setTimeout(timeout); + String target = selectEventMesh(); + + try { + String response = HttpUtils.post(httpClient, target, requestParam); + EventMeshRetObj ret = JsonUtils.deserialize(response, EventMeshRetObj.class); + if (ret.getRetCode() == EventMeshRetCode.SUCCESS.getRetCode()) { + return transformMessage(ret); + } + throw new EventMeshException(ret.getRetCode(), ret.getRetMsg()); + } catch (Exception e) { + throw new EventMeshException(String.format("Request message error, target:%s", target), e); + } + } + + @Override + public void request(Message message, RRCallback rrCallback, long timeout) throws EventMeshException { + validateOpenMessage(message); + RequestParam requestParam = buildCommonPostParam(message) + .addHeader(ProtocolKey.REQUEST_CODE, RequestCode.MSG_SEND_SYNC.getRequestCode()) + .setTimeout(timeout); + String target = selectEventMesh(); + RRCallbackResponseHandlerAdapter adapter = + new RRCallbackResponseHandlerAdapter<>(message, rrCallback, timeout); + try { + HttpUtils.post(httpClient, null, target, requestParam, adapter); + } catch (IOException e) { + throw new EventMeshException(String.format("Request message error, target:%s", target), e); + } + } + + private void validateOpenMessage(Message openMessage) { + Preconditions.checkNotNull(openMessage, "Message cannot be null"); + } + + private RequestParam buildCommonPostParam(Message openMessage) { + RequestParam requestParam = new RequestParam(HttpMethod.POST); + requestParam + .addHeader(ProtocolKey.ClientInstanceKey.USERNAME, eventMeshHttpClientConfig.getUserName()) + .addHeader(ProtocolKey.ClientInstanceKey.PASSWD, eventMeshHttpClientConfig.getPassword()) + .addHeader(ProtocolKey.VERSION, ProtocolVersion.V1.getVersion()) + .addHeader(ProtocolKey.LANGUAGE, Constants.LANGUAGE_JAVA) + // todo: add producerGroup to header, set protocol type, protocol version + .addBody(SendMessageRequestBody.PRODUCERGROUP, eventMeshHttpClientConfig.getProducerGroup()) + .addBody(SendMessageRequestBody.CONTENT, JsonUtils.serialize(openMessage)); + return requestParam; + } + + private Message transformMessage(EventMeshRetObj retObj) { + SendMessageResponseBody.ReplyMessage replyMessage = JsonUtils.deserialize(retObj.getRetMsg(), + SendMessageResponseBody.ReplyMessage.class); + // todo: deserialize message + return null; + } +} diff --git a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/producer/RRCallback.java b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/producer/RRCallback.java index c5187984de..08470961a2 100644 --- a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/producer/RRCallback.java +++ b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/producer/RRCallback.java @@ -17,12 +17,17 @@ package org.apache.eventmesh.client.http.producer; +/** + * ProtocolMessage can be + *
    + *
  • {@link org.apache.eventmesh.common.EventMeshMessage}
  • + *
  • {@link io.cloudevents.CloudEvent}
  • + *
  • {@link io.openmessaging.api.Message}
  • + *
+ */ +public interface RRCallback { -import org.apache.eventmesh.common.LiteMessage; - -public interface RRCallback { - - void onSuccess(LiteMessage liteMessage); + void onSuccess(ProtocolMessage protocolMessage); void onException(Throwable e); diff --git a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/producer/RRCallbackResponseHandlerAdapter.java b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/producer/RRCallbackResponseHandlerAdapter.java index 1dcefe59ec..25237da861 100644 --- a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/producer/RRCallbackResponseHandlerAdapter.java +++ b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/producer/RRCallbackResponseHandlerAdapter.java @@ -19,89 +19,90 @@ import org.apache.eventmesh.client.http.EventMeshRetObj; import org.apache.eventmesh.common.Constants; -import org.apache.eventmesh.common.EventMeshException; -import org.apache.eventmesh.common.LiteMessage; +import org.apache.eventmesh.common.EventMeshMessage; +import org.apache.eventmesh.common.exception.EventMeshException; import org.apache.eventmesh.common.protocol.http.body.message.SendMessageResponseBody; import org.apache.eventmesh.common.protocol.http.common.EventMeshRetCode; import org.apache.eventmesh.common.utils.JsonUtils; -import org.apache.commons.lang3.time.DateFormatUtils; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.nio.charset.Charset; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import com.google.common.base.Preconditions; + +import io.cloudevents.CloudEvent; +import io.openmessaging.api.Message; +import lombok.extern.slf4j.Slf4j; /** * RRCallbackResponseHandlerAdapter. */ -public class RRCallbackResponseHandlerAdapter implements ResponseHandler { - - public Logger logger = LoggerFactory.getLogger(RRCallbackResponseHandlerAdapter.class); +@Slf4j +public class RRCallbackResponseHandlerAdapter implements ResponseHandler { - private long createTime; + private final long createTime; - private LiteMessage liteMessage; + private final ProtocolMessage protocolMessage; - private RRCallback rrCallback; + private final RRCallback rrCallback; - private long timeout; + private final long timeout; - public RRCallbackResponseHandlerAdapter(LiteMessage liteMessage, RRCallback rrCallback, + public RRCallbackResponseHandlerAdapter(ProtocolMessage protocolMessage, RRCallback rrCallback, long timeout) { - this.liteMessage = liteMessage; + Preconditions.checkNotNull(rrCallback, "rrCallback invalid"); + Preconditions.checkNotNull(protocolMessage, "message invalid"); + if (!(protocolMessage instanceof EventMeshMessage) && !(protocolMessage instanceof CloudEvent) + && !(protocolMessage instanceof Message)) { + throw new IllegalArgumentException(String.format("ProtocolMessage: %s is not supported", protocolMessage)); + } + this.protocolMessage = protocolMessage; this.rrCallback = rrCallback; this.timeout = timeout; this.createTime = System.currentTimeMillis(); } @Override - public String handleResponse(HttpResponse response) - throws ClientProtocolException, IOException { + public String handleResponse(HttpResponse response) throws IOException { if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { rrCallback.onException(new EventMeshException(response.toString())); return response.toString(); } if (System.currentTimeMillis() - createTime > timeout) { - String err = String.format( - "response too late, bizSeqNo=%s, uniqueId=%s, createTime=%s, ttl=%s, cost=%sms", - liteMessage.getBizSeqNo(), - liteMessage.getUniqueId(), - DateFormatUtils.format(createTime, Constants.DATE_FORMAT), - timeout, - System.currentTimeMillis() - createTime); - logger.warn(err); + String err = String.format("response too late, message: %s", protocolMessage); rrCallback.onException(new EventMeshException(err)); return err; } - String res = - EntityUtils.toString(response.getEntity(), Charset.forName(Constants.DEFAULT_CHARSET)); + String res = EntityUtils.toString(response.getEntity(), Charset.forName(Constants.DEFAULT_CHARSET)); EventMeshRetObj ret = JsonUtils.deserialize(res, EventMeshRetObj.class); if (ret.getRetCode() != EventMeshRetCode.SUCCESS.getRetCode()) { rrCallback.onException(new EventMeshException(ret.getRetCode(), ret.getRetMsg())); return res; } - LiteMessage liteMessage = new LiteMessage(); - try { - SendMessageResponseBody.ReplyMessage replyMessage = - JsonUtils.deserialize(ret.getRetMsg(), SendMessageResponseBody.ReplyMessage.class); - liteMessage.setContent(replyMessage.body).setProp(replyMessage.properties) - .setTopic(replyMessage.topic); - rrCallback.onSuccess(liteMessage); - } catch (Exception ex) { - rrCallback.onException(new EventMeshException(ex)); - return ex.toString(); - } + // todo: constructor protocol message + ProtocolMessage protocolMessage = transformToProtocolMessage(ret); + rrCallback.onSuccess(protocolMessage); + + return protocolMessage.toString(); + } - return liteMessage.toString(); + private ProtocolMessage transformToProtocolMessage(EventMeshRetObj ret) { + // todo: constructor other protocol message, can judge by protocol type in properties + SendMessageResponseBody.ReplyMessage replyMessage = JsonUtils.deserialize(ret.getRetMsg(), + SendMessageResponseBody.ReplyMessage.class); + EventMeshMessage eventMeshMessage = EventMeshMessage.builder() + .content(replyMessage.body) + .prop(replyMessage.properties) + .topic(replyMessage.topic) + .build(); + return (ProtocolMessage) eventMeshMessage; } } diff --git a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/util/HttpLoadBalanceUtils.java b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/util/HttpLoadBalanceUtils.java index 5db7e5415b..d2a779e518 100644 --- a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/util/HttpLoadBalanceUtils.java +++ b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/util/HttpLoadBalanceUtils.java @@ -19,8 +19,9 @@ import com.google.common.base.Splitter; import org.apache.commons.collections4.CollectionUtils; -import org.apache.eventmesh.client.http.conf.LiteClientConfig; -import org.apache.eventmesh.common.EventMeshException; + +import org.apache.eventmesh.client.http.conf.EventMeshHttpClientConfig; +import org.apache.eventmesh.common.exception.EventMeshException; import org.apache.eventmesh.common.loadbalance.LoadBalanceSelector; import org.apache.eventmesh.common.loadbalance.RandomLoadBalanceSelector; import org.apache.eventmesh.common.loadbalance.Weight; @@ -36,18 +37,22 @@ public class HttpLoadBalanceUtils { private static final Pattern IP_PORT_PATTERN = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}:\\d{4,5}"); private static final Pattern IP_PORT_WEIGHT_PATTERN = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}:\\d{4,5}:\\d{1,6}"); - public static LoadBalanceSelector createEventMeshServerLoadBalanceSelector(LiteClientConfig liteClientConfig) + public static LoadBalanceSelector createEventMeshServerLoadBalanceSelector( + EventMeshHttpClientConfig eventMeshHttpClientConfig) throws EventMeshException { LoadBalanceSelector eventMeshServerSelector = null; - switch (liteClientConfig.getLoadBalanceType()) { + switch (eventMeshHttpClientConfig.getLoadBalanceType()) { case RANDOM: - eventMeshServerSelector = new RandomLoadBalanceSelector<>(buildClusterGroupFromConfig(liteClientConfig)); + eventMeshServerSelector = new RandomLoadBalanceSelector<>(buildClusterGroupFromConfig( + eventMeshHttpClientConfig)); break; case WEIGHT_RANDOM: - eventMeshServerSelector = new WeightRandomLoadBalanceSelector<>(buildWeightedClusterGroupFromConfig(liteClientConfig)); + eventMeshServerSelector = new WeightRandomLoadBalanceSelector<>(buildWeightedClusterGroupFromConfig( + eventMeshHttpClientConfig)); break; case WEIGHT_ROUND_ROBIN: - eventMeshServerSelector = new WeightRoundRobinLoadBalanceSelector<>(buildWeightedClusterGroupFromConfig(liteClientConfig)); + eventMeshServerSelector = new WeightRoundRobinLoadBalanceSelector<>(buildWeightedClusterGroupFromConfig( + eventMeshHttpClientConfig)); break; default: // ignore @@ -58,9 +63,10 @@ public static LoadBalanceSelector createEventMeshServerLoadBalanceSelect return eventMeshServerSelector; } - private static List> buildWeightedClusterGroupFromConfig(LiteClientConfig liteClientConfig) + private static List> buildWeightedClusterGroupFromConfig( + EventMeshHttpClientConfig eventMeshHttpClientConfig) throws EventMeshException { - List eventMeshAddrs = Splitter.on(";").trimResults().splitToList(liteClientConfig.getLiteEventMeshAddr()); + List eventMeshAddrs = Splitter.on(";").trimResults().splitToList(eventMeshHttpClientConfig.getLiteEventMeshAddr()); if (CollectionUtils.isEmpty(eventMeshAddrs)) { throw new EventMeshException("liteEventMeshAddr can not be empty"); } @@ -69,7 +75,7 @@ private static List> buildWeightedClusterGroupFromConfig(LiteClie for (String eventMeshAddrWight : eventMeshAddrs) { if (!IP_PORT_WEIGHT_PATTERN.matcher(eventMeshAddrWight).matches()) { throw new EventMeshException( - String.format("liteEventMeshAddr:%s is not illegal", liteClientConfig.getLiteEventMeshAddr())); + String.format("liteEventMeshAddr:%s is not illegal", eventMeshHttpClientConfig.getLiteEventMeshAddr())); } int splitIndex = eventMeshAddrWight.lastIndexOf(":"); Weight weight = new Weight<>( @@ -81,9 +87,9 @@ private static List> buildWeightedClusterGroupFromConfig(LiteClie return eventMeshAddrWeightList; } - private static List buildClusterGroupFromConfig(LiteClientConfig liteClientConfig) + private static List buildClusterGroupFromConfig(EventMeshHttpClientConfig eventMeshHttpClientConfig) throws EventMeshException { - List eventMeshAddrs = Splitter.on(";").trimResults().splitToList(liteClientConfig.getLiteEventMeshAddr()); + List eventMeshAddrs = Splitter.on(";").trimResults().splitToList(eventMeshHttpClientConfig.getLiteEventMeshAddr()); if (CollectionUtils.isEmpty(eventMeshAddrs)) { throw new EventMeshException("liteEventMeshAddr can not be empty"); } @@ -92,7 +98,7 @@ private static List buildClusterGroupFromConfig(LiteClientConfig liteCli for (String eventMeshAddr : eventMeshAddrs) { if (!IP_PORT_PATTERN.matcher(eventMeshAddr).matches()) { throw new EventMeshException( - String.format("liteEventMeshAddr:%s is not illegal", liteClientConfig.getLiteEventMeshAddr())); + String.format("liteEventMeshAddr:%s is not illegal", eventMeshHttpClientConfig.getLiteEventMeshAddr())); } eventMeshAddrList.add(eventMeshAddr); } diff --git a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/http/HttpUtil.java b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/util/HttpUtils.java similarity index 82% rename from eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/http/HttpUtil.java rename to eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/util/HttpUtils.java index 4093a89ea1..ef3c5ab76c 100644 --- a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/http/HttpUtil.java +++ b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/http/util/HttpUtils.java @@ -15,23 +15,13 @@ * limitations under the License. */ -package org.apache.eventmesh.client.http.http; +package org.apache.eventmesh.client.http.util; -import java.io.IOException; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import com.google.common.base.Preconditions; - -import io.netty.handler.codec.http.HttpMethod; +import org.apache.eventmesh.client.http.model.RequestParam; +import org.apache.eventmesh.common.Constants; import org.apache.commons.collections4.MapUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.eventmesh.common.Constants; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; @@ -43,12 +33,23 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -public class HttpUtil { +import java.io.IOException; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import com.google.common.base.Preconditions; - public static Logger logger = LoggerFactory.getLogger(HttpUtil.class); +import io.netty.handler.codec.http.HttpMethod; +import lombok.Data; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +public class HttpUtils { public static String post(CloseableHttpClient client, String uri, @@ -58,10 +59,11 @@ public static String post(CloseableHttpClient client, post(client, null, uri, requestParam, new ResponseHandler() { @Override public String handleResponse(HttpResponse response) throws IOException { - responseHolder.response = EntityUtils.toString(response.getEntity(), Charset.forName(Constants.DEFAULT_CHARSET)); + responseHolder.response = + EntityUtils.toString(response.getEntity(), Charset.forName(Constants.DEFAULT_CHARSET)); countDownLatch.countDown(); - if (logger.isDebugEnabled()) { - logger.debug("{}", responseHolder); + if (log.isDebugEnabled()) { + log.debug("{}", responseHolder); } return responseHolder.response; } @@ -84,10 +86,11 @@ public static String post(CloseableHttpClient client, post(client, forwardAgent, uri, requestParam, new ResponseHandler() { @Override public String handleResponse(HttpResponse response) throws IOException { - responseHolder.response = EntityUtils.toString(response.getEntity(), Charset.forName(Constants.DEFAULT_CHARSET)); + responseHolder.response = + EntityUtils.toString(response.getEntity(), Charset.forName(Constants.DEFAULT_CHARSET)); countDownLatch.countDown(); - if (logger.isDebugEnabled()) { - logger.debug("{}", responseHolder); + if (log.isDebugEnabled()) { + log.debug("{}", responseHolder); } return responseHolder.response; } @@ -96,6 +99,7 @@ public String handleResponse(HttpResponse response) throws IOException { try { countDownLatch.await(requestParam.getTimeout(), TimeUnit.MILLISECONDS); } catch (InterruptedException ie) { + // ignore } return responseHolder.response; @@ -105,7 +109,7 @@ public static void post(CloseableHttpClient client, HttpHost forwardAgent, String uri, RequestParam requestParam, - ResponseHandler responseHandler) throws Exception { + ResponseHandler responseHandler) throws IOException { Preconditions.checkState(client != null, "client can't be null"); Preconditions.checkState(StringUtils.isNotBlank(uri), "uri can't be null"); Preconditions.checkState(requestParam != null, "requestParam can't be null"); @@ -133,8 +137,8 @@ public static void post(CloseableHttpClient client, //ttl RequestConfig.Builder configBuilder = RequestConfig.custom(); configBuilder.setSocketTimeout(Integer.parseInt(String.valueOf(requestParam.getTimeout()))) - .setConnectTimeout(Integer.parseInt(String.valueOf(requestParam.getTimeout()))) - .setConnectionRequestTimeout(Integer.parseInt(String.valueOf(requestParam.getTimeout()))); + .setConnectTimeout(Integer.parseInt(String.valueOf(requestParam.getTimeout()))) + .setConnectionRequestTimeout(Integer.parseInt(String.valueOf(requestParam.getTimeout()))); if (forwardAgent != null) { configBuilder.setProxy(forwardAgent); @@ -142,8 +146,8 @@ public static void post(CloseableHttpClient client, httpPost.setConfig(configBuilder.build()); - if (logger.isDebugEnabled()) { - logger.debug("{}", httpPost); + if (log.isDebugEnabled()) { + log.debug("{}", httpPost); } client.execute(httpPost, responseHandler); @@ -176,8 +180,8 @@ public static void get(CloseableHttpClient client, //ttl RequestConfig.Builder configBuilder = RequestConfig.custom(); configBuilder.setSocketTimeout(Integer.parseInt(String.valueOf(requestParam.getTimeout()))) - .setConnectTimeout(Integer.parseInt(String.valueOf(requestParam.getTimeout()))) - .setConnectionRequestTimeout(Integer.parseInt(String.valueOf(requestParam.getTimeout()))); + .setConnectTimeout(Integer.parseInt(String.valueOf(requestParam.getTimeout()))) + .setConnectionRequestTimeout(Integer.parseInt(String.valueOf(requestParam.getTimeout()))); if (forwardAgent != null) { configBuilder.setProxy(forwardAgent); @@ -185,8 +189,8 @@ public static void get(CloseableHttpClient client, httpGet.setConfig(configBuilder.build()); - if (logger.isDebugEnabled()) { - logger.debug("{}", httpGet); + if (log.isDebugEnabled()) { + log.debug("{}", httpGet); } client.execute(httpGet, responseHandler); @@ -200,10 +204,11 @@ public static String get(CloseableHttpClient client, get(client, null, url, requestParam, new ResponseHandler() { @Override public String handleResponse(HttpResponse response) throws IOException { - responseHolder.response = EntityUtils.toString(response.getEntity(), Charset.forName(Constants.DEFAULT_CHARSET)); + responseHolder.response = + EntityUtils.toString(response.getEntity(), Charset.forName(Constants.DEFAULT_CHARSET)); countDownLatch.countDown(); - if (logger.isDebugEnabled()) { - logger.debug("{}", responseHolder); + if (log.isDebugEnabled()) { + log.debug("{}", responseHolder); } return responseHolder.response; } @@ -226,10 +231,11 @@ public static String get(CloseableHttpClient client, get(client, forwardAgent, url, requestParam, new ResponseHandler() { @Override public String handleResponse(HttpResponse response) throws IOException { - responseHolder.response = EntityUtils.toString(response.getEntity(), Charset.forName(Constants.DEFAULT_CHARSET)); + responseHolder.response = + EntityUtils.toString(response.getEntity(), Charset.forName(Constants.DEFAULT_CHARSET)); countDownLatch.countDown(); - if (logger.isDebugEnabled()) { - logger.debug("{}", responseHolder); + if (log.isDebugEnabled()) { + log.debug("{}", responseHolder); } return responseHolder.response; } @@ -243,12 +249,9 @@ public String handleResponse(HttpResponse response) throws IOException { return responseHolder.response; } + @Data public static class ResponseHolder { public String response; - @Override - public String toString() { - return "ResponseHolder=" + response + ""; - } } } diff --git a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/EventMeshClient.java b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/EventMeshTCPClient.java similarity index 55% rename from eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/EventMeshClient.java rename to eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/EventMeshTCPClient.java index 96c4aa5808..fa81cf0faa 100644 --- a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/EventMeshClient.java +++ b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/EventMeshTCPClient.java @@ -17,44 +17,48 @@ package org.apache.eventmesh.client.tcp; -import io.cloudevents.CloudEvent; import org.apache.eventmesh.client.tcp.common.AsyncRRCallback; import org.apache.eventmesh.client.tcp.common.ReceiveMsgHook; +import org.apache.eventmesh.common.exception.EventMeshException; +import org.apache.eventmesh.common.protocol.SubscriptionMode; import org.apache.eventmesh.common.protocol.SubscriptionType; import org.apache.eventmesh.common.protocol.tcp.Package; -import org.apache.eventmesh.common.protocol.SubscriptionMode; -public interface EventMeshClient { - - Package rr(Package msg, long timeout) throws Exception; +import io.cloudevents.CloudEvent; - void asyncRR(Package msg, AsyncRRCallback callback, long timeout) throws Exception; +/** + * EventMesh Tcp client, it contains all publish/subscribe method. + * todo: Should we only keep EventMeshTcpPubClient/EventMeshTcpSubClient and remove this EventMeshTcpClient? + */ +public interface EventMeshTCPClient { - Package publish(Package msg, long timeout) throws Exception; + // todo: use protocol message instead of Package + Package rr(Package msg, long timeout) throws EventMeshException; - Package publish(CloudEvent cloudEvent, long timeout) throws Exception; + void asyncRR(Package msg, AsyncRRCallback callback, long timeout) throws EventMeshException; - void broadcast(CloudEvent cloudEvent, long timeout) throws Exception; + Package publish(Package msg, long timeout) throws EventMeshException; - void broadcast(Package msg, long timeout) throws Exception; + Package publish(CloudEvent cloudEvent, long timeout) throws EventMeshException; - void init() throws Exception; + void broadcast(CloudEvent cloudEvent, long timeout) throws EventMeshException; - void close(); + void broadcast(Package msg, long timeout) throws EventMeshException; - void heartbeat() throws Exception; + void init() throws EventMeshException; - void listen() throws Exception; + void close() throws EventMeshException; - void subscribe(String topic, SubscriptionMode subscriptionMode, SubscriptionType subscriptionType) throws Exception; + void heartbeat() throws EventMeshException; - void unsubscribe() throws Exception; + void listen() throws EventMeshException; - void registerPubBusiHandler(ReceiveMsgHook handler) throws Exception; + void subscribe(String topic, SubscriptionMode subscriptionMode, SubscriptionType subscriptionType) + throws EventMeshException; - void registerSubBusiHandler(ReceiveMsgHook handler) throws Exception; + void unsubscribe() throws EventMeshException; - SimplePubClient getPubClient(); + void registerPubBusiHandler(ReceiveMsgHook handler) throws EventMeshException; - SimpleSubClient getSubClient(); + void registerSubBusiHandler(ReceiveMsgHook handler) throws EventMeshException; } diff --git a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/SimplePubClient.java b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/EventMeshTCPPubClient.java similarity index 57% rename from eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/SimplePubClient.java rename to eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/EventMeshTCPPubClient.java index 95a4a38897..f4d9f66a34 100644 --- a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/SimplePubClient.java +++ b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/EventMeshTCPPubClient.java @@ -17,36 +17,36 @@ package org.apache.eventmesh.client.tcp; - -import io.cloudevents.CloudEvent; import org.apache.eventmesh.client.tcp.common.AsyncRRCallback; import org.apache.eventmesh.client.tcp.common.ReceiveMsgHook; +import org.apache.eventmesh.common.exception.EventMeshException; import org.apache.eventmesh.common.protocol.tcp.Package; import org.apache.eventmesh.common.protocol.tcp.UserAgent; -public interface SimplePubClient { - - void init() throws Exception; +/** + * EventMesh TCP publish client. + */ +public interface EventMeshTCPPubClient extends AutoCloseable { - void close(); + void init() throws EventMeshException; - void heartbeat() throws Exception; + void heartbeat() throws EventMeshException; - void reconnect() throws Exception; + void reconnect() throws EventMeshException; - Package rr(Package msg, long timeout) throws Exception; + Package rr(Package msg, long timeout) throws EventMeshException; - void asyncRR(Package msg, AsyncRRCallback callback, long timeout) throws Exception; + void asyncRR(Package msg, AsyncRRCallback callback, long timeout) throws EventMeshException; - Package publish(Package msg, long timeout) throws Exception; + Package publish(Package msg, long timeout) throws EventMeshException; - Package publish(CloudEvent cloudEvent, long timeout) throws Exception; + Package publish(ProtocolMessage cloudEvent, long timeout) throws EventMeshException; - void broadcast(CloudEvent cloudEvent, long timeout) throws Exception; + void broadcast(ProtocolMessage cloudEvent, long timeout) throws EventMeshException; - void broadcast(Package msg, long timeout) throws Exception; + void broadcast(Package msg, long timeout) throws EventMeshException; - void registerBusiHandler(ReceiveMsgHook handler) throws Exception; + void registerBusiHandler(ReceiveMsgHook handler) throws EventMeshException; - UserAgent getUserAgent(); + void close() throws EventMeshException; } diff --git a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/SimpleSubClient.java b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/EventMeshTCPSubClient.java similarity index 65% rename from eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/SimpleSubClient.java rename to eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/EventMeshTCPSubClient.java index 3439f208f9..924b9ecbe6 100644 --- a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/SimpleSubClient.java +++ b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/EventMeshTCPSubClient.java @@ -17,28 +17,30 @@ package org.apache.eventmesh.client.tcp; - import org.apache.eventmesh.client.tcp.common.ReceiveMsgHook; -import org.apache.eventmesh.common.protocol.SubscriptionType; +import org.apache.eventmesh.common.exception.EventMeshException; import org.apache.eventmesh.common.protocol.SubscriptionMode; +import org.apache.eventmesh.common.protocol.SubscriptionType; import org.apache.eventmesh.common.protocol.tcp.UserAgent; -public interface SimpleSubClient { - void init() throws Exception; - - void close(); +/** + * EventMesh TCP subscribe client. + */ +public interface EventMeshTCPSubClient { + void init() throws EventMeshException; - void heartbeat() throws Exception; + void heartbeat() throws EventMeshException; - void reconnect() throws Exception; + void reconnect() throws EventMeshException; - void subscribe(String topic, SubscriptionMode subscriptionMode, SubscriptionType subscriptionType) throws Exception; + void subscribe(String topic, SubscriptionMode subscriptionMode, SubscriptionType subscriptionType) + throws EventMeshException; - void unsubscribe() throws Exception; + void unsubscribe() throws EventMeshException; - void listen() throws Exception; + void listen() throws EventMeshException; - void registerBusiHandler(ReceiveMsgHook handler) throws Exception; + void registerBusiHandler(ReceiveMsgHook handler) throws EventMeshException; - UserAgent getUserAgent(); + void close() throws EventMeshException; } diff --git a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/common/ReceiveMsgHook.java b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/common/ReceiveMsgHook.java index 858e80bdd0..eb29f174cd 100644 --- a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/common/ReceiveMsgHook.java +++ b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/common/ReceiveMsgHook.java @@ -17,16 +17,28 @@ package org.apache.eventmesh.client.tcp.common; -import io.netty.channel.ChannelHandlerContext; import org.apache.eventmesh.common.protocol.tcp.Package; +import io.netty.channel.ChannelHandlerContext; + /** * ReceiveMsgHook. * - * @param receive message type. + * @param receive message type. */ -public interface ReceiveMsgHook { +public interface ReceiveMsgHook { void handle(Package msg, ChannelHandlerContext ctx); - T convert(Package pkg); + /** + * Convert tcp package to protocolMessage. + *
    + *
  • {@link org.apache.eventmesh.common.EventMeshMessage}
  • + *
  • {@link io.openmessaging.api.Message}
  • + *
  • {@link io.cloudevents.CloudEvent}
  • + *
+ * + * @param pkg + * @return + */ + ProtocolMessage convertToProtocolMessage(Package pkg); } diff --git a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/common/TcpClient.java b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/common/TcpClient.java index 5513e1310e..2b9bfaf38b 100644 --- a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/common/TcpClient.java +++ b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/common/TcpClient.java @@ -17,17 +17,24 @@ package org.apache.eventmesh.client.tcp.common; +import org.apache.eventmesh.client.tcp.conf.EventMeshTcpClientConfig; +import org.apache.eventmesh.common.exception.EventMeshException; +import org.apache.eventmesh.common.protocol.tcp.Command; +import org.apache.eventmesh.common.protocol.tcp.Package; +import org.apache.eventmesh.common.protocol.tcp.codec.Codec; + import java.io.Closeable; -import java.io.IOException; import java.net.InetSocketAddress; import java.util.Random; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; +import com.google.common.base.Preconditions; +import com.google.common.util.concurrent.ThreadFactoryBuilder; + import io.netty.bootstrap.Bootstrap; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.AdaptiveRecvByteBufAllocator; @@ -35,6 +42,7 @@ import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; +import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; @@ -43,65 +51,70 @@ import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; +import lombok.extern.slf4j.Slf4j; -import org.apache.eventmesh.common.protocol.tcp.Package; -import org.apache.eventmesh.common.protocol.tcp.codec.Codec; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - +@Slf4j public abstract class TcpClient implements Closeable { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - public int clientNo = (new Random()).nextInt(1000); + public final int clientNo = (new Random()).nextInt(1000); protected ConcurrentHashMap contexts = new ConcurrentHashMap<>(); - private final String host; - private final int port; + protected final String host; + protected final int port; - private Bootstrap bootstrap = new Bootstrap(); + private final Bootstrap bootstrap = new Bootstrap(); - private EventLoopGroup workers = new NioEventLoopGroup(); + private final EventLoopGroup workers = new NioEventLoopGroup(); private Channel channel; - protected static final ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(4, new EventMeshThreadFactoryImpl("TCPClientScheduler", true)); + protected static final ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor( + Runtime.getRuntime().availableProcessors(), + new ThreadFactoryBuilder().setNameFormat("TCPClientScheduler").setDaemon(true).build()); - public TcpClient(String host, int port) { - this.host = host; - this.port = port; + public TcpClient(EventMeshTcpClientConfig eventMeshTcpClientConfig) { + Preconditions.checkNotNull(eventMeshTcpClientConfig, "EventMeshTcpClientConfig cannot be null"); + Preconditions.checkNotNull(eventMeshTcpClientConfig.getHost(), "Host cannot be null"); + Preconditions.checkState(eventMeshTcpClientConfig.getPort() > 0, "port is not validated"); + this.host = eventMeshTcpClientConfig.getHost(); + this.port = eventMeshTcpClientConfig.getPort(); } protected synchronized void open(SimpleChannelInboundHandler handler) throws Exception { bootstrap.group(workers); bootstrap.channel(NioSocketChannel.class); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1_000) - .option(ChannelOption.SO_KEEPALIVE, true) - .option(ChannelOption.SO_SNDBUF, 64 * 1024) - .option(ChannelOption.SO_RCVBUF, 64 * 1024) - .option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(1024, 8192, 65536)) - .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); + .option(ChannelOption.SO_KEEPALIVE, true) + .option(ChannelOption.SO_SNDBUF, 64 * 1024) + .option(ChannelOption.SO_RCVBUF, 64 * 1024) + .option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(1024, 8192, 65536)) + .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); bootstrap.handler(new ChannelInitializer() { - public void initChannel(SocketChannel ch) throws Exception { + public void initChannel(SocketChannel ch) { ch.pipeline().addLast(new Codec.Encoder(), new Codec.Decoder()) - .addLast(handler, newExceptionHandler()); + .addLast(handler, newExceptionHandler()); } }); ChannelFuture f = bootstrap.connect(host, port).sync(); InetSocketAddress localAddress = (InetSocketAddress) f.channel().localAddress(); channel = f.channel(); - logger.info("connected|local={}:{}|server={}", localAddress.getAddress().getHostAddress(), localAddress.getPort(), host + ":" + port); + log + .info("connected|local={}:{}|server={}", localAddress.getAddress().getHostAddress(), localAddress.getPort(), + host + ":" + port); } @Override - public void close() throws IOException { + public void close() throws EventMeshException { try { channel.disconnect().sync(); + workers.shutdownGracefully(); } catch (InterruptedException e) { - logger.warn("close tcp client failed.|remote address={}", channel.remoteAddress(), e); + Thread.currentThread().interrupt(); + log.warn("close tcp client failed.|remote address={}", channel.remoteAddress(), e); + throw new EventMeshException(e); } - workers.shutdownGracefully(); } protected synchronized void reconnect() throws Exception { @@ -117,7 +130,7 @@ protected void send(Package msg) throws Exception { if (channel.isWritable()) { channel.writeAndFlush(msg).addListener((ChannelFutureListener) future -> { if (!future.isSuccess()) { - logger.warn("send msg failed", future.cause()); + log.warn("send msg failed", future.cause()); } }); } else { @@ -132,19 +145,21 @@ protected Package io(Package msg, long timeout) throws Exception { if (!contexts.contains(c)) { contexts.put(key, c); } else { - logger.info("duplicate key : {}", key); + log.info("duplicate key : {}", key); } send(msg); - if (!c.getLatch().await(timeout, TimeUnit.MILLISECONDS)) + if (!c.getLatch().await(timeout, TimeUnit.MILLISECONDS)) { throw new TimeoutException("operation timeout, context.key=" + c.getKey()); + } return c.getResponse(); } private ChannelDuplexHandler newExceptionHandler() { return new ChannelDuplexHandler() { @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { - logger.info("exceptionCaught, close connection.|remote address={}", ctx.channel().remoteAddress(), cause); + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { + log + .info("exceptionCaught, close connection.|remote address={}", ctx.channel().remoteAddress(), cause); ctx.close(); } }; diff --git a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/conf/EventMeshTcpClientConfig.java b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/conf/EventMeshTcpClientConfig.java new file mode 100644 index 0000000000..6b916a1934 --- /dev/null +++ b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/conf/EventMeshTcpClientConfig.java @@ -0,0 +1,14 @@ +package org.apache.eventmesh.client.tcp.conf; + +import org.apache.eventmesh.common.protocol.tcp.UserAgent; + +import lombok.Builder; +import lombok.Data; + +@Data +@Builder +public class EventMeshTcpClientConfig { + private String host; + private int port; + private UserAgent userAgent; +} diff --git a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/DefaultEventMeshClient.java b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/DefaultEventMeshTCPClient.java similarity index 64% rename from eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/DefaultEventMeshClient.java rename to eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/DefaultEventMeshTCPClient.java index ef2db7f167..46c844a5ed 100644 --- a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/DefaultEventMeshClient.java +++ b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/DefaultEventMeshTCPClient.java @@ -17,78 +17,81 @@ package org.apache.eventmesh.client.tcp.impl; - -import io.cloudevents.CloudEvent; -import org.apache.eventmesh.client.tcp.EventMeshClient; -import org.apache.eventmesh.client.tcp.SimplePubClient; -import org.apache.eventmesh.client.tcp.SimpleSubClient; +import org.apache.eventmesh.client.tcp.EventMeshTCPClient; +import org.apache.eventmesh.client.tcp.EventMeshTCPPubClient; +import org.apache.eventmesh.client.tcp.EventMeshTCPSubClient; import org.apache.eventmesh.client.tcp.common.AsyncRRCallback; import org.apache.eventmesh.client.tcp.common.MessageUtils; import org.apache.eventmesh.client.tcp.common.ReceiveMsgHook; +import org.apache.eventmesh.common.exception.EventMeshException; +import org.apache.eventmesh.common.protocol.SubscriptionMode; import org.apache.eventmesh.common.protocol.SubscriptionType; import org.apache.eventmesh.common.protocol.tcp.Package; -import org.apache.eventmesh.common.protocol.SubscriptionMode; import org.apache.eventmesh.common.protocol.tcp.UserAgent; -public class DefaultEventMeshClient implements EventMeshClient { +import io.cloudevents.CloudEvent; +import lombok.ToString; + +@ToString +public class DefaultEventMeshTCPClient implements EventMeshTCPClient { protected UserAgent agent; - private String accessHost; - private int accessPort; + private String accessHost; + private int accessPort; - private SimplePubClient pubClient; - private SimpleSubClient subClient; + private EventMeshTCPPubClient pubClient; + private EventMeshTCPSubClient subClient; - public DefaultEventMeshClient(String accessHost, int accessPort, UserAgent agent) { + public DefaultEventMeshTCPClient(String accessHost, int accessPort, UserAgent agent) { this.accessHost = accessHost; this.accessPort = accessPort; this.agent = agent; UserAgent subAgent = MessageUtils.generateSubClient(agent); - this.subClient = new SimpleSubClientImpl(accessHost, accessPort, subAgent); + this.subClient = new EventMeshTCPSubClientImpl(accessHost, accessPort, subAgent); UserAgent pubAgent = MessageUtils.generatePubClient(agent); - this.pubClient = new SimplePubClientImpl(accessHost, accessPort, pubAgent); + this.pubClient = new EventMeshTCPPubClientImpl(accessHost, accessPort, pubAgent); } - public SimplePubClient getPubClient() { + public EventMeshTCPPubClient getPubClient() { return pubClient; } - public void setPubClient(SimplePubClient pubClient) { + public void setPubClient(EventMeshTCPPubClient pubClient) { this.pubClient = pubClient; } - public SimpleSubClient getSubClient() { + public EventMeshTCPSubClient getSubClient() { return subClient; } - public void setSubClient(SimpleSubClient subClient) { + public void setSubClient(EventMeshTCPSubClient subClient) { this.subClient = subClient; } - public Package rr(Package msg, long timeout) throws Exception { + public Package rr(Package msg, long timeout) throws EventMeshException { return this.pubClient.rr(msg, timeout); } - public Package publish(Package msg, long timeout) throws Exception { + public Package publish(Package msg, long timeout) throws EventMeshException { return this.pubClient.publish(msg, timeout); } @Override - public Package publish(CloudEvent cloudEvent, long timeout) throws Exception { + public Package publish(CloudEvent cloudEvent, long timeout) throws EventMeshException { return this.pubClient.publish(cloudEvent, timeout); } - public void broadcast(Package msg, long timeout) throws Exception { + public void broadcast(Package msg, long timeout) throws EventMeshException { this.pubClient.broadcast(msg, timeout); } @Override - public void broadcast(CloudEvent cloudEvent, long timeout) throws Exception { + public void broadcast(CloudEvent cloudEvent, long timeout) throws EventMeshException { this.pubClient.broadcast(cloudEvent, timeout); } - public void init() throws Exception { + public void init() throws EventMeshException { this.subClient.init(); this.pubClient.init(); } @@ -98,44 +101,36 @@ public void close() { this.subClient.close(); } - public void heartbeat() throws Exception { + public void heartbeat() throws EventMeshException { this.pubClient.heartbeat(); this.subClient.heartbeat(); } - public void listen() throws Exception { + public void listen() throws EventMeshException { this.subClient.listen(); } @Override - public void subscribe(String topic, SubscriptionMode subscriptionMode, SubscriptionType subscriptionType) throws Exception { + public void subscribe(String topic, SubscriptionMode subscriptionMode, SubscriptionType subscriptionType) + throws Exception { this.subClient.subscribe(topic, subscriptionMode, subscriptionType); } @Override - public void unsubscribe() throws Exception { + public void unsubscribe() throws EventMeshException { this.subClient.unsubscribe(); } - public void registerSubBusiHandler(ReceiveMsgHook handler) throws Exception { + public void registerSubBusiHandler(ReceiveMsgHook handler) throws EventMeshException { this.subClient.registerBusiHandler(handler); } @Override - public void asyncRR(Package msg, AsyncRRCallback callback, long timeout) throws Exception { + public void asyncRR(Package msg, AsyncRRCallback callback, long timeout) throws EventMeshException { this.pubClient.asyncRR(msg, callback, timeout); } - public void registerPubBusiHandler(ReceiveMsgHook handler) throws Exception { + public void registerPubBusiHandler(ReceiveMsgHook handler) throws EventMeshException { this.pubClient.registerBusiHandler(handler); } - - @Override - public String toString() { - return "DefaultEventMeshClient{" + - "accessHost='" + accessHost + '\'' + - ", accessPort=" + accessPort + - ", agent=" + agent + - '}'; - } } diff --git a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/SimplePubClientImpl.java b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/EventMeshTCPPubClientImpl.java similarity index 79% rename from eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/SimplePubClientImpl.java rename to eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/EventMeshTCPPubClientImpl.java index 36db2c6a33..922a738e8f 100644 --- a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/SimplePubClientImpl.java +++ b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/EventMeshTCPPubClientImpl.java @@ -17,16 +17,7 @@ package org.apache.eventmesh.client.tcp.impl; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; - -import io.cloudevents.CloudEvent; -import io.netty.channel.ChannelHandler; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.SimpleChannelInboundHandler; - -import org.apache.eventmesh.client.tcp.SimplePubClient; +import org.apache.eventmesh.client.tcp.EventMeshTCPPubClient; import org.apache.eventmesh.client.tcp.common.AsyncRRCallback; import org.apache.eventmesh.client.tcp.common.EventMeshCommon; import org.apache.eventmesh.client.tcp.common.MessageUtils; @@ -34,37 +25,44 @@ import org.apache.eventmesh.client.tcp.common.ReceiveMsgHook; import org.apache.eventmesh.client.tcp.common.RequestContext; import org.apache.eventmesh.client.tcp.common.TcpClient; +import org.apache.eventmesh.common.exception.EventMeshException; import org.apache.eventmesh.common.protocol.tcp.Command; import org.apache.eventmesh.common.protocol.tcp.Package; import org.apache.eventmesh.common.protocol.tcp.UserAgent; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; -public class SimplePubClientImpl extends TcpClient implements SimplePubClient { +import io.cloudevents.CloudEvent; +import io.netty.channel.ChannelHandler; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.SimpleChannelInboundHandler; +import lombok.extern.slf4j.Slf4j; - private final Logger logger = LoggerFactory.getLogger(this.getClass()); +@Slf4j +public class EventMeshTCPPubClientImpl extends TcpClient implements EventMeshTCPPubClient { - private UserAgent userAgent; + private final UserAgent userAgent; private ReceiveMsgHook callback; - private ConcurrentHashMap callbackConcurrentHashMap = new ConcurrentHashMap(); - private ScheduledFuture task; + private final ConcurrentHashMap callbackConcurrentHashMap = new ConcurrentHashMap<>(); + private ScheduledFuture task; - public SimplePubClientImpl(String accessIp, int port, UserAgent agent) { + public EventMeshTCPPubClientImpl(String accessIp, int port, UserAgent agent) { super(accessIp, port); this.userAgent = agent; } - public void registerBusiHandler(ReceiveMsgHook handler) throws Exception { + public void registerBusiHandler(ReceiveMsgHook handler) { callback = handler; } public void init() throws Exception { open(new Handler()); hello(); - logger.info("SimplePubClientImpl|{}|started!", clientNo); + log.info("SimplePubClientImpl|{}|started!", clientNo); } public void reconnect() throws Exception { @@ -72,7 +70,7 @@ public void reconnect() throws Exception { hello(); } - public void close() { + public void close() throws EventMeshException { try { task.cancel(false); goodbye(); @@ -88,11 +86,12 @@ public void heartbeat() throws Exception { public void run() { try { if (!isActive()) { - SimplePubClientImpl.this.reconnect(); + EventMeshTCPPubClientImpl.this.reconnect(); } Package msg = MessageUtils.heartBeat(); io(msg, EventMeshCommon.DEFAULT_TIME_OUT_MILLS); } catch (Exception ignore) { + // ignore } } }, EventMeshCommon.HEARTBEAT, EventMeshCommon.HEARTBEAT, TimeUnit.MILLISECONDS); @@ -117,7 +116,7 @@ private void hello() throws Exception { * @throws Exception */ public Package rr(Package msg, long timeout) throws Exception { - logger.info("SimplePubClientImpl|{}|rr|send|type={}|msg={}", clientNo, msg.getHeader().getCommand(), msg); + log.info("SimplePubClientImpl|{}|rr|send|type={}|msg={}", clientNo, msg.getHeader().getCommand(), msg); return io(msg, timeout); } @@ -143,7 +142,7 @@ public void asyncRR(Package msg, AsyncRRCallback callback, long timeout) throws * @throws Exception */ public Package publish(Package msg, long timeout) throws Exception { - logger.info("SimplePubClientImpl|{}|publish|send|type={}|msg={}", clientNo, msg.getHeader().getCommand(), msg); + log.info("SimplePubClientImpl|{}|publish|send|type={}|msg={}", clientNo, msg.getHeader().getCommand(), msg); return io(msg, timeout); } @@ -151,7 +150,7 @@ public Package publish(Package msg, long timeout) throws Exception { @Override public Package publish(CloudEvent cloudEvent, long timeout) throws Exception { Package msg = MessageUtils.asyncCloudEvent(cloudEvent); - logger.info("SimplePubClientImpl cloud event|{}|publish|send|type={}|protocol={}|msg={}", + log.info("SimplePubClientImpl cloud event|{}|publish|send|type={}|protocol={}|msg={}", clientNo, msg.getHeader().getCommand(), msg.getHeader().getProperty(PropertyConst.PROPERTY_MESSAGE_PROTOCOL), msg); return io(MessageUtils.asyncCloudEvent(cloudEvent), timeout); @@ -160,7 +159,7 @@ public Package publish(CloudEvent cloudEvent, long timeout) throws Exception { @Override public void broadcast(CloudEvent cloudEvent, long timeout) throws Exception { Package msg = MessageUtils.asyncCloudEvent(cloudEvent); - logger.info("SimplePubClientImpl cloud event|{}|publish|send|type={}|protocol={}|msg={}", + log.info("SimplePubClientImpl cloud event|{}|publish|send|type={}|protocol={}|msg={}", clientNo, msg.getHeader().getCommand(), msg.getHeader().getProperty(PropertyConst.PROPERTY_MESSAGE_PROTOCOL), msg); super.send(msg); @@ -174,7 +173,8 @@ public void broadcast(CloudEvent cloudEvent, long timeout) throws Exception { * @throws Exception */ public void broadcast(Package msg, long timeout) throws Exception { - logger.info("SimplePubClientImpl|{}|broadcast|send|type={}|msg={}", clientNo, msg.getHeader().getCommand(), msg); + log + .info("SimplePubClientImpl|{}|broadcast|send|type={}|msg={}", clientNo, msg.getHeader().getCommand(), msg); super.send(msg); } @@ -187,7 +187,7 @@ public UserAgent getUserAgent() { private class Handler extends SimpleChannelInboundHandler { @Override protected void channelRead0(ChannelHandlerContext ctx, Package msg) throws Exception { - logger.info("SimplePubClientImpl|{}|receive|type={}|msg={}", clientNo, msg.getHeader(), msg); + log.info("SimplePubClientImpl|{}|receive|type={}|msg={}", clientNo, msg.getHeader(), msg); Command cmd = msg.getHeader().getCommand(); if (cmd == Command.RESPONSE_TO_CLIENT) { @@ -208,8 +208,4 @@ protected void channelRead0(ChannelHandlerContext ctx, Package msg) throws Excep } } - @Override - public String toString() { - return "SimplePubClientImpl|clientNo=" + clientNo + "|" + userAgent; - } } diff --git a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/SimpleSubClientImpl.java b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/EventMeshTCPSubClientImpl.java similarity index 92% rename from eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/SimpleSubClientImpl.java rename to eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/EventMeshTCPSubClientImpl.java index 68d607bde8..b721d957d0 100644 --- a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/SimpleSubClientImpl.java +++ b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/EventMeshTCPSubClientImpl.java @@ -27,7 +27,7 @@ import io.netty.channel.SimpleChannelInboundHandler; import org.apache.commons.collections4.CollectionUtils; -import org.apache.eventmesh.client.tcp.SimpleSubClient; +import org.apache.eventmesh.client.tcp.EventMeshTCPSubClient; import org.apache.eventmesh.client.tcp.common.EventMeshCommon; import org.apache.eventmesh.client.tcp.common.MessageUtils; import org.apache.eventmesh.client.tcp.common.ReceiveMsgHook; @@ -42,7 +42,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class SimpleSubClientImpl extends TcpClient implements SimpleSubClient { +public class EventMeshTCPSubClientImpl extends TcpClient implements EventMeshTCPSubClient { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @@ -50,11 +50,11 @@ public class SimpleSubClientImpl extends TcpClient implements SimpleSubClient { private ReceiveMsgHook callback; - private List subscriptionItems = new ArrayList(); + private List subscriptionItems = new ArrayList<>(); private ScheduledFuture task; - public SimpleSubClientImpl(String accessIp, int port, UserAgent agent) { + public EventMeshTCPSubClientImpl(String accessIp, int port, UserAgent agent) { super(accessIp, port); this.userAgent = agent; } @@ -97,10 +97,10 @@ public void heartbeat() throws Exception { public void run() { try { if (!isActive()) { - SimpleSubClientImpl.this.reconnect(); + EventMeshTCPSubClientImpl.this.reconnect(); } Package msg = MessageUtils.heartBeat(); - SimpleSubClientImpl.this.io(msg, EventMeshCommon.DEFAULT_TIME_OUT_MILLS); + EventMeshTCPSubClientImpl.this.io(msg, EventMeshCommon.DEFAULT_TIME_OUT_MILLS); } catch (Exception ignore) { } } @@ -144,7 +144,7 @@ private class Handler extends SimpleChannelInboundHandler { @Override protected void channelRead0(ChannelHandlerContext ctx, Package msg) throws Exception { Command cmd = msg.getHeader().getCommand(); - logger.info(SimpleSubClientImpl.class.getSimpleName() + "|receive|type={}|msg={}", cmd, msg); + logger.info(EventMeshTCPSubClientImpl.class.getSimpleName() + "|receive|type={}|msg={}", cmd, msg); if (cmd == Command.REQUEST_TO_CLIENT) { if (callback != null) { callback.handle(msg, ctx); diff --git a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/cloudevent/CloudEventTCPPubClient.java b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/cloudevent/CloudEventTCPPubClient.java new file mode 100644 index 0000000000..0c03cb4e76 --- /dev/null +++ b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/cloudevent/CloudEventTCPPubClient.java @@ -0,0 +1,78 @@ +package org.apache.eventmesh.client.tcp.impl.cloudevent; + +import org.apache.eventmesh.client.tcp.EventMeshTCPPubClient; +import org.apache.eventmesh.client.tcp.common.AsyncRRCallback; +import org.apache.eventmesh.client.tcp.common.ReceiveMsgHook; +import org.apache.eventmesh.common.exception.EventMeshException; +import org.apache.eventmesh.common.protocol.tcp.Package; +import org.apache.eventmesh.common.protocol.tcp.UserAgent; + +import io.cloudevents.CloudEvent; +import lombok.extern.slf4j.Slf4j; + +/** + * A CloudEvent TCP publish client implementation. + */ +@Slf4j +public class CloudEventTCPPubClient implements EventMeshTCPPubClient { + + @Override + public void init() throws EventMeshException { + + } + + @Override + public void heartbeat() throws EventMeshException { + + } + + @Override + public void reconnect() throws EventMeshException { + + } + + @Override + public Package rr(Package msg, long timeout) throws EventMeshException { + return null; + } + + @Override + public void asyncRR(Package msg, AsyncRRCallback callback, long timeout) throws EventMeshException { + + } + + @Override + public Package publish(Package msg, long timeout) throws EventMeshException { + return null; + } + + @Override + public Package publish(CloudEvent cloudEvent, long timeout) throws EventMeshException { + return null; + } + + @Override + public void broadcast(CloudEvent cloudEvent, long timeout) throws EventMeshException { + + } + + @Override + public void broadcast(Package msg, long timeout) throws EventMeshException { + + } + + @Override + public void registerBusiHandler(ReceiveMsgHook handler) throws EventMeshException { + + } + + @Override + public UserAgent getUserAgent() { + return null; + } + + @Override + public void close() throws EventMeshException { + + } +} diff --git a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/cloudevent/CloudEventTCPSubClient.java b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/cloudevent/CloudEventTCPSubClient.java new file mode 100644 index 0000000000..9f572c2643 --- /dev/null +++ b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/cloudevent/CloudEventTCPSubClient.java @@ -0,0 +1,64 @@ +package org.apache.eventmesh.client.tcp.impl.cloudevent; + +import org.apache.eventmesh.client.tcp.EventMeshTCPSubClient; +import org.apache.eventmesh.client.tcp.common.ReceiveMsgHook; +import org.apache.eventmesh.common.exception.EventMeshException; +import org.apache.eventmesh.common.protocol.SubscriptionMode; +import org.apache.eventmesh.common.protocol.SubscriptionType; +import org.apache.eventmesh.common.protocol.tcp.UserAgent; + +import io.cloudevents.CloudEvent; +import lombok.extern.slf4j.Slf4j; + +/** + * CloudEvent TCP subscribe client implementation. + */ +@Slf4j +public class CloudEventTCPSubClient implements EventMeshTCPSubClient { + + @Override + public void init() throws EventMeshException { + + } + + @Override + public void heartbeat() throws EventMeshException { + + } + + @Override + public void reconnect() throws EventMeshException { + + } + + @Override + public void subscribe(String topic, SubscriptionMode subscriptionMode, SubscriptionType subscriptionType) + throws EventMeshException { + + } + + @Override + public void unsubscribe() throws EventMeshException { + + } + + @Override + public void listen() throws EventMeshException { + + } + + @Override + public void registerBusiHandler(ReceiveMsgHook handler) throws EventMeshException { + + } + + @Override + public UserAgent getUserAgent() { + return null; + } + + @Override + public void close() throws EventMeshException{ + + } +} diff --git a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/eventmeshmessage/EventMeshMessageTCPPubClient.java b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/eventmeshmessage/EventMeshMessageTCPPubClient.java new file mode 100644 index 0000000000..4779278192 --- /dev/null +++ b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/eventmeshmessage/EventMeshMessageTCPPubClient.java @@ -0,0 +1,210 @@ +package org.apache.eventmesh.client.tcp.impl.eventmeshmessage; + +import org.apache.eventmesh.client.tcp.EventMeshTCPPubClient; +import org.apache.eventmesh.client.tcp.common.AsyncRRCallback; +import org.apache.eventmesh.client.tcp.common.EventMeshCommon; +import org.apache.eventmesh.client.tcp.common.MessageUtils; +import org.apache.eventmesh.client.tcp.common.PropertyConst; +import org.apache.eventmesh.client.tcp.common.ReceiveMsgHook; +import org.apache.eventmesh.client.tcp.common.RequestContext; +import org.apache.eventmesh.client.tcp.common.TcpClient; +import org.apache.eventmesh.client.tcp.conf.EventMeshTcpClientConfig; +import org.apache.eventmesh.common.EventMeshMessage; +import org.apache.eventmesh.common.exception.EventMeshException; +import org.apache.eventmesh.common.protocol.tcp.Command; +import org.apache.eventmesh.common.protocol.tcp.Package; +import org.apache.eventmesh.common.protocol.tcp.UserAgent; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + +import io.netty.channel.ChannelHandler; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.SimpleChannelInboundHandler; +import lombok.extern.slf4j.Slf4j; + +/** + * EventMeshMessage TCP publish client implementation. + */ +@Slf4j +public class EventMeshMessageTCPPubClient extends TcpClient implements EventMeshTCPPubClient { + + private final UserAgent userAgent; + + private ReceiveMsgHook callback; + + private final ConcurrentHashMap callbackConcurrentHashMap = new ConcurrentHashMap<>(); + private ScheduledFuture task; + + public EventMeshMessageTCPPubClient(EventMeshTcpClientConfig eventMeshTcpClientConfig) { + super(eventMeshTcpClientConfig); + this.userAgent = eventMeshTcpClientConfig.getUserAgent(); + } + + @Override + public void init() throws EventMeshException { + try { + open(new Handler()); + hello(); + } catch (Exception ex) { + throw new EventMeshException("Initialize EventMeshMessageTCPPubClient error", ex); + } + + } + + @Override + public void heartbeat() throws EventMeshException { + if (task != null) { + synchronized (EventMeshMessageTCPPubClient.class) { + task = scheduler.scheduleAtFixedRate(() -> { + try { + if (!isActive()) { + reconnect(); + } + Package msg = MessageUtils.heartBeat(); + io(msg, EventMeshCommon.DEFAULT_TIME_OUT_MILLS); + } catch (Exception ignore) { + // ignore + } + }, EventMeshCommon.HEARTBEAT, EventMeshCommon.HEARTBEAT, TimeUnit.MILLISECONDS); + } + } + } + + @Override + public void reconnect() throws EventMeshException { + try { + super.reconnect(); + hello(); + } catch (Exception ex) { + throw new EventMeshException("reconnect error", ex); + } + } + + @Override + public Package rr(Package msg, long timeout) throws EventMeshException { + try { + log.info("SimplePubClientImpl|{}|rr|send|type={}|msg={}", clientNo, msg.getHeader().getCommand(), msg); + return io(msg, timeout); + } catch (Exception ex) { + throw new EventMeshException("rr error"); + } + } + + @Override + public void asyncRR(Package msg, AsyncRRCallback callback, long timeout) throws EventMeshException { + try { + super.send(msg); + this.callbackConcurrentHashMap.put((String) RequestContext._key(msg), callback); + } catch (Exception ex) { + // should trigger callback? + throw new EventMeshException("asyncRR error", ex); + } + } + + // todo: remove this method, just keep protocol message publish method + @Override + public Package publish(Package msg, long timeout) throws EventMeshException { + try { + log.info("SimplePubClientImpl|{}|publish|send|type={}|msg={}", clientNo, msg.getHeader().getCommand(), msg); + return io(msg, timeout); + } catch (Exception ex) { + throw new EventMeshException("Publish error", ex); + } + } + + @Override + public Package publish(EventMeshMessage eventMeshMessage, long timeout) throws EventMeshException { + try { + // todo: transform EventMeshMessage to Package + Package msg = MessageUtils.asyncCloudEvent(eventMeshMessage); + log.info("SimplePubClientImpl cloud event|{}|publish|send|type={}|protocol={}|msg={}", + clientNo, msg.getHeader().getCommand(), + msg.getHeader().getProperty(PropertyConst.PROPERTY_MESSAGE_PROTOCOL), msg); + return io(msg, timeout); + } catch (Exception ex) { + throw new EventMeshException("publish error", ex); + } + } + + @Override + public void broadcast(EventMeshMessage eventMeshMessage, long timeout) throws EventMeshException { + try { + // todo: transform EventMeshMessage to Package + Package msg = MessageUtils.asyncCloudEvent(cloudEvent); + log.info("SimplePubClientImpl cloud event|{}|publish|send|type={}|protocol={}|msg={}", + clientNo, msg.getHeader().getCommand(), + msg.getHeader().getProperty(PropertyConst.PROPERTY_MESSAGE_PROTOCOL), msg); + super.send(msg); + } catch (Exception ex) { + throw new EventMeshException("Broadcast message error", ex); + } + } + + // todo: remove this method + @Override + public void broadcast(Package msg, long timeout) throws EventMeshException { + try { + log.info("SimplePubClientImpl|{}|broadcast|send|type={}|msg={}", clientNo, msg.getHeader().getCommand(), + msg); + super.send(msg); + } catch (Exception ex) { + throw new EventMeshException("Broadcast message error", ex); + } + } + + @Override + public void registerBusiHandler(ReceiveMsgHook receiveMsgHook) throws EventMeshException { + this.callback = receiveMsgHook; + } + + @Override + public void close() throws EventMeshException { + try { + task.cancel(false); + goodbye(); + super.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + // todo: move to abstract class + @ChannelHandler.Sharable + private class Handler extends SimpleChannelInboundHandler { + @Override + protected void channelRead0(ChannelHandlerContext ctx, Package msg) throws Exception { + log.info("SimplePubClientImpl|{}|receive|type={}|msg={}", clientNo, msg.getHeader(), msg); + + Command cmd = msg.getHeader().getCommand(); + if (cmd == Command.RESPONSE_TO_CLIENT) { + if (callback != null) { + callback.handle(msg, ctx); + } + Package pkg = MessageUtils.responseToClientAck(msg); + send(pkg); + } else if (cmd == Command.SERVER_GOODBYE_REQUEST) { + //TODO + } + + RequestContext context = contexts.get(RequestContext._key(msg)); + if (context != null) { + contexts.remove(context.getKey()); + context.finish(msg); + } + } + } + + // todo: remove hello + private void hello() throws Exception { + Package msg = MessageUtils.hello(userAgent); + this.io(msg, EventMeshCommon.DEFAULT_TIME_OUT_MILLS); + } + + // todo: remove goodbye + private void goodbye() throws Exception { + Package msg = MessageUtils.goodbye(); + this.io(msg, EventMeshCommon.DEFAULT_TIME_OUT_MILLS); + } +} diff --git a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/eventmeshmessage/EventMeshMessageTCPSubClient.java b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/eventmeshmessage/EventMeshMessageTCPSubClient.java new file mode 100644 index 0000000000..b5a871d9f2 --- /dev/null +++ b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/eventmeshmessage/EventMeshMessageTCPSubClient.java @@ -0,0 +1,191 @@ +package org.apache.eventmesh.client.tcp.impl.eventmeshmessage; + +import org.apache.eventmesh.client.tcp.EventMeshTCPSubClient; +import org.apache.eventmesh.client.tcp.common.EventMeshCommon; +import org.apache.eventmesh.client.tcp.common.MessageUtils; +import org.apache.eventmesh.client.tcp.common.ReceiveMsgHook; +import org.apache.eventmesh.client.tcp.common.RequestContext; +import org.apache.eventmesh.client.tcp.common.TcpClient; +import org.apache.eventmesh.client.tcp.conf.EventMeshTcpClientConfig; +import org.apache.eventmesh.client.tcp.impl.EventMeshTCPSubClientImpl; +import org.apache.eventmesh.common.EventMeshMessage; +import org.apache.eventmesh.common.exception.EventMeshException; +import org.apache.eventmesh.common.protocol.SubscriptionItem; +import org.apache.eventmesh.common.protocol.SubscriptionMode; +import org.apache.eventmesh.common.protocol.SubscriptionType; +import org.apache.eventmesh.common.protocol.tcp.Command; +import org.apache.eventmesh.common.protocol.tcp.Package; +import org.apache.eventmesh.common.protocol.tcp.UserAgent; + +import org.apache.commons.collections4.CollectionUtils; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.SimpleChannelInboundHandler; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +public class EventMeshMessageTCPSubClient extends TcpClient implements EventMeshTCPSubClient { + + private final UserAgent userAgent; + private final List subscriptionItems = Collections.synchronizedList(new ArrayList<>()); + private ReceiveMsgHook callback; + private ScheduledFuture task; + + public EventMeshMessageTCPSubClient(EventMeshTcpClientConfig eventMeshTcpClientConfig) { + super(eventMeshTcpClientConfig); + this.userAgent = eventMeshTcpClientConfig.getUserAgent(); + } + + @Override + public void init() throws EventMeshException { + try { + open(new Handler()); + hello(); + log.info("SimpleSubClientImpl|{}|started!", clientNo); + } catch (Exception ex) { + throw new EventMeshException("Initialize EventMeshMessageTcpSubClient error", ex); + } + } + + @Override + public void heartbeat() throws EventMeshException { + if (task == null) { + synchronized (EventMeshMessageTCPSubClient.class) { + task = scheduler.scheduleAtFixedRate(new Runnable() { + @Override + public void run() { + try { + if (!isActive()) { + reconnect(); + } + Package msg = MessageUtils.heartBeat(); + io(msg, EventMeshCommon.DEFAULT_TIME_OUT_MILLS); + } catch (Exception ignore) { + // + } + } + }, EventMeshCommon.HEARTBEAT, EventMeshCommon.HEARTBEAT, TimeUnit.MILLISECONDS); + } + } + } + + @Override + public void reconnect() throws EventMeshException { + try { + super.reconnect(); + hello(); + if (!CollectionUtils.isEmpty(subscriptionItems)) { + for (SubscriptionItem item : subscriptionItems) { + Package request = MessageUtils.subscribe(item.getTopic(), item.getMode(), item.getType()); + this.io(request, EventMeshCommon.DEFAULT_TIME_OUT_MILLS); + } + } + listen(); + } catch (Exception ex) { + // + } + } + + @Override + public void subscribe(String topic, SubscriptionMode subscriptionMode, SubscriptionType subscriptionType) + throws EventMeshException { + try { + subscriptionItems.add(new SubscriptionItem(topic, subscriptionMode, subscriptionType)); + Package request = MessageUtils.subscribe(topic, subscriptionMode, subscriptionType); + io(request, EventMeshCommon.DEFAULT_TIME_OUT_MILLS); + } catch (Exception ex) { + throw new EventMeshException("Subscribe error", ex); + } + } + + @Override + public void unsubscribe() throws EventMeshException { + try { + Package request = MessageUtils.unsubscribe(); + io(request, EventMeshCommon.DEFAULT_TIME_OUT_MILLS); + } catch (Exception ex) { + throw new EventMeshException("Unsubscribe error", ex); + } + } + + + @Override + public void registerBusiHandler(ReceiveMsgHook receiveMsgHook) throws EventMeshException { + this.callback = receiveMsgHook; + } + + @Override + public void close() throws EventMeshException { + try { + task.cancel(false); + goodbye(); + super.close(); + } catch (Exception ex) { + throw new EventMeshException("Close EventMeshMessageTcpSubClient error", ex); + } + } + + private class Handler extends SimpleChannelInboundHandler { + @SuppressWarnings("Duplicates") + @Override + protected void channelRead0(ChannelHandlerContext ctx, Package msg) throws Exception { + Command cmd = msg.getHeader().getCommand(); + log.info(EventMeshTCPSubClientImpl.class.getSimpleName() + "|receive|type={}|msg={}", cmd, msg); + if (cmd == Command.REQUEST_TO_CLIENT) { + if (callback != null) { + callback.handle(msg, ctx); + } + Package pkg = MessageUtils.requestToClientAck(msg); + send(pkg); + } else if (cmd == Command.ASYNC_MESSAGE_TO_CLIENT) { + Package pkg = MessageUtils.asyncMessageAck(msg); + if (callback != null) { + callback.handle(msg, ctx); + } + send(pkg); + } else if (cmd == Command.BROADCAST_MESSAGE_TO_CLIENT) { + Package pkg = MessageUtils.broadcastMessageAck(msg); + if (callback != null) { + callback.handle(msg, ctx); + } + send(pkg); + } else if (cmd == Command.SERVER_GOODBYE_REQUEST) { + //TODO + } else { + log.error("msg ignored|{}|{}", cmd, msg); + } + RequestContext context = contexts.get(RequestContext._key(msg)); + if (context != null) { + contexts.remove(context.getKey()); + context.finish(msg); + } else { + log.error("msg ignored,context not found.|{}|{}", cmd, msg); + } + } + } + + private void goodbye() throws Exception { + Package msg = MessageUtils.goodbye(); + this.io(msg, EventMeshCommon.DEFAULT_TIME_OUT_MILLS); + } + + private void hello() throws Exception { + Package msg = MessageUtils.hello(userAgent); + this.io(msg, EventMeshCommon.DEFAULT_TIME_OUT_MILLS); + } + + public void listen() throws EventMeshException { + try { + Package request = MessageUtils.listen(); + io(request, EventMeshCommon.DEFAULT_TIME_OUT_MILLS); + } catch (Exception ex) { + throw new EventMeshException("Listen error", ex); + } + } +} diff --git a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/openmessage/OpenMessageTCPPubClient.java b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/openmessage/OpenMessageTCPPubClient.java new file mode 100644 index 0000000000..47a6c56c42 --- /dev/null +++ b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/openmessage/OpenMessageTCPPubClient.java @@ -0,0 +1,75 @@ +package org.apache.eventmesh.client.tcp.impl.openmessage; + +import io.openmessaging.api.Message; +import lombok.extern.slf4j.Slf4j; + +import org.apache.eventmesh.client.tcp.EventMeshTCPPubClient; +import org.apache.eventmesh.client.tcp.common.AsyncRRCallback; +import org.apache.eventmesh.client.tcp.common.ReceiveMsgHook; +import org.apache.eventmesh.common.exception.EventMeshException; +import org.apache.eventmesh.common.protocol.tcp.Package; +import org.apache.eventmesh.common.protocol.tcp.UserAgent; + +@Slf4j +public class OpenMessageTCPPubClient implements EventMeshTCPPubClient { + + @Override + public void init() throws EventMeshException { + + } + + @Override + public void heartbeat() throws EventMeshException { + + } + + @Override + public void reconnect() throws EventMeshException { + + } + + @Override + public Package rr(Package msg, long timeout) throws EventMeshException { + return null; + } + + @Override + public void asyncRR(Package msg, AsyncRRCallback callback, long timeout) throws EventMeshException { + + } + + @Override + public Package publish(Package msg, long timeout) throws EventMeshException { + return null; + } + + @Override + public Package publish(Message cloudEvent, long timeout) throws EventMeshException { + return null; + } + + @Override + public void broadcast(Message cloudEvent, long timeout) throws EventMeshException { + + } + + @Override + public void broadcast(Package msg, long timeout) throws EventMeshException { + + } + + @Override + public void registerBusiHandler(ReceiveMsgHook handler) throws EventMeshException { + + } + + @Override + public UserAgent getUserAgent() { + return null; + } + + @Override + public void close() throws EventMeshException { + + } +} diff --git a/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/openmessage/OpenMessageTCPSubClient.java b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/openmessage/OpenMessageTCPSubClient.java new file mode 100644 index 0000000000..db7396f1e6 --- /dev/null +++ b/eventmesh-sdk-java/src/main/java/org/apache/eventmesh/client/tcp/impl/openmessage/OpenMessageTCPSubClient.java @@ -0,0 +1,60 @@ +package org.apache.eventmesh.client.tcp.impl.openmessage; + +import org.apache.eventmesh.client.tcp.EventMeshTCPSubClient; +import org.apache.eventmesh.client.tcp.common.ReceiveMsgHook; +import org.apache.eventmesh.common.exception.EventMeshException; +import org.apache.eventmesh.common.protocol.SubscriptionMode; +import org.apache.eventmesh.common.protocol.SubscriptionType; +import org.apache.eventmesh.common.protocol.tcp.UserAgent; + +import io.openmessaging.api.Message; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +public class OpenMessageTCPSubClient implements EventMeshTCPSubClient { + @Override + public void init() throws EventMeshException { + + } + + @Override + public void heartbeat() throws EventMeshException { + + } + + @Override + public void reconnect() throws EventMeshException { + + } + + @Override + public void subscribe(String topic, SubscriptionMode subscriptionMode, SubscriptionType subscriptionType) + throws EventMeshException { + + } + + @Override + public void unsubscribe() throws EventMeshException { + + } + + @Override + public void listen() throws EventMeshException { + + } + + @Override + public void registerBusiHandler(ReceiveMsgHook handler) throws EventMeshException { + + } + + @Override + public UserAgent getUserAgent() { + return null; + } + + @Override + public void close() throws EventMeshException { + + } +} diff --git a/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/http/demo/AsyncPublishInstance.java b/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/http/demo/AsyncPublishInstance.java index c3447aa438..1095de392b 100644 --- a/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/http/demo/AsyncPublishInstance.java +++ b/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/http/demo/AsyncPublishInstance.java @@ -17,69 +17,49 @@ package org.apache.eventmesh.client.http.demo; -import org.apache.commons.lang3.StringUtils; -import org.apache.eventmesh.client.http.conf.LiteClientConfig; -import org.apache.eventmesh.client.http.producer.LiteProducer; +import org.apache.eventmesh.client.http.conf.EventMeshHttpClientConfig; +import org.apache.eventmesh.client.http.producer.EventMeshHttpProducer; import org.apache.eventmesh.common.Constants; -import org.apache.eventmesh.common.IPUtil; -import org.apache.eventmesh.common.LiteMessage; -import org.apache.eventmesh.common.RandomStringUtil; -import org.apache.eventmesh.common.ThreadUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.apache.eventmesh.common.EventMeshMessage; +import org.apache.eventmesh.common.utils.IPUtils; +import org.apache.eventmesh.common.utils.RandomStringUtils; +import org.apache.eventmesh.common.utils.ThreadUtils; -public class AsyncPublishInstance { +import lombok.extern.slf4j.Slf4j; - public static Logger logger = LoggerFactory.getLogger(AsyncPublishInstance.class); +@Slf4j +public class AsyncPublishInstance { public static void main(String[] args) throws Exception { - LiteProducer liteProducer = null; - try { -// String eventMeshIPPort = args[0]; - String eventMeshIPPort = ""; -// final String topic = args[1]; - final String topic = "TEST-TOPIC-HTTP-ASYNC"; - if (StringUtils.isBlank(eventMeshIPPort)) { - // if has multi value, can config as: 127.0.0.1:10105;127.0.0.2:10105 - eventMeshIPPort = "127.0.0.1:10105"; - } + String eventMeshIPPort = "127.0.0.1:10105"; + final String topic = "TEST-TOPIC-HTTP-ASYNC"; - LiteClientConfig eventMeshClientConfig = new LiteClientConfig(); - eventMeshClientConfig.setLiteEventMeshAddr(eventMeshIPPort) - .setProducerGroup("EventMeshTest-producerGroup") - .setEnv("env") - .setIdc("idc") - .setIp(IPUtil.getLocalAddress()) - .setSys("1234") - .setPid(String.valueOf(ThreadUtil.getPID())); + EventMeshHttpClientConfig eventMeshClientConfig = EventMeshHttpClientConfig.builder() + .liteEventMeshAddr(eventMeshIPPort) + .producerGroup("EventMeshTest-producerGroup") + .env("env") + .idc("idc") + .ip(IPUtils.getLocalAddress()) + .sys("1234") + .pid(String.valueOf(ThreadUtils.getPID())).build(); - liteProducer = new LiteProducer(eventMeshClientConfig); - liteProducer.start(); - for (int i = 0; i < 1; i++) { - LiteMessage liteMessage = new LiteMessage(); - liteMessage.setBizSeqNo(RandomStringUtil.generateNum(30)) -// .setContent("contentStr with special protocal") - .setContent("testPublishMessage") - .setTopic(topic) - .setUniqueId(RandomStringUtil.generateNum(30)) - .addProp(Constants.EVENTMESH_MESSAGE_CONST_TTL, String.valueOf(4 * 1000)); + EventMeshHttpProducer eventMeshHttpProducer = new EventMeshHttpProducer(eventMeshClientConfig); + for (int i = 0; i < 1; i++) { + EventMeshMessage eventMeshMessage = EventMeshMessage.builder() + .bizSeqNo(RandomStringUtils.generateNum(30)) + .content("testPublishMessage") + .topic(topic) + .uniqueId(RandomStringUtils.generateNum(30)) + .build() + .addProp(Constants.EVENTMESH_MESSAGE_CONST_TTL, String.valueOf(4 * 1000)); - boolean flag = liteProducer.publish(liteMessage); - Thread.sleep(1000); - logger.info("publish result , {}", flag); - } - } catch (Exception e) { - logger.warn("publish msg failed", e); + eventMeshHttpProducer.publish(eventMeshMessage); + Thread.sleep(1000); } - - try { - Thread.sleep(30000); - if (liteProducer != null) { - liteProducer.shutdown(); - } - } catch (Exception e1) { - logger.warn("producer shutdown exception", e1); + Thread.sleep(30000); + try (EventMeshHttpProducer ignore = eventMeshHttpProducer) { + // ignore } } } diff --git a/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/http/demo/AsyncSyncRequestInstance.java b/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/http/demo/AsyncSyncRequestInstance.java index d9888ebfae..28fe47ccae 100644 --- a/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/http/demo/AsyncSyncRequestInstance.java +++ b/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/http/demo/AsyncSyncRequestInstance.java @@ -18,14 +18,16 @@ package org.apache.eventmesh.client.http.demo; -import org.apache.commons.lang3.StringUtils; -import org.apache.eventmesh.client.http.conf.LiteClientConfig; -import org.apache.eventmesh.client.http.producer.LiteProducer; +import org.apache.eventmesh.client.http.conf.EventMeshHttpClientConfig; +import org.apache.eventmesh.client.http.producer.EventMeshHttpProducer; import org.apache.eventmesh.client.http.producer.RRCallback; -import org.apache.eventmesh.common.IPUtil; -import org.apache.eventmesh.common.LiteMessage; -import org.apache.eventmesh.common.RandomStringUtil; -import org.apache.eventmesh.common.ThreadUtil; +import org.apache.eventmesh.common.EventMeshMessage; +import org.apache.eventmesh.common.utils.IPUtils; +import org.apache.eventmesh.common.utils.RandomStringUtils; +import org.apache.eventmesh.common.utils.ThreadUtils; + +import org.apache.commons.lang3.StringUtils; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -35,7 +37,7 @@ public class AsyncSyncRequestInstance { public static void main(String[] args) throws Exception { - LiteProducer liteProducer = null; + EventMeshHttpProducer eventMeshHttpProducer = null; try { // String eventMeshIPPort = args[0]; String eventMeshIPPort = ""; @@ -46,28 +48,29 @@ public static void main(String[] args) throws Exception { eventMeshIPPort = "127.0.0.1:10105"; } - LiteClientConfig eventMeshClientConfig = new LiteClientConfig(); - eventMeshClientConfig.setLiteEventMeshAddr(eventMeshIPPort) - .setProducerGroup("EventMeshTest-producerGroup") - .setEnv("env") - .setIdc("idc") - .setIp(IPUtil.getLocalAddress()) - .setSys("1234") - .setPid(String.valueOf(ThreadUtil.getPID())); + EventMeshHttpClientConfig eventMeshClientConfig = EventMeshHttpClientConfig.builder() + .liteEventMeshAddr(eventMeshIPPort) + .producerGroup("EventMeshTest-producerGroup") + .env("env") + .idc("idc") + .ip(IPUtils.getLocalAddress()) + .sys("1234") + .pid(String.valueOf(ThreadUtils.getPID())).build(); - liteProducer = new LiteProducer(eventMeshClientConfig); + eventMeshHttpProducer = new EventMeshHttpProducer(eventMeshClientConfig); final long startTime = System.currentTimeMillis(); - final LiteMessage liteMessage = new LiteMessage(); - liteMessage.setBizSeqNo(RandomStringUtil.generateNum(30)) - .setContent("testAsyncMessage") - .setTopic(topic) - .setUniqueId(RandomStringUtil.generateNum(30)); + final EventMeshMessage eventMeshMessage = EventMeshMessage.builder() + .bizSeqNo(RandomStringUtils.generateNum(30)) + .content("testAsyncMessage") + .topic(topic) + .uniqueId(RandomStringUtils.generateNum(30)).build(); - liteProducer.request(liteMessage, new RRCallback() { + eventMeshHttpProducer.request(eventMeshMessage, new RRCallback() { @Override - public void onSuccess(LiteMessage o) { - logger.debug("sendmsg : {}, return : {}, cost:{}ms", liteMessage.getContent(), o.getContent(), System.currentTimeMillis() - startTime); + public void onSuccess(EventMeshMessage o) { + logger.debug("sendmsg : {}, return : {}, cost:{}ms", eventMeshMessage.getContent(), o.getContent(), + System.currentTimeMillis() - startTime); } @Override @@ -81,11 +84,9 @@ public void onException(Throwable e) { logger.warn("async send msg failed", e); } - try { - Thread.sleep(30000); - if (liteProducer != null) { - liteProducer.shutdown(); - } + Thread.sleep(30000); + try (final EventMeshHttpProducer ignore = eventMeshHttpProducer) { + // close producer } catch (Exception e1) { logger.warn("producer shutdown exception", e1); } diff --git a/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/http/demo/SyncRequestInstance.java b/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/http/demo/SyncRequestInstance.java index 2b16cde5af..0b261619be 100644 --- a/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/http/demo/SyncRequestInstance.java +++ b/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/http/demo/SyncRequestInstance.java @@ -18,12 +18,13 @@ package org.apache.eventmesh.client.http.demo; import org.apache.commons.lang3.StringUtils; -import org.apache.eventmesh.client.http.conf.LiteClientConfig; -import org.apache.eventmesh.client.http.producer.LiteProducer; -import org.apache.eventmesh.common.IPUtil; -import org.apache.eventmesh.common.LiteMessage; -import org.apache.eventmesh.common.RandomStringUtil; -import org.apache.eventmesh.common.ThreadUtil; + +import org.apache.eventmesh.client.http.conf.EventMeshHttpClientConfig; +import org.apache.eventmesh.client.http.producer.EventMeshHttpProducer; +import org.apache.eventmesh.common.utils.IPUtils; +import org.apache.eventmesh.common.EventMeshMessage; +import org.apache.eventmesh.common.utils.RandomStringUtils; +import org.apache.eventmesh.common.utils.ThreadUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -33,7 +34,7 @@ public class SyncRequestInstance { public static void main(String[] args) throws Exception { - LiteProducer liteProducer = null; + EventMeshHttpProducer eventMeshHttpProducer = null; try { String eventMeshIPPort = args[0]; @@ -44,28 +45,28 @@ public static void main(String[] args) throws Exception { eventMeshIPPort = "127.0.0.1:10105"; } - LiteClientConfig eventMeshClientConfig = new LiteClientConfig(); + EventMeshHttpClientConfig eventMeshClientConfig = new EventMeshHttpClientConfig(); eventMeshClientConfig.setLiteEventMeshAddr(eventMeshIPPort) .setProducerGroup("EventMeshTest-producerGroup") .setEnv("env") .setIdc("idc") - .setIp(IPUtil.getLocalAddress()) + .setIp(IPUtils.getLocalAddress()) .setSys("1234") - .setPid(String.valueOf(ThreadUtil.getPID())); + .setPid(String.valueOf(ThreadUtils.getPID())); - liteProducer = new LiteProducer(eventMeshClientConfig); - liteProducer.start(); + eventMeshHttpProducer = new EventMeshHttpProducer(eventMeshClientConfig); + eventMeshHttpProducer.start(); long startTime = System.currentTimeMillis(); - LiteMessage liteMessage = new LiteMessage(); - liteMessage.setBizSeqNo(RandomStringUtil.generateNum(30)) + EventMeshMessage eventMeshMessage = new EventMeshMessage(); + eventMeshMessage.setBizSeqNo(RandomStringUtils.generateNum(30)) .setContent("contentStr with special protocal") .setTopic(topic) - .setUniqueId(RandomStringUtil.generateNum(30)); + .setUniqueId(RandomStringUtils.generateNum(30)); - LiteMessage rsp = liteProducer.request(liteMessage, 10000); + EventMeshMessage rsp = eventMeshHttpProducer.request(eventMeshMessage, 10000); if (logger.isDebugEnabled()) { - logger.debug("sendmsg : {}, return : {}, cost:{}ms", liteMessage.getContent(), rsp.getContent(), System.currentTimeMillis() - startTime); + logger.debug("sendmsg : {}, return : {}, cost:{}ms", eventMeshMessage.getContent(), rsp.getContent(), System.currentTimeMillis() - startTime); } } catch (Exception e) { logger.warn("send msg failed", e); @@ -73,8 +74,8 @@ public static void main(String[] args) throws Exception { try { Thread.sleep(30000); - if (liteProducer != null) { - liteProducer.shutdown(); + if (eventMeshHttpProducer != null) { + eventMeshHttpProducer.shutdown(); } } catch (Exception e1) { logger.warn("producer shutdown exception", e1); diff --git a/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/http/util/HttpLoadBalanceUtilsTest.java b/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/http/util/HttpLoadBalanceUtilsTest.java index 7355c4f156..4c03ee120e 100644 --- a/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/http/util/HttpLoadBalanceUtilsTest.java +++ b/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/http/util/HttpLoadBalanceUtilsTest.java @@ -17,8 +17,8 @@ package org.apache.eventmesh.client.http.util; -import org.apache.eventmesh.client.http.conf.LiteClientConfig; -import org.apache.eventmesh.common.EventMeshException; +import org.apache.eventmesh.client.http.conf.EventMeshHttpClientConfig; +import org.apache.eventmesh.common.exception.EventMeshException; import org.apache.eventmesh.common.loadbalance.LoadBalanceSelector; import org.apache.eventmesh.common.loadbalance.LoadBalanceType; import org.junit.Assert; @@ -28,30 +28,30 @@ public class HttpLoadBalanceUtilsTest { @Test public void testCreateRandomSelector() throws EventMeshException { - LiteClientConfig liteClientConfig = new LiteClientConfig() + EventMeshHttpClientConfig eventMeshHttpClientConfig = new EventMeshHttpClientConfig() .setLiteEventMeshAddr("127.0.0.1:1001;127.0.0.2:1002"); LoadBalanceSelector randomSelector = HttpLoadBalanceUtils - .createEventMeshServerLoadBalanceSelector(liteClientConfig); + .createEventMeshServerLoadBalanceSelector(eventMeshHttpClientConfig); Assert.assertEquals(LoadBalanceType.RANDOM, randomSelector.getType()); } @Test public void testCreateWeightRoundRobinSelector() throws EventMeshException { - LiteClientConfig liteClientConfig = new LiteClientConfig() + EventMeshHttpClientConfig eventMeshHttpClientConfig = new EventMeshHttpClientConfig() .setLiteEventMeshAddr("127.0.0.1:1001:1;127.0.0.2:1001:2") .setLoadBalanceType(LoadBalanceType.WEIGHT_ROUND_ROBIN); LoadBalanceSelector weightRoundRobinSelector = HttpLoadBalanceUtils - .createEventMeshServerLoadBalanceSelector(liteClientConfig); + .createEventMeshServerLoadBalanceSelector(eventMeshHttpClientConfig); Assert.assertEquals(LoadBalanceType.WEIGHT_ROUND_ROBIN, weightRoundRobinSelector.getType()); } @Test public void testCreateWeightRandomSelector() throws EventMeshException { - LiteClientConfig liteClientConfig = new LiteClientConfig() + EventMeshHttpClientConfig eventMeshHttpClientConfig = new EventMeshHttpClientConfig() .setLiteEventMeshAddr("127.0.0.1:1001:1;127.0.0.2:1001:2") .setLoadBalanceType(LoadBalanceType.WEIGHT_RANDOM); LoadBalanceSelector weightRoundRobinSelector = HttpLoadBalanceUtils - .createEventMeshServerLoadBalanceSelector(liteClientConfig); + .createEventMeshServerLoadBalanceSelector(eventMeshHttpClientConfig); Assert.assertEquals(LoadBalanceType.WEIGHT_RANDOM, weightRoundRobinSelector.getType()); } } \ No newline at end of file diff --git a/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/tcp/demo/AsyncPublish.java b/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/tcp/demo/AsyncPublish.java index ef9a3b6a14..01ccbfb6b0 100644 --- a/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/tcp/demo/AsyncPublish.java +++ b/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/tcp/demo/AsyncPublish.java @@ -17,10 +17,10 @@ package org.apache.eventmesh.client.tcp.demo; -import org.apache.eventmesh.client.tcp.EventMeshClient; +import org.apache.eventmesh.client.tcp.EventMeshTCPClient; import org.apache.eventmesh.client.tcp.common.EventMeshCommon; import org.apache.eventmesh.client.tcp.common.EventMeshTestUtils; -import org.apache.eventmesh.client.tcp.impl.DefaultEventMeshClient; +import org.apache.eventmesh.client.tcp.impl.DefaultEventMeshTCPClient; import org.apache.eventmesh.common.protocol.tcp.Package; import org.apache.eventmesh.common.protocol.tcp.UserAgent; import org.slf4j.Logger; @@ -30,14 +30,14 @@ public class AsyncPublish { public static Logger logger = LoggerFactory.getLogger(AsyncPublish.class); - private static EventMeshClient client; + private static EventMeshTCPClient client; public static AsyncPublish handler = new AsyncPublish(); public static void main(String[] agrs) throws Exception { try { UserAgent userAgent = EventMeshTestUtils.generateClient1(); - client = new DefaultEventMeshClient("127.0.0.1", 10002, userAgent); + client = new DefaultEventMeshTCPClient("127.0.0.1", 10002, userAgent); client.init(); client.heartbeat(); diff --git a/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/tcp/demo/AsyncPublishBroadcast.java b/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/tcp/demo/AsyncPublishBroadcast.java index 0b3d45c728..e674c02ee8 100644 --- a/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/tcp/demo/AsyncPublishBroadcast.java +++ b/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/tcp/demo/AsyncPublishBroadcast.java @@ -17,10 +17,10 @@ package org.apache.eventmesh.client.tcp.demo; -import org.apache.eventmesh.client.tcp.EventMeshClient; +import org.apache.eventmesh.client.tcp.EventMeshTCPClient; import org.apache.eventmesh.client.tcp.common.EventMeshCommon; import org.apache.eventmesh.client.tcp.common.EventMeshTestUtils; -import org.apache.eventmesh.client.tcp.impl.DefaultEventMeshClient; +import org.apache.eventmesh.client.tcp.impl.DefaultEventMeshTCPClient; import org.apache.eventmesh.common.protocol.tcp.Package; import org.apache.eventmesh.common.protocol.tcp.UserAgent; import org.slf4j.Logger; @@ -30,12 +30,12 @@ public class AsyncPublishBroadcast { public static Logger logger = LoggerFactory.getLogger(AsyncPublishBroadcast.class); - private static EventMeshClient client; + private static EventMeshTCPClient client; public static void main(String[] agrs) throws Exception { try { UserAgent userAgent = EventMeshTestUtils.generateClient1(); - client = new DefaultEventMeshClient("127.0.0.1", 10002, userAgent); + client = new DefaultEventMeshTCPClient("127.0.0.1", 10002, userAgent); client.init(); client.heartbeat(); diff --git a/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/tcp/demo/AsyncSubscribe.java b/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/tcp/demo/AsyncSubscribe.java index 9929d974a3..0652826d58 100644 --- a/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/tcp/demo/AsyncSubscribe.java +++ b/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/tcp/demo/AsyncSubscribe.java @@ -20,10 +20,10 @@ import io.netty.channel.ChannelHandlerContext; -import org.apache.eventmesh.client.tcp.EventMeshClient; +import org.apache.eventmesh.client.tcp.EventMeshTCPClient; import org.apache.eventmesh.client.tcp.common.EventMeshTestUtils; import org.apache.eventmesh.client.tcp.common.ReceiveMsgHook; -import org.apache.eventmesh.client.tcp.impl.DefaultEventMeshClient; +import org.apache.eventmesh.client.tcp.impl.DefaultEventMeshTCPClient; import org.apache.eventmesh.common.protocol.SubscriptionType; import org.apache.eventmesh.common.protocol.SubscriptionMode; import org.apache.eventmesh.common.protocol.tcp.EventMeshMessage; @@ -36,14 +36,14 @@ public class AsyncSubscribe implements ReceiveMsgHook { public static Logger logger = LoggerFactory.getLogger(AsyncSubscribe.class); - private static EventMeshClient client; + private static EventMeshTCPClient client; public static AsyncSubscribe handler = new AsyncSubscribe(); public static void main(String[] agrs) throws Exception { try { UserAgent userAgent = EventMeshTestUtils.generateClient2(); - client = new DefaultEventMeshClient("127.0.0.1", 10002, userAgent); + client = new DefaultEventMeshTCPClient("127.0.0.1", 10002, userAgent); client.init(); client.heartbeat(); @@ -63,12 +63,12 @@ public static void main(String[] agrs) throws Exception { @Override public void handle(Package msg, ChannelHandlerContext ctx) { - EventMeshMessage eventMeshMessage = convert(msg); + EventMeshMessage eventMeshMessage = convertToProtocolMessage(msg); logger.info("receive async msg====================={}", eventMeshMessage); } @Override - public EventMeshMessage convert(Package pkg) { + public EventMeshMessage convertToProtocolMessage(Package pkg) { return (EventMeshMessage) pkg.getBody(); } } diff --git a/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/tcp/demo/AsyncSubscribeBroadcast.java b/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/tcp/demo/AsyncSubscribeBroadcast.java index e950122be2..1ab68e543d 100644 --- a/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/tcp/demo/AsyncSubscribeBroadcast.java +++ b/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/tcp/demo/AsyncSubscribeBroadcast.java @@ -17,33 +17,30 @@ package org.apache.eventmesh.client.tcp.demo; - -import io.netty.channel.ChannelHandlerContext; - -import org.apache.eventmesh.client.tcp.EventMeshClient; +import org.apache.eventmesh.client.tcp.EventMeshTCPClient; import org.apache.eventmesh.client.tcp.common.EventMeshTestUtils; import org.apache.eventmesh.client.tcp.common.ReceiveMsgHook; -import org.apache.eventmesh.client.tcp.impl.DefaultEventMeshClient; -import org.apache.eventmesh.common.protocol.SubscriptionType; +import org.apache.eventmesh.client.tcp.impl.DefaultEventMeshTCPClient; import org.apache.eventmesh.common.protocol.SubscriptionMode; +import org.apache.eventmesh.common.protocol.SubscriptionType; import org.apache.eventmesh.common.protocol.tcp.EventMeshMessage; -import org.apache.eventmesh.common.protocol.tcp.UserAgent; import org.apache.eventmesh.common.protocol.tcp.Package; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.apache.eventmesh.common.protocol.tcp.UserAgent; -public class AsyncSubscribeBroadcast implements ReceiveMsgHook { +import io.netty.channel.ChannelHandlerContext; +import lombok.extern.slf4j.Slf4j; - public static Logger logger = LoggerFactory.getLogger(AsyncSubscribeBroadcast.class); +@Slf4j +public class AsyncSubscribeBroadcast implements ReceiveMsgHook { - private static EventMeshClient client; + private static EventMeshTCPClient client; public static AsyncSubscribeBroadcast handler = new AsyncSubscribeBroadcast(); - public static void main(String[] agrs) throws Exception { + public static void main(String[] agrs) { try { UserAgent userAgent = EventMeshTestUtils.generateClient2(); - client = new DefaultEventMeshClient("127.0.0.1", 10002, userAgent); + client = new DefaultEventMeshTCPClient("127.0.0.1", 10002, userAgent); client.init(); client.heartbeat(); @@ -52,23 +49,19 @@ public static void main(String[] agrs) throws Exception { client.listen(); - //client.unsubscribe(); - - // release resource and close client - // client.close(); } catch (Exception e) { - logger.warn("AsyncSubscribeBroadcast failed", e); + log.warn("AsyncSubscribeBroadcast failed", e); } } @Override public void handle(Package msg, ChannelHandlerContext ctx) { - EventMeshMessage eventMeshMessage = convert(msg); - logger.info("receive broadcast msg==============={}", eventMeshMessage); + EventMeshMessage eventMeshMessage = convertToProtocolMessage(msg); + log.info("receive broadcast msg==============={}", eventMeshMessage); } @Override - public EventMeshMessage convert(Package pkg) { + public EventMeshMessage convertToProtocolMessage(Package pkg) { return (EventMeshMessage) pkg.getBody(); } } diff --git a/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/tcp/demo/SyncRequest.java b/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/tcp/demo/SyncRequest.java index 21a28baf1d..272ece079d 100644 --- a/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/tcp/demo/SyncRequest.java +++ b/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/tcp/demo/SyncRequest.java @@ -17,10 +17,10 @@ package org.apache.eventmesh.client.tcp.demo; -import org.apache.eventmesh.client.tcp.EventMeshClient; +import org.apache.eventmesh.client.tcp.EventMeshTCPClient; import org.apache.eventmesh.client.tcp.common.EventMeshCommon; import org.apache.eventmesh.client.tcp.common.EventMeshTestUtils; -import org.apache.eventmesh.client.tcp.impl.DefaultEventMeshClient; +import org.apache.eventmesh.client.tcp.impl.DefaultEventMeshTCPClient; import org.apache.eventmesh.common.protocol.tcp.UserAgent; import org.apache.eventmesh.common.protocol.tcp.Package; import org.slf4j.Logger; @@ -30,12 +30,12 @@ public class SyncRequest { public static Logger logger = LoggerFactory.getLogger(SyncRequest.class); - private static EventMeshClient client; + private static EventMeshTCPClient client; public static void main(String[] agrs) throws Exception { try { UserAgent userAgent = EventMeshTestUtils.generateClient1(); - client = new DefaultEventMeshClient("127.0.0.1", 10000, userAgent); + client = new DefaultEventMeshTCPClient("127.0.0.1", 10000, userAgent); client.init(); client.heartbeat(); diff --git a/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/tcp/demo/SyncResponse.java b/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/tcp/demo/SyncResponse.java index 68ea58b086..65d921dc89 100644 --- a/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/tcp/demo/SyncResponse.java +++ b/eventmesh-sdk-java/src/test/java/org/apache/eventmesh/client/tcp/demo/SyncResponse.java @@ -17,32 +17,30 @@ package org.apache.eventmesh.client.tcp.demo; -import io.netty.channel.ChannelHandlerContext; - -import org.apache.eventmesh.client.tcp.EventMeshClient; +import org.apache.eventmesh.client.tcp.EventMeshTCPClient; import org.apache.eventmesh.client.tcp.common.EventMeshTestUtils; import org.apache.eventmesh.client.tcp.common.ReceiveMsgHook; -import org.apache.eventmesh.client.tcp.impl.DefaultEventMeshClient; -import org.apache.eventmesh.common.protocol.SubscriptionType; +import org.apache.eventmesh.client.tcp.impl.DefaultEventMeshTCPClient; import org.apache.eventmesh.common.protocol.SubscriptionMode; +import org.apache.eventmesh.common.protocol.SubscriptionType; import org.apache.eventmesh.common.protocol.tcp.EventMeshMessage; -import org.apache.eventmesh.common.protocol.tcp.UserAgent; import org.apache.eventmesh.common.protocol.tcp.Package; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.apache.eventmesh.common.protocol.tcp.UserAgent; -public class SyncResponse implements ReceiveMsgHook { +import io.netty.channel.ChannelHandlerContext; +import lombok.extern.slf4j.Slf4j; - public static Logger logger = LoggerFactory.getLogger(SyncResponse.class); +@Slf4j +public class SyncResponse implements ReceiveMsgHook { - private static EventMeshClient client; + private static EventMeshTCPClient client; public static SyncResponse handler = new SyncResponse(); - public static void main(String[] agrs) throws Exception { + public static void main(String[] agrs) { try { UserAgent userAgent = EventMeshTestUtils.generateClient2(); - client = new DefaultEventMeshClient("127.0.0.1", 10000, userAgent); + client = new DefaultEventMeshTCPClient("127.0.0.1", 10000, userAgent); client.init(); client.heartbeat(); @@ -52,24 +50,20 @@ public static void main(String[] agrs) throws Exception { client.listen(); - //client.unsubscribe(); - - // release resource and close client - // client.close(); } catch (Exception e) { - logger.warn("SyncResponse failed", e); + log.warn("SyncResponse failed", e); } } @Override public void handle(Package msg, ChannelHandlerContext ctx) { - logger.info("receive sync rr msg================{}", msg); + log.info("receive sync rr msg================{}", msg); Package pkg = EventMeshTestUtils.rrResponse(msg); ctx.writeAndFlush(pkg); } @Override - public EventMeshMessage convert(Package pkg) { + public EventMeshMessage convertToProtocolMessage(Package pkg) { return null; } } diff --git a/eventmesh-spi/build.gradle b/eventmesh-spi/build.gradle index 7c61ebcf9d..f5933ae0f1 100644 --- a/eventmesh-spi/build.gradle +++ b/eventmesh-spi/build.gradle @@ -16,5 +16,4 @@ */ dependencies { compileOnly project(":eventmesh-common") - testImplementation project(":eventmesh-common") } \ No newline at end of file diff --git a/eventmesh-starter/build.gradle b/eventmesh-starter/build.gradle index 48aafcb72d..0bc2208fd1 100644 --- a/eventmesh-starter/build.gradle +++ b/eventmesh-starter/build.gradle @@ -17,6 +17,4 @@ dependencies { implementation project(":eventmesh-runtime") - testImplementation project(":eventmesh-runtime") - //testImplementation group: 'junit', name: 'junit', version: '4.12' } \ No newline at end of file