💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
~~~ import org.apache.activemq.ActiveMQConnectionFactory; import javax.jms.*; public class TextConsumer { public String receiveTextMessage(){ String resultCode = ""; ConnectionFactory factory = null; Connection connection = null; Session session = null; Destination destination = null; // 消息的消费者,用于接受消息的对象 MessageConsumer consumer = null; Message message = null; try { factory = new ActiveMQConnectionFactory("admin", "admin", "tcp://114.116.69.58:61616"); connection = factory.createConnection(); //消费者必须启动连接,否则无法处理消息 connection.start(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); destination = session.createQueue("first-mq"); //创建消息消费者对象,在指定的目的地中获取消息 consumer = session.createConsumer(destination); //获取队列中的消息 message = consumer.receive(); //处理文本消息 resultCode = ((TextMessage)message).getText(); //System.in.read(); }catch (Exception e){ e.printStackTrace(); }finally { if (consumer != null){ try { consumer.close(); } catch (JMSException e) { e.printStackTrace(); } } if (session != null){ try { session.close(); } catch (JMSException e) { e.printStackTrace(); } } if (connection != null){ try { connection.close(); } catch (JMSException e) { e.printStackTrace(); } } } return resultCode; } public static void main(String[] args) { TextConsumer textConsumer = new TextConsumer(); String s = textConsumer.receiveTextMessage(); System.out.println(s); } } ~~~ ~~~ consumer = session.createConsumer(destination); //注册监听器,注册成功后,队列中的消息变化会自动触发监听器代码,接收消息并处理 consumer.setMessageListener(new MessageListener() { /** * 监听器一旦注册,永久有效,consumer线程不关闭 * 只要有消息未处理,自动调用onMessage方法处理消息 * 监听器可以注册多个,注册多个监听器,相当于集群 * ActiveMQ自动的循环调用多个监听器,处理队列中的消息,实现并行处理 */ @Override public void onMessage(Message message) { try { // ObjectMessage om = (ObjectMessage)message; // Object data = om.getObject(); // System.out.println(data); } catch (Exception e) { e.printStackTrace(); } } }); System.in.read(); ~~~