一、开启rabbitMQ服务,导入MQ jar包和gson jar包(MQ默认的是jackson,但是效率不如Gson,所以我们用gson)

二、发送端配置,在spring配置文件中配置

<?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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd">

 <!-- 连接服务配置 如果MQ服务器在远程服务器上,请新建用户用新建的用户名密码  guest默认不允许远程登录-->
<rabbit:connection-factory id="connectionFactory"
host="localhost" username="guest" password="guest" port="5672"
virtual-host="/" channel-cache-size="5" />
<!-- 配置爱admin,自动根据配置文件生成交换器和队列,无需手动配置 -->
<rabbit:admin connection-factory="connectionFactory" /> <!-- queue 队列声明 -->
<rabbit:queue durable="true"
auto-delete="false" exclusive="false" name="spring.queue.tag" /> <!-- exchange queue binging key 绑定 -->
<rabbit:direct-exchange name="spring.queue.exchange"
durable="true" auto-delete="false">
<rabbit:bindings>
<rabbit:binding queue="spring.queue.tag" key="spring.queue.tag.key" />
</rabbit:bindings>
</rabbit:direct-exchange> <!-- spring amqp默认的是jackson 的一个插件,目的将生产者生产的数据转换为json存入消息队列,由于Gson的速度快于jackson,这里替换为Gson的一个实现 -->
<bean id="jsonMessageConverter" class="sendMQ.Gson2JsonMessageConverter" /> <!-- spring template声明 -->
<rabbit:template id="amqpTemplate" exchange="spring.queue.exchange" routing-key="spring.queue.tag.key"
connection-factory="connectionFactory" message-converter="jsonMessageConverter" />

发送端代码:GSON配置

package sendMQ;

import java.io.IOException;
import java.io.UnsupportedEncodingException; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.AbstractJsonMessageConverter;
import org.springframework.amqp.support.converter.ClassMapper;
import org.springframework.amqp.support.converter.DefaultClassMapper;
import org.springframework.amqp.support.converter.MessageConversionException; import com.google.gson.Gson; public class Gson2JsonMessageConverter extends AbstractJsonMessageConverter{ private static Log log = LogFactory.getLog(Gson2JsonMessageConverter.class); private static ClassMapper classMapper = new DefaultClassMapper(); private static Gson gson = new Gson(); public Gson2JsonMessageConverter() {
super();
} @Override
protected Message createMessage(Object object,
MessageProperties messageProperties) {
byte[] bytes = null;
try {
String jsonString = gson.toJson(object);
bytes = jsonString.getBytes(getDefaultCharset());
}
catch (IOException e) {
throw new MessageConversionException(
"Failed to convert Message content", e);
}
messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON);
messageProperties.setContentEncoding(getDefaultCharset());
if (bytes != null) {
messageProperties.setContentLength(bytes.length);
}
classMapper.fromClass(object.getClass(),messageProperties);
return new Message(bytes, messageProperties);
} @Override
public Object fromMessage(Message message)
throws MessageConversionException {
Object content = null;
MessageProperties properties = message.getMessageProperties();
if (properties != null) {
String contentType = properties.getContentType();
if (contentType != null && contentType.contains("json")) {
String encoding = properties.getContentEncoding();
if (encoding == null) {
encoding = getDefaultCharset();
}
try {
Class<?> targetClass = getClassMapper().toClass(
message.getMessageProperties());
content = convertBytesToObject(message.getBody(),
encoding, targetClass);
}
catch (IOException e) {
throw new MessageConversionException(
"Failed to convert Message content", e);
}
}
else {
log.warn("Could not convert incoming message with content-type ["
+ contentType + "]");
}
}
if (content == null) {
content = message.getBody();
}
return content;
} private Object convertBytesToObject(byte[] body, String encoding,
Class<?> clazz) throws UnsupportedEncodingException {
String contentAsString = new String(body, encoding);
return gson.fromJson(contentAsString, clazz);
}
}

发送类接口:

public interface MQProducer {
/**
* 发送消息到指定队列
* @param queueKey
* @param object
*/
public void sendDataToQueue(String queueKey, Object object);
}

