国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Java JavaBase Detailed graphic explanation of Java RMI (with examples)

Detailed graphic explanation of Java RMI (with examples)

Dec 24, 2019 pm 05:33 PM
java

Detailed graphic explanation of Java RMI (with examples)

Java RMI: Java Remote Method Invocation, or Java RMI (Java Remote Method Invocation), is an application programming interface used to implement remote procedure calls in the Java programming language.

It enables programs running on the client to call objects on the remote server. The remote method invocation feature enables Java programmers to distribute operations in a network environment. The entire purpose of RMI is to simplify the use of remote interface objects as much as possible.

We know that Remote Procedure Call (RPC) can be used by one process to call a process in another process (probably on another remote host), thereby providing process distribution capabilities. Java's RMI takes another step forward based on RPC, that is, providing communication between distributed objects.

RMI (Remote Method Invocation) is remote method invocation, which allows an object running on one Java virtual machine to call a method on an object running on another Java virtual machine.

The two virtual machines can be running in different processes on the same computer, or they can be running on different computers on the network.

【JavaRMI】

1. Working principle

RMI allows a Java program to call another computer on the network The method of the Java object of the computer, then the effect of calling it is the same as calling it on the local machine. In layman's terms: There is a class on machine A, and through remote calling, machine B calls the methods in this class.

RMI, Remote Method Invocation (Remote Method Invocation) is the backbone of Enterprise JavaBeans and a convenient way to build distributed Java applications. RMI is very easy to use, but it is very powerful.

The foundation of RMI is the interface. The RMI architecture is based on an important principle: defining the interface and defining the specific implementation of the interface are separate. Below we use specific examples to build a simple remote computing service and a client program that uses it

2. RMI includes:

1. Remote service interface Definition

2. Specific implementation of the remote service interface

3. Stub and Skeleton files

4. A server running the remote service

5. An RMI naming service, which allows the client to discover the remote service.

6. A provider of class files (an HTTP or FTP server)

7. One that requires this Remote service client program

3. What is the purpose of RMI?

The purpose of RMI is to provide services for remote communication between distributed Java applications and provide distribution service.

Currently, the main applications are encapsulated in various J2EE project frameworks, such as Spring, EJB (both Spring and EJB encapsulate RMI technology)

Implement RMI in Spring:

① Define service interfaces on the server side and define specific classes to implement these interfaces;

② Use the org.springframework.remoting.rmi.RmiServiceExporter class on the server side to register services;

③ In The client uses org.springframework.remoting.rmi.RmiProxyFactoryBean to implement the proxy function of the remote service;

④Define a class on the client that accesses the same service interface as the server

four , What are the limitations of RMI???????????????????????????????????????????????????????????????????????????????????????JRMP is a protocol specially developed for Java remote objects. Since JRMP is specially developed for Java objects, RMI has insufficient support for application systems developed in non-Java languages.

Cannot communicate with objects written in non-Java languages ??(meaning that only remote calls with code in which both the client and server are Java programs are supported).

5. What are the limitations of using RMI?

Since both the client and the server are written in Java, the only requirement for platform compatibility is that both parties run on version compatible Java virtual machine.

6. Parameters and return values ??of RMI calls to remote methods

When calling methods on remote objects, the client can not only use original type data as parameters In addition, objects can also be passed as parameters, corresponding to the return value, which can return primitive types or objects. These are all implemented through Java's object serialization (serialization) technology. (In other words: if the parameter or return value is an object, it must implement the Serializable interface)

7. Basic model of RMI application

Detailed graphic explanation of Java RMI (with examples)8. RMI architecture

Stub/Framework (Stub/Skeleton) layer: client-side stub and server-side framework;Detailed graphic explanation of Java RMI (with examples)

Remote reference layer: Handling remote reference behavior

Transport layer: Connection establishment and management, and tracking of remote objects

9. RMI Classes and interfaces (classes needed to complete a simple RMI).

Detailed graphic explanation of Java RMI (with examples)

(1) Remote interface: It is a tagged interface that does not define methods

Public interface Remote{}

In In RMI, the remote interface declares the set of methods that can be called from the remote Java virtual machine. The remote interface meets the following requirements:

1. The remote interface must extend the Java.rmi.Remote interface directly or indirectly, and must be declared as public, unless the client and the remote interface are in the same package

