Nats Learning--Conceptual learning messages (message) and publishing subscriptions (Publish Subscribe)

Source: Internet
Author: User
Tags publish subscribe

1 theory article 1.1来 from the official introduction

NATS acts as a central nervous system for distributed systems such as mobile devices, IoT networks, Enterprise Microservic ES and cloud native infrastructure. Unlike traditional enterprise messaging systems, NATS provides an always on ' dial-tone '.

Nats plays a central nervous system in distributed systems, which include mobile devices, the Internet of Things, enterprise microservices, and native cloud infrastructures. Unlike traditional enterprise messaging systems, NATS offers always-on online services.

NATS was created by Derek Collison, founder and CEO at Apcera. Derek has spent over twenty years designing, building and using publish-subscribe messaging systems. Learn why traditional enterprise messaging systems don ' t work for today's distributed infrastructure, in the This talk from De Rek on designing a new cloud-native messaging framework.

1.2 NATS messages (message)

NATS messaging involves the electronic exchange of data among computer.

NATS provides a layer between the application and the underlying physical network. Application data is encoded as a message and sent by the publisher. The message is received, decoded, and processed by one or more subscribers. A subscriber can process a NATS message asynchronously or synchronously.

NATS messages refer to the interaction of messages between different computer applications.

NATS provides an abstraction layer between the application and the underlying network. The app data is wrapped as a message and sent by the publisher. Messages are received, decoded, and processed by one or more subscribers. Subscribers can process messages asynchronously or synchronously.

1.2.1 Asynchronous processing

Asynchronous processing uses a callback message handler to process messages. When a message is arrives, the registered callback handler receives control to process the message. The client or consuming application is not blocked from performing other work while it's waiting for a message. Asynchronous processing lets you create multi-threaded dispatching designs.

Asynchronous Message Processing

Asynchronous message processing uses a message callback handler to process the message, and when the message arrives, the callback handler is registered to process the message. The client or consumer program does not block from other events while waiting for the message. Asynchronous message processing allows programmers to create multi-threaded distribution designs.

1.2.2 Synchronous Processing

Synchronous processing requires that application code explicitly call a method to the process an incoming message. Typically an explicit call are a blocking call that suspends processing until a message becomes available. IF no message is available, the period for which the message processing call blocks are set by the client. Synchronous processing is typically used by a server whose purpose are to wait for and process incoming request messages, a nd to send replies to the requesting application.

Synchronous message Processing

Synchronous message processing requires the application code to display the function that is called to process the incoming message. The normally displayed function call is a blocking call, and it waits for a known message to be available. If no messages are available, the client will be blocked until the message is invoked. Synchronous message processing is usually performed by a server side, and its job is to wait and process the incoming message and send the reply to the party sending the message.

1.3 Nats's release subscription (Publish Subscribe)

NATS implements a publish Subscribe messaging model. NATS Publish Subscribe is a One-to-many communication. A publisher sends a message on a subject. Any active subscriber listening on that subject receives the message. Subscribers can register interest in wildcard subjects.

NATS implements a message model based on the publication subscription. NATS's release subscription model is a one-to-many communication model. The publisher of the message sends a message to a principal (subject), and any active subscriber strengthens the subject and receives the message. Subscribers can use wildcard characters to register topics of interest.

If A subscriber is isn't listening on the subject (no subject match), or isn't active when the message is sent, the message is not received. NATS is a Fire-and-forget messaging system. If you need higher levels of service, you build it into the client.

If the subscriber does not have a listening topic (or no matching topic), or is not online, it will not receive a message when the message is sent. Nats is a once and for all messaging system. If a higher service is required, it is built into the client.

In an asynchronous exchange, messages is delivered to the Subscriber ' s message handler. If There is no handler, the subscription are synchronous and the client may be blocked until it can process the message.

In asynchronous message processing, the message will be sent to the subscriber's message callback processor, if there is no message callback processor, the Subscriber is synchronous, the client will block, know that it processed the message.

2 Practical Articles

First make sure that the Nats server program is set up.

Reference

http://blog.csdn.net/frankcheng5143/article/details/51141804

2.1 Starting the Service

At the command line, enter

gnastd

2.2 Writing of client programs

Dependent jar Packages

<dependency>  <groupId>io.nats</groupId>  <artifactId>jnats</artifactId>  <version>0.4.1</version></dependency>

Other dependencies

No logs, it's going to get an error, and here I'm using log4j.

<dependency>    <groupId>org.slf4j</groupId>    <artifactId>slf4j-api</artifactId>    <version>1.7.21</version></dependency><dependency>    <groupId>org.slf4j</groupId>    <artifactId>slf4j-log4j12</artifactId>    <version>1.7.21</version></dependency><dependency>    <groupId>log4j</groupId>    <artifactId>log4j</artifactId>    <version>1.2.17</version></dependency>

