ProducerTool /MessageBroker /getConnectionFactoryF

lib:
jms1.1.jar
activemq-all-5.0.jar

首先启动 activemq.bat或者执行以下代码启动一个broker

1.import org.apache.activemq.broker.BrokerService;   
2.  
3./**  
4. * This example demonstrates how to run an embedded broker inside your Java code  
5. *   
6. * @version $Revision: 565003 $  
7. */  
8.public final class EmbeddedBroker {   
9.  
10.    private EmbeddedBroker() {   
11.    }   
12.  
13.    public static void main(String[] args) throws Exception {   
14.        BrokerService broker = new BrokerService();   
15.        broker.setUseJmx(true);   
16.        broker.addConnector("tcp://localhost:61616");   
17.        broker.start();   
18.  
19.        // now lets wait forever to avoid the JVM terminating immediately   
20.        Object lock = new Object();   
21.        synchronized (lock) {   
22.            lock.wait();   
23.        }   
24.    }   
25.}  

 

消费端

1.package com.jms;   
2.  
3.import javax.jms.Connection;   
4.import javax.jms.Destination;   
5.import javax.jms.JMSException;   
6.import javax.jms.Message;   
7.import javax.jms.MessageConsumer;   
8.import javax.jms.MessageListener;   
9.import javax.jms.Session;   
10.import javax.jms.TextMessage;   
11.  
12.import org.apache.activemq.ActiveMQConnection;   
13.import org.apache.activemq.ActiveMQConnectionFactory;   
14.  
15.public class ConsumerTool implements MessageListener {   
16.       
17.     private String user = ActiveMQConnection.DEFAULT_USER;   
18.  
19.     private String password = ActiveMQConnection.DEFAULT_PASSWORD;   
20.  
21.     private String url = ActiveMQConnection.DEFAULT_BROKER_URL;   
22.  
23.     private String subject = "TOOL.DEFAULT";   
24.  
25.     private Destination destination = null;   
26.  
27.     private Connection connection = null;   
28.  
29.     private Session session = null;   
30.  
31.     private MessageConsumer consumer = null;   
32.  
33.     //初始化   
34.     private void initialize() throws JMSException, Exception{   
35.         ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);   
36.         connection = connectionFactory.createConnection();   
37.         session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);   
38.         destination = session.createQueue(subject);   
39.         consumer = session.createConsumer(destination);   
40.     }   
41.  
42.     //消费消息   
43.     public void consumeMessage() throws JMSException, Exception{   
44.         initialize();   
45.         connection.start();   
46.  
47.         System.out.println("Consumer:->Begin listening...");   
48.         //开始监听   
49.         consumer.setMessageListener(this);   
50.         //Message message = consumer.receive();   
51.     }   
52.  
53.     //关闭连接   
54.     public void close() throws JMSException{   
55.         System.out.println("Consumer:->Closing connection");   
56.         if (consumer != null)   consumer.close();   
57.         if (session != null)    session.close();   
58.         if (connection != null)     connection.close();   
59.     }     
60.  
61.    public void onMessage(Message message) {   
62.        try{   
63.            if (message instanceof TextMessage){   
64.                TextMessage txtMsg = (TextMessage) message;   
65.                String msg = txtMsg.getText();   
66.                System.out.println("Consumer:->Received: " + msg);   
67.            } else{   
68.                System.out.println("Consumer:->Received: " + message);   
69.            }   
70.        } catch (JMSException e){   
71.            e.printStackTrace();   
72.        }   
73.    }   
74.  
75.}  

 

producter:

