【深入理解RabbitMQ原理】RabbitMQ 配置,生产者和消费者

实战 Java 并发编程
实战为导向,从Java 并发原理出发,并集合开发实践,全面剖析 Java 并发编程。
wangxiaoming

   RabbitMQ 配置,生产者和消费者

 

1. 生产者的配置

 

       1)配置都要先声明队列

      

        队列的声明方式:

   

     <rabbit:queueid="Bgate_Bgate1001Response_Paytt" durable="true"auto-delete="false" exclusive="false"name="Bgate_Bgate1001Response_Paytt" />

 

 

 

       2)声明一个交换机,然后将队列绑定上去

         

 

 

<rabbit:direct-exchangename="Payt" durable="true" auto-delete="false"id="Payt">
<rabbit:bindings>
    <rabbit:bindingqueue="Bgate_Bgate1001Response_Paytt"key="Bgate_Bgate1001Response_Paytt_key" />
</rabbit:bindings>
</rabbit:direct-exchange>

 

 

      3)定义一个生产者

 

 

	<bean id="bgate1001ResponseProducer" class="cpcn.payment.tool.middleware.mq.SmartMQProducer">
		<property name="messageConverter" ref="msgConverter" />
		<property name="connectionFactory" ref="mqConnectionFactory" />
		<property name="retryTemplate" ref="retryTemplate" />
		<property name="exchange" value="Payt" />
		<property name="queue" value="Bgate_Bgate1001Response_Paytt" />
		<property name="routingKey" value="Bgate_Bgate1001Response_Paytt_key" />
	</bean>	

 

 

 

    

   2、消费者

        1)   也要先声明一个队列

          

<rabbit:queue id="Bgate_Bgate1001Response_Paytt" durable="true" auto-delete="false" exclusive="false" name="Bgate_Bgate1001Response_Paytt" />	

 

 

 

       2)定义一个交换机,并且绑定队列

        

<rabbit:direct-exchange name="Payt" durable="true" auto-delete="false" id="Payt">
		<rabbit:bindings>
		
			<rabbit:binding queue="Bgate_Bgate1001Response_Paytt" key="Bgate_Bgate1001Response_Paytt_key" />
		</rabbit:bindings>
</rabbit:direct-exchange>

 

 

 

 

       3) 定义一个消费者

 

	<bean id="bgate1001ResponseConsumer" class="cpcn.payment.paymenttool.mqconsumer.Bgate1001ResponseConsumer" />
		<bean id="bgate1001ResponseAdapter"  class="org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter">  
	        <constructor-arg ref="bgate1001ResponseConsumer" />  
	        <property name="defaultListenerMethod" value="handleTxMsg"></property>  
	        <property name="messageConverter" ref="messageConverter"></property>  
	    </bean>
		<bean id="bgate1001ResponselistenerContainer"  class="org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer">  
	        <property name="queueNames" value="Bgate_Bgate1001Response_Paytt"></property> 
	        <property name="connectionFactory" ref="mqConnectionFactory"></property>  
	        <property name="messageListener" ref="bgate1001ResponseAdapter"></property>
	        <property name="concurrentConsumers" value="20" />
			<property name="channelTransacted" value="true" /> 
			<property name="adviceChain">
				<array>
					<ref bean="retryInterceptor" />
				</array>
			</property> 
	    </bean> 

 

 

 

 

Rabbit MQ 消息发送的关键代码:

 

 

	protected RabbitTemplate rabbitTemplate = new RabbitTemplate();
	public RabbitTemplate getRabbitTemplate() {
	        return rabbitTemplate;
	    }
	
	    public void setRabbitTemplate(RabbitTemplate rabbitTemplate) {
	        this.rabbitTemplate = rabbitTemplate;
	    }
	
  this.rabbitTemplate.convertAndSend(this.routingKey, message, correlationId);

 

 

 

 

 

 

给个消息发送的实例方法:

 

 public void sendDataToMQ(Object message) {
        CorrelationData correlationId = null;
        try {
            correlationId = new CorrelationData(GUID.genTxNo(25));
        } catch (Exception e) {
            logger.error(LogType.EX, "产生消息id失败",e);
            correlationId = new CorrelationData(UUID.randomUUID().toString());
        }
        this.rabbitTemplate.convertAndSend(this.routingKey, message, correlationId);
        logger.info(LogType.EX, "发送到MQ的消息内容["+message.getClass().getSimpleName()+JsonUtil.toJSONString(message)+"],消息ID["+correlationId.getId()+"]");
    }

 

 

 

 

 

 

 

 

