创建程序测试MQ

1,创建生产者

package com.robert;
import java.util.Hashtable;
import java.util.Map; import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session; import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQMapMessage; public class Publisher { protected int MAX_DELTA_PERCENT = 1;
protected Map<String, Double> LAST_PRICES = new Hashtable<String, Double>();
protected static int count = 10;
protected static int total; protected static String brokerURL = "tcp://localhost:61616";
protected static transient ConnectionFactory factory;
protected transient Connection connection;
protected transient Session session;
protected transient MessageProducer producer; public Publisher() throws JMSException {
factory = new ActiveMQConnectionFactory(brokerURL);
connection = factory.createConnection();
try {
connection.start();
} catch (JMSException jmse) {
connection.close();
throw jmse;
}
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
producer = session.createProducer(null);
} public void close() throws JMSException {
if (connection != null) {
connection.close();
}
} public static void main(String[] args) throws JMSException {
Publisher publisher = new Publisher();
while (total < 1000) {
for (int i = 0; i < count; i++) {
publisher.sendMessage(args);
}
total += count;
System.out.println("Published '" + count + "' of '" + total + "' price messages");
try {
Thread.sleep(1000);
} catch (InterruptedException x) {
}
}
publisher.close();
} protected void sendMessage(String[] stocks) throws JMSException {
int idx = 0;
while (true) {
idx = (int)Math.round(stocks.length * Math.random());
if (idx < stocks.length) {
break;
}
}
String stock = stocks[idx];
Destination destination = session.createTopic("STOCKS." + stock);
Message message = createStockMessage(stock, session);
System.out.println("Sending: " + ((ActiveMQMapMessage)message).getContentMap() + " on destination: " + destination);
producer.send(destination, message);
} protected Message createStockMessage(String stock, Session session) throws JMSException {
Double value = LAST_PRICES.get(stock);
if (value == null) {
value = new Double(Math.random() * 100);
} // lets mutate the value by some percentage
double oldPrice = value.doubleValue();
value = new Double(mutatePrice(oldPrice));
LAST_PRICES.put(stock, value);
double price = value.doubleValue(); double offer = price * 1.001; boolean up = (price > oldPrice); MapMessage message = session.createMapMessage();
message.setString("stock", stock);
message.setDouble("price", price);
message.setDouble("offer", offer);
message.setBoolean("up", up);
return message;
} protected double mutatePrice(double price) {
double percentChange = (2 * Math.random() * MAX_DELTA_PERCENT) - MAX_DELTA_PERCENT; return price * (100 + percentChange) / 100;
}
}

2,创建消费者

package com.robert;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session; import org.apache.activemq.ActiveMQConnectionFactory; public class Consumer { private static String brokerURL = "tcp://localhost:61616";
private static transient ConnectionFactory factory;
private transient Connection connection;
private transient Session session; public Consumer() throws JMSException {
factory = new ActiveMQConnectionFactory(brokerURL);
connection = factory.createConnection();
connection.start();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
} public void close() throws JMSException {
if (connection != null) {
connection.close();
}
} public static void main(String[] args) throws JMSException {
Consumer consumer = new Consumer();
for (String stock : args) {
Destination destination = consumer.getSession().createTopic("STOCKS." + stock);
MessageConsumer messageConsumer = consumer.getSession().createConsumer(destination);
messageConsumer.setMessageListener(new Listener());
}
} public Session getSession() {
return session;
}
}

3,创建消息监听

package com.robert;

import java.text.DecimalFormat;

import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener; public class Listener implements MessageListener { @Override
public void onMessage(Message message) {
try {
MapMessage map = (MapMessage)message;
String stock = map.getString("stock");
double price = map.getDouble("price");
double offer = map.getDouble("offer");
boolean up = map.getBoolean("up");
DecimalFormat df = new DecimalFormat( "#,###,###,##0.00" );
System.out.println(stock + "\t" + df.format(price) + "\t" + df.format(offer) + "\t" + (up?"up":"down"));
} catch (Exception e) {
e.printStackTrace();
}
}
}

a,启动mq服务

b,先启动 消费者程序 Consumer.java

eclipse中添加运行参数如下:

c,启动生产者,发消息。

运行Publisher.java ,添加运行参数如上图所示。

d,登录  http://localhost:8161/admin/topics.jsp

运行如下所示:

转自:http://hi.baidu.com/tuoxinquyu/item/1e9bcfd069641a332a35c73d

