EJB Advocates: loosely coupled SOA applications using Java EE

Source: Internet
Author: User
Tags websphere application server enterprise integration patterns

Level: Intermediate

Geoff Hambrick (ghambric@us.ibm.com), distinguished engineer, IBM

February 13, 2006

This article explores various forms of loose coupling in the service-oriented architecture, and focuses on the best time to use the asynchronous processing capabilities provided by message-driven bean.

From the IBM WebSphere developer technology journal.

In each column, EJB advocates communicate with actual customers and developers through a unique frontend-to-backend dialogue mode, and recommend solutions to design issues that everyone cares about during this period. No definite details were introduced, and no "novel" or proprietary architecture was proposed. For more information, see Introduction to EJB advocates.

Is your definition of loose coupling too narrow?

Since this was the last article in 2005, and this communication was conducted by Java platform, Enterprise Edition (Java ee) components rather than session and entity beans, therefore, we can use this article to summarize the one-year discussion in this column and put all the components into a complete service-oriented architecture.



Back to Top

Problem: too much attention to sessions and entities in SOA

Dear EJB advocates:

So far, all your columns are about service sessions and entity ejbs. It is very important to directly connect to Java applications, for example, httpservlets or rich (we do not like to say "fat") Client swing applications based on web clients. However, we have heard that the service-oriented architecture is loosely coupled. Does this mean that soap should be used as much as possible to provide language neutral and asynchronous protocols that allow client and server applications to run independently? In other words, why are you not talking much about JMS and message-driven beans?

Signature:
Feeling disconnected



Back to Top

There are many considerations for loose coupling.

Dear disconnected:

EJB advocates focus on the service layer of the application, but seldom talk about the client, because of the old sayingForm follows function)Believe it.

The reason is that many SOA projects fail because they did not first establish a good model for defining services and began to implement details.

This kind of inclination is quite normal, because most people I have come to contact with in SOA projects are architects and programmers who know that the tricky thing is always to be detailed and want to solve them as soon as possible. So, once we agree that good services are characterized by coarse granularity, stateless, and can be passed and adapted through mediation (see is it ever best to use EJB components without facades in service oriented ubuntures ?), Obviously, session beans with data transmission objects play an important role in implementation.

However, the previous column introduced the possibility of using the Entity Bean and its home method to replace the Session Bean, so that people have doubts about whether the session bean is really necessary. Figure 1 shows the two methods used at the same time.

Figure 1. Services implemented using the available sessions and entity ejbs

Figure 1 shows how the pure entity method (available from EJB 2) can have fewer components and shorter path lengths when a session bean is passed. The Green Box indicates the client, and the blue box indicates various interfaces and facade classes. The orange box is the most frequently accessed Entity Bean. Use a two-way arrow connection between the box and the box. The Arrow is marked with the protocol used for communication between components. The blue arrow indicates the Java call in the same JVM, the red arrow indicates remote connection (RMI/IIOP is used in this example ). To represent an end-to-end flow, the process arrow is numbered, where the A1-A10 represents the process from the Java client through the session bean to the entity and the returned process, and the B1-B4 represents the process from the client directly to the Entity Bean and the returned process.

The programming model used by the client to retrieve the service interface is also very simple, although it is not shown in the figure. To retrieve a session bean interface, you need to search for the session home in the JNDI context and use it to create a session. The object home only needs to be searched once, and its method can be called directly without the need to create a reference to the EJB object. The following two sample codes show the differences between them.

List 1. Locate and call the remote session EJB Method


Context initCtx = new InitialContext();
Object obj = initCtx.lookup("java:comp/env/ejb/OrderEntry");
OrderEntryHome home = (OrderEntryHome)PortableObjectRemote(
obj, OrderEntryHome.class
);
OrderEntry ref = home.create();
// Method must be invoked on a session reference
CustomerData data = ref.getOpenOrderForCustomer(cID);

Listing 2. Locating and calling the equivalent remote entity EJB home Method


