J2ee Best Practices

  • November 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View J2ee Best Practices as PDF for free.

More details

  • Words: 5,894
  • Pages: 30
       J2EE Best Practices using a Real-life Example.

 

 

 Architecture:     How to Go… eBay

Carol McDonald

From there…

…to here?

Microsoft IIS

J2EE™ Container

Presentation Tier

eBayISAPI.dll EJB™ Container Business Tier

MSXML

Services

Logging

Web Container

Sun™ Tech Days

Security

[email protected]

Configuration

Technology Evangelist

Integration Tier

 

Monolithic Proprietary

   

1

Layered Loosely coupled Modular Standards based

2

 Is      What Needed…

 

™  J2EE      Core Patterns

 

 Collection of best practices and Patterns for for

J2EE™ architecture



Learning the technology is not enough  Industry best practices

 Also J2EE™ architecture bad practices and



 Proven solutions

refactorings  Based on Sun Java Center Services experience

Proven solutions  How to avoid bad practices?

 Reuse design  Robust and scalable architecture  Improve quality  Flexibility and maintainability

 Create a common vocabulary

3

4

1

 BluePrints      Java Program TM

 

 http://java.sun.com/blueprints  JavaTM Technology Series

 Web Tier best practices  EJB Tier best practices

books

 Persistence Options

 Designing Enterprise Applications

 Container Managed Persistence

with the J2EE Platform, 2nd Edition 

 

       Agenda

Covers J2EE 1.3 platform features TM

 J2EE Performance

 Designing Web Services with the

 JMS Best Practices (depending on the time)

J2EE Platform (available soon)

 Sample applications  Java Pet Store Demo  Java Adventure Builder Demo  Concrete code for the BluePrints

guidelines  Starting points for your applications

5

6

       Application Resources

 

       Standard performance

problems

 

 

Watch memory, and garbage collection  watch network traffic  Minimize object creation

Standard application resources: 

CPU



Memory



I/O





Network



Database



 Use Caching and Pooling

Watch for memory leaks inefficient database access, poor SQL code  Use Caching and Pooling

 7

8

Watch disk I/O  Avoid excessive logging

2

      

 

 

       Layering

   

     

 

Web Tier or Client

Presentation Layer

Network

Data Transfer Objects i.e. Business Data Values

EJB Session Beans

Business Logic Layer Service Layer

Entity EJBs

9

Domain Layer Persistent Entities

10

       Rationale for Layers

 

 

       Model View Controller

 Model = business data and rules, shared by all clients

 More flexible, extensible:

 Controller defines the application behaviour, interprets user

actions and maps them into actions performed on the model

 Presentation Layers

 View = renders the contents of the Model

 Frequent changes, design to be flexible

 Business Services

Client

Thin Browser

 Implement “use-cases”

HTTP Request

HTML Page

 Public Service interface  Interface should remain valid for changes in presentation

Presentation Layer

Controller

View

and data store

 Data Layers

Model Layer

 Fewer changes, designed to optimize data access

Persistence Layer

11

Problem Domain Services

Enterprise Resources

12

3

 

       Model View Controller

 

       Service to Worker = MVC Pattern with more detail

Separate: Model data Control Presentation of view 

  

 

 

Command Factory

3. Parse Request 5. Create 1. Request Client

  

    

 

 







4. Get cmd

Front Controller

6. Execute

2. Common logic



Command Helper

8. Dispatch 10. Response

 

7. Business logic

View Dispatcher

  

View Helper Data Bean

Servlet JSP

9. Get Data

Java™ Objects

13

14

    Use an    MVC Framework

 

 

   

      

 Use Struts, JSF, or Sun Java Studio ... application

framework  Frameworks provide a skeleton which you can extend

Form Bean

View 1

1 ActionServlet (Controller)

 Request processing

3

2 4

 Faster, easier development of

Action Action

Model

5

 Response generation

Action

 Improve

View 2 Struts-config.xml ........ ........ ........

 Design  Modularity

Action

 Maintainability

15

16

4

     Struts and Core  J2EE Patterns Front Controller

Command

 

 

       Ebay.com: Presentation Tier

Model Request Handler

Request Request Action Servlet

Action Mapping (xml)

Action

Intercepting Filter

Business Service