小菜鸟学 MQ(三)的更多相关文章

  1. 小菜鸟 学MQ(二)

    mq服务启动以后 接着要做的事情就是 [发送]和[接受]消息. 首先有两种不同类型的Message:Topic,Queue 第一种Topic JMS规范定义了,Topic需要实现 发布和订阅两个功能, ...

  2. 小菜鸟学 MQ(一)

    第一步: 从http://activemq.apache.org/ 下载相关文件. apache-activemq-5.8.0-bin.zip 解压到指定目录下. 第二步: cmd 下切换到   mq ...

  3. 小菜鸟学Spring-读取属性文件值(三)

    Example: the PropertyPlaceholderConfigurer 属性配置文件内容如下所示: jdbc.driverClassName=org.hsqldb.jdbcDriver ...

  4. 小菜鸟学 Spring-Dependency injection(二)

    注入方式一:set注入 <bean id="exampleBean" class="examples.ExampleBean"> <!-- s ...

  5. 小菜鸟学 Spring-bean scope (一)

    this information below just for study record of mine. 默认情况下:Spring 创建singleton bean 以便于错误能够被发现. 延迟加载 ...

  6. 菜鸟学Java(十五)——Java反射机制(二)

    上一篇博文<菜鸟学编程(九)——Java反射机制(一)>里面,向大家介绍了什么是Java的反射机制,以及Java的反射机制有什么用.上一篇比较偏重理论,理论的东西给人讲出来总感觉虚无缥缈, ...

  7. 菜鸟学Java(十四)——Java反射机制(一)

    说到反射,相信有过编程经验的人都不会陌生.反射机制让Java变得更加的灵活.反射机制在Java的众多特性中是非常重要的一个.下面就让我们一点一点了解它是怎么一回事. 什么是反射 在运行状态中,对于任意 ...

  8. 【菜鸟学Linux】Cron Job定期删除Log(日志)文件

    以前一直做Windows开发,近期的项目中要求使用Linux.作为小菜鸟一枚,赶紧买了一本经典书<鸟哥的Linux私房菜>学习.最近刚好有一个小任务 - 由于产品产生的Log很多,而且增长 ...

  9. 菜鸟学自动化测试(八)----selenium 2.0环境搭建(基于maven)

    菜鸟学自动化测试(八)----selenium 2.0环境搭建(基于maven) 2012-02-04 13:11 by 虫师, 11419 阅读, 5 评论, 收藏, 编辑 之前我就讲过一种方试来搭 ...

随机推荐

  1. 一致性哈希算法学习及JAVA代码实现分析

    1,对于待存储的海量数据,如何将它们分配到各个机器中去?---数据分片与路由 当数据量很大时,通过改善单机硬件资源的纵向扩充方式来存储数据变得越来越不适用,而通过增加机器数目来获得水平横向扩展的方式则 ...

  2. mysql 存储过程,以及mybatis如何调用

    说道存储过程,很多人都知道,但是真正用的人其实很少,但是在某些必要的场景,是必须使用的,虽然可以使用java代码解决,但是效率性能远不及存储过程 曾经在sqlserver 以及pgadmin上用过,m ...

  3. C# explicit与implicit

    1.它们解决什么问题? 考虑下面的需求,Person类有个字段age.我想使用Person p = (Person) 18 来创建一个age为18的Person对象,怎么办? 更进一步,我想使用Per ...

  4. JMeter学习(二)录制脚本

    ---------------------------------------------------------------------------------------------------- ...

  5. 使用EditText+ListView并结合TextWatcher实现输入关键字筛选数据

    想必大家应该遇到过这样的情况,当点击Spinner控件后弹出的列表内容超多,一个一个滑动着去寻找所要的项很麻烦,尤其是当自己知道想要选择的内容,这时候如果我们只需要输入某些关键字,就可以讲上百条数据筛 ...

  6. sqlzoo.net刷题3

    Find the continents where all countries have a population <= 25000000. Then find the names of the ...

  7. js对象深潜拷贝(从requirejs中抠出来的)

    var op = Object.prototype, ostring = op.toString, hasOwn = op.hasOwnProperty; function isFunction(it ...

  8. 应用python编写简单新浪微博应用(一)

    转载至:http://blog.sina.com.cn/s/blog_6c39196501016o7n.html 首先,你要有一个新浪微博账号. 申请页面:http://weibo.com 其次,你要 ...

  9. Lua windows环境搭建

    Lua语言的小巧和功能强大在朋友做的一个项目中得以验证,自己也尝试着了解一下,首先在window系统上搭建一个学习环境. 官网:https://www.lua.org/ 搭建运行环境提供2种方式,源码 ...

  10. result默认返回action中的所有数据,要想返回指定的数据怎么做呢

    result默认返回action中的所有数据,要想返回指定的数据怎么做呢?