消息中间键(ActiveMQ)

1. 消息服务概述

1.1 优点

  • 耦合
  • 异步
  • 削峰

1.2 JMS

  • JMS:Java针对消息机制提出的一套规范
  • ActiveMQ:是JMS一种实现

1.3 消息正文格式

  • TextMessage:字符串
  • MapMessage:Map类型
  • ObjectMessage:序列化对象
  • BytesMessage:字节数据
  • StreamMessage:原始流对象

1.4 两种消息类型

  • 点对点
  1. 一个消息的生产者对应一个消费者
  2. 如果当前的消费方不存在,那么消息就会存储在消息队列中.
  • 发布/订阅
  1. 一个消息的消息生产者可以对应多个消费者
  2. 如果当前的消费方不存在,那么消息就会过期了

2.JMS原生开发

2.1 点对点

2.1.1 消息生产者
//1.创建连接工厂
ConnectionFactory connectionFactory=new ActiveMQConnectionFactory("tcp://IP地址:端口号");
//2.创建连接
Connection connection = connectionFactory.createConnection();
//3.启动连接
connection.start();
//4.获取session(会话对象)  参数1:是否启动事务  参数2:消息确认方式
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//5.创建队列对象
Queue queue = session.createQueue("test-queue");		//消息对象
//6.创建消息生产者对象
MessageProducer producer = session.createProducer(queue);
//7.创建消息对象(文本消息)
TextMessage textMessage = session.createTextMessage("消息测试");
//8.发送消息
producer.send(textMessage);

//9.关闭资源
producer.close();
session.close();
connection.close();
2.1.2 消息消费者
//1.创建连接工厂
ConnectionFactory connectionFactory=new ActiveMQConnectionFactory("tcp://IP地址:端口号");
//2.创建连接
Connection connection = connectionFactory.createConnection();
//3.启动连接
connection.start();
//4.获取session(会话对象)  参数1:是否启动事务  参数2:消息确认方式
final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//5.创建队列对象
Queue queue = session.createQueue("test-queue");

//6.创建消息消费者对象
MessageConsumer consumer = session.createConsumer(queue);

//7.设置监听
consumer.setMessageListener(new MessageListener() {
	public void onMessage(Message message) {
		TextMessage textMessage=(TextMessage)message;
		try {
			System.out.println("提取的消息:"+ textMessage.getText() );
			textMessage.acknowledge();
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}
});
//8.等待键盘输入
System.in.read();


//9.关闭资源
//session.close();
//connection.close();

2.2 发布订阅

消息生产者
//1.创建连接工厂
ConnectionFactory connectionFactory=new ActiveMQConnectionFactory("tcp://ip地址:端口号");
//2.创建连接
Connection connection = connectionFactory.createConnection();
//3.启动连接
connection.start();
//4.获取session(会话对象)  参数1:是否启动事务  参数2:消息确认方式
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//5.创建主题对象
Topic topic = session.createTopic("test-topic");		
//6.创建消息生产者对象
MessageProducer producer = session.createProducer(topic);
//7.创建消息对象(文本消息)
TextMessage textMessage = session.createTextMessage("测试消息");
//8.发送消息
producer.send(textMessage);
//9.关闭资源
producer.close();
session.close();
connection.close();
消息消费者
//1.创建连接工厂
ConnectionFactory connectionFactory=new ActiveMQConnectionFactory("tcp://IP地址:端口号");
//2.创建连接
Connection connection = connectionFactory.createConnection();
//3.启动连接
connection.start();
//4.获取session(会话对象)  参数1:是否启动事务  参数2:消息确认方式
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//5.创建主题对象
Topic topic = session.createTopic("test-topic");		
//6.创建消息消费者对象
MessageConsumer consumer = session.createConsumer(topic);
//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();
		}
		
	}
});
//8.等待键盘输入
System.in.read();

//9.关闭资源
consumer.close();
session.close();
connection.close();

3. SpringJMS

3.1 点对点

消息生产者
  • spring配置文件
<context:component-scan base-package="cn.corn.demo"></context:component-scan> 

<!-- 真正可以产生Connection的ConnectionFactory,由对应的 JMS服务厂商提供-->  
<bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">  
    <property name="brokerURL" value="tcp://IP地址:端口号"/>  
</bean>
   
<!-- Spring用于管理真正的ConnectionFactory的ConnectionFactory -->  
<bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">  
    <property name="targetConnectionFactory" ref="targetConnectionFactory"/>
</bean>  
	   
<!-- Spring提供的JMS工具类,它可以进行消息发送、接收等 -->  
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">  
    <property name="connectionFactory" ref="connectionFactory"/>
</bean> 

<!--这个是队列目的地,点对点的  文本信息-->  
<bean id="queueTextDestination" class="org.apache.activemq.command.ActiveMQQueue">  
    <constructor-arg value="queue_text"/>  
</bean>    
  • 生产者
@Component
public class QueueProducer {
	@Autowired
	private JmsTemplate jmsTemplate;
	@Autowired
	private Destination queueTextDestination;		//消息类型
	