实现类:test是测试用的。

package sendMQ;

import java.util.HashMap;
import java.util.Map; import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(value = SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
"classpath:/spring-common.xml"}) @Component
public class MQProducerImpl implements MQProducer { @Autowired
private AmqpTemplate amqpTemplate; @Override
public void sendDataToQueue(String queueKey, Object object) {
System.out.println("--"+amqpTemplate);
try {
amqpTemplate.convertAndSend(object);
System.out.println("------------消息发送成功");
} catch (Exception e) {
System.out.println(e);
} } @Test
public void test() {
Map<String,Object> msg = new HashMap<>();
msg.put("data","hello,456");
while(true){
amqpTemplate.convertAndSend(msg);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
} } }

接收端配置:

  <!-- 连接服务配置  -->
<rabbit:connection-factory id="connectionFactory" host="localhost" username="guest"
password="guest" port="5672" virtual-host="/" channel-cache-size="5" /> <rabbit:admin connection-factory="connectionFactory"/> <!-- queue 队列声明-->
<rabbit:queue durable="true" auto-delete="false" exclusive="false" name="spring.queue.tag"/> <!-- exchange queue binging key 绑定 -->
<rabbit:direct-exchange name="spring.queue.exchange" durable="true" auto-delete="false">
<rabbit:bindings>
<rabbit:binding queue="spring.queue.tag" key="spring.queue.tag.key"/>
</rabbit:bindings>
</rabbit:direct-exchange> <bean id="receiveMessageListener"
class="receiveMQ.QueueListenter" /> <!-- queue litener 观察 监听模式 当有消息到达时会通知监听在对应的队列上的监听对象-->
<rabbit:listener-container connection-factory="connectionFactory" acknowledge="auto" >
<rabbit:listener queues="spring.queue.tag" ref="receiveMessageListener" />
</rabbit:listener-container>

接收端代码:

package receiveMQ;