Front Controller

Navigation

Client

Command

?

Business Service

and Dispatch

Client Navigator

Dispatcher

Uses Response

XML

View Processor

JSP View

Action Forward

Intercepting Filter

Action Form

View Processor

Transformer Helper

Core J2EE

XSL

Pattern

Response

Strategy

View

Dispatcher

View Helper

17

18

      

Business Delegate

 

 

       Ebay.com: Presentation Tier

Service Interface

Request Handler



Client independent from ejb tier  Ejb details hidden  Mock objects can be used to test client w/o ejb tier

Request Intercepting Filter

Front Controller

Navigation

Command

Service Locator

Dispatcher

XML

View Processor Intercepting Filter

Response

Business Service

and Dispatch

Client Navigator

Business Delegate

View Processor

Transformer Helper

XSL

Core J2EE Pattern Strategy

19

20

5

       Cache for Performance

 

 Some things can be cached and shared, use a

singleton:  InitialContext object (JNDI object used for lookups)  Anything retrieved from JNDI, EJB Home interfaces  Repeated lookups can be expensive! Use Service Locator Pattern

 Some things are user specific, cached in session:  Cache search results when you are only displaying a few

at a time (static data)  Value List Pattern

21

       ServiceLocator code 01 public class ServiceLocator { 02 private InitialContext ic; 03 private Map cache; 04 private static ServiceLocator me; 05 06 private ServiceLocator() { 07 ic = new InitialContext(); 08 cache =new HashMap(); 09 } 10 public static ServiceLocator getInstance() { 11 if (me == null) { 12 me = new ServiceLocator(); 13 } 14 return me; 15 }

23

 

       ServiceLocator code

 

01 public EJBHome getRemoteHome(String jndiHomeName, Class className){

EJBHome home = null; 03 if (cache.containsKey(jndiHomeName)) { 04 home = (EJBHome) cache.get(jndiHomeName); 05 } else { 06 Object objref = ic.lookup(jndiHomeName); 07 Object obj = PortableRemoteObject.narrow(objref, className); 08 home = (EJBHome)obj; 09 cache.put(jndiHomeName, home); 10 } 11 return home; 12 } 15 02

24

6

  code      Client

 

     Tips for Servlet  Performance



Don't store a lot of data in the HTTP Session  Remove servlet sessions when they are no longer needed:

01 ServiceLocator serviceLocator = 02

ServiceLocator.getInstance();

03 try { 04

ProjectHome projectHome =(ProjectHome) serviceLocator.getHome(“ProjectHome.class”);

05

 

...

 In logoff call session.invalidate()

25

26

     Servlet Tips  



 

     Tips for JSPs  

DO use high performance J2EE design patterns



Avoid scriptlets in JSP  Use JSTL (JSP 2.0 Standard Tag Libraries):

 MVC, Service Locator



 



DON’T hold resources – explicitly free them



Pass data to JSP in Servlet request object not session  If JSP does not use the HTTP session  Use <%page session="false"%> to prevent HTTP

Sessions from being automatically created

27

28

7

      

 



Do you need declarative transactional support?  Do you need to distribute your business logic?  Do you need JMS, JAX-RPC, RMI?

   

     

  29

 

    Do you    need EJBs?



Do you need to support multiple client types?



Do you need method-level security on your objects?



Do you need Clustering for Scalability?

30

       Architecting Applications

 

ebay Case Study

 

 Use    ebay case   realization

ebay Case Study

View Items



Functional requirements captured via use-cases  Use-cases implemented using MVC & Command design patterns  Implement Business Logic as Services

View Items by category Any User

 Verbs in use cases help define services

Any user can view auction items by category

 Nouns in use cases help define business data

objects

31

32

8

 Items     Requirements View Design

 

ebay Case Study

 

 Items      View Design

ebay Case Study Front Controller

Centralize Request Hndlg

Transfer Object Assembler

Action Command

Transfer Object

Convert to Biz Command Assemble Data

Business Delegate

Use case Biz logic Retrieve Data by category

33

Session Facade

Value List Handler

Service Locator

Data Access Object

34

 

    Object   Data Transfer Client Object

EJB Network boundary

GetCity() GetState()

Before

DON'T DO too much network traffic

GetZipCode()

Client Object

Item Info Data Transfer Object

EJB

                           

GetItemInfo() Return DTO GetCity()

After

DO Reduce network traffic with Data Transfer Object

GetState() GetZipCode() Network boundary

36

9

 

       Data Access Object Use DAO for read-only tabular access to a large set of data, when query results are large and short-lived BusinessObject

Uses

DataAccessObject

creates/uses

obtains/modifies

Encapsulates

DataSource

Use Data Access Objects to encapsulate data-access logic -provides a simplified interface for performing complex JDBC operations -allows decoupling of data-access optimizations

TransferObject

38

           

 

Data Access Object (DAO)

public class FacadeEJB implements SessionBean { protected EbayDAO dao; public void ejbCreate() { try { dao = EbayDAOFactory.getDAO(); } catch (EbayDAOSysException se) { throw new EJBException(se.getMessage()); }} … public ListChunk getItems(String categoryId, int startIndex, int count, Locale locale) { try { return dao.getItems(categoryId, startIndex, count, locale); } catch (EbayDAOSysException se) { throw new EJBException(se.getMessage()); }} …. }

39

10

 

  List      Value Handler

 For querying, filtering, and

Interface

ValueListIterator

+GetSize():int +getCurrentElement():Object +getPreviousElements(count:int):List +getNextElements(count:int):List +resetIndex():void

Stateful Session

Client

displaying large amounts of data: 

ValueListHandler

ValueList

ValueListiterator

Execute Search

Value List Handler handles the search, can cache results and provides a traversable result set

DataAccessObject

ValueListHandler

Create

Execute Search

Create Return Value List

Return Sub List

Get Next

Get Sub-list Return Sub-list

<>

Client

 

       Example Caching Results

TransferObject

ValueList

Get Sub-list

Get Previous Return Sub-list Get Current

Get Current

Return Value Object Get Size

DataAccessObject

Get Size Return Size

41

42

       Returning Search Results Options

 

Stateless Session

Client



ValueList Handler as a Stateful Session EJB caches search results, and returns sub list  ValueList Handler as Stateless Session EJB: 



 

       Stateless Example

Create

DataAccessObject

ValueListHandler ValueListiterator

Execute Search (index, count)

Execute Search (index, count)

Create Return Sub List

Execute Search (index+count, count)

Select * FROM item WHERE id=? LIMIT [count] OFFSET [startIndex]

Return Sub List

Instead of Value list could use JDBC 2.0 scrollable ResultSet but keeps JDBC data

ValueList

Return sub List

Execute Search (index+count, count)

Create

Return sub List

Select * FROM item WHERE id=? LIMIT [count]OFFSET [startIndex]

source connection open ! (J2SE 1.5 will have disconnected scrollable ResultSet) 43

44

11

 

       Session Facade pattern Session Bean

Entity Bean 1

Entity Bean Plain Java™ Object

2. getData()

Client

2. getData() Entity Bean 2

Data Access Object 1

Session Bean

Data Access Object 2

Session Facade

1. doThis(...)

3. process



Use the Session Facade:

Java™ Object

 provide a simple interface to a complex subsystem of

enterprise beans  Enforce a clear and strict separation of business logic from

presentation and data logic 46

      Use the Session Facade

 

pattern

 

 the     Facade Use Session

To Execute complex use cases in a single network call to

To group finer grained calls to local entity beans

reduce network overhead Direct Bean Access

Don’t:

Local vs. Remote Interfaces

EJB

Remote Interfaces

Client

Local Interfaces

Network EJB Object

EJB client

Direct Entity Bean access results in excessive network overhead

EJB client

EJB Object

and multiple transactions

Network

Do: Network Client

47

F a c a d e

Pass by Value: Serialize/deserialize method parameters

EJB

Direct Entity Bean access results in excessive network overhead

Pass by Reference: Better performance

48

12

       Design your local &

 

remote EJBs

Use Session Facade to group calls to local EJBs in a Coarse Grained Interface

     !

    

    

    

Determine which EJBs will be collocated within same VM

  & 

" # 

   

 !

Relationship Reference

 !$ % 

  

 

49

 

       Tier eBay.com: Business

       Session EJB tips

 

ebay Case Study Dispatch Application Controller

Command

Context Object

Persistence Domain Store

DAO



Data Source

Remove stateful session beans when finished (user logs out) 

Business Logic/Data Application Service Facade

Business Object

Transfer Object Assembler

Value List Handler



   

Limit size of objects stored in session beans due to memory cost and I/O for passivation

Transfer Object

Core J2EE Pattern Strategy

51

52

13

 

       Session EJB? Stateless or Stateful



       s Service Tier DON'T

Stateless session beans are pooled and can service multiple clients

 



DO NOT store large amount of data in Stateful SessionEJB  DO NOT access of Entity EJBs remotely

 give best performance



Stateful store conversational state=1 per client (are activated and passivated)  For Performance Strive for Statelessness when application has a high number of users



DO NOT implement fine-grained components as remote EJBs

 convert Stateful to stateless by adding parameters

to the bean methods that hold the extra state 53

54

 

     Design Patterns  Summary Mediate business processing Locate services

Session Facade Obtain composite value objects

Entity

Encapsulate data

Access data sources

Message Driven Bean

 Exchanges data J2EE tiers

Service Locator

 Service Locator

 Holds results of JNDI lookups

Access business list

 Value List Handler

Value List handler

 Handles larger result sets from database queries

 Business Delegate

Encapsulate data

Transactional Data Business Components

 

 Data Transfer Object

Locate services

Encapsulate data

Value Object Assembler Invoke business methods

       Design Patterns Summary

Transfer Object

 Simplifies the coupling between the J2EE Web &

EJB tiers

Access data sources

 Session Facade

 Provide business logic functionality

Encapsulate data

 Data Access Object

 Isolation layer for interfaces to a systems resources

Data Access Object

 Etc.

 www.sun.com/developer/blueprints/

55

56

14

 

      

       Data Access Options



     

 Great choice for ease and performance



data rows; they should have business logic. To simply access data, use Plain JDBC encapsulated in a DAO

 

 vs.    BMP CMP  

SQL

Non-relational, non-object data access, Legacy systems, CRM, SAP...  Use J2EE Connectors

     Effect of Good   CMP

Bean State

Optimizations

24 20

1) Bean provider manages State and Data consistency 2) Bean provider handles relationships and OR Mapping

