Reverse Ajax, Part 1: event-driven Web Development)

Source: Internet
Author: User
Tags eventbus

This article series discusses how to use reverse Ajax (reverse Ajax) technology to develop event-driven Web applications. Part 1 describes different methods for implementing reverse Ajax communication; part 1 describes how to use websocket to implement reverse Ajax and discusses the limitations of web servers using comet and websocket; part 1 explores the difficulties in implementing your own comet or websocket communication system, and introduces the socket. io; the fourth part talks about atmosphere and cometd. In the last part of this series, we will learn about event-driven development and use the accompanying source code to build an exemplary event-driven web application.

 

Preface

This article series shows how to use reverse Ajax (reverse Ajax) technology to develop event-driven Web applications. Part 1 describes reverse Ajax, polling, and streaming) comet and long polling; Part 1 describes how to use websocket to implement reverse Ajax and discusses the limitations of web servers using comet and websocket; part 1 describes how to support multiple servers or provide users with independent web applications deployed on their own servers, what are the difficulties in implementing your own comet or websocket communication system? This section also discusses socket. io; the fourth part talks about atmosphere and cometd-the most well-known open-source reverse Ajax library for Java technology servers.

So far, you have learned how to create components that communicate through events. In the last part of this series, we apply the event-driven development principles to practices, build an exemplary event-driven web application.

You can download the source code used in this article.

Prerequisites

Ideally, you should have a certain understanding of javascrpit and Java, and have some web development experience. To run the example in this article, you also need the latest version of Maven and JDK (see references ).

Terms

You may have an event-driven architecture (EDA), eventbus system, message system, complex event processing, CEP, and channel) these terms and concepts have been around for many years. With the maturity of the technology, you may hear such arguments more frequently. This section provides some brief explanations for these concepts.

Event)

In the system, events usually have attributes, such as the time (timestamp), source, or location (the component we click ), and some data describing the event. Depending on the system, the event can have other attributes.

Event-driven architecture (EDA)

It is also called event-based programming. This is an architectural design in which applications are composed of components that send and receive events to communicate and execute. Swing's graphical user interface (GUI) is an EDA example. Each swing component can listen to events, respond to events, and send other events. Eda consists of several parts: Event producer, event consumer, event and processing software.

1. Event producer-This component issues an event. In this example, the form submission button is an event producer.

2. Event consumer-a component that listens to a specific event. For example, in the form submission example, the browser listens to the click operation on the form submission button and sends the form data to the server.

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

Esper is such a software example. The event processing software not only represents an independent running application, but also can be integrated into your application library.

Messaging System)

An event-driven application type in which the event producer publishes messages to the channel, and the event consumer subscribes through the channel. Event producers and consumers are completely independent of each other. In this type of event-driven applications, the term is message rather than event ).

Channel)

One way to classify events in a message 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 an event producer can send messages, graphical components should subscribe to this channel to display the latest messages.

Some messaging systems provide two types of channels: queue and topic ).

1. queue-when a message is sent to the queue, only one event consumer receives and processes the message, and other consumers will not see it. The queue can be persisted to ensure delivery. The best queue example is a mail request. A Web application publishes a message to the queue/MyApp/mail/user-registration at user registration, multiple email applications may subscribe to this queue, and messages will not be lost if they are not.

2. Topic-when a message is sent to a topic, each subscriber can receive it. The topic is usually not persistent. One example is a topic/event/system/CPU/usage of the monitoring software. The producer regularly sends CPU usage information to it. On the other hand, this topic may have no or multiple subscribers, depending on their interests.

Publish/subscribe (publish/subscribe)

The event-driven solution implements the publishing/subscription mode. Event producers publish events in the processing software, and event consumers subscribe to them. The method of event consumer subscription depends on the software. In message applications, they subscribe to channels (for example, filter rules can also be selectively applied to event types ). With CEP such as Esper, you can use SQL-like requests to define events you are interested in and complete subscription operations.

Why use event-driven solutions

In a traditional communication scheme, if system A needs information from system B, a request is sent to system B. System B processes the request, and system a stops there waiting for response. When the processing is complete, the response is sent back to system. In this synchronous communication mode, resource consumption is inefficient because processing time is wasted while waiting for the response.

In asynchronous mode, system a subscribes to the response information from system B. Then system A can selectively send a notification to system B and return immediately. System A can continue to handle other tasks. This step is optional. Generally, in an event-driven application, you do not need to request other systems to send events because you do not know who they are. When system B releases the response, system A immediately receives the response.

One advantage of the event-driven architecture is that it allows better scalability. Scalability is the ability of a system to adapt to demand, capacity, or intensity changes while meeting its goals. By eliminating the pause time, the event-driven architecture usually performs better and has higher processing efficiency.

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

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

Apply event-driven solutions on the Web

In the past, the Web framework relied on the traditional request-response mode, which led to page refresh. With the emergence of Ajax, reverse Ajax, and powerful frameworks such as cometd and atmosphere, it is no longer difficult to apply the concept of the event-driven architecture to the Web to obtain the benefits of decoupling, scalability, and responsiveness.

Client

The event-driven architecture can be applied to Gui-developed clients. 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. You can put a Java swing GUI on the web, just like a small tool (gadget) for more information, see references ).

You need an event bus. For example, you need to develop a javascript event bus that allows each page component to subscribe from the channel or publish in the channel. Events can also be asynchronous and trigger behavior only when two or more events arrive. The event bus can be used for partial events on the page, but you can also use cometd or socket. Io to support remote events as a plug-in.

