您好,登錄后才能下訂單哦!
本篇文章為大家展示了如何編寫Springweb集成rabbitmq代碼,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
引入java包:
本項目中僅引入了四個java包:amqp-client-5.7.3.jar,spring-rabbit-2.2.2.RELEASE.jar,spring-retry-1.2.4.RELEASE.jar,spring-amqp-2.2.2.RELEASE.jar
spring-rabbitmq.xml
<?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: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/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit.xsd"> <!--配置connection-factory,指定連接rabbit server參數 --> <rabbit:connection-factory id="connectionFactory" username="guest" password="guest" host="localhost" port="5672" /> <!--定義rabbit template用于數據的發送 --> <rabbit:template id="amqpTemplate" connection-factory="connectionFactory" exchange="exchangeTest" /> <!--通過指定下面的admin信息,當前producer中的exchange和queue會在rabbitmq服務器上自動生成 --> <rabbit:admin connection-factory="connectionFactory" /> <!--定義queue --> <rabbit:queue name="queueTest" durable="true" auto-delete="false" exclusive="false" /> <!-- 定義direct exchange,綁定queueTest --> <rabbit:direct-exchange name="exchangeTest" durable="true" auto-delete="false"> <rabbit:bindings> <rabbit:binding queue="queueTest" key="queueTestKey"></rabbit:binding> </rabbit:bindings> </rabbit:direct-exchange> <!-- 消息接收者 --> <bean id="messageReceiver" class="club.codeapes.web.core.rabbitmq.RabbitMqMessageConsumer"></bean> <!-- queue litener 觀察 監聽模式 當有消息到達時會通知監聽在對應的隊列上的監聽對象--> <rabbit:listener-container connection-factory="connectionFactory"> <rabbit:listener queues="queueTest" ref="messageReceiver"/> </rabbit:listener-container></beans>
spring中需要引入這個xml, 主要在總spring.xml。或者web.xml中需要引入下。
RabbitMqMessageConsumer
package club.codeapes.web.core.rabbitmq;import club.codeapes.common.date.DateUtil;import com.alibaba.fastjson.JSON;import org.springframework.amqp.core.Message;import org.springframework.amqp.core.MessageListener;public class RabbitMqMessageConsumer implements MessageListener { @Override public void onMessage(Message message) { System.out.println("消費信息," + DateUtil.getNow("yyyy-MM-dd HH:mm:ss") + "---->" + message); }}
RabbitMqMessageProducer:
package club.codeapes.web.core.rabbitmq;import org.springframework.amqp.core.AmqpTemplate;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Repository;@Repositorypublic class RabbitMqMessageProducer{ @Autowired private AmqpTemplate amqpTemplate; public void sendMessage(Object message) { System.out.println("to send message:" + message); amqpTemplate.convertAndSend("queueTestKey", message); }}
上述內容就是如何編寫Springweb集成rabbitmq代碼,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。