Sunteți pe pagina 1din 63

Java Remote Method Invocation (RMI)

Alexander Day Chaffee alexc@purpletech.com

Copyright 1997 Alex Chaffee

Introduction
Java
Networking Distributed

Computing

Copyright 1997 Alex Chaffee

Who is in Attendance?
Find

out any relevant background and interest of the audience Java Programmers? C++ Programmers? TCP/IP Gurus? Smalltalk?

Copyright 1997 Alex Chaffee

Agenda
Background
APIs Q&A

and Usage

Copyright 1997 Alex Chaffee

Overview
RMI

JDBC

CORBA

java.net

TCP/IP

Network OS
Copyright 1997 Alex Chaffee

What Is RMI?
Access

to Remote Objects Java-to-Java only Client-Server Protocol High-level API Transparent Lightweight

Copyright 1997 Alex Chaffee

Examples of Use
Database

access Computations Any custom protocol Not for standard protocols (HTTP, FTP, etc.)

Copyright 1997 Alex Chaffee

Related Technologies

RPC

(Remote Procedure Calls)

Developed by Sun Platform-specific


(Common Object Request Broker Architecture)

CORBA

Developed by OMG Access to non-Java objects (as well as Java)


(Distributed Common Object Model)

DCOM

Developed by Microsoft Access to Win32 objects


(Lightweight Directory Access Protocol)

LDAP

Finding resources on a network


Copyright 1997 Alex Chaffee

Part I: RMI Concepts

Copyright 1997 Alex Chaffee

Remote Objects (Diagram)


Java Virtual Machine Java Virtual Machine

Client Object

TCP

Remote Object

Copyright 1997 Alex Chaffee

RMI Layers
Java Virtual Machine Client Object Java Virtual Machine Remote Object

Stub

Skeleton

Remote Reference Layer

Remote Reference Layer

Transport Layer

TCP

Transport Layer
Copyright 1997 Alex Chaffee

Remote Objects
Remote
Live

Objects

on server Accessed as if they were local

Copyright 1997 Alex Chaffee

Registries
Name

and look up remote objects Servers can register their objects Clients can find server objects and obtain a remote reference A registry is a running process on a host machine

Copyright 1997 Alex Chaffee

Remote References and Interfaces


Remote
Refer

References

to remote objects Invoked on client exactly like local object references


Remote

Interfaces

Declare

exposed methods Implemented on client Like a proxy for the remote object
Copyright 1997 Alex Chaffee

Stubs and Skeletons


Stub
lives

on client pretends to be remote object


Skeleton
lives

on server receives requests from stub talks to true remote object delivers response to stub
Copyright 1997 Alex Chaffee

Remote Interfaces and Stubs


Remote Interface

implements

implements

Client

Stub

Skeleton

Remote Object (Server)

Copyright 1997 Alex Chaffee

Remote Reference Layer


Local

pointers not good enough Figures out which remote object is being referenced Could span multiple virtual machines Communicates via TCP/IP

Copyright 1997 Alex Chaffee

Transport Layer
Deals

with communications Connection management Dispatching messages between stub and skeleton Distributed Garbage Collection Sits on top of java.net

Copyright 1997 Alex Chaffee

HTTP Tunneling
Cool:

if it cant make the connection normally, it will tunnel through port 80 Allows clients behind firewall to make remote calls to server Note: does not work server -> client

Copyright 1997 Alex Chaffee

RMI System Architecture


Client Virtual Machine Client Server Virtual Machine Remote Object

Stub

Skeleton Server

Fred Registry Virtual Machine


Copyright 1997 Alex Chaffee

RMI Flow
1. Server Creates Remote Object Client Virtual Machine 2. Server Registers Remote Object Client Server Virtual Machine Remote Object
1

Stub

Skeleton Server
2

Fred Registry Virtual Machine


Copyright 1997 Alex Chaffee

RMI Flow
Client Virtual Machine Client Server Virtual Machine Remote 3. Client requests object from Registry Object 4. Registry returns remote reference (and stub gets created) Stub
3 4

Skeleton Server

Fred Registry Virtual Machine


Copyright 1997 Alex Chaffee

RMI Flow
Client Virtual Machine Client
5 6 7

Server Virtual Machine Remote Object

Stub

Skeleton Server

5. Client invokes stub method 6. Stub talks to skeleton 7. Skeleton invokes remote object Fred method Registry Virtual Machine
Copyright 1997 Alex Chaffee

Part II: RMI Usage