	/**
	 * 发送文本消息
	 * @param text
	 */
	public void sendTextMessage(final String text){
		jmsTemplate.send(queueTextDestination, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				return session.createTextMessage(text);
			}
		});
	}
}
  • 测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext-jms-producer.xml")
public class TestQueue {

	@Autowired
	private  QueueProducer queueProducer;
	
	@Test
	public void testSend(){
		queueProducer.sendTextMessage("spring JMS 点对点");
	}
}
消息消费者
  • spring配置文件
<!-- 真正可以产生Connection的ConnectionFactory,由对应的 JMS服务厂商提供-->  
<bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">  
    <property name="brokerURL" value="tcp://IP地址:端口号"/>  
</bean>
   
<!-- Spring用于管理真正的ConnectionFactory的ConnectionFactory -->  
<bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">  
    <property name="targetConnectionFactory" ref="targetConnectionFactory"/>  
</bean>  

<!--这个是队列目的地,点对点的  文本信息-->  
<bean id="queueTextDestination" class="org.apache.activemq.command.ActiveMQQueue">  
    <constructor-arg value="queue_text"/>  
</bean>    

<!-- 我的监听类 -->
<bean id="myMessageListener" class="cn.corn.demo.MyMessageListener"></bean>

<!-- 消息监听容器 -->
<bean class="org.springframework.jms.listener.DefaultMessageListenerContainer">
	<property name="connectionFactory" ref="connectionFactory" />
	<property name="destination" ref="queueTextDestination" />
	<property name="messageListener" ref="myMessageListener" />
</bean>
  • 消费者监听器
public class MyMessageListener implements MessageListener {

	public void onMessage(Message message) {
		
		TextMessage textMessage=(TextMessage)message;
		try {
			System.out.println("接收到消息:"+textMessage.getText());
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
  • 测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext-jms-consumer-queue.xml")
public class TestQueue {

	@Test
	public void testQueue(){
		try {
			System.in.read();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

3.2 发布/订阅

消息生产者
  • Spring配置文件
<context:component-scan base-package="cn.corn.demo"></context:component-scan>     

<!-- 真正可以产生Connection的ConnectionFactory,由对应的 JMS服务厂商提供-->  
<bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">  
    <property name="brokerURL" value="tcp://IP地址:端口号"/>  
</bean>
   
<!-- Spring用于管理真正的ConnectionFactory的ConnectionFactory -->  
<bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">  
    <property name="targetConnectionFactory" ref="targetConnectionFactory"/>
</bean>  
	   
<!-- Spring提供的JMS工具类,它可以进行消息发送、接收等 -->  
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">   
    <property name="connectionFactory" ref="connectionFactory"/>
</bean>      

<!--这个是订阅模式  文本信息-->  
<bean id="topicTextDestination" class="org.apache.activemq.command.ActiveMQTopic">  
    <constructor-arg value="topic_text"/>  
</bean>  
  • 消息生产者
@Component
public class TopicProducer {

	@Autowired
	private JmsTemplate jmsTemplate;
	
	@Autowired
	private Destination topicTextDestination;
	
	/**
	 * 发送文本消息
	 * @param text
	 */
	public void sendTextMessage(final String text){
		jmsTemplate.send(topicTextDestination, new MessageCreator() {
			
			public Message createMessage(Session session) throws JMSException {
				return session.createTextMessage(text);
			}
		});	
	}	
}
  • 测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext-jms-producer.xml")
public class TestTopic {

	@Autowired
	private  TopicProducer topicProducer;
	
	@Test
	public void testSend(){
		topicProducer.sendTextMessage("spring JMS 发布订阅");
	}	
}
消息消费者
  • Spring配置文件
<!-- 真正可以产生Connection的ConnectionFactory,由对应的 JMS服务厂商提供-->  
<bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">  
    <property name="brokerURL" value="tcp://IP地址:端口号"/>  
</bean>
   
<!-- Spring用于管理真正的ConnectionFactory的ConnectionFactory -->  
<bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">  
    <property name="targetConnectionFactory" ref="targetConnectionFactory"/>  
</bean>  

<!--这个是队列目的地,点对点的  文本信息-->  
<bean id="topicTextDestination" class="org.apache.activemq.command.ActiveMQTopic">  
    <constructor-arg value="topic_text"/>  
</bean>    

<!-- 我的监听类 -->
<bean id="myMessageListener" class="cn.corn.demo.MyMessageListener"></bean>

<!-- 消息监听容器 -->
<bean class="org.springframework.jms.listener.DefaultMessageListenerContainer">
	<property name="connectionFactory" ref="connectionFactory" />
	<property name="destination" ref="topicTextDestination" />
	<property name="messageListener" ref="myMessageListener" />
</bean>
  • 消费者监听器
public class MyMessageListener implements MessageListener {
	public void onMessage(Message message) {
		
		TextMessage textMessage=(TextMessage)message;
		try {
			System.out.println("接收到消息:"+textMessage.getText());
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
  • 测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext-jms-consumer-topic.xml")
public class TestTopic {

	@Test
	public void testTopic(){
		try {
			System.in.read();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值