Вы находитесь на странице: 1из 57

CmpE 275

Section: Java EE 5 - Enterprise Java Beans

Part 1: Session Beans, Timer service

Design v. Design
The distinction between designing applications and designing distributed applications is key; the technology is not.
Technologies provide the raw materials to build distributed systems, they are not distributed systems.

Examples: Sockets, ONC-RPC, DCE, CORBA, Java RMI, .NET, JMS, Java EE, Web Services

Designing a distributed system is difficult


How do you measure a successful architecture/system?
Nines? Ability to handle success? Cost to maintain? Cost of change?

Factors: Availability
Defining availability Two perspectives host and application Uptime of a machine/software Accessible for use Nines How to describe the level of availability Percent the system is available (accumulative) Down Mon, Tue, Wed, Thu is bad 7.2 hours of planned maintenance and upgrades per month is okay
Availability (%) 90% 99% 99.9% 99.99% Down/Year 36.5 days 3.65 days 8.76 hrs 52.6 min Down/Month 72 hrs 7.2 hrs 43.2 min 4.32 min

99.999%

5.26 min

25.9 sec

Distributed systems provide replication to solve availability


Perspective of the software Distributed systems provide the ability to have more than one unit provide services At any one time, one of the units is available to provide services. Architecture solutions Messaging, routing strategies allow for the lookup, and routing of requests Building duplicate servers - deploying to multiple application servers Clustering application servers - synchronizing session data between servers Complexity Cost to build, cost to support Synchronization of data requires bandwidth and cycles Where to apply replication? Web, middle, data?

Factors: Scalability
Scalability is the ability to allow more concurrent access to a service (resource) Scalability is not performance
Performance is how fast a request can be processed

Architecture solutions
Messaging, routing allows distribution of requests Clustering provides the ability to bring additional services online to support demand

Complexity
Additional servers increases the burdens to the infrastructure (people, power, floor space, cooling)

Why designing for scalability is so hard


Causes Expansion exceeds original purpose (design) Mission changes, increased load Expansion that is cost prohibitive Upgrade costs (e.g., hardware) Issues Unable to support complexity or costs Aging software and/or hardware Increased support effort (out paces growth) Decreased efficiency Behavior is hard to predict or completely model (anticipate) all possible problems before they happen Scalability should Not change consistency (reliability) External latency does not decrease Code base does not change

Scalability (and availability) design examples


Examining hardware solutions, we can create scalable software designs.

Cluster, Blade, Shard


Cluster - N/2 (like) systems offer a platform for scaling and availability
Pattern for two should allow for many more - up to a point where issues of replication and caching become a factor to the design Software updates are easier - redirect all to one, bring down other to update, switch procedure and then reset (assumes all hosts are identical) Shared data with symmetric services is easy to implement. However, the use of local caching will prevent failover consistency this may not be a problem if the system and consumers agree to occasional break in continuity of service

Designs (cont.)
Shard - a bladed architecture with no collective memory - truly independent.
Finding data is important if shards do not share databases Hops to find the data may be a performance issue Separation of data is a referential integrity (RI) defeating design breaks optimization and reduction of duplication of normal form database design

Minimizes hot spots - file system, database, or key subsystems


Why?

Java Enterprise Edition (Java EE)

JEE is a collection of standards and tools


Java Enterprise Edition (JEE) is a set of best of technologies, standards and practices built upon the Java SE. This includes lifecycle management, transactions, security, and deployment configuration. Technologies Enterprise Java Beans v3.0 (EJBs) Java Persistence (JPA) Java Message Service (JMS) JavaMail, J2EE Connector Architecture (JCA v1.5), JAF v1.1, JTS, JTA, Web Services (WS) SOAP and SAAJ (AXIX2, JAX-WS 2.0) Java Architecture for XML Binding v2.0 (JAXB) Web Application JavaServer Pages (JSP) v2.1 Java Servlet v2.5 JavaServer Faces (JSF) v1.2 Misc. XML, JDBC, HTTP,

1. Application Servers
In the beginning, there was darkness and cold. Then,
mainframe terminals terminals

Centralized, non-distributed

Application Servers
In the 90s, systems should be clientserver

Application Servers
Today, enterprise applications use the multi-tier model

Application Servers
Multi-tier applications have several independent components An application server provides the infrastructure and services to run such applications

Application Servers
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.)

J2EE Application Servers


Major J2EE products:
BEA WebLogic IBM WebSphere Sun iPlanet Application Server Oracle 9iAS HP/Bluestone Total-e-Server Jboss (free open source)

Web Server and Application Server


App Server 1 Internet Browser Web Server (HTTP Server)

HTTP(S)

