Spring boot下使用RabbitMQ实例
环境搭建教程请参考:http://blog.csdn.net/yy756127197/article/details/73693527
application.properties资源文件
## rabbit mq properties
rabbitmq.queuename=task.start.queue
rabbitmq.exchange=task.start.exchange
rabbitmq.routingkey=task.start.#
rabbitmq配置文件
@Configuration
//@ConditionalOnProperty(prefix = "rabbitmq",name = "queuename")
public class MQConfig {
@Configuration
@Profile("dev") //dev环境的配置
static class LocalConfiguration {
@Value("${rabbitmq.queuename}")
private String queueName;
@Value("${rabbitmq.exchange}")
private String queueExchange;
@Value("${rabbitmq.routingkey}")
private String routingkey;
@Value("${cf.rabbit.service.name}")
private String rabbitService;
@Bean
public ConnectionFactory connectionFactory() {
CachingConnectionFactory factory = new CachingConnectionFactory();
factory.setUsername("yang");
factory.setPassword("guest");
factory.setVirtualHost("test");
factory.setHost("localhost");
// factory.setPort(15672);
factory.setPublisherConfirms(true);
return factory;
}
@Bean
public MessageConverter messageConverter() {
return new Jackson2JsonMessageConverter();
}
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
// 必须是prototype类型
public RabbitTemplate rabbitTemplate() {
RabbitTemplate template = new RabbitTemplate(connectionFactory());
return template;
}
@Bean
public MessageListenerAdapter listenerAdapter(MQAwareListener listener,
MessageConverter converter) {
return new MessageListenerAdapter(listener, converter);
}
@Bean
public Queue queue() {
return new Queue(queueName, true);
}
// TopicExchange(*、#模糊匹配routing key,routing
// key必须包含"."),DirectExchange,FanoutExchange(无routing key概念)
@Bean
public TopicExchange exchange() {
return new TopicExchange(queueExchange);
}
@Bean
public Binding binding(Queue queue, TopicExchange exchange) {
return BindingBuilder.bind(queue).to(exchange).with(routingkey);
}
}
}
listener 客户端
@Component
public class MQAwareListener implements ChannelAwareMessageListener {
@Resource
private MessageConverter messageConverter;
@Resource
private RabbitTemplate rabbitTemplate;
@Override
public void onMessage(Message message, Channel channel) throws IOException {
byte[] body = message.getBody();
TUserTest user= DataConverterUtil.json2Object(new String(body), TUserTest.class);
System.out.println("接收消息 : " + user.getName());
// 消息消费失败
// channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
//确认消息成功消费
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
}
}
DataConverterUtil.json2Object()是我自己封装的类型转换工具类。json转对象,网上搜一大把
发送端
@Service
public class BasicService implements ConfirmCallback {
@Resource
public RabbitTemplate rabbitTemplate;
@Value("${rabbitmq.exchange}")
private String queueExchange;
@Value("${rabbitmq.routingkey}")
private String routingkey;
public void sendMessage(final String correlationId, Object request) {
String content = DataConverterUtil.object2Json(request);
rabbitTemplate.setConfirmCallback(this);
rabbitTemplate.setCorrelationKey(correlationId);
rabbitTemplate.convertAndSend(queueExchange,routingkey, content, new MessagePostProcessor() {
//设置消息的通用属性
@Override
public Message postProcessMessage(Message message) throws AmqpException {
message.getMessageProperties().setTimestamp(new Date());
// message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
return message;
}
}, new CorrelationData(correlationId));
}
@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);
}
}
}
DataConverterUtil.object2Json()是我自己封装的类型转换工具类。对象转json,网上搜一大把
测试类
@Component
@EnableScheduling
public class TestSend {
@Resource
private BasicService basicService;
@Scheduled(fixedDelay = 60000)
public void send() {
TUserTest user = new TUserTest();
user.setId(UUID.randomUUID().toString());
user.setName("我是拯救世界的Programmer");
basicService.sendMessage(user.getId(), user);
}
}
以上是带回调的事例(手动回调)
远离监听,长命百岁
总觉得这种实现方式不是很好,下一章讲客户端注解的形式。
但是注解的形式手动回调怎么设置,没搞明白,只能自动回调。玩明白的小伙伴分享下哦。
喜欢的请点赞,欢迎交流^^