distributed objects

74
分分分分 (2) Distributed Objects 22/3/30 Institute of Computer Software Nanjing University 1

Upload: winifred-buckley

Post on 03-Jan-2016

27 views

Category:

Documents


0 download

DESCRIPTION

Distributed Objects. 分布对象 (2). 摘要. More about RMI J2EE/EJB. 摘要. More about RMI J2EE/EJB. RMI. Java 语言之内,充分利用这一点! Stub 可下载! 可以传“对象”! Garbage Collection! 传“引用” java.rmi.Remote (RemoteException). Some important parts of RMI. Stubs: - PowerPoint PPT Presentation

TRANSCRIPT

分布对象 (2)

Distributed Objects

23/4/20Institute of Computer Software

Nanjing University

1

摘要 More about RMI J2EE/EJB

23/4/20Institute of Computer Software

Nanjing University

2

摘要 More about RMI J2EE/EJB

23/4/20Institute of Computer Software

Nanjing University

3

RMI

Java 语言之内,充分利用这一点! Stub 可下载! 可以传“对象”! Garbage Collection!

传“引用” java.rmi.Remote (RemoteException)

23/4/20Institute of Computer Software

Nanjing University

4

23/4/20Institute of Computer Software

Nanjing University5

Some important parts of RMI

Stubs: Each remote object class has an associated stub class,

which implements the same remote interfaces. An instance of the stub class is needed on each client. Client-side remote invocations are “actually” local invocations on the stub class.

Serialization: Arguments and results have to be “marshalled”—

converted to a representation that can be sent over the Net. In general this is a non-trivial transformation for Java objects. Serialization is also used for distributing stubs.

The Server-side “Run-time System”: This is responsible for listening for invocating requests

on suitable IP ports, and dispatching them to the proper, local resident, remote object.

23/4/20Institute of Computer Software

Nanjing University

6

RMI Architecture overview

RMI Layers Stub/skeleton layer

objects used by client and server applications

Remote reference layer creation/management of

remote references distributed garbage collection

Transport protocol layer binary data protocol

23/4/20Institute of Computer Software

Nanjing University

7

By using a layered architecture each layer could be enhanced or replaced without affecting the rest of the system: → transport layer: UDP/IP layer or secure sockets (SSL).

Remote Reference Layer

RemoteRef Interprets and manages references to

remote objects. The stub objects use the invoke() method in RemoteRef to forward the method call. The RemoteRef object understands the invocation semantics for remote services.

Leasing for distributed garbage collection Naming/Registry Service -- rmiregistry

23/4/20Institute of Computer Software

Nanjing University

8

23/4/20Institute of Computer Software

Nanjing University

9

Remote Reference Layer

Invocation Semantics v1.1: unicast / point-to-point. v1.2: support for activation of dormant

remote service objects: Remote Object Activation RMI will instantiate a dormant object and

restore its state from disk. As now: No multicast semantics.

Using RMI

1. Define interfaces for remote classes

2. Create and compile implementation of the remote classes

3. Create stub and skeleton classes using the rmic compilerNo longer necessary in Java 1.5 because Java

1.5 adds support for the dynamic generation of stub classes at runtime.

rmic must still be used to pre-generate stub classes for remote objects that need to support clients running on Java versions ≤ 1.4.

23/4/20Institute of Computer Software

Nanjing University

10

Using RMI

4. Create and compile the server application (registration)

5. Create and compile a client program to access the remote objects

6. Start the RMI Registry and the server application

7. Test the client

23/4/20Institute of Computer Software

Nanjing University

11

Point 1 – Remote Interface

Remote All remote interfaces must extend the

interface java.rmi.Remote (tagging interface)

All methods must throw a java.rmi.RemoteException (extension of java.io.IOException)

23/4/20Institute of Computer Software

Nanjing University

12

Point 2 – Implementation

UnicastRemoteObject Application must implement the defined remote

interface Application extends class UnicastRemoteObject or

calls explicitly UnicastRemoteObject.exportObject link to RMI system base class performs RMI linking and remote object

initialization constructor may throw a RemoteException

Activatable Base class to be used for activatable objects 激活服务的目标:只有在需要时才启动服务进程

23/4/20Institute of Computer Software

Nanjing University

13

Dynamic stubs in Java 1.5

Dynamic Proxies Implemented using java.lang.reflect.Proxy

(where the implementation is based on a RemoteObjectInvocationHandler)

Dynamic proxy is only used if no pre-generated stub class is available or if the system property java.rmi.server.ignoreStubClasses = true.

It is only possible if clients run on Java 5. Notice : If a remote object has pre-1.5 clients, then

