消息中间件三部曲:
- 开启服务器
- 配置文件
- 发送与接受
1, 生产者的Rabbitmq.xml配置
1.1 配置文件
<?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-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/rabbit
http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd">
<!--配置connection-factory,指定连接rabbit server参数-->
<rabbit:connection-factory id="connectionFactory" username="guest" password="guest"
host="localhost"
port="5672"
virtual-host="/"/>
<!--通过指定下面的admin信息,当前producer中的exchange和queue会在rabbitmq服务器上自动生成-->
<rabbit:admin connection-factory="connectionFactory"/>
<!--定义queue-->
<rabbit:queue id="com.mj.test" name="com.mj.test" durable="true" auto-delete="false" exclusive="false"/>
<!-- 定义direct exchange,绑定com.mj.test queue -->
<rabbit:direct-exchange name="myChange" durable="true" auto-delete="false">
<rabbit:bindings>
<rabbit:binding queue="com.mj.test" key="hello"></rabbit:binding>
</rabbit:bindings>
</rabbit:direct-exchange>
<!--定义rabbit template用于数据的接收和发送-->
<rabbit:template id="myAmqpTemplate" connection-factory="connectionFactory" exchange="myChange"/>
</beans>
1.2. 生产消息
@Service
public class MessageSender {
@Resource(name="myAmqpTemplate")
AmqpTemplate amqpTemplate;
public void sendMessage(Object message){
amqpTemplate.convertAndSend("hello",message);
}
}
2, 消费消息
2.1 配置文件
<?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-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/rabbit
http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd">
<rabbit:connection-factory id="connectionFactory" username="guest" password="guest"
host="localhost"
port="5672"
virtual-host="/"/>
<rabbit:queue id="com.mj.test" name="com.mj.test" durable="true" auto-delete="false" exclusive="false"/>
<bean id="messageReceiver" class="com.mj.amq.MessageReceiver"></bean>
<rabbit:listener-container connection-factory="connectionFactory">
<rabbit:listener queues="com.mj.test" ref="messageReceiver"/>
</rabbit:listener-container>
</beans>
2.2 监听消息
public class MessageReceiver implements MessageListener {
public void onMessage(Message message) {
System.out.println(message);
}
public static void main(String[]args){
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("ApplicationContext.xml");
}
}