Reverse Ajax, part 5th: Event-driven web development

Source: Internet
Author: User
Tags eventbus

English Original: Reverse Ajax, part 5:event-driven Web development

  Objective

This article series shows how to develop event-driven Web applications using reverse Ajax (Reverse Ajax) technology, and part 1th describes reverse Ajax, polling (polling), streaming (streaming), comet, and long polling (long polling) The 2nd section describes how to use WebSocket to implement reverse Ajax, and discusses the limitations of using Comet and WebSocket Web servers, and part 3rd explains if you need to support multiple servers, Or to provide users with a standalone Web application deployed on their own servers, it is difficult to implement their own comet or websocket communication system, which also discusses Socket.io, and part 4 covers atmosphere and cometd --the most well-known open source reverse Ajax Library for Java technology servers.

So far you've learned about creating components that communicate through events, and in the final part of this series, we apply the principle of event-driven development to practice and build an exemplary event-driven Web application.

You can download the source code used in this article.

  Pre-conditions

Ideally, to fully appreciate this article, you should have some knowledge of javascrpit and Java, and have some experience in web development. To run the examples in this article, you'll also need the latest version of Maven and JDK (see Resources).

  Terms

You may have event-driven architectures (Event-driven Architecture,eda), Eventbus systems, message systems, complex event handlers (complex event processing, CEP) and channels (channel) are not unfamiliar, these terms and concepts have been present for many years. As technology matures, you may hear such statements more often. The contents of this section provide some brief explanations for these concepts.

  Events (Event)

Some of the things that happen in the system, events usually have attributes, such as the time (timestamp), source or location (the component we clicked on), and some data that describes the event. Depending on the system, events can also have other property choices.

  Event-Driven Architecture (Event-driven Architecture,eda)

Also known as event-based programming, an architectural design in which applications are composed of components that communicate and execute by sending and receiving events. Swing's graphical user interface (GUI) is an EDA example where each swing component can listen for events, react to events, send other events, and so on. EDA consists of several parts: event producer, event consumer, event and processing software.

1. Event Producer-this component issues events. In the example in this article, the form's Submit button is an event producer.

2. Event consumer--the component that listens for a particular event. For example, in the case of form submission, the browser listens to the Click Action on the form's submit button and sends the form data to the server.

3. Event processing software (event-processing software)-This is the core of the system, event producers issue events, and event consumers register themselves to receive events. Depending on the software, the process can be very simple (just forward the received event to the consumer), or very complex (CEP). With CEP, software can support a wide variety of processing methods, such as event pooling, filtering, and conversion.

Esper is such a software example. Event processing software can be used not only as a standalone running application, but also as a library for integration into your application.

  Messaging Systems (messaging system)

An event-driven application type in which event producers publish messages to a channel, and event consumers subscribe via channels. Event producers and consumers have no links to each other and are completely independent. In this type of event-driven application, the term commonly used is a message rather than an event.

  Channels (channel)

A way of classifying events in a messaging system. It represents the destination where the event producer wants the event to be sent. For example, in a chat room application, a channel may be/chatapplication/chatrooms/asdrt678, which identifies a specific chat room where the producer of the event can send a message, and the graphical component should subscribe to that channel. The purpose is to display the latest arrival message.

Some messaging systems provide two types of channels: Queue and Subject (topic).

1. Queue--When a message is sent to the queue, only one event consumer gets and processes the message, and no other consumer sees it. The queue can be persisted to ensure delivery. The best queue example is a mail request, a web app that publishes a message to the queue/myapp/mail/user-registration when the user registers, there may be multiple mail applications subscribing to the queue, and if not, the message is not lost.

2. Theme (topic)--When a message is sent to a topic, each Subscriber can receive it, and the subject is usually not persisted. An example is a subject of monitoring software/event/system/cpu/usage, where producers regularly send CPU usage; On the other hand, the subject may not have or have multiple subscribers, depending on where they are interested.

  Publish/Subscribe (publish/subscribe)