that remote object should use a stub class pre-generated with rmic. There are two stub class.

protocols: v1.1 / v1.2 (default).

23/4/20Institute of Computer Software

Nanjing University

14

Point 3 – Server

RMI service must be hosted in a server process whose job is: to create an instance; to register the object with the naming

service. Naming/Registry service

RMI can use different naming services: (i) Simple service: RMI Registry; (ii) JNDI (Java Naming and Directory interface).

23/4/20Institute of Computer Software

Nanjing University

15

Point 4 – Start RMI Register

rmiregistry <port> default port: 1099 error if port is already used by another process (e.g.

another rmiregistry) daemon has to be started in directory which

contains used classes or the classes have to be on the CLASSPATH

Code Base: You must specify where are the class files.

Security policy file: You must give permission to use port 1099.

23/4/20Institute of Computer Software

Nanjing University

16

load classes dynamically

Required classes can be loaded over the network: e.g. provided by a web server via http; other protocols are also possible (file://, ftp://, ….)

RMI class loading and security. Two conditions must be met: 1. a special class loader is provided: RMIClassLoader 2. a security manager has to support remote class

loading System.setSecurityManager(new

RMISecurityManager()) Start of RMI-Registry in this case:

rmiregistry must not contain the needed classes in its path (otherwise what is the point of dynamically load the classes?)

23/4/20Institute of Computer Software

Nanjing University

17

load classes dynamically

Start of server: specify codebase for downloading class files

java -Djava.rmi.server.codebase=http://10.0.2.112:8080/calculator.jar nju.ics.yuping.dc.rmi.CalculatorServer

Start of client: permission to access server has to be provided (due to security

manager): java -Djava.security.policy=java.policy

nju.ics.yuping.dc.rmi.CalculatorClient Policy file:

grant { // connect to or accept connections on unprivileged ports // (ports greater than 1024) on host loki.cs.fh-aargau.ch

permission java.net.SocketPermission ”10.0.2.112:2001-", "connect,resolve"; };

23/4/20Institute of Computer Software

Nanjing University

18

Point 5 - Codebase

23/4/20Institute of Computer Software

Nanjing University

19

-Djava.rmi.server.codebase=file:///e:\course\code\rmi\server\

-Djava.rmi.server.codebase=http://10.0.2.112:8080/calculator.jar

Point 6 - Marshalling

How are parameters transferred to remote objects? Primitive Parameters

passed by value, in a machine-independent format Serializable Objects

serializable objects are copied → call by value Remote Object Parameters

only the reference to the remote object is passed, i.e. a new proxy is generated → call by reference

Non-Serializable/Remote Objects cannot be transferred checked at runtime (not by rmic!)

23/4/20Institute of Computer Software

Nanjing University

20

Note on passing remote objects

Remote objects are commonly defined as parameters and return types.

Example of usage: → Callbacks → Factory classes that create remote references

Reminder: Remote objects are passed by reference.

When Remote exported objects are passed to a client, RMI substitutes the reference with that of the Remote proxy (stub).

23/4/20Institute of Computer Software

Nanjing University

21

Callbacks

In many cases, applications require more complex bi-directional interactions. Servers may wish to make calls to the client (this is known as a callback). Why? → Error or problem reporting → Periodic updating and progress reports → UI notification (Observer pattern ! )

In OO programs the role of clients and servers are not always clear cut.

Client-server applications often operate in a peer-to-peer manner. At different stages an object may either act as a server or as a client.

23/4/20Institute of Computer Software

Nanjing University

22

Callback: How to

How do you create a callback? → Make your client into a server!

1. Make your client implement a Remote interface:→ Define a client remote interface

2. Make it available as a server (export your client interface as a Remote object)→ extend UnicastRemoteObject→ or use

UnicastRemoteObject.exportObject(Remote)

3. Pass a client Remote reference to the server. The server can then use this reference to make calls on the client.

23/4/20Institute of Computer Software

Nanjing University

23

Callback Example

23/4/20Institute of Computer Software

Nanjing University

24

摘要 More about RMI J2EE/EJB

23/4/20Institute of Computer Software

Nanjing University

25

J2EE

JDBC JNDI EJB RMI Java IDL/CORBA JSP Java Servlet

23/4/20Institute of Computer Software

Nanjing University

26

XML JMS JTA JavaMail JAF

Application Servers

"The Multi- tier applications" have several independent components

An application server provides the infrastructure and services to run such applications

Application server products can be separated into 3 categories: J2EE-based solutions Non-J2EE solutions (PHP, ColdFusion, Perl, etc.) And the Microsoft solution (ASP/COM and now .NET

with ASP.NET, VB.NET, C#, etc.)

23/4/20Institute of Computer Software

Nanjing University

27

J2EE Application Servers

Major J2EE products: BEA WebLogic IBM WebSphere Borland AppServer Sun/Oracle GlassFish JBoss

23/4/20Institute of Computer Software

Nanjing University

28

Web Server and Application Server

23/4/20Institute of Computer Software

Nanjing University

29

Web Server

(HTTP Server)

App Server 1

App Server 2

Internet Browser

HTTP(S)

J2EE Multi-tier Model

23/4/20Institute of Computer Software

Nanjing University

30

J2EE Application Scenarios

Multi-tier typical application

23/4/20Institute of Computer Software

Nanjing University

31

J2EE Application Scenarios

Stand-alone client

23/4/20Institute of Computer Software

Nanjing University

32

J2EE Application Scenarios

Web-centric application

23/4/20Institute of Computer Software

Nanjing University

33

J2EE Application Scenarios

Business-to-business

23/4/20Institute of Computer Software

Nanjing University

34

J2EE Architecture

23/4/20Institute of Computer Software

Nanjing University

35

Now

JEE 5 JEE 6

Homepage: http://www.oracle.com/technetwork/java/javaee/tech/index-jsp-142185.html

23/4/20Institute of Computer Software

Nanjing University

36

Main technologies

JavaServer Pages (JSP) Servlet Enterprise JavaBeans (EJB)

JSPs, servlets and EJBs are application components

23/4/20Institute of Computer Software

Nanjing University

37

JSP

Used for web pages with dynamic content

Processes HTTP requests (non-blocking call-and-return)

Accepts HTML tags, special JSP tags, and scriptlets of Java code

Separates static content from presentation logic

Can be created by web designer using HTML tools

23/4/20Institute of Computer Software

Nanjing University

38

Servlet

Used for web pages with dynamic content

Processes HTTP requests (non-blocking call-and-return)

Written in Java; uses print statements to render HTML

Loaded into memory once and then called many times

Provides APIs for session management

23/4/20Institute of Computer Software

Nanjing University

39

EJB

EJBs are distributed components used to implement business logic (no UI)

Developer concentrates on business logic

Availability, scalability, security, interoperability and integrability handled by the J2EE server

Client of EJBs can be JSPs, servlets, other EJBs and external aplications

Clients see interfaces

23/4/20Institute of Computer Software

Nanjing University

40

EJB

EJB 1.1 EJB 2.0 EJB 2.1 EJB 3.0 EJB 3.1

23/4/20Institute of Computer Software

Nanjing University

41

更简单

EJB 技术要解决的问题 EJB™ 技术的初衷是简化企业级应用的开发 通过 EJB 容器环境

提供可共享的服务: Concurrency , Distribution, Transactions, EIS integration, Resource pooling, Security, Persistence

提供 EJB 运行环境 减轻企业级应用开发人员的负担

23/4/20Institute of Computer Software

Nanjing University

42

EJB 的相关概念 EJB 容器:由厂商提供的位于 EJB 服务器上的

实体,管理 EJB 的系统级服务,控制 EJB 的生命周期。针对每一种组件,都有相应的容器进行处理。

EJB 服务器:作为容器和低层平台的桥梁管理着 EJB 容器和函数,向 EJB 容器提供了访问系统服务的能力。

EJB 接口 (2.x) : Home 接口, Remote 接口,Local 和 LocalHome 接口

23/4/20Institute of Computer Software

Nanjing University

43

EJB 分类 Session Bean

Stateless Stateful

Entity Bean Message Driven Bean

23/4/20Institute of Computer Software

Nanjing University

44

同步通信

异步通信

Session Bean

Stateless session bean: Contains no user-specific data Business process that provides a generic

service Container can pool stateless beans Example: shopping catalog

23/4/20Institute of Computer Software

Nanjing University

45

Session Bean

Stateful session bean: Retains conversational state (data) on

behalf of an individual client If state changed during this invocation, the

same state will be available upon the following invocation

Example: shopping cart

23/4/20Institute of Computer Software

Nanjing University

46

Entity Bean

Represents business data stored in a database persistent object

Underlying data is normally one row of a table

A primary key uniquely identifies each bean instance

Allows shared access from multiple clients Can live past the duration of client' s session Example: shopping order

23/4/20Institute of Computer Software

Nanjing University

47

Message-Driven Bean

Message consumer for a JMS queue or topic

Benefits from EJB container services that are not available to standard JMS consumers

Has no home or remote interface Example: Order processing – stock info

23/4/20Institute of Computer Software

Nanjing University

48

EJB 2.x 的问题 APIs 设计的角度不对,多是为了容器正常工作设计,

较少考虑易用性 EJBHome interface EJBObject interface EnterpriseBean interfaces JNDI interfaces Deployment descriptor …

解决了老问题,引入了新问题 程序复杂,臃肿,普及度不高。 Boiler Code 部署脚本

23/4/20Institute of Computer Software

Nanjing University

49

简单的 EJB 2.x 例子// EJB 2.1 Stateless Session Bean: Bean Class

public class PayrollBean implements javax.ejb.SessionBean {SessionContext ctx;DataSource payrollDB;public void setSessionContext(SessionContext ctx) {

this.ctx = ctx;}public void ejbActivate() {}public void ejbPassivate() {}public void ejbRemove() {}

23/4/20Institute of Computer Software

Nanjing University

50

简单的 EJB 2.x 例子// EJB 2.1 Stateless Session Bean: Bean Class (continued)

public void ejbCreate() { ...

Context initialCtx = new InitialContext();

payrollDB = (DataSource)initialCtx.lookup(“java:com/env/jdbc/empDB”);

...}public void setTaxDeductions(int empId,int deductions){

...Connection conn = payrollDB.getConnection();Statement stmt = conn.createStatement();...

}}

23/4/20Institute of Computer Software

Nanjing University

51

简单的 EJB 2.x 例子// EJB 2.1 Stateless Session Bean: Interfacespublic interface PayrollHome

extends javax.ejb.EJBLocalHome {public Payroll create() throws CreateException;

}public interface Payroll

extends javax.ejb.EJBLocalObject {public void setTaxDeductions(int empID, int

deductions);}

23/4/20Institute of Computer Software

Nanjing University

52

简单的 EJB 2.x 例子// EJB 2.1 Stateless Session Bean: Deployment Descriptor<session>

<ejb-name>PayrollBean</ejb-name><local-home>com.example.PayrollHome</local-home><local>com.example.Payroll</local><ejb-class>com.example.PayrollBean</ejb-class><session-type>Stateless</session-type><transaction-type>Container</transaction-type><resource-ref>

<res-ref-name>jdbc/empDB</res-ref-name><res-type>javax.sql.DataSource</res-type><res-auth>Container</res-auth>

</resource-ref></session>

23/4/20Institute of Computer Software

Nanjing University

53

简单的 EJB 2.x 例子// Deployment Descriptor(continued)<assembly-descriptor>

<method-permission><unchecked/><method>

<ejb-name>PayrollBean</ejb-name><method-name>*</method-name>

</method></method-permission><container-transaction>

<method><ejb-name>PayrollBean</ejb-name><method-name>*</method-name>

</method><trans-attribute>Required</trans-attribute>

</container-transaction></assembly-descriptor>

23/4/20Institute of Computer Software

Nanjing University

54

为什么开发 EJB 3.0 ?

简化 EJB!

23/4/20Institute of Computer Software

Nanjing University

55

EJB 类 POJO (Plain Old Java Object)

会话 Bean 和消息驱动 Bean 本身是普通的 Java类

通过注解来指定 EJB 的类型 注解

用在类的级别上 @Stateless, @Stateful, @MessageDriven

EJB 3.0 取消实体 Bean JPA(Java Persistence API) 取而代之 通过 @Entity 注解

23/4/20Institute of Computer Software

Nanjing University

56

EJB 2.x 中的 EJB 类// EJB 2.1 Stateless Session Bean: Bean Classpublic class PayrollBean implements javax.ejb.SessionBean

{SessionContext ctx;public void setSessionContext(SessionContext ctx) {

this.ctx = ctx;}public void ejbCreate() {...}public void ejbActivate() {}public void ejbPassivate() {}public void ejbRemove() {}public void setTaxDeductions(int empId, int deductions) {

...}

}

23/4/20Institute of Computer Software

Nanjing University

57

EJB 3.0 中的 EJB 类// EJB 3.0 Stateless Session Bean: Bean Class@Statelesspublic class PayrollBean implements Payroll {

public void setTaxDeductions(int empId,int deductions){

...}

}

23/4/20Institute of Computer Software

Nanjing University

58

EJB 接口 接口就是最普通的接口

不再需要 extend: EJBObject, EJBHome 接口可以是 local 或 remote

注解: @Local, @Remote Remote 方法不需抛出 RemoteException

23/4/20Institute of Computer Software

Nanjing University

59

EJB 2.x 中的 EJB 接口// EJB 2.1 Stateless Session Bean: Interfacespublic interface PayrollHome extends

javax.ejb.EJBLocalHome {public Payroll create() throws CreateException;

}public interface Payroll extends

javax.ejb.EJBLocalObject {public void setTaxDeductions(int empId, int

deductions);}

23/4/20Institute of Computer Software

Nanjing University

60

EJB 3.0 中的 EJB 接口// Local Interface@Localpublic interface Payroll {

public void setTaxDeductions(int empId, intdeductions);

}// Remote Interface@Remotepublic interface Payroll {

public void setTaxDeductions(int empId, intdeductions);

}

