
利用 Java 函数和发布/订阅模式增强代码可复用性
在 Java 中,发布/订阅模式是一种设计模式,它允许多个事件消费者订阅事件发布者发布的事件。这种模式可以显著提高代码的可复用性,特别是对于事件驱动的系统。
实现
在 Java 中,可以使用 Google Cloud Pub/Sub 库来实现发布/订阅模式。该库提供了 Publisher 和 Subscriber 类来分别发布和订阅事件。
立即学习“Java免费学习笔记(深入)”;
MOKI
MOKI是美图推出的一款AI短片创作工具,旨在通过AI技术自动生成分镜图并转为视频素材。
375 查看详情
为了使用 Pub/Sub,首先需要创建一个项目并启用 Pub/Sub API。然后,可以使用以下步骤发布消息:
import com.google.api.client.util.Base64;import com.google.cloud.pubsub.v1.Publisher;import com.google.protobuf.ByteString;import com.google.pubsub.v1.ProjectTopicName;import com.google.pubsub.v1.PubsubMessage;import java.io.IOException;public class MessagePublisher { public static void main(String... args) throws Exception { String projectId = "your-project-id"; String topicId = "your-topic-id"; ProjectTopicName topicName = ProjectTopicName.of(projectId, topicId); Publisher publisher = null; try { // Create a publisher instance with default settings bound to the topic publisher = Publisher.newBuilder(topicName).build(); String message = "Hello World!"; // Data must be a bytestring ByteString data = ByteString.copyFromUtf8(message); PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build(); // Once published, returns a server-assigned message id (unique within the topic) String messageId = publisher.publish(pubsubMessage).get(); System.out.println("Published a message with message id: " + messageId); } catch (IOException e) { System.out.println(e.toString()); } finally { if (publisher != null) { // When finished with the publisher, shutdown to free up resources. publisher.shutdown(); publisher.awaitTermination(1, TimeUnit.MINUTES); } } }}
消息发布到主题后,可以由一个或多个订阅者接收。使用以下步骤订阅消息:
import com.google.cloud.pubsub.v1.AckReplyConsumer;import com.google.cloud.pubsub.v1.MessageReceiver;import com.google.cloud.pubsub.v1.Subscriber;import com.google.pubsub.v1.ProjectSubscriptionName;import com.google.pubsub.v1.PubsubMessage;import java.util.concurrent.TimeUnit;import java.util.concurrent.TimeoutException;public class MessageSubscriber { public static void main(String... args) throws Exception { String projectId = "your-project-id"; String subscriptionId = "your-subscription-id"; ProjectSubscriptionName subscriptionName = ProjectSubscriptionName.of(projectId, subscriptionId); Subscriber subscriber = null; try { subscriber = Subscriber.newBuilder(subscriptionName, new MessageReceiver() { @Override public void receiveMessage(PubsubMessage message, AckReplyConsumer consumer) { // Handle incoming message, then ack the received message. System.out.println("Id: " + message.getMessageId()); System.out.println("Data: " + message.getData().toStringUtf8()); consumer.ack(); } }).build(); // Start the subscriber. subscriber.startAsync().awaitRunning(); System.out.printf("Listening for messages on %s:n", subscriptionName.toString()); // Allow the subscriber to run for 30s unless an unrecoverable error occurs. subscriber.awaitTerminated(30, TimeUnit.SECONDS); } catch (TimeoutException timeoutException) { // Shut down the subscriber after 30s. Stop receiving messages. subscriber.stopAsync(); } }}
实战案例
以下是发布/订阅模式如何提高代码可复用性的一个实战案例:
微服务架构:在微服务架构中,不同的服务可以作为独立的发布者和订阅者。这允许服务松散耦合,并使开发和维护变得更加容易。事件驱动系统:事件驱动系统使用发布/订阅模式来触发基于事件的动作。这可以简化系统设计并提高应用程序的可扩展性。数据处理管道:数据处理管道可以使用发布/订阅模式将数据从一个阶段移动到另一个阶段。这允许数据处理管道以可伸缩且松散耦合的方式构建。
以上就是Java函数如何利用发布/订阅模式提升代码可复用性?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/815752.html
微信扫一扫
支付宝扫一扫