rabbitmq 的消息类型 大概分以下几种
1 . fanout(订阅) 即 fanout类型的Exchange可以将producer 发送的消息绑定到所有订阅的队列中去. 即发布/订阅机制
2, direct(路由) 即 producer发送消息的时候需要设置一个消息类型,然后consumer订阅的时候只订阅自己需要的消息类型即可。
3,topic(主题) 即 direct并不能满足我们的业务需求,因为direct只能绑定一个固定的消息类型,但是topic就可以使用通配符,绑定一类的消息类型。
4. Header: 即 header模式与routing不同的地方在于,header模式取消routingkey,使用header中的 key/value(键值对)匹配队列。
回调模式
配置文件
final static String CALLBACK = "callback";
@Bean
public Queue callBackQueue() {
return new Queue(CALLBACK);
}
@Autowired
private ConnectionFactory connectionFactory;
@Bean
/** 因为要设置回调类,所以应是prototype类型,如果是singleton类型,则回调类为最后一次设置 */
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public RabbitTemplate rabbitTemplatenew() {
RabbitTemplate template = new RabbitTemplate(connectionFactory);
return template;
}
生产者
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.amqp.rabbit.connection.CorrelationData;
/**
* 执行回调的生产者
*/
@Component
public class CallBackProducer implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback {
@Autowired
private RabbitTemplate rabbitTemplate;
public void send() {
rabbitTemplate.setReturnCallback(this);
rabbitTemplate.setConfirmCallback(this);
rabbitTemplate.convertAndSend("callback", "回调函数:生产者发出的消息");
}
/**
* 发送后的回调函数
*
* @param correlationData
* @param b
* @param s
*/
public void confirm(CorrelationData correlationData, boolean b, String s) {
System.out.println("回调函数:" + "b=" + b);
}
/**
* 消息发送失败的回调函数(未测试)
*
* @param message
* @param replyCode
* @param replyText
* @param exchange
* @param routingKey
*/
@Override
public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
System.out.println("发送消息失败");
}
}
消费者
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
@RabbitListener(queues = "callback")
public class CallBackCustomer {
@RabbitHandler
public void process(String msg){
System.out.println("回调函数-消费者:"+msg);
}
}
测试方法
@RestController
public class CallBackController {
@Autowired
private CallBackProducer callBackProducer;
@RequestMapping("/callback")
public void send(){
callBackProducer.send();
}
}