App Server 2

2. What is J2EE?
It is a public specification that embodies several technologies Current version is 3.x J2EE defines a model for developing multi-tier, web based, enterprise applications with distributed components

J2EE Benefits
High availability Scalability Integration with existing systems Freedom to choose vendors of application servers, tools, components Multi-platform

J2EE Benefits
Flexibility of scenarios and support to several types of clients Programming productivity:
Services allow developer to focus on business Component development facilitates maintenance and reuse Enables deploy-time behaviors Supports division of labor

Main technologies
JavaServer Pages (JSP) Servlet Enterprise JavaBeans (EJB)
JSPs, servlets and EJBs are application components

JSP
Used for web pages with dynamic content Processes HTTP requests (non-blocking calland-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

Servlet
Used for web pages with dynamic content Processes HTTP requests (non-blocking call-andreturn) Written in Java; uses print statements to render HTML Loaded into memory once and then called many times Provides APIs for session management

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

Brief timeline of the EJB specification


EJB v1 1998-1999 XML Deployment descriptors RMI over IIOP Entity, Stateless, and Stateful beans Role-based security EJB v2 2001 - 2003-ish CORBA compatible protocols (IIOP) Object lifecycle management Timer and Message-driven beans EJB v3 2006 Simplify development Annotations (JDK 1.5) Java Persistence API (JPA) Replaces Entity Bean concept of earlier EJBs

Comparing POJOs, JavaBeans and EJBs


Plain Old Java Object (POJO)
To put it simply, a class - Person, String Basic object oriented representation of a feature, process, or behavior

JavaBean
POJO plus naming, metadata, and access rules
Getter/Setter methods:
void setName(String name) void setCool(boolean yes) String getName() boolean isCool()

Bean Info

Enterprise Java Beans (EJBs)


EJBs are not JavaBeans

J2EE Multi-tier Model

J2EE Application Scenarios


Multi-tier typical application

J2EE Application Scenarios


Stand-alone client

J2EE Application Scenarios


Web-centric application

J2EE Application Scenarios


Business-to-business

J2EE Services and APIs


Java Message Service (JMS)
Implicit invocation Communication is loosely coupled, reliable and asynchronous Supports 2 models:
point-to-point publish/subscribe

JMS
Point-to-point
Destination is queue

JMS
Publish-subscribe
Destination is topic

J2EE Services and APIs


JNDI - Naming and directory services
Applications use JNDI to locate objects, such as environment entries, EJBs, datasources, message queues JNDI is implementation independent Underlying implementation varies: LDAP, DNS, DBMS, etc.

JEE/EJBs provide distributed design support by


EJBs is a framework that provides an integrated environment that includes:
Lifecycle management Transaction support Security Discovery Specifications (Interfaces) to use the frameworks features. These interfaces include:
Session Bean (Stateless and Stateful) Message Driven Bean (MDB) Timer service (simple scheduling service) Persistence (JPA) Resource Adapters (JCA)
Transactional integration of external systems/services

EJB Restrictions - what you cannot (should not) do


Restrictions are placed on EJBs to ensure behavior and management of resources that may be accessed by multiple instances (across JVMs), compromise security safeguards, does not disrupt container control Key Restrictions applicable to EJBs and classes they use
Static fields for read & write (read only okay - final) Java UI classes (awt, swing, etc) Prompt for information from the stdin or redirect stdin, stdout, stderr Create or manage threads
Thread synchronization primitives

Stop the JVM Native library access Override/Use object substitution features of the Java serialization API Directly read or write from/to a file descriptor (java.io) Use sockets Modify class loaders

Remote Interface
Remote interfaces can be used to invoke an
EJB across a network in a client-server fashion At minimum the interface must be annotated with @Remote either in the interface itself or in the bean class
@Remote public interface CalculatorRemote { public int sum(int add1, int add2); }

Local Interface
Local interfaces in EJB are pass-byreference interfaces. Meaning that normal java semantics are used Unless specified otherwise, every interface your bean implements is considered to be a local business interface
@Local public interface CalculatorLocal { public int sum(int add1, int add2); }

Types of EJB
EJB Taxonomy

EnterpriseBean
SessionBean Stateful EntityBean BMP MessageDrivenBean

Stateless

CMP

EJB 3 : Simplifying with annotations

@Stateless @Stateful @MessageDriven @Entity

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 New EJB 3.0 introduces a simplified declaration and lifecycle (e.g., no ejbCreate(),) Annotation: @Stateless Best for handling blocking requests, Instance pooling, timer capable, WS capable
Note: ejbCreate(), ejbRemove() are EJB 2.x methods that in EJB 3.x are replaced by lifecycle annotation

Local and remote interfaces for session beans (Stateless, Stateful)


Session beans can run in a local container for optimization within the same JVM Annotations
@Remote @Local
@Local public interface EchoPointLocal extends EchoPoint

@Remote public interface EchoPointRemote extends EchoPoint

Stateless example
public interface EchoPoint extends Serializable { String echo(String what); }

@Local EchoPointLocal

@Remote EchoPointRemote

@Stateless public class EchoPointEJB implements EchoPointLocal, EchoPointRemote { public String echo(String what) { System.out.println("Echo: " + what); return what; } }

Simplify EJB Development


POJO (Plain Old Java Object) Class
EJB Class will be a plain java class

POJI (Plain Old Java interface)


Regular business interface EJB interface does not have to implement EJBObject

No need of home interface Annotations for type of EJB and interface

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 EJB 3.0 simplified declaration and lifecycle methods (no ejbCreate(),) Annotation: @Stateful Best for mult-part (steps) input without persisting data between steps No pooling, not timer capable, not WS capable

Stateful passivation
Unlike stateless which can be limited to the number of instances (pooled), a stateless is created per client, which can create a memory burden on the server. The lifecycle includes passivation and activation of a stateful instance
Invoked when the server is experiencing heavy memory usage or the instance is idle for a period of time (configurable) Data contained in the instance is saved to disk or database A passivated object is activated before removing

Creating stateful EJBs


public interface AccountCreator extends Serializable { void addAccount(Account acct); void addAddress(Address addr); }

@Local AccountCreatorLocal

@Remote AccountCreatorRemote

@Stateful public class AccountCreatorEJB implements AccountCreatorRemote { ...

Detailed look at the stateful implementation


@Stateful public class AccountCreatorEJB implements AccountCreatorRemote { private Account acct; private Address addr; public void addAccount(Account acct) { this.acct = acct; }

public void addAddress(AccountAddress addr) { this.addr = addr;


} @Remove public void cancelCreation() { acct = null; } ...

Annotation to indicate that once this method is called, the stateless EJB instance can be removed.

Latency not found in POJO/JavaBeans (single JVM). JEE changes how distributed services (objects) are designed
Fine grain access pattern

Singe JVM/Process
getFirstName()

Remote: Container + Object


Person id : Long lastName : String firstName: String

Requesting Object

getLasttName() getAddressName() getID()

Application space ( single JVM): Access time per method ~0 msec Distributed space: The connection between the requestor and remote system introduces a tax (time and load) to marshal / unmarshal data and transmit across the network. Assume access time per method is ~1000 msec (example requires ~4000 msec per object)

Why so many interfaces?


Cannot mark the same interface with more than one access annotation. Alternative to creating multiple interfaces
Declare the local and/or remote interfaces in the bean class
@Remote(EchoPoint.class) @Stateless public class EchoPointEJB { ... }

EJB3.1 (JSR 318) proposes to remove the need to declare remote and local interfaces more POJO-like

Deploying session beans


Java EE 5 (EJB3) deployment has been greatly simplified through the use of annotations
Deployment configuration files (Deployment Descriptors) are optional for session beans

Deployment Descriptors
XML file defining what is being deployed
Jars Declarative transaction statements for methods Security

Examples where DD are applied


Enterprise Archive (EAR) Web Application Archive (WAR) EJBs ejb-jar.xml (JAR)

Deploying a EJB package consisting of session beans


Create an archive (.jar) of the EJB classes Copy to the application servers deployment directory (JBoss)

EJB timer service


Simple scheduling service (time delayed callbacks)

Easy to use scheduling Provides scheduling through Single action timer expire once Interval timer - multiple After the timer expires, the container will call the ejbTimeout() method Annotation: @Timeout Specify a the callback method within a stateless or message beans Container invoked method Transactional - can rollback
Timer Example: http://www.java2s.com/Code/Java/EJB3/UseTimerService.htm

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 clients session Example: shopping order

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

References
Tutorials and References
http://www.addsimplicity.com/adding_simplicity_an_engi/2008/08/shardlessons.html http://www.perfdynamics.com/Test/gcaprules.html http://java.sun.com/javaee/5/docs/tutorial/doc/

Books
Beginning EJB 3 Application Development, Kodali, et. al (2006) EJB3 In Action, panda, Rahman, Lane (2007) Pro EJB 3: Java Persistence API, Keith, Schincariol (2006)

Pattern Books
Java Enterprise Design Patterns, Grand (2002) Core J2EE Patterns 2nd Ed., Alur, Crupi, Malks (2003) EJB Design Patterns, Marinescu (2002)

Вам также может понравиться