天易48----Springmvc结合rabbitmq简单示例

本文介绍如何在Spring框架下搭建RabbitMQ消息队列服务,包括依赖配置、发送端与接收端代码示例,并演示了从消息发送到接收的全过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一:rabbitmq的服务安装步骤这里就省略了,网上参考教程很多,在开发之前需要导入一下rabbitmq与Spring的依赖包:


如果是maven架构,可以在pom.xml文件中添加如下配置:

<dependency>
    <groupId>com.rabbitmq</groupId>
    <artifactId>amqp-client</artifactId>
    <version>4.2.0</version>
</dependency>
<dependency>
    <groupId>org.springframework.amqp</groupId>
    <artifactId>spring-rabbit</artifactId>
    <version>1.4.5.RELEASE</version>
</dependency>

在加载的文件中需导入rabbitmq的发送端与接收端配置(我这里是在application-context.xml配置文件中引进也可直接在web.xml中直接引进),如下:

application-context.xml文件中引进,web.xml文件中已经引进加载application-context.xml配置

<import resource="application-rabbitProduce.xml"/>
<import resource="application-rabbitConsume.xml"/>

或在web.xml文件中,如下图中箭头指向方向的位置添加引进上述两个文件:



二:rabbitmq发送端代码:

1)发送端application-rabbitProduce.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:rabbit="http://www.springframework.org/schema/rabbit"
       xmlns:context="http://www.springframework.org/schema/context"  
       xsi:schemaLocation="http://www.springframework.org/schema/beans    
                        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 
                        http://www.springframework.org/schema/context    
                        http://www.springframework.org/schema/context/spring-context-4.0.xsd 
				        http://www.springframework.org/schema/rabbit  
				        http://www.springframework.org/schema/rabbit/spring-rabbit-1.4.xsd"> 
    
    <!-- 定义连接工厂,用于创建连接等 -->
    <rabbit:connection-factory id="connectionFactory" username="ty" password="ty" host="192.168.120.154" port="5672"/>
    
    <!-- 定义admin,producer中的exchange,queue会自动的利用该admin自动在spring中生成 -->
    <rabbit:admin connection-factory="connectionFactory"/>
    
    <!-- 定义rabbitmq模板,用于接收以及发送消息 -->
    <rabbit:template id="amqpTemplate" connection-factory="connectionFactory" exchange="hjexchange" routing-key="wzh"/>
    
    <!-- 利用admin来定义队列,spring会自动根据下面的定义创建队列 
    	队列名	是否持久化	是否是排他队列	不使用的时候是否删除	-->
    <rabbit:queue name="com.ty.test" auto-delete="false" durable="true" exclusive="false" auto-declare="true"/>
	
	<!-- 定义Exchange,并且将队列与Exchange绑定,设定Routing Key -->
	<!-- name为Echange的name -->
	<rabbit:direct-exchange name="hjexchange" durable="true" auto-delete="false">
		<rabbit:bindings>
			<rabbit:binding key="com.ty.test" queue="com.ty.test"></rabbit:binding>
		</rabbit:bindings>
	</rabbit:direct-exchange>
	
</beans>
2)发送端controller类,这里我用了get方式接收,实际应用中用post方式:

package com.jy.app.controller.mobile.rabbitmq;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jy.app.controller.mobile.aop.User;

@Controller
@RequestMapping("/rabbitmq")
public class RabbitmqController {

	@Resource  
    	private MessageProducer messageProducer; 
	
	@RequestMapping(value="/rabbitmqSend",method = RequestMethod.GET)
	@ResponseBody
	public Map<String,Object> rabbitmqSend(HttpServletRequest request,HttpServletResponse response,
			User user,String name){
			String message = name;
			Map<String,Object> map=new HashMap<String,Object>();
	        map.put("info", message);
	        messageProducer.send(message);
		return map;
	}
	

}
3)MessageProducer

package com.jy.app.controller.mobile.rabbitmq;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.jy.app.controller.mobile.aop.User;
/**
 * 通过调用rabbitmq AmqpTemplate对象发送消息
 * @author Administrator
 *
 */

@Service
public class MessageProducer {
private Logger log = Logger.getLogger(MessageProducer.class);
	
	@Resource
	private AmqpTemplate amqpTemplate;
	
	public void send(Object message) {
		log.info("发送消息为 : " + message);
		Gson gson=new Gson();
		User user=new User();
		user.setName("ty");
		user.setAge("27");
		amqpTemplate.convertAndSend("com.ty.test", gson.toJson(user));
	}
}
4)在没有引进rabbitmq接收文件时,页面输入访问地址:http://localhost:8082/StanClaimProd-app/rabbitmq/rabbitmqSend?name=wzh,输入如下地址:http://localhost:15672(输入登录名和密码)查看rabbitmq页面端,效果图如下:(可以看出队列中已有一条数据)


