"Pulsar is a distributed Pub-sub messaging platform with a very flexible messaging model and an intuitive client API."
Pulsar is a distributed messaging platform in Pub-sub mode with a flexible messaging model and intuitive client API.
Pulsar, a next-generation messaging system developed and open-source by Yahoo, is currently an incubator for the Apache Software Foundation.
This article is a brief introduction to Pulsar's producer, which contains the following content:
- The design of producer
- Implementation of Message Delivery
1. Producer Design 1.1 Create producer
The above is a sample code for creating a producer on the Pulsar website.
The process is created as follows:
- Specify serviceurl Create Pulsarclient
- Specifies the topic of the producer Send Message, created by pulsarclient producer
The creation of the code above can be inferred:
- Serviceurl should be used for service discovery, find broker information through Serviceurl
- Producer Specifies topic, then a producer can only send messages to a specific topic
1.2 Producer API
Pulsar, send the relevant interface as producer, as shown in:
- Producer defines the Send interface
- Producerbase, as an abstract class, provides a basic implementation
- Producerimpl is the real implementation class.
- Partitionedproducerimpl looked at and the partition related, this later looked
The Producer interface is as follows:
Public interface Producer<t> extends closeable {/** * return Producer Send Message topic */String gettopic (); /** * Producer Name */String getproducername (); /** * synchronously Send message */MessageId Send (T message) throws Pulsarclientexception; /** * have send message */completablefuture<messageid> SendAsync (T message); /** * Flush Client completes the message and waits for all messages to persist successfully * @since 2.1.0 * @see #flushAsync () */void Flush () throws Pulsarclien Texception; /** * Asynchronous Flush Client completes the message and waits for all messages to persist successfully * @since 2.1.0 * @see #flush () */completablefuture<void> Flus Hasync (); /** * Create typedmessagebuilder for building messages */typedmessagebuilder<t> newmessage (); /** * Synchronous sending of messages, has been deprecated */@Deprecated MessageId Send (message<t> message) throws Pulsarclientexception; /** * Asynchronously sends a message that has been deprecated */@Deprecated completablefuture<messageid> SendAsync (message<t> message); /** * Get the last serial number sent by producer */Long Getlastsequenceid (); /** * Get statistics on producer */Producerstats getstats (); /** * Asynchronously shuts down producer and frees resources */completablefuture<void> closeasync (); /** * Returns whether the producer is connected to the broker */boolean isconnected ();}
The capabilities provided by the Pulsar producer can be seen through the producer interface:
- Send messages synchronously
- Sending messages asynchronously
- A Producer can only send a message to a specific topic (PRODUCER#TOPIC () returns a topic, stating that Producer is bound to a topic)
- Bulk send (the Flush method indicates that the batch should be supported and the message will be saved in client memory)
- Does the sequenceid include the ability to do things like idempotent?
- Statistical capacity
1.3 Producerbase
Producerbase, as an abstract class, implements the producer interface.
Producerbase contains four properties:
- Producercreatedfuture: Asynchronously creates the future of producer
- Configuration of the Conf:producer
- Schema: Message-related schema information
- Interceptors:producer Interceptor, insert some actions before and after the send
Producercreatedfuture
Renaming on this property is used to create producer asynchronously.
But providing the future of creating an entity asynchronously in a base class is more difficult to understand. General programming ideas define some of the underlying public properties in the base class for storing state or configuration, such as Conf. Here the producercreatedfuture is actually used to Partitionedproducerimpl asynchronously create multiple producer, this follow-up look again.
Conf
Producerconfigurationdata provides producer-related configuration information, including whether to bulk send, the size of the memory cache message, the timeout sent, and so on.
Schema
The schema specifies the format of the message, which completes the encode and decode of the message through the schema.
Interceptors
Producerinterceptor is an interceptor provided by producer and contains two methods: Beforesend, Onsendacknowledgement, respectively, for inserting behavior before and after sending.
1.4 Producerimpl
Producerimpl inherits the Producerbase and is the core implementation of the producer interface.
Producerimpl adds a large number of attributes on the basis of producerbase, including:
- Producerid: Unique producer ID generated by Atomiclong in-process
- Msgidgenerator: Message ID
- Pendingmessages: In-Memory cached messages
- Pendingcallbacks: In-memory cached messages correspond to callback
- Timeout: The Sent timeout configuration
- Batchmessagecontainer: Container for bulk messages
- Producername: Globally unique producer name
- Wait a minute... (The related properties are described in the subsequent send implementation)
PRODUCERIMPL implements specific sending behavior, such as synchronous sending, asynchronous sending (which is described in the implementation section of the message delivery).
1.5 Partitionedproducerimpl
Producer provides a delivery-related API definition, Producerbase provides a basic implementation, PRODUCERIMPL provides a concrete implementation, so what does Partitionedproducerimpl do?
With the Partitionedproducerimpl property you can see that the internal contains a list of Producerimpl, then Partitionedproducerimpl and Producerimpl are a combination of relationships.
Through the Start method, it can be seen that Partitionedproducerimpl creates a corresponding number of Producerimpl instances based on the number of partitions corresponding to the Topicmetadata (this also illustrates the purpose of producercreatedfuture in Producerbase) 。
Why do I need to create a set of Producerimpl instances in Partitionedproducerimpl?
Partitionedproducerimpl also adds a Routerpolicy attribute with the interface:
public interface MessageRouter extends Serializable { @Deprecated default int choosePartition(Message<?> msg) { throw new UnsupportedOperationException("Use #choosePartition(Message, TopicMetadata) instead"); } default int choosePartition(Message<?> msg, TopicMetadata metadata) { return choosePartition(msg); }}
It is not difficult to understand the Messagerouter interface through the definition of interface to implement the mapping of message and partition.
Through the implementation of the Internalsendasync method, it can be seen that the message is sent through Routerpolicy to map the message to partition, by partition select the corresponding producer to perform the Send, That long explains why the Partitionedproducerimpl will create and correspond to the topic partition number of the same producerimpl.
Through the above content, can summarize the producer module of the various classes of responsibility:
- Producer: Define the Send interface, the core API that the user uses
- Basic implementation of the Producerbase:producer interface
- Producerimpl: Implementation of specific send behavior, a producerimpl can only write to a topic message
- Partitionedproducerimpl: Integration of multiple Producerimpl to send messages to multiple partitions
2. Implementation of Message Delivery
After a complete understanding of the Producer module, the following content specifically describes the sending process of a message.
In the message system, from the perspective of producer, a message writing process typically consists of:
- Message validation
- Message property Enhancement (add some necessary system properties)
- Message routing (select Destination partition)
- Serialization of messages
- Message data is written to the network
- Wait for write result response
- Return write results
The following is an implementation of Producerimpl to understand the process of pulsar producer sending messages.
2.1 Addressing
To send a message, in addition to verifying that the message is legitimate, the message is first written to the target (the partition of the message target is found by routing).
The GRABCNX () method was called in the last row of the Producerimpl constructor to create the link (the context in which the link was built).
The Grabcnx method creates the connection through Pulsarclient, while Pubsarclient internally completes the Lookupservice-to-broker mapping and establishes the link through the topic interface.
The Lookupservice interface provides the Binaryprotolookupservice and Httplookupservice implementations, and through Lookupservice users can also implement their own service discovery modules.
2.2 Message Sent
The call chain that sends the message, as shown, eventually sends the message through the Producerimpl Internalsendasync. Whether you send synchronously or asynchronously, and you end up sending asynchronously (and just waiting to send the results on an asynchronous basis), you can see that the pulsar producer on the API implementation focuses on the reusability of the code, the least functional principle of the API.
Take a heads-up message to send as an example, the specific implementation of SendAsync is as follows:
- Wraps the message into a Opsendmsg object after the necessary checksum (contains the callback after the asynchronous send is completed)
- Add a message to the Pendingmessages
- Send operation via EventLoop of connection
Producerimpl will handle the response of the service side to the write message in the Ackreceived method, identify the corresponding opsendmsg through the SequenceID of the message, and invoke the corresponding callback to execute the callback logic. In callback, some statistics are completed to respond to user's operation and send behavior.
Producerimpl only establishes a link, and both the send and ACK are executed through synchronized, so the intermediate message is sent and responded to by Pendingmessages, and the processing of timeouts is done. This piece is specific to the code implementation.
Summarize
This paper introduces the design of Pulsar producer module, including the responsibilities of each class, and briefly introduces the sending process of the message. Puslar producer in the design and ROCKETMQ thought difference is still relatively large, such as Puslar producer will be producer corresponding to the partition, each partition has its own producer, which can be relatively easy to complete some idempotent operations.