Context initCtx = new InitialContext();
Object obj = initCtx.lookup("java:comp/env/Customer");
CustomerHome ref = (CustomerHome)PortableObjectRemote(
obj, CustomerHome.class
);
// Note how the method is invoked directly
CustomerData data = ref.getOpenOrder(cID);

Figure 1 and related code examples show the real benefits of the Java EE programming model, whether or not you choose to use the entity home method. Gradually improve the programming model and provideBackward compatibility. In short, your best practices can evolve without forcing changes to existing applications. In addition, the JNDI context provides a loose coupling aspect that cannot be ignored:Independence.

The remote interface of the session or object EJB component providesLocation independence. Using remote interfaces makes it possible to deploy client applications and service components in the same JVM, where it applies to systems (for example, web applications that use httpservlets) the response time, throughput, and maintainability goals are meaningful. Figure 2 shows this configuration, in which the enterprise quality Application Server (such as IBM WebSphere Application Server) when the client and service components are jointly deployed, the remote interface is short-circuited to use Java and passed by reference (whether the service implementation is the real home method or session bean ). The process A1-A6 shows the use of httpservlet that is deployed together with service components. The process B1-B4 shows how it is reused by remote rich client Java EE applications.

Figure 2. services deployed to local web applications and remote rich clients

But it sounds like you have determined that the most important aspect of loose coupling isLanguage neutralityAndAsynchronous Operation. In addition, you think that asynchronous operations will make it necessary to use message-driven Bean (MDB) and JMS on the server side.

When implementing mdb, many programmers call the EJB component of the service through its remote interface to maximize the independence of the above positions. Then, whether the service is deployed remotely or locally, MDB serves as a simple adapter to connect the MQ layer to the EJB container that hosts the service. JMS may be used by asynchronous client applications (if it is Java) or MDB (usually used for response queues ). Figure 3 shows the configuration of another input channel for Service implementation.

Figure 3. services deployed using MDB that provides asynchronous client Channels

The process C1-C2 and D1-D6 are displayed separately to illustrate the independence of client and server processes. C2 and D6 only "Confirm" Whether the writer writes the message, does not mean waiting. Listing 3 shows the typical structure of MDB, which should help clarify what it must do:

Listing 3. Typical message-driven bean implementation


public class OrderSubmitMsgHandler implements MessageDrivenBean {
private transient MessageDrivenContext context = null;
// Interface supported by either the session Bean or entity Home
private transient OrderEntry ref;
public void ejbCreate() {
// Cache the home according to either snippet one or two
}
public void ejbRemove() {}
public void setMessageDrivenContext(MessageDrivenContext mdc) {
context = mdc;
}
// Message acknowledge and database update participate
public void onMessage(Message inMessage) {
// Parse the customer from the message
try {
ref.submit(customer);
}
catch (CustomerDoesNotExist e) {
// Send JMS message to reply queue from exception
}
catch (OrderNotOpen e) {
// Send JMS message to reply queue from exception
}
catch (OrderHasNoItemsException e) {
// Send JMS message to reply queue from exception
}
}
}

EJB advocates will now return to the language neutral issues you have mentioned. It seems that you have closely linked the language neutral requirements with the requirements of asynchronous processing. There is no reason not to separate these considerations; the ability to parse a SOAP message and use it to call a session bean should be asynchronous with the processing of the message (through MQ or another protocol that transmits the JMS equivalent message) synchronization (for example, HTTP or even IIOP) is irrelevant. In fact, some early "invented" Web Services on Java EE applications use httpservlet to parse XML messages transmitted over HTTP. This method eventually evolved into soap/HTTP. Figure 4 shows another path that can be provided on the service implemented by the EJB component.

Figure 4. Separating language neutrality and Asynchronization