给一个完整的配置:

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:rabbit="http://www.springframework.org/schema/rabbit"
	xsi:schemaLocation="
            http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
                http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/rabbit
                http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd">

	<!-- 连接服务配置 -->
	<bean id="mqConnectionFactory" class="org.springframework.amqp.rabbit.connection.CachingConnectionFactory">
        <property name="addresses" value="${mq.addresses}"/>
        <property name="username" value="${mq.username}" />
        <property name="password" value="${mq.password}" />
        <property name="virtualHost" value="/" />
        <property name="channelCacheSize" value="50" />
        <property name="publisherReturns" value="true" />
    </bean>

	<rabbit:admin connection-factory="mqConnectionFactory" />

	<!--处理异常信息不再入队列,解决死信消息问题  -->
	<bean id="messageRecoverer" class="cpcn.payment.tool.middleware.mq.MQRejectAndLogRecoverer" />
	<!--监听异常重试次数  -->
	<bean id="retryTemplate" class="org.springframework.retry.support.RetryTemplate">
		<property name="backOffPolicy">
			<bean class="org.springframework.retry.backoff.ExponentialBackOffPolicy">
				<!-- 初始 -->
				<property name="initialInterval" value="500" />
				<!-- 倍数 -->
				<property name="multiplier" value="10.0" />
				<!-- 最大值 -->
				<property name="maxInterval" value="10000" />
			</bean>
		</property>
		<property name="retryPolicy">
			<bean class="org.springframework.retry.policy.SimpleRetryPolicy">
				<!-- 最大尝试次数 -->
				<property name="maxAttempts" value="3" />
			</bean>
		</property>
	</bean>
	
	<!-- 消息重试设置 -->
	<bean id="retryInterceptor" class="org.springframework.amqp.rabbit.config.StatelessRetryOperationsInterceptorFactoryBean">
		<property name="messageRecoverer" ref="messageRecoverer" />
		<property name="retryOperations" ref="retryTemplate" />
	</bean>
	
	<!-- 声明消息转换器为SimpleMessageConverter -->
	<bean id="messageConverter" class="org.springframework.amqp.support.converter.SimpleMessageConverter"></bean>

    <!-- 新建一个队列 -->
    <rabbit:queue id="Dcen_Test1022Request_Dcen" durable="true" auto-delete="false" exclusive="false" name="Dcen_Test1022Request_Dcen" />
 
    <!-- 定义一个交换机 -->
   <rabbit:direct-exchange name="Dcen" durable="true" auto-delete="false" id="Dcen">
		<rabbit:bindings>
			<rabbit:binding queue="Dcen_Test1022Request_Dcen" key="Dcen_Test1022Request_Dcen_key" />
		</rabbit:bindings>
	</rabbit:direct-exchange>

    <!-- 生产者申明 -->
    <bean id="test1022RequestProducer" class="cpcn.payment.tool.middleware.mq.SmartMQProducer">
		<property name="messageConverter" ref="messageConverter" />
		<property name="connectionFactory" ref="mqConnectionFactory" />
		<property name="retryTemplate" ref="retryTemplate" />
		<property name="exchange" value="Dcen" />
		<property name="queue" value="Dcen_Test1022Request_Dcen" />
		<property name="routingKey" value="Dcen_Test1022Request_Dcen_key" />
	</bean>
    <!-- 消费者声明 -->
	<bean id="test1022RequestConsumer" class="cpcn.payment.datacenter.mqconsumer.Test1022RequestConsumer" />
	<bean id="test1022RequestAdapter" class="org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter">
		<constructor-arg ref="test1022RequestConsumer" />
		<property name="defaultListenerMethod" value="handleTxMsg"></property>
		<property name="messageConverter" ref="messageConverter"></property>
	</bean>
	<bean id="payt1021ResponselistenerContainer" class="org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer">
		<property name="queueNames" value="Dcen_Test1022Request_Dcen"></property>
		<property name="connectionFactory" ref="mqConnectionFactory"></property>
		<property name="messageListener" ref="test1022RequestAdapter"></property>
		<property name="concurrentConsumers" value="20" />
		<property name="adviceChain">
			<array>
				<ref bean="retryInterceptor" />
			</array>
		</property> 
	</bean>

</beans>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

wangxiaoming CSDN认证博客专家 架构 Spring Boot Redis
博客是很好的总结和记录工具,如果有问题,来不及回复,关注微信公众号:程序员开发者社区,获取我的联系方式,向我提问,也可以给我发送邮件,联系 1275801617@qq.com
©️2020 CSDN 皮肤主题: Age of Ai 设计师: meimeiellie 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值