采用JMS实现的聚合器

聚合器从某个通道接收竞标消息,把相关的竞标消息集中起来,并把有最低竞标价的消息发布给另一个通道。竞标消息通过拍卖ID属性关联起来,它相当于消息的关联标识符。
其中:
1.Aggregator包含接收消息、把消息集中起来并发送结果消息的逻辑。它通过aggregate接口与集合交互。
2.AuctionAggregate实现了Aggregate接口
3.Auction是已接收的相关竞标消息的集合。
4.Bid是一个便利类,用于储存与竞标有关的数据项

sendMessage类用来模拟发送拍卖消息:
package com.foshanshop.ejb3.app;

import javax.jms.*;
import javax.jms.Queue;
import java.util.*;
import javax.naming.*;

public class sendMessage {

	static String PROP_AUCTIONID="AuctionID";
	static String ITEMID="ItemID";
	static String VENDOR="Vendor";
	static String PRICE="price";
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		QueueConnection conn=null;
		QueueSession session=null;

		try
		{
			Properties props=new Properties();
			props.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
            props.setProperty(Context.PROVIDER_URL, "localhost:1099");
            props.setProperty(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
            InitialContext ctx = new InitialContext(props);
            
            QueueConnectionFactory factory=(QueueConnectionFactory)ctx.lookup("QueueConnectionFactory");
            
            conn=factory.createQueueConnection();
            
            session=conn.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
            
            Destination destination=(Queue)ctx.lookup("queue/FQueueA");
            
            MessageProducer producer=session.createProducer(destination);
            
            MapMessage msg=session.createMapMessage();
            
            for(int i=0;i<3;i++)
            {
            	String [] vendor={"cy","chenyuan","yuanchen"};
            	msg.setStringProperty(PROP_AUCTIONID,"123");
    			msg.setString(ITEMID, "1234");
    			msg.setString(VENDOR, vendor[i]);
    			msg.setDouble(PRICE, i+10);
    			producer.send(msg);
            }
            
            //producer.send(msg);
		}
		catch(Exception e)
		{
			System.out.println("queueSender main has a problem"+":"+e.toString());
		}
	}

}


Aggregate接口:
package com.foshanshop.ejb3.app;

import javax.jms.*;

public interface Aggregate {

	public void addMessage(Message msg);
	public boolean isComplete();
	public Message getResultMessage();
}


package com.foshanshop.ejb3.app;

import javax.jms.Message;
import javax.jms.*;
import com.foshanshop.ejb3.bean.*;

public class AuctionAggregate implements Aggregate {

	static String PROP_AUCTIONID="AuctionID";
	static String ITEMID="ItemID";
	static String VENDOR="Vendor";
	static String PRICE="price";
	
	private Session session;
	private Auction auction;
	
	public AuctionAggregate(Session session)
	{
		this.session=session;
		auction=new Auction();
	}	
	
	public void addMessage(Message msg) {
		// TODO Auto-generated method stub
		Bid bid=null;
		if(msg instanceof MapMessage)
		{
			try
			{
				MapMessage mapmsg=(MapMessage)msg;
				String auctionID=mapmsg.getStringProperty(PROP_AUCTIONID);
				String itemID=mapmsg.getString(ITEMID);
				String vendor=mapmsg.getString(VENDOR);
				double price=mapmsg.getDouble(PRICE);
				
				bid=new Bid(auctionID,itemID,vendor,price);
				auction.addBid(bid);
			}
			catch(Exception e)
			{
				System.out.println(e.toString());
			}
		}
	}

	public Message getResultMessage() {
		// TODO Auto-generated method stub
		Bid bid=auction.getBestBid();
		try
		{
			MapMessage msg=session.createMapMessage();
			msg.setStringProperty(PROP_AUCTIONID,bid.getCorrelationID());
			msg.setString(ITEMID, bid.getItemId());
			msg.setString(VENDOR, bid.getVendorName());
			msg.setDouble(PRICE, bid.getPrice());
			return msg;
		}
		catch(Exception e)
		{
			System.out.println(e.toString());
		}
		return null;
	}