1.package com.jms;   
2.  
3.import javax.jms.Connection;   
4.import javax.jms.DeliveryMode;   
5.import javax.jms.Destination;   
6.import javax.jms.JMSException;   
7.import javax.jms.MessageProducer;   
8.import javax.jms.Session;   
9.import javax.jms.TextMessage;   
10.  
11.import org.apache.activemq.ActiveMQConnection;   
12.import org.apache.activemq.ActiveMQConnectionFactory;   
13.  
14.public class ProducerTool {   
15.       
16.     private String user = ActiveMQConnection.DEFAULT_USER;   
17.  
18.     private String password = ActiveMQConnection.DEFAULT_PASSWORD;   
19.  
20.     private String url = ActiveMQConnection.DEFAULT_BROKER_URL;   
21.  
22.     private String subject = "TOOL.DEFAULT";   
23.  
24.     private Destination destination = null;   
25.  
26.     private Connection connection = null;   
27.  
28.     private Session session = null;   
29.  
30.     private MessageProducer producer = null;      
31.  
32.     //初始化   
33.     private void initialize() throws JMSException, Exception{   
34.         ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);   
35.         connection = connectionFactory.createConnection();   
36.         session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);   
37.         destination = session.createQueue(subject);   
38.         producer = session.createProducer(destination);   
39.         producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);   
40.     }   
41.        
42.     //发送消息   
43.     public void produceMessage(String message) throws JMSException, Exception{   
44.         initialize();   
45.         TextMessage msg = session.createTextMessage(message);   
46.         connection.start();   
47.         System.out.println("Producer:->Sending message: " + message);   
48.         producer.send(msg);   
49.         System.out.println("Producer:->Message sent complete!");   
50.     }   
51.        
52.     //关闭连接   
53.     public void close() throws JMSException{   
54.         System.out.println("Producer:->Closing connection");   
55.         if (producer != null) producer.close();   
56.         if (session != null) session.close();   
57.         if (connection != null) connection.close();   
58.     }      
59.  
60.}  

 

下面是一个Broker实现,不属于同一个例子!

