activeMq实例

JMS的全称是Java Message Service,即Java消息服务。它主要用于在生产者和消费者之间进行消息传递,生产者负责产生消息,而消费者负责接收消息。把它应用到实际的业务需 求中的话我们可以在特定的时候利用生产者生成一消息,并进行发送,对应的消费者在接收到对应的消息后去完成对应的业务逻辑。对于消息的传递有两种类型,一 种是点对点的,即一个生产者和一个消费者一一对应;另一种是发布/订阅模式,即一个生产者产生消息并进行发送后,可以由多个消费者进行接收。

           既然是使用的apacheactiveMQ作为JMS的实现,那么首先我们应该到apache官网上下载activeMQhttp://activemq.apache.org/download.html),进行解压后运行其bin目录下面的activemq.bat文件启动activeMQ。这里我下载的是apache-activemq-5.8.0-bin,如果下载的版本高的话,那么也要相应的升级JDK的版本,否则会报错。

           安装好以后可以访问http://localhost:8161/ ,如果可以访问,则表示安装成功。然后可以开始配置Spring了。   

 

           POM文件:

         

<dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
            <version>${spring-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring-version}</version>
        </dependency>
        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>jsr250-api</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-core</artifactId>
            <version>5.7.0</version>
        </dependency>
</dependencies>

 

 

    实例:

   

    发送消息端:

    

public class ActiveSender implements Controller{
 
	 private JmsTemplate jmsTemplate; 
	 public JmsTemplate getJmsTemplate() {
		return jmsTemplate;
	}
	public void setJmsTemplate(JmsTemplate jmsTemplate) {
		this.jmsTemplate = jmsTemplate;
	}
	public ModelAndView handleRequest(HttpServletRequest arg0,
				HttpServletResponse arg1) throws Exception {
			
	System.out.println("begin");
			MessageCreator messageCreator = new MessageCreator() {
				
				public Message createMessage(Session session) throws JMSException {
					
			    
					TextMessage message = session.createTextMessage("张悦发送一条消息");
					System.out.println("发送消息:" + "张悦 发送的消息");
			                message.setJMSPriority(7);  //消息优先级,JMS把消息分为10个等级,0-4为普通优先级,5-9为加快优先级,ActiveMQ中默认的消息优先级为4
				        return message;
				}
			};
			
			jmsTemplate.send(messageCreator);
			
			return null;
		}
	}

 

 

 

    消费者端:

   

public class ActiveReceive implements MessageListener   {
	

	 public static void main(String[] args) {
	        // ConnectionFactory :连接工厂,JMS 用它创建连接
	        ConnectionFactory connectionFactory;
	        // Connection :JMS 客户端到JMS Provider 的连接
	        Connection connection = null;
	        // Session: 一个发送或接收消息的线程
	        Session session;
	        // Destination :消息的目的地;消息发送给谁.
	        Destination destination;
	        // 消费者,消息接收者
	        MessageConsumer consumer;
	        connectionFactory = new ActiveMQConnectionFactory(
	                ActiveMQConnection.DEFAULT_USER,
	                ActiveMQConnection.DEFAULT_PASSWORD,
	                "tcp://localhost:61616");
	        try {
	            // 构造从工厂得到连接对象
	            connection = connectionFactory.createConnection();
	            // 启动
	            connection.start();
	            // 获取操作连接
	            session = connection.createSession(Boolean.FALSE,
	                    Session.AUTO_ACKNOWLEDGE);
	            // 获取session注意参数值xingbo.xu-queue是一个服务器的queue,须在在ActiveMq的console配置
	            destination = session.createQueue("zyQueue");
	            consumer = session.createConsumer(destination);
	            while (true) {
	                //设置接收者接收消息的时间,为了便于测试,这里谁定为100s
	                TextMessage message = (TextMessage) consumer.receive(100000);
	                if (null != message) {
	                    System.out.println("收到消息" + message.getText());
	                } else {
	                    break;
	                }
	            }
	        } catch (Exception e) {
	            e.printStackTrace();
	        } finally {
	            try {
	                if (null != connection)
	                    connection.close();
	            } catch (Throwable ignore) {
	            }
	        }
	    }

	public void onMessage(Message message) {
		
	    //这里我们知道生产者发送的就是一个纯文本消息,所以这里可以直接进行强制转换,或者直接把onMessage方法的参数改成Message的子类TextMessage  
        TextMessage textMsg = (TextMessage) message;   
        System.out.println("接收到一个纯文本消息。");   
        try {   
            System.out.println("消息内容是:" + textMsg.getText());   
        } catch (JMSException e) {   
            e.printStackTrace();   
        }  
		
	}



	}

 

 

    activeMq.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    
    http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
    <!--创建连接工厂-->
    <bean id="connectionFactory"
        class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL" value="tcp://localhost:61616"></property>
    </bean>
    <!-- 声明ActiveMQ消息目标,目标可以是一个队列,也可以是一个主题ActiveMQTopic-->
    <bean id="destination" class="org.apache.activemq.command.ActiveMQQueue">
        <constructor-arg index="0" value="zyQueue"></constructor-arg>
    </bean>
    <!---->
    <bean id="JmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory" ref="connectionFactory"></property>
        <property name="defaultDestination" ref="destination"></property>
        <property name="receiveTimeout" value="600"></property>

    </bean>

    <!-- 消息监听器 -->  
    <bean id="consumerMessageListener" class="org.huodong.action.ActiveReceive"/>       
      
    <!-- 消息监听容器 -->  
    <bean id="jmsContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">  
        <property name="connectionFactory" ref="connectionFactory" />  
        <property name="destination" ref="destination" />  
        <property name="messageListener" ref="consumerMessageListener" />  
    </bean>
    
    </beans>  

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值