skill:RabbitMq

如何使用

  • 安装RabbitMq服务

安装 Eralng OTP ,安装 Rabbit MQ Server,具体可以到网上搜教程。

  • spring 集成 RabbitMq

spring配置文件:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:rabbit="http://www.springframework.org/schema/rabbit" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
    http://www.springframework.org/schema/rabbit
    http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd" >
    <description>rabbitmq 连接服务配置description>
    
    <rabbit:connection-factory id="connectionFactory" host="${mq.host}" 
        username="${mq.username}" password="${mq.password}" port="${mq.port}"/> 
    
    <rabbit:admin connection-factory="connectionFactory"/>
    
    <rabbit:template id="amqpTemplate" exchange="sms_exchange" 
        connection-factory="connectionFactory" message-converter="jsonMessageConverter" /> 
    
    <bean id="jsonMessageConverter" 
        class="org.springframework.amqp.support.converter.Jackson2JsonMessageConverter" /> 
    
    <rabbit:queue name="sms_code_queue" durable="true" auto-delete="false" 
        exclusive="false" />
    
    <rabbit:direct-exchange  name="sms_exchange" durable="true" auto-delete="false" >
        <rabbit:bindings>
            <rabbit:binding queue="sms_code_queue" key="sms_code_queue_key"/>
        rabbit:bindings>
    rabbit:direct-exchange>
    
    <rabbit:listener-container connection-factory="connectionFactory" acknowledge="auto">
        <rabbit:listener queues="sms_code_queue" ref="smsCodeQueueListenter"/>
    rabbit:listener-container>    
beans>

生产者:

@Service
public class SmsMQProducerImpl implements MQProducer{
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Override
    public void sendDataToQueue(String key, Object object) {
        amqpTemplate.convertAndSend("sms_code_queue_key", object);
    }
}

消费者:

@Component
public class SmsCodeQueueListenter implements MessageListener {
    @Override
    public void onMessage(Message message) {}
}

简单解释

核心要素

生产者、消费者、队列、交换机

关系

生产者通过将消息发送到指定交换机的指定队列
<rabbit:template id="amqpTemplate" exchange="sms_exchange" 
        connection-factory="connectionFactory" message-converter="jsonMessageConverter" />

通过RabbitTemplate.void convertAndSend(String routingKey, final Object object)中的routingKey参数来指定队列,队列的 routingKey在中指定

关联队列,并指定队列的routingKey:
<rabbit:direct-exchange  name="sms_exchange" durable="true" auto-delete="false" >
    <rabbit:bindings>
        <rabbit:binding queue="sms_code_queue" key="sms_code_queue_key"/>
    rabbit:bindings>
rabbit:direct-exchange>
配置队列的消费者
<rabbit:listener-container connection-factory="connectionFactory" acknowledge="auto">
    <rabbit:listener queues="sms_code_queue" ref="smsCodeQueueListenter"/>
rabbit:listener-container>

你可能感兴趣的:(java)