消息中间件
作用:解耦 削峰 异步
JMS编码总体架构:
一般代码流程
@Test public void test1(){ //创建连接工厂 ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(MQ_URL); try { Connection connection = factory.createConnection(); connection.start(); //创建会话session Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE); //创建目的地(具体是队列还是主题) Queue queue = session.createQueue("myFirstQueue"); //创建消息的生产者 MessageProducer producer = session.createProducer(queue); for (int i = 0; i < 3; i++) { //创建消息 TextMessage message = session.createTextMessage("hello--->"+i); //通过消息生产者发送消息至mq producer.send(message); } producer.close(); session.close(); connection.close(); }catch (Exception e){ e.printStackTrace(); } System.out.println("********************"); }
@Test public void test2(){ //创建连接工厂 ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(MQ_URL); try { Connection connection = factory.createConnection(); connection.start(); //创建会话session Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE); //创建目的地(具体是队列还是主题) Queue queue = session.createQueue("myFirstQueue"); //创建消息的消费者 MessageConsumer consumer = session.createConsumer(queue); for (int i = 0; i < 3; i++) { TextMessage message = (TextMessage)consumer.receive(); //阻塞式接收 if(message!=null){ System.out.println("receive---->"+message.getText()); } }
//监听器式接收
consumer.setMessageListener((Message message) -> {
if (message != null && message instanceof TextMessage) {
try {
System.out.println(((TextMessage) message).getText());
} catch (Exception e) {
e.printStackTrace();
}
}
});
consumer.close(); session.close(); connection.close(); }catch (Exception e){ e.printStackTrace(); } System.out.println("********************"); }
consumer.setMessageListener((Message message) -> {
if (message != null && message instanceof TextMessage) {
try {
System.out.println(((TextMessage) message).getText());
} catch (Exception e) {
e.printStackTrace();
}
}
});