Design the network application of RMI mode using adapter mode

zhaozj2021-02-08  272

Design the network application of RMI mode using adapter mode

Write local Java Object Guide for web applications

Introduction:

Writing a network-based application using Java's RMI is very simple. However, use is not based on a network-based class, but also complicates it to be a good way for network services. This will make the program become confusing, slow, difficult to read and difficult to maintain. Dan Becker demonstrates an effective way to apply local Java classes to the network, which is the use of Adapter Design Pattern. Using this design technology is very easy to establish a well-maintenance, and the excellent application is working.

If you have used Java's remote call (RMI), you must know that it is easy to understand and easily establish a remote object and service method. In fact, there is an excellent example in the Sun's Java tutorial to help you build your first RMI program. But I also saw some designs on this example, which became very awkward due to the increase in functions. Not very skilled programmers often distinguish between local behavior and remote behavior by means of some agreements. Also, as new remote services join, remote objects can easily become a big trouble in bad network traffic.

In this article, I will argue what is the use of adapter patterns and adaptation Qimo. It is very simple to use it to distinguish between local behavior and remote behavior. And you can continue to use your local category in non-network applications. Using this design pattern with this design pattern, it is easy to understand that those objects must be processed, and those objects must be synchronized. Finally, using this technology, your design will become easier to understand, easier to make more development modifications and use.

What is adapter mode?

The adapter mode is one of the structured patterns, which appears in the "Erich Gamma, Richard Helm, Ralph Johnson, And John Vlissides" reference "Design Mode". Adapter patterns are not only applicable to remote C / S programming, but also for this situation: You want to reuse a class, but the program's interface does not match the excuse of this class. In this case, you can use an adapter or package to match the existing excuse of the existing class interface. In software development, an adapter simply maps the excuse of other classes, which is always constantly being used during development, eventually become a design pattern.

Figure 1 explains how the adapter works. In this figure, Client wants to call method request () in the interface target. Since the AdapteE class does not have a request () method, the process transforming into a valid matching method becomes the task of the adapter. Here the adapter converts the call to method Request to the call of method specitiveRequest. The adapter makes this transition for each required method, just like a package.

Figure one

This type of adaptation is precisely a person who wants to build a web remote service. Your presence publication is not to adapt local categories by adding a local class. I will think of you all this is how you do it.

Design a network-based application

As mentioned above, it is the best "web class" by transforming the local approach to a remote interface. Sun's Java tutorial has told us to make RMI's work must be observed, these steps are as follows:

1 Create a remote interface, it must inherit from Java.rmi.Remote Interface

2 provides a remote interface implementation.

3 Remote methods in remote client call.

Coincidentally, these steps just match the functionality of the adapter mode. When the remote client wants to use the method published in the remote interface, the adapter mode is initialized, the remote interface inherits from java.rmi.Remote to let RMI know that the interface implements RMI, not to focus on implementing remote methods Local class. The call to the remote service is completed by calling the simple method in the local class, while the local class has not changed and does not perceive that it can complete the service of the network request. Figure 2 illustrates the class relationship of the application adapter mode to RMI. Figure II

Conceptually, we have built a program map that applies adapter modes to RMI. Now let's complete a specific implementation based on this design. The function of this example is to make many remote client queries, add, and delete elements. In this example I use the Haxi table in the java.util package, many programmers have used this class multiple times.

Design local class

Establishing the first cloth for remote Collection is to design a local class to implement some features. This step is convenient, Sun has established a HashTable class for us, and we will use this class to complete some features. I ignore the concept of synchronization, but I will discuss thread safety behind it. For convenience, I list some of the related methods of the Haxi table in the list.

List one

Int size ();

Boolean iSempty ();

Boolean Contains (Object Value);

Boolean Containskey;

Object Get (Object Key);

Object Put (Object Key, Object Value);

Object Remove (Object Key);

Void clear ();

ENUMERATION Keys ();

ENUMENTS ();

Design remote interface

The second step in this practice is to create a remote interface, which is made to publish the network's remote service. The interface RemoteMap is a Collection interface built on java.util.map, and the following method framework-based remote clients can call our network Haxi table.