import java.io.UnsupportedEncodingException;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener; public class QueueListenter implements MessageListener{
@Override
public void onMessage(Message msg) {
try {
System.out.print("-------------------"+new String(msg.getBody(),"UTF-8"));
} catch (UnsupportedEncodingException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
} }

接收端测试启动:

package receiveMQ;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ConsumerMain {
public static void main(String[] args) {
new ClassPathXmlApplicationContext("spring-common.xml");
}
}

上面代码均有注释,应该不难看懂,复制即可使用,实现了MQ的简单功能。

说明:可以配置多个接收端,spring默认的是负载均衡机制,每个接收端接收一条的来,这些扩展功能待后面有时间再讲解

rabbitMQ教程(三) spring整合rabbitMQ代码实例的更多相关文章

  1. RabbitMQ学习总结(7)——Spring整合RabbitMQ实例

    1.RabbitMQ简介 RabbitMQ是流行的开源消息队列系统,用erlang语言开发.RabbitMQ是AMQP(高级消息队列协议)的标准实现.  官网:http://www.rabbitmq. ...

  2. RabbitMQ入门到进阶(Spring整合RabbitMQ&SpringBoot整合RabbitMQ)

    1.MQ简介 MQ 全称为 Message Queue,是在消息的传输过程中保存消息的容器.多用于分布式系统 之间进行通信. 2.为什么要用 MQ 1.流量消峰 没使用MQ 使用了MQ 2.应用解耦 ...

  3. activiti自定义流程之Spring整合activiti-modeler5.16实例(三):流程模型列表展示

    注:(1)环境搭建:activiti自定义流程之Spring整合activiti-modeler5.16实例(一):环境搭建        (2)创建流程模型:activiti自定义流程之Spring ...

  4. activiti自定义流程之Spring整合activiti-modeler5.16实例(九):历史任务查询

    注:(1)环境搭建:activiti自定义流程之Spring整合activiti-modeler5.16实例(一):环境搭建        (2)创建流程模型:activiti自定义流程之Spring ...

  5. activiti自定义流程之Spring整合activiti-modeler5.16实例(八):完成个人任务

    注:(1)环境搭建:activiti自定义流程之Spring整合activiti-modeler5.16实例(一):环境搭建        (2)创建流程模型:activiti自定义流程之Spring ...

  6. activiti自定义流程之Spring整合activiti-modeler5.16实例(七):任务列表展示

    注:(1)环境搭建:activiti自定义流程之Spring整合activiti-modeler5.16实例(一):环境搭建        (2)创建流程模型:activiti自定义流程之Spring ...

  7. activiti自定义流程之Spring整合activiti-modeler5.16实例(六):启动流程

    注:(1)环境搭建:activiti自定义流程之Spring整合activiti-modeler5.16实例(一):环境搭建        (2)创建流程模型:activiti自定义流程之Spring ...

  8. activiti自定义流程之Spring整合activiti-modeler5.16实例(五):流程定义列表

    注:(1)环境搭建:activiti自定义流程之Spring整合activiti-modeler5.16实例(一):环境搭建        (2)创建流程模型:activiti自定义流程之Spring ...

  9. activiti自定义流程之Spring整合activiti-modeler5.16实例(四):部署流程定义

    注:(1)环境搭建:activiti自定义流程之Spring整合activiti-modeler5.16实例(一):环境搭建        (2)创建流程模型:activiti自定义流程之Spring ...

  10. activiti自己定义流程之Spring整合activiti-modeler5.16实例(四):部署流程定义

    注:(1)环境搭建:activiti自己定义流程之Spring整合activiti-modeler5.16实例(一):环境搭建         (2)创建流程模型:activiti自己定义流程之Spr ...

随机推荐

  1. 11-散列4 Hashing - Hard Version

    题目 Sample Input: 11 33 1 13 12 34 38 27 22 32 -1 21 Sample Output: 1 13 12 21 33 34 38 27 22 32 基本思路 ...

  2. devdependencies与dependencies的区别

    一直在纠结devdependencies与dependencies的区别是什么,下面就对此作出详细介绍,希望对你有所帮助! 我们在使用npm install 安装模块或插件的时候,有两种命令把他们写入 ...

  3. php+jQuery+Mysql找回密码----ThinkPHP

    最近用ThinkPHP做了一个邮箱找回密码功能,在遭遇了N个bug之后终于做成了,下面分享一下邮箱找回密码功能的实现: 邮箱找回密码实际上就是在用户通过验证之后重置密码的过程,一般开发者会在验证用户信 ...

  4. Hibernate学习(三)自动建表

    一般情况下有如下两种方法: 1.在配置文件中添加如下配置 <property name="hibernate.hbm2ddl.auto">create</prop ...

  5. 网页设计——2. html入门

    开始正式的课程讲解了,首先来看看课程体系: Java EE(java 企业应用程序版本) java2 有三个版本:J2 SE(标准版),J2 EE(企业版).J2 ME(微缩版). 我们要掌握J2EE ...

  6. [置顶] spring集成mina 实现消息推送以及转发

    spring集成mina: 在学习mina这块时,在网上找了很多资料,只有一些demo,只能实现客户端向服务端发送消息.建立长连接之类.但是实际上在项目中,并不简单实现这些,还有业务逻辑之类的处理以及 ...

  7. Python爬虫(十一)_案例:使用正则表达式的爬虫

    本章将结合先前所学的爬虫和正则表达式知识,做一个简单的爬虫案例,更多内容请参考:Python学习指南 现在拥有了正则表达式这把神兵利器,我们就可以进行对爬取到的全部网页源代码进行筛选了. 下面我们一起 ...

  8. 二分PkU3258

    <span style="color:#330099;">/* E - 二分 Time Limit:2000MS Memory Limit:65536KB 64bit ...

  9. 命令行界面下使用emca安装配置Oracle Database Control实战

    作为命令行忠有用户,server端软件的运维都倾向于使用命令或 脚本完毕,非常讨厌资源占用非常大的GUI.Oracle数据库作为重要的server端软件.其安装运维自然也全然支持纯命令行方式.虽然同一 ...

  10. 趋势科技PC-cillin2015,你来公測我发奖!

    watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvaXF1c2hp/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/d ...