1、MQ是什么 ---------异步机制
2、一些常用MQ:RabbitMQ、kafka、RocketMQ、ActiveMQ
3、RabbitMQ的优点(重点):
a)异步消息队列,缓解服务器的压力;
b)处理高并发,基于开发语言Erlang设计;
c)队列、消息的持久化;
d)有一个后台管理界面,支持集群
4、RabbitMQ的使用场景:将耗时、无须及时返回的场景都可采用RabbitMQ进行处理
a) 系统日志;
b)短信、邮件、消息推送;
c)行为日志,后台管理的操作日志等;
d) 处理高比发的场景:秒杀、团购、活动、12306抢票等;
e) 处理分布式事务:最终一致性(其他处理方案:强一致性、弱一致性)
5、Spring集成RabbitMQ
1、引入jar包
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
<version>1.7.4.RELEASE</version>
</dependency>
2、先创建连接工厂:AbstractConnectionFactory connectionFactory = new CachingConnectionFactory();
AbstractConnectionFactory connectionFactory = new CachingConnectionFactory();
connectionFactory.setUsername("genpeng");
connectionFactory.setPassword("123456");
// connectionFactory.setHost();
// connectionFactory.setPort();
// connectionFactory.setVirtualHost();
3、通过RabbitAdmin声明Queue、Exchange、Bind queue to exchange
RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
Queue queue = new Queue("java-queue");
rabbitAdmin.declareQueue(queue);
TopicExchange topicExchange = new TopicExchange("java-exchange");
rabbitAdmin.declareExchange(topicExchange);
rabbitAdmin.declareBinding(BindingBuilder.bind(queue).to(topicExchange).with("foo.*"));
4、声明一个监听容器、监听队列获取消息
// set up the listener and container
SimpleMessageListenerContainer listenerContainer = new SimpleMessageListenerContainer(connectionFactory);
Object listener = new Object(){
public void handleMessage1(String foo) {
System.out.println("接受到的消息是:" + foo);
}
};
MessageListenerAdapter messageListenerAdapter = new MessageListenerAdapter(listener);
messageListenerAdapter.setDefaultListenerMethod("handleMessage1");
listenerContainer.setMessageListener(messageListenerAdapter);
listenerContainer.setQueues(queue);
listenerContainer.start();
5、使用RabbitTemplate发送消息
// send something
RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
rabbitTemplate.convertAndSend("java-exchange", "foo.abc", "你好。。。");