Copyright 1997 Alex Chaffee

Creating Remote Objects


Define
Define

a Remote Interface
java.rmi.Remote

extends

a class that implements the Remote Interface


extends

java.rmi.RemoteObject or java.rmi.UnicastRemoteObject

Copyright 1997 Alex Chaffee

Remote Interface Example


import java.rmi.*; public interface Adder extends Remote { public int add(int x, int y) throws RemoteException; }

Copyright 1997 Alex Chaffee

Remote Class Example


import java.rmi.*; import java.rmi.server.*; public class AdderImpl extends UnicastRemoteObject implements Adder { public AdderImpl() throws RemoteException { } public int add(int x, int y) throws RemoteException { return x + y; } }

Copyright 1997 Alex Chaffee

Compiling Remote Classes


Compile
javac
reads

the Java class

.java file produces .class file Compile


rmic
reads

the Stub and Skeleton

.class file produces _Skel.class and _Stub.class


Copyright 1997 Alex Chaffee

Compiling Remote Classes (Diagram)


Adder.java (interface)

javac

Adder.class (interface classfile)

AdderImpl_Skel.class (skeleton classfile)

AdderImpl.java (remote class)

javac

AdderImpl.class (classfile)

rmic

AdderImpl_Stub.class (stub classfile)


Copyright 1997 Alex Chaffee

Registering Remote Classes


start

the registry
process

running

Unix:

rmiregistry &
Windows:

start /m rmiregistry

Copyright 1997 Alex Chaffee

Registry CLASSPATH
Registry

VM needs to be able to find stub

file(s) You must set the CLASSPATH to include the directory containing the stub file

An easy way to check CLASSPATH is to use the javap command, supplying a fully package qualified class name. It uses the current CLASSPATH to find and print the interface to a class.

Or,

your server needs to specify the java.rmi.server.codebase System property (more later) Copyright 1997 Alex Chaffee

Create the server


Creates

a new instance of the remote object Registers it in the registry with a unique name Thats it

Copyright 1997 Alex Chaffee

RMI Server Example


try { AdderImpl adder = new AdderImpl(); Naming.rebind("adder", adder); System.out.println("Adder bound"); } catch (RemoteException re) { re.printStackTrace(); } catch (MalformedURLException me) { me.printStackTrace(); }
Copyright 1997 Alex Chaffee

Launch the Server


% java AdderServer & Adder bound

Copyright 1997 Alex Chaffee

Server Logging
invoke

from command line

java -Djava.rmi.server.logCalls=true YourServerImpl


or

enable inside program RemoteServer.setLog(System.err);

Copyright 1997 Alex Chaffee

Creating an RMI Client


Install
to

a Security Manager

protect from malicious stubs

Find

a registry
java.rmi.Naming

use

Lookup

the name, returns a reference Cast the reference to the appropriate Remote Interface Just use it!
Copyright 1997 Alex Chaffee

RMI URLs
rmi://host[:port]/name
default

port is 1099 Specifies hostname of registry can also use relative URLs
name

only assumes registry is on local host

Copyright 1997 Alex Chaffee

RMI Client Example


System.setSecurityManager( new RMISecurityManager()); Adder a = (Adder) Naming.lookup("adder");
int sum = a.add(2,2); System.out.println("2+2=" + sum);

Copyright 1997 Alex Chaffee

Remote Interfaces vs. Remote Classes


Remember

that the reference is to an

interface You must make references, arrays, etc. out of the interface type, not the implementation type You cant cast the remote reference to a normal reference So name your Remote Objects with Impl (so you dont get confused) Copyright 1997 Alex Chaffee

Parameter Passing
Primitive
passed

types

by value

Remote
passed

objects
by reference

Non-remote
passed

objects

by value uses Java Object Serialization


Copyright 1997 Alex Chaffee

Object Serialization
aka

Persistence saves the state (data) of a particular instance of an object serialize - to save unserialize - to load

Copyright 1997 Alex Chaffee

Java Serialization
writes

object as a sequence of bytes writes it to a Stream recreates it on the other end creates a brand new object with the old data

Copyright 1997 Alex Chaffee

java.io.Serializable
Objects

that implement the java.io.Serializable interface are marked as serializable Also subclasses Magically, all non-static and non-transient data members will be serialized Actually, its not magic, its Reflection (its done with mirrors) empty interface - just a marker Copyright 1997 Alex Chaffee

Not All Objects Are Serializable


Any

object that doesnt implement Serializable Any object that would pose a security risk
e.g.

