创建程序测试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. 【温故而知新-Javascript】使用 Document 对象

    Document 对象时通往DOM功能的入口,它向你提供了当前文档的信息,以及一组可供探索.导航.搜索或操作结构与内容的功能. 我们通过全局变量document访问Document对象,它是浏览器为我 ...

  2. Axure学习笔记1--原型设计概述

    Axure原型 1.原型的出现 -软件功能复杂,用户需求多 -挖掘用户的实际需求 -项目组之间降低沟通成本 2.类型: [草图原型]描述产品大概需求,记录瞬间灵感 [低保真原型]展示系统的大致结构和基 ...

  3. JS的构造及其事件注意点总结

    一:js的组成 ECMAscript bom dom 类型包括: number boolean  string undefined  object function 二:基本函数作用 parseInt ...

  4. linux --备份oracle

    1.exp\imp 导入导出命令使用exp username/pwd@sid file=path.dmp owner=user 不导出表数据:rows=n举例:exp iflashbuy/qwerwh ...

  5. DataGridView 行、列的隐藏和删除

    ) 行.列的隐藏 [VB.NET] ' DataGridView1的第一列隐藏 DataGridView1.Columns(0).Visible = False ' DataGridView1的第一行 ...

  6. AE二次开发技巧之撤销、重做

    原文地址:http://www.cnblogs.com/wylaok/articles/2363208.html 可以把AE自带的重做.撤销按钮或工具添加到axToolBarControl上,再把ax ...

  7. PHP5.5 + IIS + Win7的配置

    PHP运行环境主要分windows环境和linux环境,本文主要简单介绍下我自己的配置,其他就不一一说明了. windows环境 方式一:.Apache的安装配置:2.MySQL的安装配置,可安装ph ...

  8. SSH公钥认证+优化

    一 ssh公钥认证流程: sshclinet机器:产生公私钥(公钥相当于一把锁) sshclient:将公钥发给sshserver(抛出锁子) sshclinet去连sshserver不需要密钥   ...

  9. 使用地址栏访问CXF Webservice写法

    /* * 通过url调用 * http://localhost:8080/EFP/webService/TestWebservice/testOut/arg0/liuyx */ http://loca ...

  10. 解决memcached不能远程访问的问题

    之前安装好memcached之后,一直是在本机连接使用的,没有出现问题,今天我改用从另一台机器连接到memcached时,却怎么也连接不上.后来一直想大概是防火墙的问题,关闭了防火墙后问题依然存在. ...