Java RMI technology and RMI technology encapsulated by spring

Source: Internet
Author: User

 

I recently applied the Java RMI technology, so I will summarize the use of RMI. In addition, the implementation of EJB is also based on Java RMI. RMI remote method calls can be called across machines through the network, but Java RMI only supports Java programs on both sides. To achieve completely heterogeneous on both sides, you need to use the legendary web service. Two or more projects should be established to ensure good results. Of course, if you have two machines and connect them through a LAN, it would be better if you can connect them with the Internet.Experiments of different projects on the same machine.

Java RMI

First, create a new project. For convenience, just create a Java project.

1. Create an interface that inherits remote

Package Leon. RMI. iface; import Java. RMI. remote; import Java. RMI. remoteException;/*** defines the remote interface and must inherit the remote interface, * All methods to be remotely called must throw a RemoteException */public interface ihello extends remote {Public String sayhello (string name) throws RemoteException; Public int sum (int, int B) throws RemoteException ;}

2. Create an interface implementation class

package leon.rmi.impl;import java.rmi.RemoteException;import java.rmi.server.UnicastRemoteObject;import leon.rmi.iface.IHello;public class HelloImpl extends UnicastRemoteObject implements IHello {private static final long serialVersionUID = 1L;public HelloImpl() throws RemoteException {super();}@Overridepublic String sayHello(String name) throws RemoteException {return "Welcome, " + name;}@Overridepublic int sum(int a, int b) throws RemoteException{return a + b;}}

Note:The implementation class of the interface must also implement the serializable interface. Here, the inheritance of unicastremoteobject is also an indirect implementation of the serializable interface. At the same time, because the constructor needs to throw a RemoteException, the implicit non-argument constructor cannot be, instead, you should explicitly define the constructor.

 

3. Create an application class and register and start the server RMI to be called by the client.