23/4/20Institute of Computer Software

Nanjing University

61

消息驱动 Bean

注解 @MessageDriven

消息驱动 Bean 需要实现javax.jmx.MessageListener onMessage(Message msg) 方法

23/4/20Institute of Computer Software

Nanjing University

62

消息驱动 Bean 的例子

// EJB 3.0 Message-driven bean: Bean Class

@MessageDriven public class PayrollMDB implements

javax.jms.MessageListener {public void onMessage(Message msg) {

...}

}

23/4/20Institute of Computer Software

Nanjing University

63

调用资源 不再需要繁琐的 JNDI Lookup 。 资源注射

注解 Instance variable 注解 setter 方法

动态 Lookup 注解 class

23/4/20Institute of Computer Software

Nanjing University

64

注解 @Resource

For connection factories, simple environment entries, topics/queues, EJBContext, UserTransaction, etc.

@PersistenceContext 容器管理的 EntityManager

@PersistenceUnit EntityManagerFactory :获取非容器管理的

EntityManager

23/4/20Institute of Computer Software

Nanjing University

65

Dependency Injection

Bean instance is supplied with references to resources in environment

Occurs when instance of bean class is created

No assumptions as to order of injection Optional @PostConstruct method is

called when injection is complete

23/4/20Institute of Computer Software