2. When declaring a method in a remote interface, in addition to throwing one related to the application, it must also include a RemoteException (or its superclass, IOExcepion or Exception) exception

3. In a remote method declaration, a remote object declared as a parameter or return value must be declared as a remote interface, not as an implementation class of the interface.

(2) The RemoteObject abstract class implements the Remote interface and the Serializable interface. It and its subclasses provide RMI server functions.

(3) The LocateRegistry final() class is used to obtain a reference to the boot remote object registration server program of a specific host (that is, create a stub), or to create a remote object registration service program that can receive calls on a specific port.

Server side: Provide remote object services to other clients

SomeService servcie=……;//遠(yuǎn)程對(duì)象服務(wù)

1. Registry registry=LocateRegisty.getRegistry(); //Registry is an interface, it inherits Remote, this method returns local The host's reference to the remote object Registry on the default registry port 1099.

2. getRegistry(int port) returns the reference of the local host to the remote object Registry on the specified port;

3. getRegistry(String host) returns the specified host on the default registry port 1099 Reference to the remote object Registry;

4. getRegistry(String host, int port) returns the reference to the remote object Registry on the specified host and port

5. registry.bind(“I serve",service);//bind(String name,Remote obj) Binds the remote reference to the name specified in this registry. name: the name related to the remote reference obj: a reference to the remote object (usually a stub)

6, unbind (String name) removes the binding of the specified name in the registry.

7. Rebind (String name, Remote obj) rebinds. If the name already exists but the Remote is different, replace it. If the Remote is the same, discard the existing binding.

8. lookup(String name) Returns the remote reference bound to the specified name in the registry, returns Remote

9, String[] list() Returns an array of names bound in this registry. This array will contain a snapshot of the names in this registry that were bound when this method was called.

Client side: Provide corresponding service requests to the server.

Registry registry=LocateRegisty.getRegistry();
SomeService servcie=(SomeService)registry.lookup(“I serve”);
Servcie.requestService();

(4) Naming class is similar to Registry class.

Client:

Naming.lookup(String url)
url 格式如下"rmi://localhost/"+遠(yuǎn)程對(duì)象引用

Server:

Registry registry=LocateRegistry.createRegistry(int port);
Naming.rebind(“service”,service);

(5) RMISecurityManager class

In the RMI reference program, if the security manager is not set, Then stubs and classes can only be loaded from the local classpath, which ensures that the application is not compromised by code downloaded by remote method calls.

The following code must be executed to install RMISecurityManager before downloading code from the remote host:

System.setSecurityManager(new RMISecurityManager());

10. Demo development

In order to write a demo, we are divided into two parts, one part is Part of the server-side code is the client-side code. The client-side code is mainly for using the server-side code. Of course, this code is very simple, just to illustrate the problem. Actual use will be more complicated.

(1) Our purpose

Build a server-side java project, including the remote-side code, define the interface, define the interface implementation, and then create a client-side java project to use the remote side through RMI Methods in end services.

(2) Our code structure

Detailed graphic explanation of Java RMI (with examples)

#(3) Remote service code

1. Remote service interface definition

The first step is to create and compile the Java code of the service interface. This interface defines all the functions of providing remote services. The following is the source program:

UserManagerInterface.java

package cn.com.tt.rmiserver.stub;

import java.rmi.Remote;
import java.rmi.RemoteException;

import cn.com.tt.rmiserver.bean.Account;

public interface UserManagerInterface extends Remote{
    public String getUserName() throws RemoteException;
    public Account getAdminAccount() throws RemoteException;
}

The interface must inherit the Remote class, and each defined method must throw a RemoteException exception. object.

2. Specific implementation of the interface

The second step is to implement the above interface:

UserManagerImp.java

package cn.com.tt.rmiserver;

import java.rmi.RemoteException;

import cn.com.tt.rmiserver.stub.UserManagerInterface;
import cn.com.tt.rmiserver.bean.Account;

public class UserManagerImp implements UserManagerInterface {
    public UserManagerImp() throws RemoteException {

    }
    private static final long serialVersionUID = -3111492742628447261L;

    public String getUserName() throws RemoteException{
        return "TT";
    }
    public Account getAdminAccount() throws RemoteException{
        Account account=new Account();
        account.setUsername("TT");
        account.setPassword("123456");
        return account;
    }
}

3. Define a bean , implements the implements Serializable serialization interface. That is, a serializable object that can be transmitted between the client and server.

Account.java

package cn.com.tt.rmiserver.bean;

import java.io.Serializable;

public class Account implements Serializable,Cloneable{
    private static final long serialVersionUID = -1858518369668584532L;
    private String username;
    private String password;
    
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}

4. Define the main program entry on the server side.

Entry.java

package cn.com.tt.rmiserver.entry;

import java.rmi.AlreadyBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

import cn.com.tt.rmiserver.UserManagerImp;
import cn.com.tt.rmiserver.stub.UserManagerInterface;

public class Entry {
    public static void main(String []args) throws AlreadyBoundException, RemoteException{
        UserManagerImp userManager=new UserManagerImp();
        UserManagerInterface userManagerI=(UserManagerInterface)UnicastRemoteObject.exportObject(userManager,0);
        // Bind the remote object's stub in the registry
        Registry registry = LocateRegistry.createRegistry(2002);
       
        registry.rebind("userManager", userManagerI);
        System.out.println("server is ready");
        }
}

(4) Client-side code

1、把Server端的Account類和接口UserManagerInterface 導(dǎo)出Export成jar包,命名為:RmiServerInterface.jar。導(dǎo)入到client中。

2、項(xiàng)目——右鍵——Export——java——jar file——next——選擇Account類和接口UserManagerInterface——命名為:RmiServerInterface.jar如下圖:

Detailed graphic explanation of Java RMI (with examples)

3. 新建一個(gè)java Project,導(dǎo)入jar包,編寫(xiě)客戶端代碼。

4. 代碼

ClientEntry.java

package weiblog.rmi;

import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import cn.com.tt.rmiserver.stub.UserManagerInterface;

public class ClientEntry {
    
    public static void main(String []args){
        
        try {
            Registry registry = LocateRegistry.getRegistry("localhost",2004);
            UserManagerInterface userManager = (UserManagerInterface)registry.lookup("userManager");
            System.out.println("用戶名是"+userManager.getAdminAccount().getUsername()
                    +"密碼"+userManager.getAdminAccount().getPassword());
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NotBoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }

}

5. 先運(yùn)行服務(wù)器端代碼, 然后運(yùn)行客戶端代碼,就會(huì)顯示運(yùn)行結(jié)果,客戶端可以運(yùn)行多次,每次都可以取得服務(wù)器端的對(duì)象。如果要再次運(yùn)行客戶端代碼就需要更改端口號(hào),如果不更改就會(huì)顯示端口號(hào)被占用。

更多java知識(shí)請(qǐng)關(guān)注java基礎(chǔ)教程欄目。

The above is the detailed content of Detailed graphic explanation of Java RMI (with examples). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1502
276
How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

Understanding Network Ports and Firewalls Understanding Network Ports and Firewalls Aug 01, 2025 am 06:40 AM

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

How does garbage collection work in Java? How does garbage collection work in Java? Aug 02, 2025 pm 01:55 PM

Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces

Using HTML `input` Types for User Data Using HTML `input` Types for User Data Aug 03, 2025 am 11:07 AM

Choosing the right HTMLinput type can improve data accuracy, enhance user experience, and improve usability. 1. Select the corresponding input types according to the data type, such as text, email, tel, number and date, which can automatically checksum and adapt to the keyboard; 2. Use HTML5 to add new types such as url, color, range and search, which can provide a more intuitive interaction method; 3. Use placeholder and required attributes to improve the efficiency and accuracy of form filling, but it should be noted that placeholder cannot replace label.

Comparing Java Build Tools: Maven vs. Gradle Comparing Java Build Tools: Maven vs. Gradle Aug 03, 2025 pm 01:36 PM

Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac

go by example defer statement explained go by example defer statement explained Aug 02, 2025 am 06:26 AM

defer is used to perform specified operations before the function returns, such as cleaning resources; parameters are evaluated immediately when defer, and the functions are executed in the order of last-in-first-out (LIFO); 1. Multiple defers are executed in reverse order of declarations; 2. Commonly used for secure cleaning such as file closing; 3. The named return value can be modified; 4. It will be executed even if panic occurs, suitable for recovery; 5. Avoid abuse of defer in loops to prevent resource leakage; correct use can improve code security and readability.

See all articles