1.package com.jms;   
2.  
3.import java.io.IOException;   
4.import java.util.Hashtable;   
5.  
6.import javax.jms.Connection;   
7.import javax.jms.ConnectionFactory;   
8.import javax.jms.Destination;   
9.import javax.jms.JMSException;   
10.import javax.jms.Message;   
11.import javax.jms.MessageConsumer;   
12.import javax.jms.MessageProducer;   
13.import javax.jms.Session;   
14.import javax.naming.Context;   
15.import javax.naming.InitialContext;   
16.import javax.naming.NamingException;   
17.import javax.servlet.ServletConfig;   
18.import javax.servlet.ServletException;   
19.import javax.servlet.http.HttpServlet;   
20.import javax.servlet.http.HttpServletRequest;   
21.import javax.servlet.http.HttpServletResponse;   
22.  
23.public class MessageBroker extends HttpServlet   
24.{   
25.    private ConnectionFactory confactory=null;   
26.    private Connection jmsCon=null;   
27.    private Destination dest=null;   
28.    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException    
29.    {   
30.        this.doPost(req, resp);   
31.    }   
32.  
33.    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException    
34.    {   
35.        Session session;   
36.        try    
37.        {   
38.            String deptId=null;   
39.            String deptName=null;   
40.            deptId=req.getParameter("deptId");   
41.            deptName=req.getParameter("deptName");   
42.            session = this.jmsCon.createSession(false, Session.CLIENT_ACKNOWLEDGE);   
43.            MessageProducer msgProducer=session.createProducer(dest);   
44.            Message textMsg=session.createTextMessage();   
45.            textMsg.setStringProperty("deptId", deptId);   
46.            textMsg.setStringProperty("deptName", deptName);   
47.            msgProducer.send(textMsg);   
48.            session.close();   
49.            resp.sendRedirect("http://localhost/JmsTestWeb2/");   
50.        }   
51.        catch (Exception e)   
52.        {   
53.            // TODO Auto-generated catch block   
54.            e.printStackTrace();   
55.        }   
56.           
57.    }   
58.    /**  
59.     *   
60.     */  
61.    public void init(ServletConfig config) throws ServletException    
62.    {   
63.        super.init(config);   
64.        try    
65.        {   
66.            this.confactory=this.getConnectionFactoryFromLdap();   
67.            this.dest=this.getDestinationFromLdap();   
68.            this.jmsCon=this.confactory.createConnection();   
69.            /** 开启一个会话来创建一个消息消费者,异步监听到来的消息。*/  
70.            Session session=jmsCon.createSession(false, Session.CLIENT_ACKNOWLEDGE);   
71.            MessageConsumer msgConsumer=session.createConsumer(this.dest);   
72.            MessageListenerForOrgMsg msgListener=new MessageListenerForOrgMsg();   
73.            msgConsumer.setMessageListener(msgListener);   
74.            /** 开启另一个会话来创建另外一个消息消费者,异步监听到来的消息。*/                
75.            Session session2=jmsCon.createSession(false, Session.CLIENT_ACKNOWLEDGE);   
76.            MessageConsumer msgConsumer2=session2.createConsumer(this.dest);   
77.            MessageListenerForOrgMsg2 msgListener2=new MessageListenerForOrgMsg2();   
78.            msgConsumer2.setMessageListener(msgListener2);   
79.            this.jmsCon.start();                
80.        }    
81.        catch (Exception e)    
82.        {   
83.            e.printStackTrace();   
84.        }   
85.    }   
86.    /**  
87.     *   
88.     * @return  
89.     * @throws NamingException  
90.     */  
91.    private ConnectionFactory getConnectionFactoryFromLdap() throws NamingException   
92.    {   
93.           String account="uid=admin,ou=administrators,ou=topologymanagement,o=netscaperoot";//操作LDAP的帐户。默认就是Admin。   
94.           String password="111111" ;//帐户Admin的密码。   
95.           String root="ou=jmsstore,dc=xindongfang,dc=com"; //所操作的WLS域。也就是LDAP的根节点的DC   
96.           Hashtable env = new Hashtable();   
97.           env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");//必须这样写,无论用什么LDAP服务器。   
98.           env.put(Context.PROVIDER_URL, "ldap://192.168.0.15:2922/" + root);//LDAP服务器的地址:端口。对WLS端口就是7001  
99.           env.put(Context.SECURITY_AUTHENTICATION, "simple");//授权界别,可以有三种授权级别,但是如果设为另外两种都无法登录,我也不知道为啥,但是只能设成这个值"none"。   
100.           env.put(Context.SECURITY_PRINCIPAL, account );//载入登陆帐户和登录密码   
101.           env.put(Context.SECURITY_CREDENTIALS, password);   
102.           InitialContext ctx=null;   
103.           ConnectionFactory conFacotry=null;   
104.           try  
105.           {   
106.               ctx = new InitialContext(env);//初始化上下文   
107.               conFacotry=(ConnectionFactory)ctx.lookup("cn=topicconfac");   
108.               System.out.println("get Connection factory success");   
109.               return conFacotry;   
110.           }   
111.             
112.           finally  
113.           {   
114.               if (ctx!=null) ctx.close();      
115.           }   
116.      }   
117.     /**  
118.      *   
119.      * @return  
120.      * @throws NamingException  
121.      */  
122.      private Destination getDestinationFromLdap() throws NamingException   
123.      {   
124.           String account="uid=admin,ou=administrators,ou=topologymanagement,o=netscaperoot";//操作LDAP的帐户。默认就是Admin。   
125.           String password="111111" ;//帐户Admin的密码。   
126.           String root="ou=jmsstore,dc=xindongfang,dc=com"; //所操作的WLS域。也就是LDAP的根节点的DC   
127.           Hashtable env = new Hashtable();   
128.           env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");//必须这样写,无论用什么LDAP服务器。   
129.           env.put(Context.PROVIDER_URL, "ldap://192.168.0.15:2922/" + root);//LDAP服务器的地址:端口。对WLS端口就是7001  
130.           env.put(Context.SECURITY_AUTHENTICATION, "simple");//授权类别,可以有三种授权级别,但是如果设为另外两种都无法登录,我也不知道为啥,但是只能设成这个值"none"。   
131.           env.put(Context.SECURITY_PRINCIPAL, account );//载入登陆帐户和登录密码   
132.           env.put(Context.SECURITY_CREDENTIALS, password);   
133.           InitialContext ctx=null;   
134.           Destination dst=null;   
135.           try  
136.           {   
137.               ctx = new InitialContext(env);//初始化上下文   
138.               dst=(Destination)ctx.lookup("cn=orgmsg");   
139.               System.out.println("get destination success");   
140.               return dst;      
141.           }   
142.           finally  
143.           {   
144.               if (ctx!=null) ctx.close();   
145.           }   
146.       }   
147.  
148.    public void destroy()    
149.    {   
150.        if (this.jmsCon!=null)   
151.        {   
152.            try    
153.            {   
154.               this.jmsCon.close();   
155.            }    
156.            catch (JMSException e)    
157.            {   
158.               e.printStackTrace();   
159.            }   
160.        }   
161.        super.destroy();   
162.    }   
163.}  

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值