The is an easy sample how to receive messages via message driven approach, so call "push"
1 app-config.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:aop="http://www.springframework.org/schema/aop"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util" 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/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.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">
<rabbit:admin connection-factory="rabbitConnectionFactory" />
<rabbit:connection-factory id="rabbitConnectionFactory"
host="10.10.1.197" port="5672" channel-cache-size="1" username="tester1"
password="tester1" />
<rabbit:queue id="myqueue" name="test.queue1" />
<rabbit:listener-container
connection-factory="rabbitConnectionFactory" concurrency="1" prefetch="1">
<rabbit:listener queue-names="test.queue1" ref="myListener" />
</rabbit:listener-container>
<bean id="myListener" class="wx.mqdemo.MyListener" />
</beans>
2. message listener class
package wx.mqdemo;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
public class MyListener implements MessageListener {
public void onMessage(Message msg) {
byte[] body = msg.getBody();
System.out.println(new String(body));
// if want to roll-back message, throw runtime exception
// throw new RuntimeException("want to rollback tx");
}
}
3. java main
package wx.mqdemo;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class LaunchIt {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"app-context.xml");
context.start();
}
}
---------------
in order to run this sample, need to prepare a queue named "test.queue1" in rabbitmq, and create a user "tester1"
No comments:
Post a Comment