Web Service Servlet and message driven bean can share code for parsing data transmission objects from streams extracted from message strings or httpservletrequest. Similarly, the response or response can share the code that generates a stream from a data transmission object (which can be an exception instance.

Hopefully this will help you understand the layout of Java EE components, all of which will provide a basic form of loose coupling for the service-oriented architecture.

The conversation ends here,
Your EJB advocate



Back to Top

There are still too many options to select

Dear EJB advocates:

Thank you.

I didn't think that services like JNDI and remote interfaces would provide loose coupling. I can also learn how to "tightly couple" the concepts of soap and MQ (according to the method you mentioned) and how to separate them as much as possible. Therefore, it is meaningful to regard parsing and generating soap messages as services reused by Web Service servlets and MDB.

But thank you.

Before this discussion, SOA seems very simple: each service exposes a SOAP/MQ interface. Now there seems to be a lot of options to consider, and since we regard the parsing and generation of soap messages as a service, so why don't we create an independent Session Bean to encapsulate them so that they can be reused as shown in?

I am still:
Still disconnected



Back to Top

Not everything is a service: use the business model to determine

Dear disconnected:

This discussion is a good example of the situation that will happen when you are about to implement the details. EJB advocate column which type of EJB component shocould assemble the data returned by a service? It is very important because it describes a top-down method for defining a service, which directly associates the service with the business process model. Here we will summarize the basic details of this method:

  1. Develop a business flow model to display the major milestones in the lifecycle of important domain objects:

    1. We use the state transition diagram to describe this model. The State represents a milestone, and the transition represents an event that prompts the event to change to this state. Conversion can be seen as the service provided by the application (see Figure 5 for an example ).

    2. We use the UML "Actor" symbol to extend the state transition diagram to show the owner of the object when it is in this State. The State owner is responsible for initiating a conversion to drive the security model of the application (see figure 5 ).

    3. For each State in a business flow, we also model the attributes of the domain objects that need to support the conversion action and their relationships. We usually use the UML class relationship diagram (For examples, see Figure 6 ). Creating independent relationships for each State allows us to model the changed object "shape" at any time. These relational graphs drive persistent data.

  2. Develop a user interface flow model that shows how a given participant from a business flow interacts with the system during a typical "session.

    1. Like the business process model, we also use the state transition diagram. The State represents the screen and dialog box, and the conversion represents the actual UI events, such as selecting menu items and pressing the button. Specify the conversion-related actions based on the business flow conversion.

    2. Like the business process model, we construct a class relationship diagram to display the data that must be visible in each state to support various options. This means that the data must be derived from user input and driven to read operations on the service in a top-down manner.

    3. Unlike the business process model, we do not need to use the actor symbol to extend the state relationship graph, because the relationship graph itself can be considered as the "Day in the Life" of a single user role )".

Figure 5. Example of status Transition Graph showing the order Lifecycle

Figure 6. Class relationship diagram example showing the "shape" of an open order

This comprehensive method ensures that:

  • Group the correct operations to a service (all the conversion and read methods associated with a state in the Business Process lifecycle ).

  • The purpose of each service is well understood (actions are specified based on relevant business objects ).

  • The preconditions required for service invocation and the post conditions generated are the same (the current status and optional monitoring, and the next status are all specified through conversion ).

  • Identifies the user role that calls the service (the participant is associated with each status ).

Method signatures do not provide this information whether implemented or not, but this information is critical for good SOA. Otherwise, programmers will fall into another kind of tendency:Build again once you have doubts. Because SOA development costs are relatively high (to provide various intermediaries and adapters for full loose coupling as shown in figure 4), this tendency to oppose Reuse may lead to the least benefit.

The answer to your question about simplicity is that this information does not force you to expose the interface in a certain way, and EJB advocates know that simplicity only exists in the eyes of onlookers. If you want to make service developers do not have to choose from, you only need to provide all the "blue" components shown in Figure 5 for each service:

  • Remote service interface, used to provide the independence of the location where synchronous Java EE client accesses service operations.

  • MDB associated with each operation provides asynchronous non-Java client access by following the MQ implementation of JMS. You can choose to write this MDB or different MDB to expect Java messages from the JMS client (to avoid HTTP parsing overhead ).

  • The Web Service servlet associated with each operation is used to provide synchronous soap over HTTP client access.

Some people may worry that this method will generate a large number of unused components, so another simple method is to call the client-oriented architecture (COA) using the content favored by EJB advocates ); provide the client with the content exactly required to use the service in the most natural way.

