JMS可以建立发送和接受消息的程序.消息是在java程序或组件之间传递的信息,可以是文本,也可以是其他类型如某个类的对象。涉及到多个系统协作或者处理开销较高的,且不希望耦合度太紧密的,就会考虑用JMS来作为接口。
在下列情况下应该考虑使用JMS而不是其他的消息处理机制:
1.消息的发送者和接受者不需要依赖对方的接口
2.消息的发送者和接受者不需要对方同时在运行
3.消息的发送者不需要接收者立刻应答
JMS消息传送分为point to point(点对点)和publish/subscribe(出版/预定)两种
JMS用来做什么:
用JMS来异步发送邮件,还可以用JMS来解决很多复杂的问题,例如 分布,并发,系统解耦,负载均衡,热部署,触发器等等,这些复杂问题因为引入JMS而变的更加简单.下面简单介绍下解决分布,并发问题的场景.
1.pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.samples</groupId>
<artifactId>spring-jms-activemq-send</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<!-- Spring version -->
<spring-framework.version>4.1.0.RELEASE</spring-framework.version>
<!-- ActiveMQ version -->
<activemq.version>5.10.0</activemq.version>
</properties>
<dependencies>
<!-- Spring aritifacts -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- ActiveMQ Artifacts -->
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-spring</artifactId>
<version>${activemq.version}</version>
</dependency>
</dependencies>
<!-- Using JDK 1.7 for compiling -->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
2. Message Sender和消费者Listener
package com.deppon.test04.jms;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
@Service
public class JmsMessageSender {
@Autowired
private JmsTemplate jmsTemplate;
/**
* send text to default destination
* @param text
*/
public void send(final String text) {
this.jmsTemplate.send(new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
Message message = session.createTextMessage(text);
//set ReplyTo header of Message, pretty much like the concept of email.
message.setJMSReplyTo(new ActiveMQQueue("Recv2Send"));
return message;
}
});
}
/**
* Simplify the send by using convertAndSend
* @param text
*/
public void sendText(final String text) {
this.jmsTemplate.convertAndSend(text);
}
/**
* Send text message to a specified destination
* @param text
*/
public void send(final Destination dest,final String text) {
this.jmsTemplate.send(dest,new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
Message message = session.createTextMessage(text);
return message;
}
});
}
}
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
public class ConsumerMessageListener implements MessageListener {
public void onMessage(Message message) {
//这里我们知道生产者发送的就是一个纯文本消息,所以这里可以直接进行强制转换
TextMessage textMsg = (TextMessage) message;
System.out.println("接收到一个纯文本消息。");
try {
System.out.println("消息内容是:" + textMsg.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
}
3. Message Main函数:
package com.deppon.test04.jms;
import javax.jms.Queue;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class DemoMain {
public static void main(String[] args) {
// init spring context
ApplicationContext ctx = new ClassPathXmlApplicationContext("/applicationContext.xml");
// BeanFactory ctx = new ClassPathXmlApplicationContext("/applicationContext.xml");
// get bean from context
JmsMessageSender jmsMessageSender = (JmsMessageSender)ctx.getBean("jmsMessageSender");
// send to default destination
jmsMessageSender.send("hello JMS");
// send to a code specified destination
Queue queue = new ActiveMQQueue("AnotherDest");
jmsMessageSender.send(queue, "hello Another Message");
// close spring application context
((ClassPathXmlApplicationContext)ctx).close();
}
}
4.applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.deppon.test04.jms" />
<!-- JMS -->
<bean id="jmsMessageSender" class="com.deppon.test04.jms.JmsMessageSender"> </bean>
<!-- =============================================== -->
<!-- JMS Common, Define JMS connectionFactory -->
<!-- =============================================== -->
<!-- Activemq connection factory -->
<bean id="amqConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<!-- brokerURL, You may have different IP or port -->
<constructor-arg index="0" value="tcp://10.182.105.30:61616" />
<!-- <constructor-arg index="0" value="tcp://localhost:8161" />-->
</bean>
<!-- Pooled Spring connection factory -->
<bean id="connectionFactory"
class="org.springframework.jms.connection.CachingConnectionFactory">
<constructor-arg ref="amqConnectionFactory" />
</bean>
<!-- ======================================================= -->
<!-- JMS Send, define default destination and JmsTemplate -->
<!-- ======================================================= -->
<!-- Default Destination Queue Definition -->
<bean id="defaultDestination" class="org.apache.activemq.command.ActiveMQQueue">
<!-- name of the queue -->
<constructor-arg index="0" value="Send2Recv" />
</bean>
<!-- JmsTemplate Definition -->
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="connectionFactory" />
<property name="defaultDestination" ref="defaultDestination" />
</bean>
<!-- 消息监听器 -->
<bean id="consumerMessageListener" class="com.deppon.test04.jms.ConsumerMessageListener"/>
<!-- 消息监听容器 -->
<bean id="jmsContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory" />
<property name="destination" ref="defaultDestination" />
<property name="messageListener" ref="consumerMessageListener" />
</bean>
</beans>
5.下载ActiveMQ,并点击..\apache-activemq-5.9.0\bin\win64\activemq.bat启动MQ
http://activemq.apache.org/activemq-590-release.html
6.可以通过http://localhost:8161/index.html下的“Manage ActiveMQ broker”查看当前的Broker信息,例如地址、端口号等
http://localhost:8161/hawtio/#/jmx/attributes?tab=activemq&nid=root-org.apache.activemq-Broker-localhost
7.可以在eclispe下运行main函数,也可以在命令行下运行命令:
--------------------------------------------------------
cd 当前项目,例如c:\workspace\SpringWeb
mvn exec:java -Dexec.mainClass="com.deppon.test04.jms.DemoMain"
8.可以登入admin页面,访问“Queue Views”,用户名密码默认为admin,可以看到
<queues>
<queue name="Send2Recv">
<stats size="4" consumerCount="0" enqueueCount="4" dequeueCount="0"/>
<feed>
<atom>queueBrowse/Send2Recv?view=rss&feedType=atom_1.0</atom>
<rss>queueBrowse/Send2Recv?view=rss&feedType=rss_2.0</rss>
</feed>
</queue>
<queue name="AnotherDest">
<stats size="4" consumerCount="0" enqueueCount="4" dequeueCount="0"/>
<feed>
<atom>queueBrowse/AnotherDest?view=rss&feedType=atom_1.0</atom>
<rss>queueBrowse/AnotherDest?view=rss&feedType=rss_2.0</rss>
</feed>
</queue>
</queues>
控制台输出结果:
接收到一个纯文本消息。
消息内容是:hello JMS
接收到一个纯文本消息。
消息内容是:hello JMS
接收到一个纯文本消息。
消息内容是:hello JMS
接收到一个纯文本消息。
消息内容是:hello JMS
接收到一个纯文本消息。
消息内容是:hello JMS
9.junit测试类:
import javax.jms.Destination;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/applicationContext.xml")
public class ProducerConsumerTest {
@Autowired
private JmsMessageSender producerService;
@Autowired
@Qualifier("defaultDestination")
private Destination destination;
@Test
public void testSend() {
for (int i=0; i<2; i++) {
producerService.send(destination, "你好,生产者!这是消息:" + (i+1));
}
}
}
参考:
http://shengwangi.blogspot.jp/2014/10/spring-jms-with-activemq-helloworld-example-send.html
http://haohaoxuexi.iteye.com/blog/1893038
https://spring.io/guides/gs/messaging-jms/
http://activemq.apache.org/jms.html
http://www.cnblogs.com/huang0925/p/3558690.html
http://www.javacodegeeks.com/2015/04/configure-a-spring-jms-application-with-spring-boot-and-annotation-support.html
http://itindex.net/detail/49721-jms-jms-%E5%BA%94%E7%94%A8 JMS的应用
Spring JMS和ActiveMQ
猜你喜欢
转载自yys19781104.iteye.com/blog/2267145
今日推荐
周排行