RabbitMQ消息队列
程序员文章站
2022-05-18 11:44:26
...
一、Rabbitmq说明
RabbitMQ是一个开源的AMQP(高级消息队列协议)实现,服务器端用Erlang语言编写,支持多种客户端,如:Ruby、.NET、Java、C、PHP等,作为一个消息代理,主要接受、存储和转发
RabbitMQ是一个生产者、消费者模型:
Producer(生产者),产生消息并向RabbitMq发送消息,Consumer(消费者),等待RabbitMq消息到来并处理消息。
Queue(队列), 依存于RabbitMQ内部, 虽然消息通过RabbitMQ在你的应用中传递,但是它们只能存储在queue中,本质上是一个缓存。
二、创建连接工厂
package com.mmh.clouddemo.config;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;s
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
/**
* RabbitMQ
*/
@Configuration
@PropertySource(value = "classpath:rabbit.properties")
public class RabbitmqConfig {
private String host="127.0.0.1";
private int port=5672;
private String username="guest";
private String password="guest";
private String virtualHost="/";
// @Value("${rabbitmq.host}")
// private String host;
// @Value("${rabbitmq.port}")
// private int port;
// @Value("${rabbitmq.username}")
// private String username;
// @Value("${rabbitmq.password}")
// private String password;
// @Value("${rabbitmq.virtusal-host}")
// private String virtualHost;
/**
* 创建连接工厂
*/
@Bean
public CachingConnectionFactory connectionFactory() {
System.out.println(host+port+username+password+virtualHost);
CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(this.host, port);
cachingConnectionFactory.setUsername(username);
cachingConnectionFactory.setPassword(password);
cachingConnectionFactory.setVirtualHost(virtualHost);
cachingConnectionFactory.setPublisherConfirms(true);
return cachingConnectionFactory;
}
/**
* 定义rabbit template用于数据的接收和发送
*/
@Bean
public RabbitTemplate rabbitTemplate() {
RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory());
/**
* 若使用confirm-callback或return-callback,
* 必须要配置publisherConfirms或publisherReturns为true,
* 每个rabbitTemplate只能有一个confirm-callback和return-callback
*/
rabbitTemplate.setConfirmCallback(msgSendConfirmCallBack());
rabbitTemplate.setReturnCallback(msgSendReturnCallback());
rabbitTemplate.setMessageConverter(jsonMessageConverter());
/**
* 使用return-callback时必须设置mandatory为true,
* 或者在配置中设置mandatory-expression的值为true,
* 可针对每次请求的消息去确定’mandatory’的boolean值,
* 只能在提供’return -callback’时使用,与mandatory互斥
* */
// rabbitTemplate.setMandatory(true);
return rabbitTemplate;
}
@Bean
public MessageConverter jsonMessageConverter() {
return new Jackson2JsonMessageConverter();
}
/**
* 消息回馈信息
* Confirms给客户端一种轻量级的方式,能够跟踪哪些消息被broker处理,
* 哪些可能因为broker宕掉或者网络失败的情况而重新发布。
* 确认并且保证消息被送达,提供了两种方式:发布确认和事务。(两者不可同时使用)在channel为事务时,
* 不可引入确认模式;同样channel为确认模式下,不可使用事务。
*/
@Bean
public MsgSendReturnCallback msgSendReturnCallback() {
return new MsgSendReturnCallback();
}
/**
* 消息确认回执
*/
@Bean
public MsgSendConfirmCallBack msgSendConfirmCallBack() {
return new MsgSendConfirmCallBack();
}
}
三、消息确认机制 和 回馈机制
package com.mmh.clouddemo.config;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
/**
* 消息确认
* */
public class MsgSendConfirmCallBack implements RabbitTemplate.ConfirmCallback{
@Override
public void confirm(CorrelationData correlationData, boolean ack, String cause) {
System.out.println(" 回调id:" + correlationData);
if(ack){
System.out.println("消息确认收到");
}else{
System.out.println("消息接收失败:"+cause);
}
}
}
package com.mmh.clouddemo.config;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
/**
* 回馈消息
* */
public class MsgSendReturnCallback implements RabbitTemplate.ReturnCallback {
@Override
public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
System.out.println("回馈消息:"+message.getBody().toString());
}
}
四、发送消息
工具:
package com.mmh.clouddemo.utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.UUID;
/**
* @author Administrator
*/
@Slf4j
@Component
public class RabbitmqSendUtils {
@Autowired
private RabbitTemplate rabbitTemplate;
/**
*
* @param tmp 放入队列的消息内容
* @param que 队列名称
*/
public void putMegToQueString(String tmp,String que) {
try {
String exchangeStr = "exchange";
String queStr = que;
String uuid = UUID.randomUUID().toString();
CorrelationData correlationId = new CorrelationData(uuid);
DirectExchange directExchange = new DirectExchange(exchangeStr, true, false);
Queue queue = new Queue(queStr, true, false, false);
Binding bind = BindingBuilder.bind(queue).to(directExchange).with(queStr);
RabbitAdmin admin = new RabbitAdmin(this.rabbitTemplate.getConnectionFactory());
admin.declareQueue(queue);
admin.declareExchange(directExchange);
admin.declareBinding(bind);
log.info("开始放入队列中队列名称------》" + que + " ,放入的内容为:----->" + tmp);
rabbitTemplate.convertAndSend(exchangeStr, queStr, tmp, correlationId);
log.info("放入队列 结束 队列名称------》" + que + " ,放入的内容为:----->" + tmp);
} catch (Exception e) {
e.printStackTrace();
}
}
}
发送:
package com.mmh.clouddemo.consumer;
import com.mmh.clouddemo.utils.RabbitmqSendUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
@Controller
public class send {
@Autowired
private RabbitmqSendUtils rabbitmqSendUtils;
@RequestMapping("/test")
public void sendtest(HttpServletRequest request) {
String que = request.getParameter("que");
System.out.println("jj ");
System.out.println("jin");
rabbitmqSendUtils.putMegToQueString(que,"testqueue");
}
}
五、监听队列
package com.mmh.clouddemo.consumer;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
/**
* @author Administrator
*/
@Component
public class test {
@RabbitHandler
@RabbitListener(queues = "testqueue")
public void connsumer(String parm){
System.out.println("len");
System.out.println(parm);
}
}
推荐阅读