Package Leon. RMI. impl; import java.net. malformedurlexception; import Java. RMI. alreadyboundexception; import Java. RMI. naming; import Java. RMI. remoteException; import Java. RMI. registry. locateregistry; import Leon. RMI. iface. ihello; public class helloserver {public static void main (string ARGs []) {try {// create a remote object ihello rhello = new helloimpl (); // generate the remote object registry instance, and specify the port as 8888 (default port is 1099) locateregistry. creater Egistry (8888); // register the remote object to the RMI registration server and name it rhello // the URL to be bound in the standard format: RMI: // host: port/Name (the Protocol name can be omitted, and both of the following write methods can be used) naming. BIND ("RMI: // 10.225.112.86: 8888/rhello", rhello); // naming. BIND ("// 10.225.112.86: 8888/rhello", rhello); system. out. println ("> info: the remote ihello object is successfully bound! ");} Catch (RemoteException e) {system. Out. println (" an exception occurred when creating a remote object! "); E. printstacktrace ();} catch (alreadyboundexception e) {system. Out. println (" An error occurred while repeatedly binding objects! "); E. printstacktrace ();} catch (malformedurlexception e) {system. Out. println (" url malformed! "); E. printstacktrace ();}}}

Note:The bound IP address 10.225.112.86 is the IP address of my local network. You can use ipconfig in the doscommand line. If your machine is not connected to any Internet, you can use 127.0.0.1 or localhost.

Run helloserver. java. The Red Square shows that helloserver is running:

> Info: the remote ihello object is successfully bound!

Now the remote service provider has been established. The client is created below.

Create a new project. It is also a Java project for convenience,

1. Because the client must have an interface provided by the server side before accessIhelloThe interface is completely copied (together with the package) to the client. Of course, you can create a completely identical interface in the client project for convenience. In actual use, the server interface is usually packaged into a jar package.

2. Create a client call class

Package testrmi; import Java. RMI. naming; import Leon. RMI. iface. ihello; public class helloclient {public static void main (string ARGs []) {try {// search for an object named rhello in the RMI service registry, and call the method ihello rhello = (ihello) naming. lookup ("RMI: // 10.225.112.86: 8888/rhello"); system. out. println (rhello. sayhello (""); system. out. println (rhello. sum (454,545 7);} catch (exception e) {e. printstacktrace ();}}}

Run, displayed, succeeded.

Haha, isn't it easy? Right.

Below we will use spring-encapsulated Java RMI technology, which is also used by many projects. I have a spring RMI example later. To understand the following spring example, you need to use spring and configure spring. Otherwise, you may not understand it. If you do not understand spring, learn spring first and enter the next step.

Spring RMI

Spring RMI has two main classes:Org. springframework. remoting. RMI. rmiserviceexporterAndOrg. springframework. remoting. RMI. rmiproxyfactorybean

Server usageRmiserviceexporterExpose the remote method of RMI, which is used by the clientRmiproxyfactorybeanCall the remote method indirectly.

 

First, there are two projects. The server uses a web project. Because spring is used, we rely on Web containers to complete the project.

1. Add Interfaces to the web project of the server. common interfaces do not need to be inherited.

package leon.rmi.iface;public interface IUserDao {public String getUserList();public int sum(int a, int b);}

2. Interface implementation class

package leon.rmi.impl;import leon.rmi.iface.IUserDao;public class UserDaoImpl implements IUserDao {@Overridepublic String getUserList() {return "Hello,Get the user list from database!";}@Overridepublic int sum(int a, int b) {return a+b;}}

3. Add the spring bean configuration file in the web project of the server, for example, named RMI. xml. The content is as follows:

<?xml version="1.0" encoding="UTF-8"?><beans:beans xmlns="http://www.springframework.org/schema/security"xmlns:beans="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/securityhttp://www.springframework.org/schema/security/spring-security-3.0.xsd"><beans:bean id="userDaoRmi" class="leon.rmi.impl.UserDaoImpl">     </beans:bean>     <beans:bean id="userSvcExporter" class="org.springframework.remoting.rmi.RmiServiceExporter">         <beans:property name="service" ref="userDaoRmi"/>         <beans:property name="serviceName" value="userDaoService"/>         <beans:property name="serviceInterface" value="leon.rmi.iface.IUserDao"/>         <beans:property name="registryPort" value="9111"/>         <beans:property name="servicePort" value="10023"/>     </beans:bean> </beans:beans>

Note:It is not described in detail here. It mainly configures the real implementation class. When exposed using rmiserviceexporter, you must pay attention to service, servicename, serviceinterface, and port registryport When configuring the property.

Start the server of the web project. The configuration file should be listened to and loaded by the spring listener. After the startup is successful, the server is created. If the server is started on localhost, the exposed rmi ip address is also localhost. If you want to use another IP address, you need to start the server on another IP address.

Okay. Continue writing after lunch.
Client call

To facilitate the creation of only one simple Java project, it is called using static Java code.

1. Create a springbeans. xml file under the source file SRC.

<?xml version="1.0" encoding="UTF-8"?><beans:beans xmlns="http://www.springframework.org/schema/security"xmlns:beans="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/securityhttp://www.springframework.org/schema/security/spring-security-3.0.xsd">    <beans:bean id="userDaoProxy" class="org.springframework.remoting.rmi.RmiProxyFactoryBean"> <beans:property name="serviceUrl" value="rmi://localhost:9111/userDaoService"/>         <beans:property name="serviceInterface" value="leon.rmi.iface.IUserDao"/>     </beans:bean>    </beans:beans>

Here we notice two important properties of rmiproxyfactorybean:ServiceurlAndServiceinterfaceThe iuserdao interface can be packaged into a jar package from the server interface.

 

2. Create a Java class

package testrmi;import leon.rmi.iface.IUserDao;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class TestRMI2 {public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("springbeans.xml"); IUserDao userDao = (IUserDao) ctx.getBean("userDaoProxy"); System.out.println(userDao.getUserList()); System.out.println(userDao.sum(145, 487));}}

Run successfully.

Well, this is an example of RMI encapsulated by spring, which should be frequently used in project work.

If you have any questions, please discuss them.

 

 

 

 

 

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.