The event-driven solution implements the Publish/subscribe model. Event producers publish events in the processing software, and event consumers receive them through subscriptions. The way the event consumer subscribes depends on the software. In messaging applications, they subscribe to channels (for example, you can selectively apply filtering rules to event types). Using a CEP such as Esper, you can define the events you are interested in by the request of the class SQL to complete the subscription operation.

  Why use event-driven solutions

In a traditional communication scenario, if system a needs information from System B, a request is sent to B. System B processes the request, and system a pauses there to wait for the response. When processing is complete, the response is sent back to system a. In this synchronous communication pattern, the consumption of resources is inefficient because the processing time is wasted while waiting for a response.

In asynchronous mode, system a subscribes to the information it responds to from System B. System A can then selectively send notifications to system B and return immediately, and system A can continue to handle other things, a step that is optional. Typically, in an event-driven app, you don't need to ask other systems to send events because you don't know who they are. When system B publishes a response, system a receives it immediately.

One advantage of the event-driven architecture is that it allows for better scalability. Scalability is the ability of a system to meet its goals while adapting to demand, capacity, or strength changes. By eliminating pause times, event-driven architectures often perform better and have higher processing efficiencies.

Another advantage is in the development and maintenance of applications. With an event-driven solution, each component of the application can be completely independent and decoupled.

Event-driven solutions allow for better response times because communication has a lower latency.

  Apply event-driven solutions to the Web

The web framework used to rely on the traditional request-response pattern, which caused the page to refresh. With the advent of Ajax, reverse Ajax, and powerful frameworks such as cometd and atmosphere, it is no longer difficult to apply the concept of event-driven architecture to the web to gain the benefits of decoupling, scalability, and responsiveness.

  Client

Event-driven architectures can be applied to clients developed in the GUI. Unlike creating a traditional Web page, you can use a separate Web page as a container. Each component (each component of the page) can be independent, and you can put a Java Swing GUI on the web, just like Google pages with gadgets (gadget).

You need an event bus, for example, you need to develop a JavaScript event bus that allows each page component to be subscribed from a channel or published in a channel. Events can also be asynchronous, triggering behavior when two or more events arrive. Event bus can be used for local events in a page, but you can also support remote events in a plug-in way by using cometd or Socket.io.

  Server-side

On the server side, you need to set up a reverse AJAX framework to support the event-driven framework. In the first few parts of this series, it was found that only cometd had an event-driven approach. For other frameworks, you need to increase your custom support, which is not a big problem. You can also join third-party messaging systems such as JMS (for example, Apache ActiveMQ) or CEP like Esper. A simpler solution is Redis, which supports basic publish/subscribe.

This article series is about event-driven web and reverse Ajax, so we focus on clients and don't set up a complex messaging system.

  Example of event-driven web

The example that this article will create is a chat room web app that uses a user panel to list connected users. Your user name is shown in bold, the active user (those who are still active after 20 seconds) is shown in green, and those inactive after 20 seconds are shown in orange. If a user connects or disconnects, the list refreshes.

For security purposes, a two-minute session timeout is configured in the Web. xml file, and after two minutes of inactivity, a window pops up and you are redirected to the login page.

As long as you are no longer in session or are not connected, you will be redirected to the login page. The sign-in page asks for a user name and checks to see if you can log in to the chat room.

Once the login is successful, you can send messages to all users in the chat room. A console is also displayed, recording all the events received.

The Web App is event-based and with the information above, you can easily define several events:

1. User connection

2. User Disconnects

3. Session Expiration

4. Receive a chat message

5. If you are not logged in, the security filter blocks the request

6. The user becomes inactive

7. The user becomes active

8. All other UI coordination related events

Some events are only part of the Web application and are identified by the local bus, as shown in Listing 1:

Listing 1. Bus settings

[JavaScript]View Plaincopy
  1. Bus = {
  2. Local: new Eventbus ({
  3. Name: ' Eventbus Local '
  4. }),
  5. REMOTE:EVENTBUS.COMETD ({
  6. Name: ' Eventbus Remote ',
  7. LogLevel: ' warn ',
  8. Url:document.location.href.substring (0,
  9. Document.location.href.length-
  10. document.location.pathname.length) + '/async ',
  11. OnConnect: function () {
  12. Bus.local.topic ('/event/bus/remote/connected '). publish ();
  13. },
  14. OnDisconnect: function () {
  15. Bus.local.topic ('/event/bus/remote/disconnected '). publish ();
  16. }
  17. })
  18. };