Nanjing University

66

资源注射的例子// EJB 3.0 Stateless Session Bean: Bean Class// Data access using injection and Java Persistence

API@Statelesspublic class PayrollBean implements Payroll {

@PersistenceContext EntityManager payrollMgr;public void setTaxDeductions(int empId,int deductions){

payrollMgr.find(Employee.class,empId).setTaxDeductions(deductions);

}}

23/4/20Institute of Computer Software

Nanjing University

67

动态 Lookup 的例子// EJB 3.0 Stateless Session Bean// Using dynamic lookup@PersistenceContext(name=”payrollMgr”)@Stateless public class PayrollBean implements Payroll {

@Resource SessionContext ctx;public void setTaxDeductions(int empId,int deductions){

EntityManager payrollMgr = ctx.lookup(“payrollMgr”);

payrollMgr.find(Employee.class,empId).setDeductions(deductions);

}}

23/4/20Institute of Computer Software

Nanjing University

68

Bean Lifecycle Event

EJB 2.1 需要实现 EnterpriseBean 接口,并重写 Lifecycle 相关的方法

EJB 3.0 通过注解指定需要的方法 注解 :

@PostConstruct @PreDestroy @PostActivate @PrePassivate

多个注解可用于同一个方法。

23/4/20Institute of Computer Software