16 12

JDBC SQLJ

CMP Bean EJB Container

Persistence Manager

JDBC Driver

SQL

Simple BMP Optimized BMP CMP

8

Bean State

4 0

Database

1) Container manages State and Data consistency 2) Container/PM provides concurrency, relationships and OR Mapping

59

 

28

Database

EJB Container

Tabular access  EJBs should not be simple wrappers on database

58

JDBC Driver

Object-oriented (transactional) data model  JDO

57

JDBC SQLJ

 

 EJB Container Managed Persistence



BMP Bean

in J2EE:

Benchmark Score

# of Database Calls

60

15

 

     CMP 2.0 Entity   Beans

 

       Relationships Container Managed

Entity Bean is now an abstract class, container extends it <> java.io.Serializable

Address Local Entity

Order

1

Shipping Address <> javax.ejb.EnterpriseBean

Local Entity

1 Client

Product

OrderBean

1

1

<> javax.ejb.EntityBean

LineItems

ProductOrdered

M CMP Entity Bean abstract class (Contains data handling logic)

You (bean provider) write this code.

OrderHome

M

LineItem Local Entity

CMP Entity Bean subclass (Contains persistence logic)

EJB Tier

Container provides this class.

61

62

      and Accessors for CMP

CMR

 

 2.0      CMP Relationship



