Spring---rabbitmq生產者配置
阿新 • • 發佈:2019-01-12
這篇文章是Spring整合Rabbitmq的其中針對生產者的一個簡單的配置。如何來實現java向rabbitmq中傳送訊息
作為一個生產者,我們要配置哪些東西,我認為生產者需要配置的有幾個必要的:
<?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"> <!-- spring amqp預設的是jackson 的一個外掛,目的將生產者生產的資料轉換為json存入訊息佇列,由於Gson的速度快於jackson,這裡替換為Gson的一個實現 --> <bean id="jsonMessageConverter" class="org.springframework.amqp.support.converter.Jackson2JsonMessageConverter"></bean> <!-- 連線服務配置 --> <rabbit:connection-factory id="connectionFactory" host="127.0.0.1" username="guest" password="guest" port="5672" virtual-host="/" /> <rabbit:admin connection-factory="connectionFactory" /> <!-- spring template宣告 --> <rabbit:template id="amqpTemplate" connection-factory="connectionFactory" exchange="wdgexchange" message-converter="jsonMessageConverter" routing-key="*" /> <!-- queue 佇列宣告 --> <rabbit:queue durable="true" auto-delete="false" exclusive="false" name="wdgqueue" /> <!-- exchange queue binging key 繫結 --> <!-- rabbitmq交換器 --> <rabbit:direct-exchange name="wdgexchange" id="wdgexchange" durable="true" auto-delete="false"> <rabbit:bindings> <rabbit:binding queue="wdgqueue" key="*" /> </rabbit:bindings> </rabbit:direct-exchange> </beans>
1.jsonMessageCoverter這個bean的配置。
2.連結包括密碼,使用者名稱,和主機ip地址,埠號,以及虛擬的virtual-host
3.連結工廠
4.宣告模板,模板的聲明裡面需要有exchange,route-key ,id,connectFactory,message-converter,
5.宣告佇列
6.交換器
上面是rabbitmq-producer.xml的配置,我們應該如何實現訊息的傳送:
public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("rabbitmq-producer.xml"); AmqpTemplate amqpTemplate = context.getBean(RabbitTemplate.class); amqpTemplate.convertAndSend("444"); }
執行程式就可以實現訊息的傳送:
希望上面rabbitmq生產者的配置對你有所幫助,如果感覺確實有幫助了,可以掃描一下紅包哦