消息中间件的代码实现
JMS编码接口:
ConnectionFaction:用于创建连接到消息中间件的连接工厂。
Connection:代表应用程序和消息服务器之间的通信链路。
Destination:指消息发布和接受的地点,包括队列和主题。
Session:表示一个单线程的上下文,用于发送和接受消息。
MessageConsumer:由会话创建,用于接收发送到目标的消息。
MessageProducer:由会话创建,用于发送消息到目标。
Message:指在消费者和生产者之间传送的对象,消息头,一组消息属性,一个消息体。
一、队列模式
1、生产者代码
package com.yuwei.jms.queue;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class AppProducer {
private static final String url="tcp://169.254.147.233:61616";//本机就直接使用localhost即可
private static final String queueName="queue-test";
public static void main(String[] args) throws JMSException, UnknownHostException {
getLocalhsot();
//1、创建连接工厂
ConnectionFactory connectionFactory=new ActiveMQConnectionFactory(url);
//2、由连接工厂创建连接
Connection connection=connectionFactory.createConnection();
//3、打开连接
connection.start();
//4、由连接创建会话对象
Session session=connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
//5、会话对象创建目的地址队列
Destination destination=session.createQueue(queueName);
//6、会话对象创建消息提供者
MessageProducer producer=session.createProducer(destination);
for (int i=0;i<100;i++){
//7、创建消息
TextMessage textMessage=session.createTextMessage("test"+i);
//8、消息提供者发送消息
producer.send(textMessage);
System.out.println("发送消息"+textMessage.getText());
}
//9、关闭连接
connection.close();
}
public static void getLocalhsot() throws UnknownHostException {
String localhost= InetAddress.getLocalHost().getHostAddress();
System.out.println("localhost"+localhost);
}
}
2.消费者代码
package com.yuwei.jms.queue;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
public class AppConsumer {
private static final String url="tcp://169.254.147.233:61616";//本机就直接使用localhost即可
private static final String queueName="queue-test";
public static void main(String[] args) throws JMSException {
//1、创建连接工厂
ConnectionFactory connectionFactory=new ActiveMQConnectionFactory(url);
//2、由连接工厂创建连接
Connection connection=connectionFactory.createConnection();
//3、打开连接
connection.start();
//4、由连接创建会话对象
Session session=connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
//5、会话对象创建目的地址队列
Destination destination=session.createQueue(queueName);
//6、会话对象创建消息消费者
MessageConsumer consumer=session.createConsumer(destination);
//7、创建监听器
consumer.setMessageListener(new MessageListener() {
public void onMessage(Message message) {
TextMessage textMessage=(TextMessage)message;
try {
System.out.println("接收到的信息为:"+textMessage.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
});
//connection.close();
}
}