	public boolean isComplete() {
		// TODO Auto-generated method stub
		return auction.isComplete();
	}

}



package com.foshanshop.ejb3.app;
import com.foshanshop.ejb3.bean.*;
import java.util.*;
public class Auction {

	ArrayList bids=new ArrayList();
	public void addBid(Bid bid)
	{
		bids.add(bid);
		System.out.println(bids.size()+"  Bids in auction.");
	}
	
	public boolean isComplete()
	{
		return(bids.size()>=3);
	}
	
	public Bid getBestBid()
	{
		Bid bestBid=null;
		
		Iterator iter=bids.iterator();
		if(iter.hasNext())
		{
			bestBid=(Bid)iter.next();
			while(iter.hasNext())
			{
				Bid b=(Bid)iter.next();
				if(b.getPrice()<bestBid.getPrice())
				{
					bestBid=b;
				}
			}
		}
		return bestBid;
	}
}



package com.foshanshop.ejb3.bean;

import java.io.Serializable;

public class Bid implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7678873060248075903L;
	private String ItemId;
	private String VendorName;
	private double Price;
	private String CorrelationID;
	
	public Bid(String correlationID,String itemId,String vendorName,double price)
	{
		this.CorrelationID=correlationID;
		this.ItemId=itemId;
		this.VendorName=vendorName;
		this.Price=price;
	}
	
	public String getCorrelationID()
	{
		return this.CorrelationID;
	}
	public void setCorrelationID(String correlationID)
	{
		this.CorrelationID=correlationID;
	}
	
	public String getItemId()
	{
		return this.ItemId;
	}
	public void setItemId(String itemId)
	{
		this.ItemId=itemId;
	}
	
	public String getVendorName()
	{
		return this.VendorName;
	}
	public void setVendorName(String vendorName)
	{
		this.VendorName=vendorName;
	}
	
	public double getPrice()
	{
		return this.Price;
	}
	public void setPrice(double price)
	{
		this.Price=price;
	}

}



package com.foshanshop.ejb3.impl;

import java.util.*;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.MapMessage;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSession;
import javax.naming.Context;
import javax.naming.InitialContext;
import com.foshanshop.ejb3.app.*;
import java.util.*;
@MessageDriven(activationConfig={@ActivationConfigProperty(propertyName="destinationType",propertyValue="javax.jms.Queue"),
		@ActivationConfigProperty(propertyName="destination",propertyValue="queue/FQueueA"),@ActivationConfigProperty(propertyName="acknowledgeMode",propertyValue="Auto-acknowledge")})
public class Aggregator implements MessageListener {

	static final String PROP_CORRID="AuctionID";
	Map activeAggregates=new HashMap();
	QueueConnection conn=null;
	QueueSession session=null;
	
	public void onMessage(Message msg) {
		// TODO Auto-generated method stub
		try
		{
			Properties props=new Properties();
			props.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
            props.setProperty(Context.PROVIDER_URL, "localhost:1099");
            props.setProperty(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
            InitialContext ctx = new InitialContext(props);
            
            QueueConnectionFactory factory=(QueueConnectionFactory)ctx.lookup("QueueConnectionFactory");
            
            conn=factory.createQueueConnection();
            
            session=conn.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
            
            //Destination destinationA=(Queue)ctx.lookup("queue/FQueueA");
            Destination destinationB=(Queue)ctx.lookup("queue/FQueueB");
            MessageProducer producer=session.createProducer(destinationB);
            
            String correlationID=msg.getStringProperty(PROP_CORRID);
            Aggregate aggregate=(Aggregate)activeAggregates.get(correlationID);
            if(aggregate==null)
            {
            	aggregate=new AuctionAggregate(session);
            	activeAggregates.put(correlationID, aggregate);
            }
            
            if(!aggregate.isComplete())
            {
            	aggregate.addMessage(msg);
            	if(aggregate.isComplete())
            	{
            		MapMessage result=(MapMessage)aggregate.getResultMessage();
            		producer.send(result);
            	}
            }
		}
		catch(Exception e)
		{
			System.out.println(e.toString());
		}
	}

}


package com.foshanshop.ejb3.impl;

import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.MapMessage;
@MessageDriven(activationConfig={@ActivationConfigProperty(propertyName="destinationType",propertyValue="javax.jms.Queue"),
		@ActivationConfigProperty(propertyName="destination",propertyValue="queue/FQueueB"),@ActivationConfigProperty(propertyName="acknowledgeMode",propertyValue="Auto-acknowledge")})
public class receiveResult implements MessageListener {

