Java笔记-Spring中RabbitMQ的调用
生活随笔
收集整理的這篇文章主要介紹了
Java笔记-Spring中RabbitMQ的调用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
目錄
?
基本概念
代碼與演示
?
基本概念
Spring中已經整合了RabbitMQ,通過配置bean文件,然后在源碼中加載,可以簡化代碼操作。
身為C++程序員不得不說這種方式真的是太爽了。
在本人做過的某些項目中,很多大佬也喜歡用C++采用這種方式,進行函數的回調。
配置一個xml文件,指定dll和c接口,從而進行回調,這樣可以時得程序變得更加的靈活。
?
?
代碼與演示
程序運行截圖如下:
源碼如下:
MyConsumer.java
package spring;public class MyConsumer {//具體執行業務的方法public void listen(String foo){System.out.println("消費者:" + foo);} }SpringMain.java
package spring;import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;public class SpringMain {public static void main(String[] args) throws InterruptedException {AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("context.xml");//RabbitMQ模板RabbitTemplate template = ctx.getBean(RabbitTemplate.class);//發送消息template.convertAndSend("Hello world! spring");Thread.sleep(1000);//容器消耗ctx.destroy();} }context.xml
<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/rabbithttp://www.springframework.org/schema/rabbit/spring-rabbit.xsdhttp://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd"><!-- 定義RabbitMQ連接工廠 --><rabbit:connection-factory id="connectionFactory"host="127.0.0.1" port="5672" username="cff" password="123" virtual-host="/vhost_cff"/><!-- 定義Rabbit模板,指定連接工廠以及定義exchange --><rabbit:template id="amqpTemplate" connection-factory="connectionFactory" exchange="fanoutExchange" /><!-- MQ的管理,包括隊列、交換機 聲明等 --><rabbit:admin connection-factory="connectionFactory" /><!-- 定義隊列,自動聲明 --><rabbit:queue name="myQueue" auto-declare="true" durable="true" /><!-- 定義交換機,自動聲明 --><rabbit:fanout-exchange name="fanoutExchange" auto-declare="true"><rabbit:bindings><rabbit:binding queue="myQueue" /></rabbit:bindings></rabbit:fanout-exchange><!-- 監聽隊列 --><rabbit:listener-container connection-factory="connectionFactory"><rabbit:listener ref="foo" method="listen" queue-names="myQueue"/></rabbit:listener-container><!-- 消費者 --><bean id="foo" class="spring.MyConsumer" /></beans>log4j.properties
# Global logging configuration 開發時候建議使用 debug log4j.rootLogger=DEBUG, stdout # Console output... log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n?
?
源碼下載地址:
https://github.com/fengfanchen/Java/tree/master/SpringMQDemo
總結
以上是生活随笔為你收集整理的Java笔记-Spring中RabbitMQ的调用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Nginx笔记-使用Nginx给vue应
- 下一篇: Java笔记-JNI的基本使用(Java