public abstract class OrderBean implements EntityBean { private EntityContext context;

 

In CMP 2.0, you declare fields and relationships in deployment descriptor  Container generates all the necessary code

//access methods for cmp fields

<ejb-jar> <enterprise-beans> ... define your enterprise beans ... elements represent container-managed persistent fields ... define EJB relationships ...

public abstract String getOrderID(); //primary key public abstract void setOrderID(String id); . . . //access methods for cmr fields public abstract Collection getLineItems(); public abstract void setLineItems(Collection lineItems);

63

Handling

64

16

       Example CMP Wizard

 

     Advantages of   CMP 2.0 for developer



 

container manages the persistence and the relationships, not you!  No SQL or persistence logic in source code



Freedom from maintaining interactions with the data store  EJB™ Query Language (EJB QL)  Portable code

65

66

       2.0 Advantages of CMP for Container



 

  CMP      Some Optimizations

Optimization is possible because persistent fields are only accessible via get and set methods



Aggressive Loading  Loading data for Entities in a relationship in the

same query

 Containers knows



Which field is being accessed  Whether or not field is in a relation  Whether of not there is a transaction  What's in cache  The current clustering environment  Can optimize based on above 

67

 

Lazy Loading  Deferring loading of any data until it is accessed



Dirty Writes  Only update data which has been changed

in the database

68

17

 