	static String PROP_AUCTIONID="AuctionID";
	static String ITEMID="ItemID";
	static String VENDOR="Vendor";
	static String PRICE="price";
	
	public void onMessage(Message msg) {
		// TODO Auto-generated method stub
		try
		{
			if(msg instanceof MapMessage)
			{
				MapMessage mapmsg=(MapMessage)msg;
				System.out.println(mapmsg.getString(ITEMID)+":"+mapmsg.getDouble(PRICE));
			}
		}
		catch(Exception e)
		{
			System.out.println(e.toString());
		}
		
	}

}



build.xml
<?xml version="1.0"?>
<!-- ======================================================================= -->
<!-- EJB3 MessageDrivenBean build file                                       -->
<!-- ======================================================================= -->
<project name="aggregator" default="ejbjar" basedir="..">
	<property environment="env" />
	<property name="app.dir" value="${basedir}\aggregator" />
	<property name="src.dir" value="${app.dir}\src" />
	<property name="jboss.home" value="${env.JBOSS_HOME}" />
	<property name="jboss.server.config" value="default" />
	<property name="build.dir" value="${app.dir}\build" />
	<property name="build.classes.dir" value="${build.dir}\classes" />

	<!-- Build classpath -->
	<path id="build.classpath">
		<fileset dir="${jboss.home}\client">
			<include name="*.jar" />
		</fileset>
		<pathelement location="${build.classes.dir}" />
	</path>

	<!-- =================================================================== -->
	<!-- Prepares the build directory                                        -->
	<!-- =================================================================== -->
	<target name="prepare" depends="clean">
		<mkdir dir="${build.dir}" />
		<mkdir dir="${build.classes.dir}" />
	</target>

	<!-- =================================================================== -->
	<!-- Compiles the source code                                            -->
	<!-- =================================================================== -->
	<target name="compile" depends="prepare" description="编绎">
		<javac srcdir="${src.dir}" destdir="${build.classes.dir}" debug="on" deprecation="on" optimize="off" includes="com/**">
			<classpath refid="build.classpath" />
		</javac>
	</target>

	<target name="ejbjar" depends="compile" description="创建EJB发布包">
		<jar jarfile="${app.dir}\aggregator.jar">
			<fileset dir="${build.classes.dir}">
				<include name="com/foshanshop/ejb3/*.class" />
				<include name="com/foshanshop/ejb3/impl/*.class" />
				<include name="com/foshanshop/ejb3/bean/*.class" />
				<include name="com/foshanshop/ejb3/app/*.class" />
			</fileset>
		</jar>
	</target>

	<target name="deploy" depends="ejbjar">
		<copy file="${app.dir}\aggregator.jar" todir="${jboss.home}\server\${jboss.server.config}\deploy" />
	</target>

	<!-- =================================================================== -->
	<!-- Cleans up generated stuff                                           -->
	<!-- =================================================================== -->
	<target name="clean">
		<delete dir="${build.dir}" />
		<delete file="${jboss.home}\server\${jboss.server.config}\deploy\aggregator.jar" />
	</target>

</project>


你可能感兴趣的:(jboss,jms,UP)