主要是为了以后方便使用
rebbitMQ下载地址:http://www.rabbitmq.com/download.html
下载好后安装好,安装教程:点击打开链接
首先当然是配置了,
1.创建spring-rebbitmq.xml,我的是放在config下;
配置如下:
<?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:context="http://www.springframework.org/schema/context"
xmlns:rabbit="http://www.springframework.org/schema/rabbit"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">
<description>rabbitMa配置 </description>
<!--配置connection-factory,指定连接rabbit server参数 -->
<!-- 连接配置 -->
<rabbit:connection-factory id="connectionFactory"
host="localhost" username="guest" password="guest" port="5672" /><!--此处配置的本地的mq-->
<!--通过指定下面的admin信息,当前producer中的exchange和queue会在rabbitmq服务器上自动生成 -->
<rabbit:admin connection-factory="connectionFactory" />
<rabbit:template id="amqpTemplate" connection-factory="connectionFactory" />
<!-- ***************消息生产者*********** -->
<!--定义topic-exchange <rabbit:topic-exchange name="dynamicExchange" durable="true"
auto-delete="false"> <rabbit:bindings> <rabbit:binding queue="dynamic" pattern="dynamic.send"></rabbit:binding>
<rabbit:binding queue="mq.asdf2" pattern="mq.asdf2.send"></rabbit:binding>
<rabbit:binding queue="mq.asdf2" pattern="mq.asdf.send"></rabbit:binding>
</rabbit:bindings> </rabbit:topic-exchange> -->
<!-- ************************系统消息生产者配置************************ -->
<!--定义queue 说明:durable:是否持久化 exclusive: 仅创建者可以使用的私有队列,断开后自动删除 auto_delete:
当所有消费客户端连接断开后,是否自动删除队列 -->
<rabbit:queue name="adminCMS" durable="true" auto-delete="false"
exclusive="false" />
<!--定义direct-exchange -->
<rabbit:direct-exchange name="adminCMSChange"
durable="true" auto-delete="false">
<rabbit:bindings>
<rabbit:binding queue="adminCMS" key="adminCMS.send"></rabbit:binding><!--此处key的值是向mq服务器发送信息类里面定义的-->
</rabbit:bindings>
</rabbit:direct-exchange>
<!-- ***************消息接收者******************** -->
<!-- <bean id="asdfConsumer2" class="com.demo.action.AsdfConsumer2"></bean>
<bean id="qwerConsumer" class="com.demo.action.QwerConsumer"></bean> -->
<!-- queue litener 观察 监听模式 当有消息到达时会通知监听在对应的队列上的监听对象 -->
<!-- <rabbit:listener-container connection-factory="connectionFactory">
<rabbit:listener queues="mq.asdf2" ref="asdfConsumer2" /> </rabbit:listener-container>
<rabbit:listener-container connection-factory="connectionFactory"> <rabbit:listener
queues="mq.qwer" ref="qwerConsumer" /> </rabbit:listener-container> -->
<!-- *****************监听系统消息(短信)*************** -->
<bean id="listenerCMS" class="com.chuangke.oa.controller.rebbitMQ.CMSListenter"></bean>
<rabbit:listener-container
connection-factory="connectionFactory">
<rabbit:listener queues="adminCMS" ref="listenerCMS" />
</rabbit:listener-container>
</beans>
2.编写路由;
import org.springframework.amqp.core.AmqpTemplate;
public interface RabbitMQRouter {
/**
* @description :路由器admin
* @return
*/
public boolean sendMessAdminRouter(AmqpTemplate amqpTemplate, String msg);
}
路由实现类:
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Transactional
@Service("RabbitMQRouter")
public class RabbitMQRouterImpl implements RabbitMQRouter {
/**
* @description :路由admin
* @return
*/
public boolean sendMessAdminRouter(AmqpTemplate amqpTemplate, String msg) {
// 得到消息缓存信息
boolean returnFlag = false;
// 推送消息
if (RabbitMqHelper.sendAdminMess(amqpTemplate,msg)) {
returnFlag = true;
}
return returnFlag;
}
}
3.调用api,向mq发送消息
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.amqp.core.AmqpTemplate;
public class RabbitMqHelper {
public static final Log log = LogFactory.getLog(RabbitMqHelper.class);
/**
* 向MQ服务器发送信息
* @param amqpTemplate
* @param msg
* @return
*/
public static boolean sendAdminMess(AmqpTemplate amqpTemplate,String msg){
boolean success=false;
try {
Object back=amqpTemplate.convertSendAndReceive("adminCMSChange", "adminCMS.send", msg);//配置文件中一定不要写错了名字
if(back==null){
success= true;
}else{
success= false;
}
} catch (Exception e) {
log.error("rabbitMq send message err:msg is:"+msg+"err Log:"+e);
}
return success;
}
}
之后就是调用这些写好的方法了
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSONObject;
@Component
public class TaskTimer {
@Resource
private AmqpTemplate amqpTemplate;//AmqpTemplate注入,只有在controller层注入才可以
@Resource
private RabbitMQRouter rabbitMQRouter;//RabbitMQRouter注入,这两个是必须的
@Scheduled(cron = "0/5 * * * * ?")//定时器(秒 分 小时 日 周 月 年)
public void TaskPushTimer() {
//此处省略拼装的数据
allMsgBody.setEmployeeId(sendEmployeeIds);
allMsgBody.setSendMsg(Constant.TASK_MSG);
allMsgBody.setType(4);
String msg = JSONObject.toJSONString(allMsgBody);//注意向MQ发送消息的时候需要转成JSONObject,不知道不转是什么情况,没试过
rabbitMQRouter.sendMessRouter(amqpTemplate, msg);//这里就是调用上面写好的接口了,将拼装好的数据发送过去
}
}
}
如果配置的没有问题,到了这一步应该已经将消息发送到mq服务器了
如果是本地安装的mq,访问http://localhost:15672是可以上去看到的:里面是有过来的请求的
4.让后就是接收mq发回来的消息
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
/**
* 接收rebbitmq返回的数据
*
* @author Administrator
*
*/
public class CheckCMSListenter implements ChannelAwareMessageListener {
public static final Log log = LogFactory.getLog(CheckCMSListenter.class);
static {
log.info("前台推送已依赖成功");
}
@SuppressWarnings("unused")
public void onMessage(Message message, Channel channel) throws Exception {
// 得到mq中消息体
String msg = new String(message.getBody());
// 将消息体转为对象
JSONObject jsonObj = null;
try {
jsonObj = JSONObject.parseObject(msg);
log.info("mess:" + jsonObj);
if (jsonObj != null) {
//这里处理mq返回的数据
} else {
log.error("MQ获取消息异常,消息体:" + msg);
}
} catch (Exception e) {
log.error("MQ 消息体转换异常,原消息为:" + msg + "err:" + e);
} finally {
// 无论是否发送成功,先默认移除MQ,以防一直重复发送
basicACK(message, channel, msg);
}
}
// 正常消费掉后通知mq服务器移除此条mq
private void basicACK(Message message, Channel channel, String msg) {
try {
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
} catch (IOException e) {
log.error("MQ 消息重返队列异常,消息内容:" + msg);
}
}
// 处理异常,mq重回队列
private void basicNACK(Message message, Channel channel) {
try {
channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
} catch (IOException e) {
}
}
}
最后一定不要忘记将配置文件引入web.xml
classpath:config/rabbitmq/spring-rabbitmq.xml
看不懂不要喷,我就是记录一下。
小白一枚,不喜勿喷!!!