 Standard      CMP: Vs. Vendor Specific Features

 

       Pessimistic Locking Serialized Access to same Bean C1



Time

Standard features

1000

 Declarative specification of:

1000

 Persistent attributes, abstract schema, relationships,

queries for finder/select methods(via EJBQL), transactional attributes



C2

State in Database

2000

2000

    



   

    

Vendor specific 3000

 Tools, concurrency and consistency semantics,

    



  

   2000

 

3000



   

caching semantics, performance and usability

The entity blocks until previous transaction commits 69

70

 

       Optimistic Locking With “Update-conflict” Detection

 

       Usage Guidelines

Concurrent Access to same Bean

Time

State in Database 1000

2000

1000

2000

C1

C2

     





     



 

1000

 

   !   

3000



 Recommended for

consistency when concurrent updates would be frequent

Retry

2000



   3000

!  "!   



Optimistic

 Use when

concurrent access is mostly reading  For scalability  Requires exception handling

SunOne deployment descriptor

Concurrent Access to same Bean (same Primary Key) Lock obtained at update time, conflict detection

71

Pessimistic

72

18

   !' "  

      



 

            !' "



Sun Java System Application Server 7 supports these consistency levels (in sun-cmp-mappings.xml)

 

Chose optimistic concurrency for CMPs with “read-mostly” access

 Check-modified-at-commit = most optimistic  Check-all-at-commit  Lock-when-modified  Lock-when-loaded = most pessimistic  None

73

74

      Modes Database Isolation

 



Choose the lowest cost database transaction isolation level that avoids corrupting the data.



Transaction levels in order of increasing consistency and cost are:

       Entity Bean Tips

 Read Uncommitted  Read Committed  Repeatable Read  Serializable

 75

 



Do not use EJB entity beans for batch loading or queries that return large result sets. Use Data Access Objets encapsulating JDBC



Use CMP rather than BMP entity bean when possible



Do not call EJB entity bean get & set methods from client  Wrap with session beans to provide course

grain access and single transaction context

consider READ COMMITTED with optimistic locking 76

19

      

 

 

 App      Tune Server

 EJB Bean Cache and Pools

      

 JDBC  connection pools

            

 Prepared statement cache size  JVM Heap size  (go to garbage collection Performance session)

 Correct settings depend on application,

test to determine sizes 77

78

 Key      Parameters Tune Container



 

 &   !$ & (  #   !

 (  ( 

   !  

Stateful session bean and Entity bean cache  Cache = EJB instances with state  Minimizes activation and passivation



   

    

  

 

   !                

      

     

Stateless session and Entity bean pools  Pool = EJB instances with no assigned state  Minimizes creation and initialization

79

 

       The EJB Container

80

20

 

       Entity Bean

       Entity Bean Caching



NewInstance() setEntityContext()

minimizes creation and initialization

Commit Option A  At the end of the transaction, the instance stays

EjbActivate()

Bean pool size

ready (cached) and the instance state is valid ( ejbLoad not called )

Does not exist unsetEntityContext()



Commit Option B  At the end of the transaction, the instance stays

pooled

ejbFind()

ready (cached) but the instance state is NOT valid ( ejbLoad will be called )

EJB Instance

ejbCreate() ejbPostCreate()

ejbRemove() ejbActivate()



ejbPassivate()

Bean cache size minimizes activation and passivation

EJB Object

its state is valid (passivated)

ejbStore()

EJB Instance



business method

81

82

    The Sun's EJB   Container

!$   

 

on your app server

 

  

commit-option (B|C) (entity beans)



steady-pool-size (not for messagedriven)  max-pool-size (0 = unbounded)

Max-cache-size (0 = unbounded)  cache-idle-timeout-in-seconds (0 = indefinitely)



Best Option: Usually B, if Entity will be accessed again. do profiling with your application

    The Sun's EJB   Container





Commit Option C  At the end of the transaction, neither the instance nor

ready

ejbLoad()

 

"     #       

   $  %     & 

    %   %   %    



pool-idle-timeout-in-seconds (0 = indefinitely)



Adjust a bean’s pool size:

 Increase when observing excessive creation

and deletion of bean instances  Decrease when accumulating a large number

83

84

of instances in pool

21

 

       Stateful Session Bean

    The Sun's EJB   Container

!$  

Bean cache size minimizes activation and passivation

does not exist



Max-cache-size (0 = unbounded)



cache-idle-timeout-in-seconds (0 = indefinitely)



removal-timeout-in-seconds (stateful session)

ejbRemove()

1) newInstance()

removal time out

2) setSessioncontext()

"     #       

    $  %     & 

    %   %   %    



ejbPassivate()

3)ejbCreate()

Method-ready EJB Object

passive

EJB Instance

 

EjbActivate()

business method

85

86