Nanjing University

69

简化了 EJB 调用 使用资源注射的方式 不再需要 Home interface 不再抛出 RemoteException

23/4/20Institute of Computer Software

Nanjing University

70

EJB 2.x 的调用// EJB 2.1: Client View

...

Context initialContext = new InitialContext();

PayrollHome payrollHome = (PayrollHome)

initialContext.lookup(“java:comp/env/ejb/payroll”);

Payroll payroll = payrollHome.create();

...

// Use the bean

payroll.setTaxDeductions(1234, 3);

23/4/20Institute of Computer Software

Nanjing University

71

EJB 3.0 的调用

// EJB 3.0: Client View@EJB Payroll payroll;

// Use the beanpayroll.setTaxDeductions(1234, 3);

23/4/20Institute of Computer Software

Nanjing University

72

EJB 3.0 Summary

Major simplification of EJB technology for developers Beans are plain Java classes with plain Java interfaces APIs refocused on ease of use for developer Easy access to container services and environment Deployment descriptors available, but generally

unneeded EJB 3.0 components interoperate with existing

components/applications Gives developer powerful and easy-to-use

functionality

23/4/20Institute of Computer Software

Nanjing University

73

作业 ( 本次作业不用提交 )

Java 1.5 对 RMI 做了哪些改进? EJB 3.0 相比 EJB 2.1 有哪些改进?

23/4/20Institute of Computer Software

Nanjing University

74