Public interface remotemap extends java.rmi.remote {

// constants

Public static final string serviceName = "remotemap";

Public int size () throws remoteException;

Public Boolean ISempty () throws RemoteException;

Public Boolean ContainSkey (Object Key).

Public Boolean ContaSvalue (Object Value).

Public Object Get (Object Key) THROWS RemoteException;

Public Object Put (Object Key, Object Value) Throws RemoteException;

Public Object Remove (Object Key) THROWS RemoteException;

Public void clear () throws remoteexception;

}

List remote approach in the second remote interface

Some details are necessary to point out, all remote methods must throw java.rmi.RemoteException, which is not worried, this is a simple requirement of Java's RMI; and the RemoteMap interface must inherit from Java.rmi.Remote This is a logo, which tells Java's RMIC Tools This interface is ready to share on the web, which is another requirement of RMI. There is also a constant string serviceName in this interface, which is useful when the server publishes the name of the RMI service and the client lookup service. So, now we have a local object and a remote interface, we are now ready to write a profile class for remote interfaces.

Easy to make mistakes

Many social reporters have errors when they enter the next step, which is to adapt local categories to remote interfaces. By inheriting the HashTable class, it is very tempting to achieve a new class and achieve a remote interface, but this is a bad choice because of the following reasons:

• The use of components rather than adopting inheritance methods is a better way. why? Because inheritance design is usually used to add new methods and properties for existing classes. Here, we just simply adapt the local method to a remote method, so the component design will be more suitable.

· Inheritance design will bring inheritance of a separate parent class. Because Java only allows for separate inheritance, this brings the extension of Mo Chaos, inherits java.rmi.server.UnicastRemoteObject is the RMI requirements, and java.util.hashtable is also inherited in inheritance. Simply abandon the inheritance design to achieve the function of RMI.

· Some local categories are final, it is not allowed to be inherited. For example, this design exercise cannot be used in vector because the vector class is Final. If a class is final, then you can't use inheritance design.

• Mix the local approach and remote approach to cause the chaos of the class, especially when the remote interface is similar to the same method name. I have seen a solution in a solution to change the name of the method to prevent this situation. For example, Sizelocal and SizeRemote, how hard it is! The class of individual functions has become a huge complex feature class, how horrible!

In order to explain to you, how simple is to generate an adapter, and the list three provides all source code. You see, how simple categories are adapters, and we have not changed our local implementation.

Public Class Remotemapadapter Extends UnicastRemoteObject

