天天看點

EJB : Message-Driven-Bean

SERVER端(相當于消費者):

@MessageDriven(

activationConfig ={

// javax.jms.Queue (p2p) 或者 javax.jms.Topic

@ActivationConfigProperty(propertyName = "destinationType" , propertyValue = "javax.jms.Queue"),

@ActivationConfigProperty(propertyName = "destination" , propertyValue = "queue/myqueue")

}

)

public class MyQueueMDBBean implements MessageListener {

public void onMessage(Message msg) {

TextMessage tmx = (TextMessage) msg;

System.out.println(tmx.toString());

}

CLIENT端(相當于釋出者):

public class Main {

public static void main(String[] args) throws NamingException, JMSException {

InitialContext context = new InitialContext();

// 獲得Destination對象 如果要用Topic把所有的Queue替換成Topic

Queue queue = (Queue)context.lookup("queue/myqueue");

// 獲得QueueConnectionFactory對象

QueueConnectionFactory factory = (QueueConnectionFactory) context.lookup("ConnectionFactory");

// 建立QueueConnection對象

QueueConnection connection = factory.createQueueConnection();

// 建立QueueSession對象(agrs1:是否需要事物,agrs2:模型)

QueueSession session = connection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);

// 建立TextMessage并指派

TextMessage tms = session.createTextMessage();

tms.setText("hello world!");

// 建立發送者,指定發送對象。TopicPublisher

QueueSender qSender = session.createSender(queue);

//發送

qSender.send(tms);

}