       Bean Stateless Session and Message Driven Bean

 

    The Sun's EJB   Container

  

Bean pool size minimizes creation and initialization

 



steady-pool-size (not for messagedriven)  max-pool-size (0 = unbounded)

does not exist

1) newInstance() 2) setSessioncontext()

EjbRemove()



pool-idle-timeout-in-seconds (0 = indefinitely)



Adjust a bean’s pool size:

3)ejbCreate()

method-ready pool Business method

 Increase when observing excessive creation

EJB Instance

and deletion of bean instances  Decrease when accumulating a large number

87

88

of instances in pool

22

    The Sun's EJB   Container

 

  Tips      JDBC

 (&  &    !$ 



Select a good JDBC driver



Tune connection pool size  Close resources as soon as you’re done with them (in finally)

Per bean: in ejb module’s sun-ejbjar.xml

 and



 

 E.g. Statements, Connections, ResultSets…

Global defaults: in server instance’s server.xml



 <ejb-container> and <mdb-container>

Use JDBC’s PreparedStatement when possible:  stmt = connection.prepareStatement(..);  Tune statement caching



Turn off Auto-Commit  Group updates into a transaction

89

90

       Database Statement



Caching

 

       Database Performance

 



Common performance bottleneck  Typical problems:

'   

 15–25% Performance improvement

 primary key to big (use integer)

 Requires knowledge of database specific

 Inefficient queries - sending SQL data that asks the database to do more work than necessary

properties, i.e. Oracle <jdbc-connection-pool datasource-classname= "oracle.jdbc.pool.OracleDataSource" ...> <property name="ImplicitCachingEnabled" value="true"/> <property name="MaxStatements" value="200"/>

 run the SQL through the EXPLAIN SELECT command  index the columns in your WHERE clauses

 Large Data Sets - processing large sets

of data in ResultSets 91

92

23

    Tips  Summary Performance

 

 

      EJB Tips Summary

Tips for better performance

 

 EJB Container Services – use appropriately for:

 Tune app server and infrastructure  Container Caching and Pools

 Distributed transaction management  Robust security service

Database access

 Resource management (threads, sockets, database connections)

 Use JDBC for:

 Container persistence

 Batch loading: session bean or message bean  Large result sets: value list handler

 Remote accessibility

 Use CMP rather than BMP Entity Beans  Use right isolation level and database

 Dispatch and life-cycle management.

transactional control (locking)

93

94

       Manage Expensive

     

95

Resources

 

     Design Patterns  can Significantly Help Performance

Cache “EJB homes” Cache data sources Minimize use of HTTP sessions Release database connections Remove unused stateful session beans Use local Interfaces [Session Facade]

 



Session Facade  Service Locator  Value List Handler  Data Transfer Object

96

24

      

 ! !  "     

 

       JMS Communication

 !

      

 

  

 Loosely coupled: 

Producer doesn't need to know consumers or consumer method arguments

 Reliable: 

Message is stored until it can be delivered

 Asynchronous 

97

Producer is not blocked, consumer does not have to be available

98

    Use JMS for  



 

Asynchronous Interaction  Concurrent processing  Scalability  Batch processing



Broadcasting messages to multiple recipients  Reliable messaging  Messaging with Transaction Support 

Loose Coupling

99

25

 

       Publish and Subscribe

 

       Message-Driven Bean

Concurrent Asynchronous Processing

Example: Stock Price Changes

 High Scalability, High Throughput  MDB instances are pooled by the container  Allow for asynchronous concurrent message consumption

from the same destination

Container Topic

Container

JMS Provider

Price Change

Desti nation

Queue

Msg-

MDB Consume Consumer

MDB driven Instances Instances

r

Bean

Msg-Driven Bean Class

Traders/Brokers

101

102

 

       MDB Facade Pattern

Mailer MDB Asynchronous Message Delivery

Order Approval MDB

TRANSACTION

EJB Tier

LineItem Entity

Purchase JMS Topics Order Queue

Card Entity

1:m

Order Bean

Process Order <Entity EJB>

Address Entity

Procure Inventory

 Use the MDB Facade:

Inventory Management Bean

Mail

 provide a simple asynchronous interface to a complex

subsystem of enterprise beans

<Entity EJB>

Publish/subscribe

Purchase Order Entity MessageDrivenBean

103

 

MDBs   Container      Managed Transactions

104

26

 

       JMS Persistent Messages

 

       Example Problem Tracking

Guaranteed Delivery - but has a performance cost

 !

)*  