FileInputStream

Any

object whose value depends on VMspecific information


e.g.

Thread

Any

object that contains a (non-static, nontransient) unserializable object (recursively)


Copyright 1997 Alex Chaffee

NotSerializableException
thrown

if you try to serialize or unserialize an unserializable object maybe you subclassed a Serializable object and added some unserializable members

Copyright 1997 Alex Chaffee

Incompatible Changes
If

class has members added or removed, it becomes incompatible java.io.InvalidClassException thrown if you try to deserialize an incompatible object stream

Copyright 1997 Alex Chaffee

Serial Version
If

the changes were actually compatible find out the Serial Version UID of the original class
use

the serialver utility

add

a member variable to the changed class its marked as compatible with the old
Copyright 1997 Alex Chaffee

protected static final long serialVersionUID = -2215190743590612933L;

now

class

Using readObject
if

you need to force an object to be compatible implement readObject() method to make compatible changes
private void readObject(ObjectInputStream stream) throws java.io.IOException { defaultReadObject(stream); // do compatible stuff }

Copyright 1997 Alex Chaffee

Callbacks
They

just work Pass in a remote reference to a client object Server object can call its methods transparently Registry is out of the loop

Copyright 1997 Alex Chaffee

RMI Security
Server

is untrusted Stubs could be malicious rmic is OK, but someone could customcode an evil stub: its just a .class file

Copyright 1997 Alex Chaffee

RMI Security Managers


AppletSecurityManager
stub

can only do what an applet can do

RMISecurityManager
disables

all functions except class definition and access A downloaded class is allowed to make a connection if the connection was initiated via the RMI transport.
None
Stub

loading disabled Stubs still work if they are in local classpath

Copyright 1997 Alex Chaffee

Codebase Property
Stub
3

classpaths can be confusing

VMs, each with its own classpath Server vs. Registry vs. Client
The

RMI class loader always loads stubs from the CLASSPATH first Next, it tries downloading classes from a web server
(but

only if a security manager is in force)

java.rmi.server.codebase

specifies which web


Copyright 1997 Alex Chaffee

server

Stub File Configuration


The

best way to configure it is as follows.

NEVER have stub class files in ANY classpath make the stub files accessible via a web server set the java.rmi.server.codebase property, in the application creating the server object, to the web server's URL
The

stubs will be downloaded from your HTTP server on demand


(Thanks to Kevin.Conner@UK.Sun.COM for advice)
Copyright 1997 Alex Chaffee

Codebase and Thread Safety


Theres

a thread problem with codebase With a single remote server, and multiple remote objects on that server, each with its own stub codebase One server can step on the codebase property and foul up the registration for the other server In practice, wont happen very often
More

likely to happen in servlets

Copyright 1997 Alex Chaffee

Limitations of RMI
Java-only
but

you can use JNI on the server

Uses

TCP, not UDP At least two sockets per connection Untested for huge loads

Copyright 1997 Alex Chaffee

RMI vs. COM


Very

similar remote interfaces ~ type libraries COM is Win32-only (for now)

Copyright 1997 Alex Chaffee

Sun vs. Microsoft


RMI

is not shipped as part of Microsofts products RMI will still work in applications
include

java.rmi.* class files in your classpath download rmi.zip from ftp.microsoft.com


RMI

will work in applets

include

java.rmi.* class files (or rmi.zip) in your codebase IE4: only if theyre signed extra download time

Copyright 1997 Alex Chaffee

Part III: RMI Chat Server

Copyright 1997 Alex Chaffee

RMI Chat Server Objects


Message
interface interface

MessageReceiver
- receiveMessage(Message)

ChatServer
- login(MessageReceiver) - sendMessage(Message)

ChatClient

ChatServerImpl

implements remote reference local reference

Dispatcher

MessageQueue
Copyright 1997 Alex Chaffee

Summary
RMI

is a very clean API Easy way to write distributed programs Wire protocol may need improvement for large-scale problems

Copyright 1997 Alex Chaffee

Where to get more information


Other

training sessions Harold, Java Network Programming (OReilly) rmi-users mailing list (rmi-users@javasoft.com) http://www.developer.com/ (Gamelan) http://www.javaworld.com/ (magazine) http://www.stinky.com/java/ (Authors site)
Copyright 1997 Alex Chaffee

Q&A

Copyright 1997 Alex Chaffee

Feedback
Request

feedback of training session

Copyright 1997 Alex Chaffee

S-ar putea să vă placă și