zoukankan      html  css  js  c++  java
  • Java Messages Synchronous and Asynchronous

    //The Consumer Class Consumes Messages in a Synchronous Manner
    
    public class Consumer {
    public static void main(String[] args) {
    try {
    // Gets the JNDI context
    Context jndiContext = new InitialContext();
    // Looks up the administered objects
    ConnectionFactory connectionFactory = (ConnectionFactory) 
    jndiContext.lookup("jms/javaee7/ConnectionFactory");
    Destination queue = (Destination) jndiContext.lookup("jms/javaee7/Queue");
    // Loops to receive the messages
    try (JMSContext context = connectionFactory.createContext()) {
    while (true) {
    String message = context.createConsumer(queue).receiveBody(String.class);
    }
    }
    } catch (NamingException e) {
    e.printStackTrace();
    }
    }
    }
    //The Consumer Is a Message Listener
    
    public class Listener implements MessageListener {
    public static void main(String[] args) {
    try {
    // Gets the JNDI context
    Context jndiContext = new InitialContext();
    // Looks up the administered objects
    ConnectionFactory connectionFactory = (ConnectionFactory) 
    jndiContext.lookup("jms/javaee7/ConnectionFactory");
    Destination queue = (Destination) jndiContext.lookup("jms/javaee7/Queue");
    try (JMSContext context = connectionFactory.createContext()) {
    context.createConsumer(queue).setMessageListener(new Listener());
    }
    } catch (NamingException e) {
    e.printStackTrace();
    }
    }
    public void onMessage(Message message) {
    System.out.println("Async Message received: " + message.getBody(String.class));
    }
    }
  • 相关阅读:
    apio2018题解
    ynoi2018
    hdu2036
    Morley's Theorem
    计算几何
    luogu1355 神秘大三角
    poj2398
    洛谷---小L和小K的NOIP考后放松赛
    LibreOJ β Round #7
    python3
  • 原文地址:https://www.cnblogs.com/rojas/p/5310745.html
Copyright © 2011-2022 走看看