三:rabbitmq接收端代码:

1)接收端application-rabbitConsume.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:rabbit="http://www.springframework.org/schema/rabbit"
       xmlns:context="http://www.springframework.org/schema/context"  
       xsi:schemaLocation="http://www.springframework.org/schema/beans    
                        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 
                        http://www.springframework.org/schema/context    
                        http://www.springframework.org/schema/context/spring-context-4.0.xsd 
				        http://www.springframework.org/schema/rabbit  
				        http://www.springframework.org/schema/rabbit/spring-rabbit-1.4.xsd"> 
    
    <!-- 定义连接工厂,用于创建连接等 -->
    <rabbit:connection-factory id="connectionFactory" username="ty" password="ty" host="192.168.120.154" port="5672"/>
    
    <!-- 定义admin,producer中的exchange,queue会自动的利用该admin自动在spring中生成 -->
    <rabbit:admin connection-factory="connectionFactory"/>
    
    <!-- 利用admin来定义队列,spring会自动根据下面的定义创建队列 
    	队列名	是否持久化	是否是排他队列	不使用的时候是否删除	-->
    <rabbit:queue name="com.ty.test" auto-delete="false" durable="true" exclusive="false" auto-declare="true"/>
	
	<!-- 定义Exchange,并且将队列与Exchange绑定,设定Routing Key -->
	<!-- name为Echange的name -->
	<rabbit:direct-exchange name="hjexchange" durable="true" auto-delete="false">
		<rabbit:bindings>
			<rabbit:binding key="com.ty.test" queue="com.ty.test"></rabbit:binding>
		</rabbit:bindings>
	</rabbit:direct-exchange>
	
	<!-- 定义消费者,消费消息 -->
	<bean id="directConsumer" class="com.jy.app.controller.mobile.rabbitmq.DirectConsumer"></bean>
	
	<!--开启监听,也可以理解为: 
		将消费者与队列进行绑定,这样就会在,当队列有消息的时候,会由绑定的消费者来进行消费,
		也可以算是指定消费者来监听指定的队列.当有消息到达的时候,通知消费者进行消费 -->
	<rabbit:listener-container connection-factory="connectionFactory">
		<!-- 注入bean,指定队列 -->
		<rabbit:listener ref="directConsumer" queues="com.ty.test"/>
	</rabbit:listener-container>	
		
</beans>
2)接收端代码,该类实现rabbitmq MessageListener接口:

package com.jy.app.controller.mobile.rabbitmq;

import java.io.UnsupportedEncodingException;

import org.apache.log4j.Logger;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.jy.app.controller.mobile.aop.User;

/**
 * rabbitmq接收推送的数据
 * @author Administrator
 *
 */
@Service
public class DirectConsumer implements MessageListener {

	private Logger log = Logger.getLogger(DirectConsumer.class);
	
	public DirectConsumer(){
		log.info("===DirectConsumer====");
	}
	@Override
	public void onMessage(Message message) {
		// TODO Auto-generated method stub
		Gson gson=new Gson();
		log.info("------> DirectConsumer 接收到的消息为 : " + message);
		try {
			log.info("===endDat===="+ new String(message.getBody(),"UTF-8"));
			String data=new String(message.getBody(),"UTF-8");
			User user=gson.fromJson(data, User.class);
			log.info("===endDat===="+user.getAge()+"====="+user.getName());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
3)将之前注释掉的接收端配置文件代码放开后,再执行http://localhost:8082/StanClaimProd-app/rabbitmq/rabbitmqSend?name=wzh,输入如下地址:http://localhost:15672(输入登录名和密码)查看rabbitmq页面端,效果图如下(图中的队列信息已经被取出):
3)后台队列获取数据打印的log日志如下:

2017-08-07 15:59:11,423 INFO  - 发送消息为 : wzh
2017-08-07 15:59:11,482 INFO  - ------> DirectConsumer 接收到的消息为 : (Body:'{"name":"ty","age":"27"}'MessageProperties [headers={}, timestamp=null, messageId=null, userId=null, appId=null, clusterId=null, type=null, correlationId=null, replyTo=null, contentType=text/plain, contentEncoding=UTF-8, contentLength=0, deliveryMode=PERSISTENT, expiration=null, priority=0, redelivered=false, receivedExchange=hjexchange, receivedRoutingKey=com.ty.test, deliveryTag=1, messageCount=0])
2017-08-07 15:59:11,483 INFO  - ===endDat===={"name":"ty","age":"27"}
2017-08-07 15:59:11,488 INFO  - ===endDat====27=====ty



评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值