版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)
文檔簡介
1、企業(yè)級應(yīng)用系統(tǒng)體系架構(gòu)(五) EJB3.0中的MDB,2024/3/17,From:O’Reilly: Enterprise JavaBeans 3.0, 5th Edition, May.2006,1,Topic,Message-Driven BeansJMS and Message-Driven BeansJMS-Based Message-Driven BeansThe Life Cycle of a
2、 Message-Driven BeanConnector-Based Message-Driven BeansMessage Linking,2,JMS and Message-Driven Beans,All EJB 3.0 vendors must support a JMS provider. Most vendors have a JMS provider built in and must support other J
3、MS providers through the JCA. However, regardless of whether your vendor has its own JMS provider or allows you to integrate some other provider, a JMS provider is an absolute necessity for supporting message-driven be
4、ans. By forcing the adoption of JMS, Sun has guaranteed that EJB developers can expect to have a working JMS provider on which messages can be both sent and received.,3,JMS as a Resource,JMS is a vendor-neutral API tha
5、t can be used to access enterprise messaging systems. Enterprise messaging systems (a.k.a. message-oriented middleware) facilitate the exchange of messages between software applications over a network. The role of JMS is
6、n't unlike the role of JDBC: just as JDBC provides a common API for accessing many different relational databases, JMS provides vendor-independent access to enterprise messaging systems. Although messaging products
7、aren't as familiar as database products, there's no shortage of messaging systems that support JMS, including JBossMQ, IBM's MQSeries, BEA's WebLogic JMS service, Sun Microsystems' Sun ONE Message Que
8、ue, and Sonic's SonicMQ. Software applications that use the JMS API for sending or receiving messages are portable from one JMS vendor to another.Applications that use JMS are called JMS clients , and the messaging
9、system that handles routing and delivery of messages is called the JMS provider . A JMS application is a business system composed of many JMS clients and, generally, one JMS provider. A JMS client that sends a message is
10、 called a producer , and a JMS client that receives a message is called a consumer . A single JMS client can be both a producer and a consumer.In EJB, enterprise beans of all types can use JMS to send messages. The mess
11、ages are consumed by other Java applications or by message-driven beans. JMS facilitates sending messages from enterprise beans using a messaging service , sometimes called a message broker or router. Message brokers ha
12、ve been around for a couple of decades--the oldest and most established is IBM‘s MQSeries but JMS is fairly new, and it is specifically designed to deliver a variety of message types from one Java application to another.
13、,4,Reimplementing the TravelAgent EJB with JMS,We can modify the TravelAgent EJB so that it uses JMS to alert some other Java application that a reservation has been made. The following code shows how to modify the bookP
14、assage( ) method so that the TravelAgent EJB sends a simple text message based on a description obtained from the TicketDO object: @Resource(mappedName="ConnectionFactoryNameGoesHere") private
15、ConnectionFactory connectionFactory; @Resource(mappedName="TicketTopic") private Topic topic; @Remove public TicketDO bookPassage(CreditCardDO card, double price) throws Incom
16、pleteConversationalState { if (customer == null || cruise == null || cabin == null) { throw new IncompleteConversationalState( ); } try { Reservation rese
17、rvation = new Reservation( customer, cruise, cabin, price, new Date( )); entityManager.persist(reservation); process.byCredit(customer, card, price); TicketDO ticke
18、t = new TicketDO(customer, cruise, cabin, price);,5,Reimplementing the TravelAgent EJB with JMS,Connection connect = factory.createConnection( ); Session session = connect.createSession(true,0);
19、 MessageProducer producer = session.createProducer(topic); TextMessage textMsg = session.createTextMessage( ); textMsg.setText(ticketDescription); producer.s
20、end(textMsg); connect.close( ); return ticket; } catch(Exception e) { throw new EJBException(e); } } While all the code we added might look a little overwhelming, th
21、e basics of JMS are not all that complicated.,6,ConnectionFactory and Topic,In order to send a JMS message, we need a connection to the JMS provider and a destination address for the message. A JMS connection factory mak
22、es the connection to the provider possible; the destination address is identified by a Topic object. Both the connection factory and the Topic object are obtained by using @javax.annotation.Resource to inject these objec
23、ts directly into the fields of the TravelAgent EJB: @Resource(mappedName="ConnectionFactoryNameGoesHere") private ConnectionFactory connectionFactory; @Resource(mappedName="Ticket
24、Topic") private Topic topic; The ConnectionFactory is similar to a DataSource in JDBC. Just as the DataSource provides a JDBC connection to a database, the ConnectionFactory provides a JMS connection to a
25、message router.The Topic object itself represents a network-independent destination to which the message will be addressed. In JMS, messages aren't sent directly to applications; they're sent to topics or queues
26、. A topic is analogous to an email list or newsgroup; any application with the proper credentials can receive messages from and send messages to a topic. When a JMS client receives messages from a topic, the client is sa
27、id to subscribe to that topic. JMS decouples applications by allowing them to send messages to each other through a destination, which serves as a virtual channel. A queue is another type of destination that we'll di
28、scuss in detail later.,7,Connection and Session,The ConnectionFactory is used to create a Connection, which is an actual connection to the JMS provider: Connection connect = connectionFactory.createConnection( );
29、 Session session = connect.createSession(true,0); Once you have a Connection , you can use it to create a Session. A Session allows you to group the actions of sending and receiving messages. In this case, you ne
30、ed only a single Session. Using multiple Sessions is helpful if you wish to produce and consume messages in different threads. Session objects use a single-threaded model, which prohibits concurrent access to a single Se
31、ssion from multiple threads. The thread that creates a Session is usually the thread that uses that Session's producers and consumers (i.e., MessageProducer and MessageConsumer objects). If you wish to produce and co
32、nsume messages using multithreading, you must create a different Session object for each thread.,8,Connection and Session,The createSession( ) method has two parameters: createSession(boolean transacted, int ackn
33、owledgeMode) According to the EJB specifications, these arguments are ignored at runtime because the EJB container manages the transaction and acknowledgment mode of any JMS resource obtained from the JNDI ENC. The spe
34、cification recommends that developers use the arguments true for transacted and 0 for acknowledgeMode, but since they are supposed to be ignored, it should not matter what you use. Unfortunately, not all vendors adhere t
35、o this part of the specification. Some vendors ignore these parameters; others do not.It's good programming practice to close a Connection after it has been used: Connection connect = factory.createConnecti
36、on( ); ... connect.close( );,9,MessageProducer,The Session is used to create a MessageProducer, which sends messages from the TravelAgent EJB to the destination specified by the Topic object. Any JMS c
37、lients that subscribe to that topic will receive a copy of the message: MessageProducer producer = session.createProducer(topic); TextMessage textMsg = session.createTextMessage( ); textMsg.setTe
38、xt(ticketDescription); producer.send(textMsg);,10,Message types,In JMS, a message is a Java object with two parts: a header and a message body. The header is composed of delivery information and metadata, and th
39、e message body carries the application data, which can take several forms: text, serializable objects, byte streams, etc. The JMS API defines several message types (TextMessage, MapMessage, ObjectMessage , and others) an
40、d provides methods for delivering messages to and receiving messages from other applications.For example, we can change the TravelAgent EJB so that it sends a MapMessage rather than a TextMessage : TicketDO tick
41、et = new TicketDO(customer,cruise,cabin,price); ... MessageProducer producer = session.createProducer(topic); MapMessage mapMsg = session.createMapMessage( ); mapMsg.setInt("Customer
42、ID", ticket.customerID.intValue( )); mapMsg.setInt("CruiseID", ticket.cruiseID.intValue( )); mapMsg.setInt("CabinID", ticket.cabinID.intValue( )); mapMsg.setDouble("P
43、rice", ticket.price); producer.send(mapMsg); The attributes of MapMessage (CustomerID, CruiseID, CabinID, and Price) can be accessed by name from those JMS clients that receive it.,11,Message types,As an a
44、lternative, the TravelAgent EJB could be modified to use the ObjectMessage type, which would allow us to send the entire TicketDO object as the message using Java serialization: TicketDO ticket = new TicketDO(cus
45、tomer,cruise,cabin,price); ... MessageProducer producer = session.createProducer(topic); ObjectMessage objectMsg = session.createObjectMessage( ); ObjectMsg.setObject(ticket); p
46、roducer.send(mapMsg); In addition to TextMessage, MapMessage, and ObjectMessage, JMS provides two other message types: StreamMessage and BytesMessage . StreamMessage can take the contents of an I/O stream as its payloa
47、d. BytesMessage can take any array of bytes, which it treats as opaque data.,12,JMS Application Client,To get a better idea of how JMS is used, we can create a Java application whose sole purpose is receiving and process
48、ing reservation messages. This application is a simple JMS client that prints a description of each ticket as it receives the messages. We'll assume that the TravelAgent EJB is using TextMessage to send a description
49、 of the ticket to the JMS clients. Here's how the JMS application client might look: import javax.jms.Message; import javax.jms.TextMessage; import javax.jms.ConnectionFactory; import
50、javax.jms.Connection; import javax.jms.Session; import javax.jms.Topic; import javax.jms.JMSException; import javax.naming.InitialContext; public class JmsClient_1 implements java
51、x.jms.MessageListener { public static void main(String [] args) throws Exception { if(args.length != 2) throw new Exception("Wrong number of arguments"); new JmsC
52、lient_1(args[0], args[1]); while(true){ Thread.sleep(10000);} },13,JMS Application Client,public JmsClient_1(String factoryName, String topicName) throws Exception { InitialContext j
53、ndiContext = getInitialContext( ); ConnectionFactory factory = (ConnectionFactory) jndiContext.lookup("ConnectionFactoryNameGoesHere"); Topic topic = (Topic)jnd
54、iContext.lookup("TopicNameGoesHere"); Connection connect = factory.createConnection( ); Session session = connect.createSession(false,Session.AUTO_ACKNOWLEDGE); MessageConsum
55、er consumer = session.createConsumer(topic); consumer.setMessageListener(this); connect.start( ); } public void onMessage(Message message) { try { TextMes
56、sage textMsg = (TextMessage)message; String text = textMsg.getText( ); System.out.println("\n RESERVATION RECEIVED\n"+text); } catch(JMSException jmsE) { jmsE.printSta
57、ckTrace( ); } },14,JMS Application Client,public static InitialContext getInitialContext( ) { // create vendor-specific JNDI context here } } The constructor of JmsClient_1 obtains the ConnectionFactory and Top
58、ic from the JNDI InitialContext. This context is created with vendor-specific properties so that the client can connect to the same JMS provider as the one used by the TravelAgent EJB. For example, here's how the g
59、etInitialContext( ) method for the JBoss application server would be coded: public static InitialContext getInitialContext( ) { Properties env = new Properties( ); env.put(Context.SECURITY
60、_PRINCIPAL, "guest"); env.put(Context.SECURITY_CREDENTIALS, "guest"); env.put(Context.INITIAL_CONTEXT_FACTORY, " org.jboss.security.jndi.JndiLo
61、ginInitialContextFactory"); env.put(Context.PROVIDER_URL, " jnp://hostname:1099"); return new InitialContext(env); },15,JMS Application Client,Once the client has the Conne
62、ctionFactory and Topic, it creates a Connection and a Session in the same way as the TravelAgent EJB does. The main difference is that the Session object is used to create a MessageConsumer rather than a MessageProducer
63、. The MessageConsumer is designed to process incoming messages that are published to its Topic: Session session = connect.createSession(false,Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = session
64、.createConsumer(topic); consumer.setMessageListener(this); connect.start( ); The MessageConsumer can receive messages directly or delegate message processing to a javax.jms.MessageListener . We chose t
65、o have JmsClient_1 implement the MessageListener interface so that it can process the messages itself. MessageListener objects implement a single method, onMessage( ), which is invoked every time a new message is sent to
66、 the subscriber's topic. In this case, every time the TravelAgent EJB sends a reservation message to the topic, the JMS client's onMessage( ) method is invoked to receive and process a copy of the message:
67、 public void onMessage(Message message) { try { TextMessage textMsg = (TextMessage)message; String text = textMsg.getText( ); System.out.println("\n RE
68、SERVATION RECEIVED:\n"+text); } catch(JMSException jmsE) { jmsE.printStackTrace( ); } },16,JMS Is Asynchronous,One of the principal advantages of JMS messaging is that it's asynchronous. In ot
69、her words, a JMS client can send a message without having to wait for a reply. Contrast this flexibility with the synchronous messaging of Java RMI or JAX-RPC. Each time a client invokes a bean's method, it blocks th
70、e current thread until the method completes execution. The limitations of RMI make JMS an attractive alternative for communicating with other applications. Because messaging is inherently decoupled and asynchron
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 眾賞文庫僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 企業(yè)級軟件可復(fù)用體系架構(gòu)的研究.pdf
- 企業(yè)級信息系統(tǒng)架構(gòu)設(shè)計(jì).pdf
- 采用SOA架構(gòu)構(gòu)建靈活的企業(yè)級DMS應(yīng)用.pdf
- 基于.net的企業(yè)級分布式系統(tǒng)多層架構(gòu)的研究與應(yīng)用
- 企業(yè)級應(yīng)用軟件架構(gòu)模式的研究和應(yīng)用.pdf
- 面向服務(wù)的企業(yè)級應(yīng)用開發(fā)框架的架構(gòu)與設(shè)計(jì).pdf
- 新技術(shù)應(yīng)用在企業(yè)級架構(gòu)藍(lán)圖的規(guī)劃方法研究
- 基于Worklight的企業(yè)級移動應(yīng)用架構(gòu)設(shè)計(jì)及實(shí)現(xiàn).pdf
- 企業(yè)級應(yīng)用系統(tǒng)框架的研究及其應(yīng)用.pdf
- 部署企業(yè)級操作系統(tǒng)及應(yīng)用
- 基于Spring Security的企業(yè)級應(yīng)用安全架構(gòu)的研究與實(shí)現(xiàn).pdf
- AOP在大型企業(yè)級系統(tǒng)開發(fā)中的應(yīng)用.pdf
- 企業(yè)級應(yīng)用中面向?qū)ο罂蚣艿难芯?pdf
- 企業(yè)級應(yīng)用監(jiān)控系統(tǒng)的研究和實(shí)現(xiàn).pdf
- 基于企業(yè)級WEB架構(gòu)的航運(yùn)管理系統(tǒng)設(shè)計(jì)與實(shí)現(xiàn).pdf
- 企業(yè)級應(yīng)用中軟件復(fù)用技術(shù)的研究.pdf
- 基于ruby on rails框架構(gòu)建企業(yè)級信息系統(tǒng)的研究.pdf
- finereport在企業(yè)級bi分析中應(yīng)用案例-
- 某企業(yè)級系統(tǒng)測試方法及其應(yīng)用.pdf
- 企業(yè)級信息安全體系結(jié)構(gòu)的研究與應(yīng)用.pdf
評論
0/150
提交評論