Implements remotemap {

// conntructors

// The Owner Publishes this service in the RMI Registry.

Public RemoteMapadapter (Hashtable Adaptee) throws remoteException {

THIS.Adaptee = adaptee;

}

// Remotemap Role

Public int size () throws remoteException {

Return adaptee.size ();

Public Boolean ISempty () throws remoteException {

Return adaptee.isempty ();

Public Boolean Containskey (Object Key) THROWS RemoteException {

Return Adaptee.Containskey (Key);

Public Boolean ContaSvalue (Object Value) Throws RemoteException {

Return Adaptee.Contains (Value);

Public Object Get (Object Key) throws RemoteException {

Return adaptee.get (key);

Public Object Put (Object Key, Object Value) throws RemoteException {

Return Adaptee.Put (key, value);

Public Object Remove (Object Key) THROWS RemoteException {

Return adaptee.remove (key);

Public void clear () throws remoteException {

Adaptee.clear ();

// fields

Protected hashtable adaptee;

}

List three remote adapter classes

We have completed the most important part of this example exercises - we have already written our adapter class.

Last contact

In order to complete this exercise, we are still something to do. First, we must compile this interface and put the adapter in the two parts mentioned earlier. Second, we have to run a stub and skeleton for this example. This is done by Java's RMIC tool. Type: RMIC Remotemapadapter.

Next, we need two simple programs to run this example ----- Client and server side. First, we implements a remote server that generates a local Haxi table and publishes our design remote adapter interface. The most important code snippet is listed under the lower side. It is not like some other examples I have seen, this example can run the command line to register this step by the CreateRegistry method. Then, we have generated a local Haxi table and an adapter that makes the remote publishing work. Finally, use a string and rebind method to bind the remote service, the server starts running, waiting for a remote client. Look at the list.

...

Try {

System.out.println ("Remotemapserver Creating a Local RMI Registry on

The default port. ");

Registry LocalRegistry = LocateRegistry.createRegistry (

Registry.registry_port;

System.out.println ("RemotemapServer Creating Local Object and Remote

Adapter. ");

Adaptee = new hashtable ();

Adapter = New Remotemapadapter (Adaptee);

System.out.println ("Remotemapserver Publishing Service /"

Remotemap.serviceName "/" in local registry. ");

LocalRegistry.rebind (Remotemap.ServiceName, Adapter);

System.out.println ("Published Remotemap As Service /"

Remotemap.ServiceName "/". Ready. ");

} catch (remoteException E) {

System.out.println ("RemoteMapserver Problem with Remote Object,

Exception: / n " e);

...

Listing Four Server Director Pattern

The final step is to generate some clients, they can join, query, and clear remote objects. Listing 5 describes how the client discovers remote registration on the server and queries these services. Note that the Lookup method returns the RemoteMap interface instead of a RemoteMapadapter object, which is like this in all RMI services, because the remote object implements a remote interface.

...

Try {

System.out.println ("RemotemapClient Locating RMI Registry On Remote

Host / " Name " / ");

Registry RemoteRegistry = locateregistry.getRegistry (name);

System.out.Println ("RemotemapClient Looking Up Service /"

RemoteMap.ServiceName "/".);

RemoteMap = (RemoteMap) RemoteRegistry.lookup (RemoteMap.ServiceName

);

} Catch (Exception E) {// EXPECTING RemoteException, NotboundException

System.out.Println ("RemotemapClient Problem with Remotemap,

Exception: / n " e);

}

...

Listing Finding Remote Registration and Remote Services

We have seen RemoteMap reference, which can call any ways in the interface. In fact, the remote method calls and the call of the local approach look like it. One point to note that the call to the remote method will delay because of the traffic problem of the Internet. In theory, these calls should be placed in different threads to ensure the correct local Java program.

Listing 6 describes how to call a remote object.

...

Try {

Object value = remotemap.get (name);

IF (value! = null)

System.out.Println ("RemotemapClient Found" Name ", Value ="

Value);

Else

System.out.println ("RemotemapClient Could Not Find Key Name

".");

} catch (remoteException E) {

System.out.println ("RemotemapClient Problem with" Name ",

Exception: / n " e);

} / * endcatch * /

...

In order to use this C / S structure, first start the server. The server initializes a Haxi table and a remote adapter and puts the object into the Haxi table. The Haxi table was released by the local registration machine of RMI. Enter the command line in Windows, UNIX or OS / 2:

Java Remotemapserver Harriet Bailey Max Zuzu

Start a client query and initialize the remote object. If you don't have a network condition, you can also be on the local machine. Use your IP address (127.0.0.1), your machine name or host name, execute the following command: Java RemotemapClient Hostname Zuzu

If your Java environment is installed and running correctly, you should see the following remote response.

RemotemapClient Found Zuzu, Value = 3

You can take your breath! You have been under the way to understand the RMI and adapter mode for a long time. Take some time to relax, enjoy your labor fruit, I recommend compiling the code of the client and server side, then run it, and modify it in use. If possible, run this program on a different machine or different Java virtual machines, you should be able to find that this program can run on a different platform.

to sum up

After reading this article, you should be able to realize the value of the adapter mode in Java's RMI mode, it is the advantage that you don't have to change your local object, and do not generate a particularly complex and low-efficiency remote object. The responsibility of the classification, your design can be easy to troubleshoot, the problem in the local object is local, and the problem arising from the network object is a remote adapter class. In addition to these advantages, once you have established an adapter, you can reuse this model over and over again. This is a very useful design pattern, which is simple and easy to read by those who review and maintain your code.

About author

DAN works in the Network Computing Software Division of IBM Corporation, which is dedicated to implementing Java 2 to AIX, OS / 2, System 390, and Windows platforms. Dan's personal homepage is http://www.io.com/~beckerdo.

转载请注明原文地址:https://www.9cbs.com/read-2881.html

New Post(0)