Server

On the server side, you need to set up a reverse Ajax framework to support the event-driven framework. In the previous sections of this series, we found that only cometd has an event-driven method. For other frameworks, you need to add custom support, which is not a big problem. You can also join a third-party message system, such as JMS (such as Apache activemq) or CEP like Esper. A simpler solution is redis, which supports basic publishing/subscription.

This article series is about event-driven web and reverse Ajax. Therefore, we focus on the client and will not set up a complex messaging system.

Event-driven Web example

The example to be created in this article is a chat room web application that uses a user panel to list connected users. Your user name is displayed in bold, active users (those that are still active after 20 seconds) are displayed in green, and those that are inactive after 20 seconds are displayed in orange. If a user is connected or disconnected, the list is refreshed.

For security purposes, a two-minute session timeout is configured in the web. xml file. After two minutes of inactivity, a window will pop up and you will be redirected to the logon page.

The logon page is redirected as long as you are no longer in the session or are not connected. On the login page, enter the user name and check whether you can log on to the chat room.

Once the logon is successful, you can send messages to all users in the chat room. A console will also display and record all events received.

The Web application is event-based. With the above information, you can easily define several events:

1. User connection

2. the user is disconnected.

3. session expiration

4. Receive chat messages

5. If you have not logged on, the security filter blocks the request.

6. users become inactive

7. users become active

8. All other events related to UI coordination

Some events are only partial to web applications and are identified by the local bus, as shown in Listing 1:

Listing 1. Bus settings

Bus = {

Local: New eventbus ({
Name: 'eventbus local'
}),

Remote: eventbus. cometd ({
Name: 'eventbus remotion ',
Loglevel: 'warn ',
URL: Document. Location. href. substring (0,
Document. Location. href. Length-
Document. Location. pathname. Length) + '/async ',
Onconnect: function (){
Bus. Local. Topic ('/event/bus/remote/connected'). Publish ();
},
Ondisconnect: function (){
Bus. Local. Topic ('/event/bus/remote/disconnected'). Publish ();
}
})

};

Other events are remote, which means they need a reverse AJAX system, such as cometd, to publish them on all clients. Figure 1 shows the sample application.

Figure 1. Example Application

You can download this example application. Many classes are secure channels, sessions, and user management channels. This article provides the most important part of the code, but it is recommended that you download and run the application example to learn more about how it works.

The Web application has different components: chat room, user list, and console. Each part is independent and can be removed without affecting other parts.

The evenbus System of ovea is used in this example to set the event-driven system locally and remotely. It provides a local event bus, a ComEd bridge for an active remote event, and a way to coordinate events (trigger behavior after several events are completed ). Of course, you can choose to use another system. This example uses JavaScript For setting, as shown in Listing 1.

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

List 2. Idle Detection System

Bus. Local. Topic ('/event/DOM/loaded'). subscribe (function (){
$. Idletimer (20000 );
$ (Document). BIND ('idle. idletimer ', function (){
Bus. Local. Topic ('/event/idle'). Publish ('inactive ');
});
$ (Document). BIND ('Active. idletimer ', function (){
Bus. Local. Topic ('/event/idle'). Publish ('active ');
});
})

With the code in Listing 2, the idle system sends an event when detecting the activity. 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 user activity. It can also be implemented using JavaScript, as shown in listing 3.

Listing 3. user activity management

Bus. Local. Topic ('/event/idle'). subscribe (function (Status ){
Bus. Remote. Topic ('/event/user/status/changed'). Publish ({
Status: Status = 'active '? & Apos; online & apos;: & apos; away & apos'
});
});

Bus. Remote. Topic ('/event/user/status/changed'). subscribe (function (EVT ){
If (EVT. User! = Me. Name ){
$ ('# Users li'). Filter (function (){
Return EVT. User ==$ (this). Data ('user'). Name;
}). Removeclass ('online ')
. Removeclass ('away ')
. Addclass (EVT. status );
}
});

The first subscription receives events from the idle system and sends the user status to the server. Other subscriptions receive user status events from the server. Therefore, as long as the user's status changes, the user's color in the user list will change to green or orange.

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

List 4. User List Management

Bus. Remote. Topic ('/event/user/connected'). subscribe (function (User ){
$ ('# Users ul'). append (row (User ));
});

Bus. Remote. Topic ('/event/user/disconnected'). subscribe (function (EVT ){
$ ('# Users li'). Filter (function (){
Return EVT. User ==$ (this). Data ('user'). Name;
}). Remove ();
});

The application code is simple, decoupled, and independent. By reusing many ovea technologies, you can quickly create event-driven Web applications. However, this is not necessary because it can be replaced by other systems. This example takes only one day of development, and half of the Code is Pipeline Code, including:

1. MAVEN: Build a project

2. Security Functions (logon, logout, and Session Timeout)

3. Jersey's rest service is used

Conclusion

This article series shows how to build responsive and scalable applications that provide a good user experience. Event-driven web applications are still quite new, and some Web frameworks use these concepts internally. However, this article shows that such an application does not require a Web framework to be built. for separation of duties between Java developers and web designers, A good and professional database is more than enough. I hope you have a deep understanding of how to turn event-driven development into a part of your daily work. It is easy for people to indulge in it. Once you try it, you don't want to go back to the traditional framework.

Download

Description name size Download Method

Source code reverse_ajaxpt5_source.zip 925kb HTTP

Instructions on download Methods

Related Article

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.