目录
基本概念
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/rabbit
http://www.springframework.org/schema/rabbit/spring-rabbit.xsd
http://www.springframework.org/schema/beans
http://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