This COA method takes into account the details of business processes and UI Models to select the most likely candidates for each method. For example:

  • Transition between States in the Business Process lifecycle is likely to be candidates for asynchronous services because they will be the "owner" variant of the relevant domain object. For example, in the open order application (we call this orderentry in the above example), the submit method can simply change the order status to "submitted ", and send a JMS message to copy it to the submitted order application (this is called orderfulfillment once ).

  • The transition between States is usually synchronous because the owner has not changed. For example, to explain why these operations should not be asynchronous, imagine that if you enter a web application of a bookseller, you must also poll or wait for publishing-subscribe events to display directories or add items to the shopping cart! For readers who want to use pseudo-synchronous through asynchronous channels, refer to Bobby Woolf's book on designing a message passing system.

  • Soap over HTTP or MQ is provided only for non-Java client and service integration scenarios.

Using COA, you can develop components on time (just-in-time), which is why EJB advocates like to recommend them.

The last answer to your question (why not regard everything as a service, or even a switch associated with the intermediary and adapter) is: the fact that a simple answer is beyond the limit of being "too late. When developing an SOA or COA Java EE application, it is best to treat the service as an operation on the business process model. Services are related to functional requirements of applications. Mediation and associated conversions are related to non-functional requirements, such as reliability, availability, effectiveness, maintainability, and portability. If you regard mediation or associated conversions as the first type of service, the actual use of the application will eventually become blurred.

I know that there are many aspects that need to be understood, so when you apply these methods, don't bother with the relevant details, even if you contact me.

The conversation ends here,
Your EJB advocate.



Back to Top

Conclusion

These discussions talked about how Java EE provides a complete implementation framework for applications adopting a service-oriented architecture, each component or API plays an important role in some "loose coupling" aspects:

  • Operating System independenceIt is provided by Java itself, because Java provides the component with the language "one-time writing, running everywhere", separating your code from the basic operating system.

  • IndependenceProvided by Java Naming and Directory Interface (JNDI), it can bind the logical name to the implementation at runtime.

  • Location independenceThe remote interface uses RMI over IIOP to provide the stateless session bean or encapsulate the entity home method of the service. RMI/IIOP is a fast stateful connection with poor scalability.

  • Web Server independenceIt is provided by httpservlets and can respond to HTTP synchronization. Unlike RMI/IIOP, HTTP (usually) is a well-scalable stateless protocol, but due to message size restrictions, in addition, the connection between the client and the server needs to be established and canceled every time, so it cannot be executed well.

  • Application independenceProvided by asynchronous Java Messaging Service (or non-Java client MQ) and message-driven Bean (for queue processing programs ).

  • Language independenceIt is provided by standard message formats (such as soap), whether it is transmitted on RMI/IIOP, HTTP or MQ. Therefore, soap can be used by every component, but it is important to use it only when necessary.

I believe you can find other methods. We are happy to see such results. The difficulty is to deal with the trade-offs associated with each method. This should keep you busy until next year.

References

  • For more information, see the original article on the developerworks global site.

  • Java platform, Enterprise Edition (JEE) specification (formerly J2EE); here "2" is removed to separate the main concepts used for Enterprise Java platforms from specific versions.
  • Enterprise Java programming with IBM WebSphere, second edition, Kyle Brown, Gary Craig, Greg Hester, Russell stinehour, W. david Pitt, Mark weitzel, jimamsden, Peter M. jakab and Daniel Berg. Preface written by Martin Fowler.
  • Enterprise integration patterns: designs, building, and deploying messaging solutions, Gregor Hohe, and Bobby Wolfe. Contains a large number of good patterns and anti-patterns associated with the messaging application.

About the author

Geoff HambrickHe is the chief consultant of IBM software service department WebSphere enablement team and lives in Round Rock, Texas (near Austin ). The enablement team usually provides support for the presales process through in-depth technical lectures and Short-Term Concept verification. Geoff was selected as an outstanding IBM engineer in March 2004. His job is to create and disseminate best practices for developing J2EE applications on IBM WebSphere Application Server.

 

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.