JMS 및 메시징을 직접 사용하도록 프로그래밍
엔터프라이즈 애플리케이션이 JMS(Java™ Message Service) 프로그래밍 인터페이스를 직접 사용하여 비즈니스 로직을 구현하는 메소드와 메시징 서비스를 제공할 수 있습니다.
이 태스크 정보
WebSphere® Application Server는 JMS 프로그래밍 인터페이스를 기반으로 하는 통신 방법으로 비동기 메시징을 지원합니다. JMS를 사용하면 엔터프라이즈 애플리케이션이 JMS 대상(큐 또는 토픽)을 사용하여 다른 JMS 클라이언트와 비동기식으로 메시지를 교환할 수 있습니다. 엔터프라이즈 애플리케이션은 대상의 메시지를 명시적으로 폴링할 수 있습니다.
메시징 제공자의 구성 정보를 얻기 위해 JNDI를 사용하지 않도록 선택하면(예를 들어, 연결 팩토리 또는 대상의 경우) 대신 메시징 제공자가 제공하는 API를 사용하여 해당 구성 정보를 프로그래밍 방식으로 지정할 수 있습니다.
JMS 애플리케이션과 기존 IBM MQ 애플리케이션 간에 메시지를 전송하려면 JMS 메시지 구조가 IBM MQ 메시지에 맵핑되는 방식을 고려해야 합니다. 여기에는 IBM MQ를 사용하여 두 개 JMS 애플리케이션 간에 전송되는 메시지를 조작하는 시나리오가 포함됩니다(예를 들어, IBM MQ를 메시지 브로커로 사용).
기본적으로 IBM MQ 큐에서 보류되는 JMS 메시지는 MQRFH2 헤더를 사용하여 일부 JMS 메시지 헤더 정보를 보유합니다. 많은 기존 IBM MQ 애플리케이션은 이러한 헤더가 있는 메시지를 처리할 수 없으며 자체 특성 헤더(예를 들어, IBM MQ 워크플로우 애플리케이션의 경우 MQWIH)가 필요합니다. JMS 메시지 구조가 IBM MQ 메시지에 맵핑되는 방식에 대한 자세한 정보는 IBM MQ Information Center의 JMS 메시지 맵핑 섹션을 참조하십시오.
프로시저
예
다음 예는 기본 메시징 제공자에 대한 자원을 프로그래밍 방식으로 구성하는 방법을 보여줍니다.
이 예에서 서비스 통합 버스에 대한 JMS 연결은 com.ibm.websphere.sib 패키지에서 API를 사용하여 작성됩니다. 이는 관리 방식으로 구성된 연결 팩토리를 검색하기 위해 JNDI를 사용하는 방법의 대안입니다. 연결이 설정된 후에는 샘플 프로그램이 콘솔에서 입력 행을 읽고 지정된 대상에 JMS 텍스트 메시지로 전송합니다.
이 예는 씬 클라이언트 애플리케이션 또는 독립형 클라이언트 애플리케이션으로 실행될 수 있습니다.
/*
* Sample program
* © COPYRIGHT International Business Machines Corp. 2009
* All Rights Reserved * Licensed Materials - Property of IBM
*
* This sample program is provided AS IS and may be used, executed,
* copied and modified without royalty payment by customer
*
* (a) for its own instruction and study,
* (b) in order to develop applications designed to run with an IBM
* WebSphere product for the customer's own internal use.
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import com.ibm.websphere.sib.api.jms.JmsConnectionFactory;
import com.ibm.websphere.sib.api.jms.JmsFactoryFactory;
import com.ibm.websphere.sib.api.jms.JmsQueue;
import com.ibm.websphere.sib.api.jms.JmsTopic;
/**
* Sample code to programmatically create a connection to a bus and
* send a text message.
*
* Example command lines:
* SIBusSender topic://my/topic?topicSpace=Default.Topic.Space MyBus localhost:7276
* SIBusSender queue://myQueue MyBus localhost:7286:BootstrapSecureMessaging InboundSecureMessaging
*/
public class SIBusSender {
/**
* @param args DEST_URL,BUS_NAME,PROVIDER_ENDPOINTS,[TRANSPORT_CHAIN]
*/
public static void main(String[] args) throws JMSException, IOException {
// Parse the arguments
if (args.length < 3) {
throw new IllegalArgumentException(
"Usage: SIBusSender <DEST_URL> <BUS_NAME> <PROVIDER_ENDPOINTS> [TARGET_TRANSPORT_CHAIN]");
}
String destUrl = args[0];
String busName = args[1];
String providerEndpoints = args[2];
String targetTransportChain = "InboundBasicMessaging";
if (args.length >= 4) targetTransportChain = args[3];
// Obtain the factory factory
JmsFactoryFactory jmsFact = JmsFactoryFactory.getInstance();
// Create a JMS destination
Destination dest;
if (destUrl.startsWith("topic://")) {
JmsTopic topic = jmsFact.createTopic(destUrl);
// Setter methods could be called here to configure the topic
dest = topic ;
}
else {
JmsQueue queue = jmsFact.createQueue(destUrl);
// Setter methods could be called here to configure the queue
dest = queue;
}
// Create a unified JMS connection factory
JmsConnectionFactory connFact = jmsFact.createConnectionFactory();
// Configure the connection factory
connFact.setBusName(busName);
connFact.setProviderEndpoints(providerEndpoints);
connFact.setTargetTransportChain(targetTransportChain);
// Create the connection
Connection conn = connFact.createConnection();
Session session = null;
MessageProducer producer = null;
try {
// Create a session
session = conn.createSession(false, // Not transactional
Session.AUTO_ACKNOWLEDGE);
// Create a message producer
producer = session.createProducer(dest);
// Loop reading lines of text from the console to send
System.out.println("Ready to send to " + dest + " on bus " + busName);
BufferedReader lineInput = new BufferedReader(new InputStreamReader(System.in));
String line = lineInput.readLine();
while (line != null && line.length() > 0) {
// Create a text message containing the line
TextMessage message = session.createTextMessage();
message.setText(line);
// Send the message
producer.send(message,
Message.DEFAULT_DELIVERY_MODE,
Message.DEFAULT_PRIORITY,
Message.DEFAULT_TIME_TO_LIVE);
// Read the next line
line = lineInput.readLine();
}
}
// Finally block to ensure we close our JMS objects
finally {
// Close the message producer
try {
if (producer != null) producer.close();
}
catch (JMSException e) {
System.err.println("Failed to close message producer: " + e);
}
// Close the session
try {
if (session != null) session.close();
}
catch (JMSException e) {
System.err.println("Failed to close session: " + e);
}
// Close the connection
try {
conn.close();
}
catch (JMSException e) {
System.err.println("Failed to close connection: " + e);
}
}
}
}