Other events are remote, which means they need a reverse Ajax system, such as COMETD, to publish them in all clients. Figure 1 shows the sample app.

Figure 1. Sample App

You can download this sample application, many classes are secure channel classes, or session and user management channel classes. This article gives the most important part of the code, but it is recommended that you download and run the application example to gain a deeper understanding of how it works.

The Web app has different components: a chat room, a user list, and a console. Each is independent and can be taken away without affecting other parts.

In order to set up this event-driven system in a local and remote way, this example uses the Ovea Evenbus system. It provides a local event bus, a comed bridging of an active remote event, and a way to reconcile events (triggering behavior after several events have completed). Of course, you can choose to use another different system. This example uses JavaScript to set it up, as shown in Listing 1.

Once the bus is in place, the application and components are event-based. In this example, the idle detection system is set up, as shown in Listing 2.

Listing 2. Idle detection System

[JavaScript]View Plaincopy
  1. Bus.local.topic ('/event/dom/loaded '). Subscribe (function () {
  2. $.idletimer (20000);
  3. $ (document). Bind (' idle.idletimer ', function () {
  4. Bus.local.topic ('/event/idle '). Publish (' inactive ');
  5. });
  6. $ (document). Bind (' active.idletimer ', function () {
  7. Bus.local.topic ('/event/idle '). Publish (' active ');
  8. });
  9. })

With the code in Listing 2, the idle system sends events when an activity is detected. This code can be used in any application that requires an idle system. In this example, you need to convert the code in the remote event of the user activity. It can also be implemented using JavaScript, as shown in Listing 3.

Listing 3. User Activity Management

[JavaScript]View Plaincopy
  1. Bus.local.topic ('/event/idle '). Subscribe (function (status) {
  2. Bus.remote.topic ('/event/user/status/changed '). Publish ({
  3. Status:status = = ' active '? ' online ': ' away '
  4. });
  5. });
  6. Bus.remote.topic ('/event/user/status/changed '). Subscribe (function (evt) {
  7. if (evt.user! = me.name) {
  8. $ (' #users li '). Filter (function () {
  9. return Evt.user = = $ (this). Data (' user '). Name;
  10. }). removeclass (' online ')
  11. . Removeclass (' away ')
  12. . addclass (Evt.status);
  13. }
  14. });

The first subscription receives events from the idle system and then sends the user status to the server side. Other subscriptions receive user status events from the server side. As a result, as long as the user's condition changes, the user's color in the user list turns green or orange.

When the user connects or disconnects, an event is sent, as shown in Listing 4:

Listing 4. User list management

[JavaScript]View Plaincopy
    1. bus.remote.topic ( '/event/user/connected '). Subscribe (function (user)  {  
    2.      $ ( ' #users  ul '). Append (row (user));   
    3. });    
    4. bus.remote.topic (function (evt)  {  
    5.     $ ( Span class= "string" > ' #users  li '). Filter (function ()  {  
    6.         return evt.user ==  $ (this). Data (
    7.     }). remove ();   
    8. });   

The code of the app is simple, decoupled, and independent, and you can quickly create event-driven Web applications by reusing many of the Ovea technologies. However, because other systems can be used instead of it, this is not required. This example takes only a day of development time, and half of the code is pipeline code, including:

1. Maven: Building Engineering

2. Security features (login, exit, session timeout)

3. Use of Jersey Rest service

  Conclusion

This article series shows how to build responsive and scalable applications that provide a good user experience. Event-driven Web applications are a fairly new concept, and some Web frameworks use these concepts internally. However, this article shows an application that does not require a web framework to build, and the use of a good, professional library is more than enough to separate the responsibilities between Java developers and web designers. I hope you have a more in-depth understanding of how to turn event-driven development into a part of your daily routine. It's easy to indulge in, and once you try, you don't want to fall back on the traditional frame.

  Code download

  Reverse_ajaxpt5_source.zip

Reverse Ajax, part 5th: Event-driven web development

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.