public class Spittle implements Serializable {
private Long id;
private Spitter spitter;
private String message;
private Date postedTime;
public Spittle(Long id, Spitter spitter, String message, Date postedTime) {
this.id = id;
this.spitter = spitter;
this.message = message;
this.postedTime = postedTime;
}
public Long getId() {
return this.id;
}
public String getMessage() {
return this.message;
}
public Date getPostedTime() {
return this.postedTime;
}
public Spitter getSpitter() {
return this.spitter;
}
}
public class ProducerMain {
public static void main(String[] args) throws Exception {
ApplicationContext context = new ClassPathXmlApplicationContext("amqp/amqp-producer.xml");
AmqpTemplate template = (AmqpTemplate) context.getBean("rabbitTemplate");
for (int i = 0; i < 20; i++) {
System.out.println("Sending message #" + i);
Spittle spittle = new Spittle((long) i, null, "Hello world (" + i + ")", new Date());
template.convertAndSend(spittle);
Thread.sleep(5000);
}
System.out.println("Done!");
}
}
其中convertAndSend方法默认第一个参数是交换机名称,第二个参数是路由名称,第三个才是我们发送的数据,现在我们启动程序,效果如下
第四个:消费者程序
首先编写一个用于监听生产者发送信息的代码
/**
* Created by Administrator on 2016/11/18.
*/
public class SpittleAlertHandler implements MessageListener {
@Override
public void onMessage(Message message) {
try {
String body=new String(message.getBody(),"UTF-8");
System.out.println(body);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
一定要注意实现MessageListener,我们只需要获取message的body即可,通过json来转换我们需要的程序(比如我们可以发送一个map,map存放方法和实体,这样我们可以通过反射来调用不同的程序来运行)。
下面我们配置消费者
public class ConsumerMain {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("amqp/amqp-consumer.xml");
}
}