Configuration of the log4j

Log4j.properties

#---------------------------------------------------------# log4j Settings for log4j 1.2.x (via jakarta-commons-logging) # # The five logging levels used by Log is (in order): # 1. DEBUG (The Least serious) # 2. info# 3. warn# 4. error# 5. FATAL (the most serious) # #---------------------------------------------------------# root-categroy#--------------- ------------------------------------------Log4j.rootcategory=info, stdout, file#-------------------------------- -------------------------# stdout#--------------------------------------------------------- log4j.appender.stdout=org.apache.log4j.consoleappenderlog4j.appender.stdout.layout= Org.apache.log4j.patternlayoutlog4j.appender.stdout.layout.conversionpattern=%d{absolute}%5p%c{1}:%L-%m%n#---- -----------------------------------------------------# file (log) #---------------------------------------------- -----------Log4j.appender.file=org.apache.log4j.dailyrollingfileappenderlog4j.appender.file.file=/home/gwcheng /info.loglog4j.aPpender.file.layout=org.apache.log4j.patternlayoutlog4j.appender.file.append= Truelog4j.appender.file.datepattern= '. ' Yyyy-mm-dd log4j.appender.file.layout.conversionpattern=%d{yyyy-mm-dd HH:mm:ss:SSS}%p [%M]%c%m%n#---------------- -----------------------------------------# file (HTML) #--------------------------------------------------------- #log4j. appender.html=org.apache.log4j.fileappender#log4j.appender.html.file=### the PATH here # log4j.appender.html.layout=org.apache.log4j.htmllayout#------------------------------------------------------- --# customer#---------------------------------------------------------# my definition Io.netty=debug

OK, start writing code.

This simulates a publisher, three subscribers, and the topology diagram is the same as the diagram above.

2.2.1 Publisher Code

Publish.java

 PackageCom.gwc.nats.nats.test;ImportJava.io.IOException;ImportJava.util.ArrayList;ImportJava.util.HashMap;ImportJava.util.Map;ImportJava.util.Scanner;ImportJava.util.concurrent.TimeoutException;ImportIo.nats.client.Connection;ImportIo.nats.client.ConnectionFactory;ImportIo.nats.client.Message;/** * Hello world! * @author Gwcheng * * Public  class Publish {         Public Static void Main(string[] args)throwsIOException, TimeoutException, interruptedexception {connectionfactory CF =NewConnectionFactory ("nats://127.0.0.1:4222"); Connection NC = cf.createconnection ();//MessageMessage msg =NewMessage ();//Set ThemeMsg.setsubject ("foo");@SuppressWarnings("Resource") Scanner Scanner =NewScanner (system.in); System.out.println ("Please enter a string:"); while(true) {String line = Scanner.nextline (); Msg.setdata (Line.getbytes ());//Post a messageNc.publish (msg); }        }}
2.2.2 Publisher Code

Subscribe.java

 PackageCom.gwc.nats.nats.test;ImportJava.io.IOException;ImportJava.util.concurrent.TimeoutException;ImportIo.nats.client.Connection;ImportIo.nats.client.ConnectionFactory;ImportIo.nats.client.Message;ImportIo.nats.client.MessageHandler; Public  class Subscribe {         Public Static void Main(string[] args)throwsIOException, timeoutexception {connectionfactory CF =NewConnectionFactory ("nats://127.0.0.1:4222"); Connection NC = cf.createconnection ();//LAMBDA expression notation                / * * Nc.subscribe ("foo", M-and {System.out.printf (* "Message Received:%s\n", New String (M.get Data ()));                 }); */Nc.subscribe ("foo",NewMessageHandler () {@Override                         Public void OnMessage(Message msg) {System.out.println ("message Received:"+NewString (Msg.getdata ()));        }                }); }}

Write three identical subscribe except for the class name.

2.3 Testing

Run publish first, and enter some characters, posted to the theme Foo, there are no subscribers, a few moments, subscribers will not receive the characters just published.

Run three x Subscribe

Then enter some characters in the console of the publish, and at this time three subscribers will receive the character

Publish

Subscribe

Subscribe1

We let Subscribe2 subscribe to the theme not Foo, look at the results of the run

Subscribe

Subscribe1

Subscribe2

Note Subscribe2 did not receive a message because it did not follow the Foo theme.

Reference documents

http://nats.io/

http://nats.io/documentation/concepts/nats-messaging/

http://nats.io/documentation/concepts/nats-pub-sub/

Https://github.com/nats-io/jnats

Nats Learning--Conceptual learning messages (message) and publishing subscriptions (Publish Subscribe)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.