0* !

   ,* !-

.*  /*  

+*  

1* !-

Existing Synchronous Client Access

EJB Tier

  

Problem Solver



A Session EJB provides the business logic for the Customers or help desk to synchronously enter Problem data, or search for similar problems  Entity EJBs provide the business logic for accessing/updating the domain Data objects

2*  

Problem Rep Company

      105

106

 

       Internal View Extension Solution

Remote Help Desk New Problem

       JMS Existing Synchronous Client Access

EJB Tier

Problem

Report Request

Rep Company

Monthly Report

107



Use JMS for loosely coupled applications that need reliable, scalable document oriented message exchange



Including Message-Driven Beans and JMS in your J2EE™ application can greatly increase performance, robustness, and efficiency

Problem Solver

Problem Handler

Report Generator

 

108

27

 

 Message    Facade   XML

      Tips for XML messaging



EJB Architectural Pattern XML msg

External Application

XML Messaging Facade JMS Queues

Asynchronous

Message Driven Bean

Java™ Value Objects

Entity Bean

 Within a system just use java data objects



 Ref JavaOne

109

Use XML for messages between systems…

Convert the data from XML into a Java™ class as soon as possible  Can use JAXB for this

Example implementation of XML interaction model on top of Java™ interaction model

       JMS Do's

hit



Entity Bean

Synchronous

Inside your Application don’t overuse XML  Parsing and processing can cause a performance

Entity Bean Stateless Session EJB

 

Use XML mainly for transmission

110

 



Watch message size  Only use XML when necessary (lower performance) 

Only use reliable messaging when necessary (lower performance)

111

28

 

       FUTURE: JBI and J2EE

Web App. Module (JSP/Servlet API)

EJB Module (EJB API)

      

   #  

JBI BP Module (WS-BPEL and WSDL APIs)

208 “Machine” SPI Normalized Message “Bus”

208 “Binding” SPI

Binding Framework

WS-I

JMS

JCA

EDI VAN

SOAP

MQ

EIS resource

AS1/AS2

113

 

114

       Use Tools

 

       Summary

 

 J2EE Patterns and Best Practices are

proven solutions



Use IDE or Xdoclet to keep EJB class, home interfrace, remote interface consistent  Use Junit for Unit testing  Use Ant to automate deployment and testing  All of these are provided with Sun Java Studio

115

 Reuse design  Robust and scalable architecture  Improve quality, performance  Flexibility and maintainability

 JavaTM BluePrints Program  http://java.sun.com/blueprints  Designing Enterprise Applications

with the J2EE Platform, 2nd Edition

116

29

 

       Resources:

      

 

Carol McDonald Technology Evangelist [email protected]

Sun™ Tech Days

http://java.sun.com/blueprints Java Performance Tuning

117

J2EE Performance Testing

118

30

Related Documents