发消息到指定队列或者主题(queue,topic)
MessageBean也要对对应的主题进行listen

解决方案 »

  1.   

    配置Weblogic1.    启动WebLogic72.    打开IE6,在地址栏中输入:<http://localhost:7001/console>3.    输入用户名和密码4.    在左边的目录树中选中Services->JMS->Connection Factories,单击右侧的Configure a new JMS Connection Factory ,输入以下信息:Configuration->General页:Name = MDBDemo Connection FactoryJNDIName= MDBDemoCF其它不变,单击Create建立Connection Factory。Targets->Server页:将myserver(服务器名称)移至右侧的列表中,但击单击Apply5.    在左边的目录树中选中Services->JMS->Stores,单击右侧的Configure a new JMSFileStore,输入以下信息:Configuration->General页:Name = MDBDemo StoreDirectory: = F:\bea\user_projects\mydomain\JMSStores (任意存在的目录即可)单击Create建立JMSFileStore。6.          Services->JMS->Servers,单击右侧的Configure a new JMS Connection Factory ,输入以下信息:Configuration->General页:Name = MDBDemo JMSServerStore = MDBDemo Store其它不变,单击Create建立JMS Server。Targets->Servers页:Target = myserver(你的weblogic server的名字)单击Configuration->General页中的Configure DestinationsName = MDBDemo TopicJNDIName= MDBDemo Topic其它不变,单击Create建立Destination。配置完毕。建立Message Driven Bean:1. 关闭所有工程:File->Close Projects2. 选择File->New project 3. 在Name栏中输入MDBDemo,Directory栏中输入存放路径(不要有空格),其他不变,单击Finish。4. 选择File->New->Enterprise->EJB Module单击OK。5. 在弹出的对话框中,在Name中输入MDBMoudle, Version选择:EJB2.0 Compliant其余不变,单击OK关闭当前对话框。6. 在右侧的EJB Designer 中单击鼠标右键选择:Create EJB->Message-Driven Bean,按如下填写:Bean Name = MDBDemoTransaction Type = ContainerDestination Name = MDBDemo TopicDestination Type = javax.jms.Topic其它不变。7.Project->Make ”MDBModule”, 编译成功后,右键单击左上角的MDBModule选择Deploy Options for ”MDBModule.jar”->Deploy,将其发布至Weblogic。建立客户端:以下是客户端源码,保存成TestClient.java加入工程后,选择Run->Run “TestClient.java” using defaults运行即可,可以在weblogic console窗口看到输出。如果看不到输出,重起weblogic试一试。......
    ......(略)
      

  2.   

    没有问题,我喜欢大家一起学习一起进步。look
    这是一个实验,代码很简单,有了它,后面的功能你就自己填吧!
    顺便曾今研究过的兄弟姐妹也给点意见,看看为什么接受不到消息。有建设性的意见就发分JavaBean:(生成消息)
    package Bean;import java.io.Serializable;
    import java.rmi.RemoteException;import javax.ejb.*;
    import javax.jms.*;
    import jmsejb.*;
    import javax.naming.*;
    import java.util.*;import weblogic.jms.ServerSessionPoolFactory;
    import weblogic.jms.extensions.*;public class sessionBeanTest {
      public sessionBeanTest(){
      try{
            sessionBeanTest();
            }catch(Exception e){
             System.out.println("消息产生出错!!");
          }
      }
      public final static String JNDI_FACTORY="weblogic.jndi.WLInitialContextFactory";
      public final static String JMS_FACTORY="weblogic.examples.jms.QueueConnectionFactory";
      public final static String Queue="weblogic.examples.jms.exampleQueue";
      MessageListener listener;
      public void sessionBeanTest()throws Exception{
      /* 处理订单的逻辑从此处开始*/
              Context jndiEnc = null;
              QueueConnectionFactory Queuefactory=null;
              QueueConnection con=null;
              QueueSession session=null;
              QueueSender queuesender=null;
              QueueReceiver qreceiver=null;
              Queue queue=null;
              TextMessage message ;
              final int NUM_MSGS;
              try{
                System.out.println("取得JNDI的情景引用");
                jndiEnc=getInitialContext("t3://localhost:7001", "lyu", "netscape");
                // 使用 JNDI ENC 获取 JMS 工厂和主题标识符
                Queuefactory = (QueueConnectionFactory)jndiEnc.lookup(JMS_FACTORY);
                queue = (Queue)jndiEnc.lookup(Queue);
                  }catch(NamingException e){
                         System.out.println("JNDI lookup failed: " + e.toString());
                     }
              try{
                     System.out.println("发布一个TestMessag");
                     // 产生一个用来发送消息的发布者
                     con = Queuefactory.createQueueConnection();
                     session = con.createQueueSession(false, Session.AUTO_ACKNOWLEDGE );
                     //将一个 TextMessage 发送给主题(虚拟通道)
                     queuesender = session.createSender(queue);
                     /*处理订单以后,向其它系统发送有关此订单的一条消息*/
                     message = session.createTextMessage();
                     message.setJMSCorrelationID("19791121");
                     System.out.println("message.setJMSCorrelationID(19791121)");
                     message.setJMSType("liuyu");
                     System.out.println("message.setJMSType(liuyu)");
                     queuesender.send(message);
                     con.start();                 if(con!=null)
                        con.close();
                  }catch(Exception e){
                   System.out.println("error!!!");
                    }  }
      static Context getInitialContext(String url, String user, String password)
      throws Exception
      {
       Properties h = new Properties();
       h.put(Context.INITIAL_CONTEXT_FACTORY,
          "weblogic.jndi.WLInitialContextFactory");
       h.put(Context.PROVIDER_URL, url);
       if (user != null) {
            h.put(Context.SECURITY_PRINCIPAL, user);
            h.put(Context.SECURITY_CREDENTIALS, password == null ? "" : password);
          }   return new InitialContext(h);
      }}ejb:(接受消息)
    import java.util.*;
    import java.text.*;
    import javax.ejb.*;
    import javax.jms.*;
    import javax.naming.*;public class MessageBean implements MessageListener, MessageDrivenBean {
      private transient MessageDrivenContext messageDrivenContext;
      QueueReceiver qreceiver=null;
      public MessageBean(){
      }
      public void ejbCreate() throws CreateException {
      }
      public void ejbRemove() {
      }
      public void onMessage(Message msg) {
        System.out.println("<<<<MessageBean>>>>");
        try{
        if(msg instanceof TextMessage ){
          TextMessage text = (TextMessage)msg;
          String Id = "JMSCorrelationID = "+text.getJMSCorrelationID();
          String type = "JMSType = "+text.getJMSType();
          System.out.println(Id);
          System.out.println(type);
        }else{
             System.out.println("type is err!!");
          }
      }catch(Exception e){
              System.out.println("erro!!");
            }
      }
      public void setMessageDrivenContext(MessageDrivenContext messageDrivenContext) {
        this.messageDrivenContext = messageDrivenContext;
      }
    }
      

  3.   

    neuhawk(hawk) :
        非常感谢,只是现在我还是接受不到消息,你看看我的代码,最终的结果是不是应该为JAVABean和EJB的结果同时在后台答应出来?可是我的没有,你看是不是EJB写的有问题?
      

  4.   

    按MessageDirvenBean的说明,onMessage()是回调方法,我的理解是当有消息发上来的时候,EJB容器就通知这个onMessage()方法所在的Bean并调用它。可是楼上的说的也对EJB也需要对对应的主题进行listen,问题就出来了,我该在什么地方设置listen?EJB?JavaBean?
      

  5.   

    用instance of来区分消息类型的。
    mdb相当与接受消息的客户端吧。
      

  6.   

    在部署mdb中。
    <message-drive>有个子标签:
    <message-selector>,可以定义选择那种类型的消息。比如:
    <message-selector>
     JMSType='log'AMD logLeve='server'
    </message-selector>
    我猜想是这样的。
    queue or topic会给每个MDB发送消息,MDB会用instance of来判断消息是否是想要的。
    如果是的话,就处理。
    当然,可以想上面选择消息。
    我学j2ee才一个月,最近忙用jbuider+weblogic实际开发,所以我也不熟。
      

  7.   

    我的书上有个例子。是讲用2个mdb和一个实体bean的合作的。
    我有代码,
    不过太长。
    我也可以告诉你他们是怎么合作的。
    //我现在在做毕业设计,用j2ee+rep的知识,累死了。遇到很多问题,只能来这里救助了。
      

  8.   

    如果带光盘可以发到我的邮箱吗(代码)?活着你看看我上面发的代码有错的地方吗?我知道我现在为什么不能收消息了,因为我的EJB的状态根本就是“不存在”你的书上有讲到这种问题吗?这还不是EJB注册不成功的问题,而是注册成功了,但容器因为它的状态不对才不去触发它。rep是什么东东?我可以帮你问问我同事,了解mdb我也是才接到的任务。以前从来没搞过,都是sessionbean,这个东西配置真费劲
      

  9.   

    我打错了,是erp,而不是rep。
    我不知道怎么修改文章。所以没有修改
      

  10.   

    我今天测试了一下,按照我上面说的步骤,建好weblogic jms和mdb
    然后在onmessage里加一行代码。
      System.out.println("have received message");
    然后打包发布。
    然后建立客户端,代码是这样的:
    package mdbdemo;import java.rmi.RemoteException;import java.util.Properties;import javax.jms.JMSException;import javax.jms.Message;import javax.jms.Session;import javax.jms.TextMessage;import javax.jms.Topic;import javax.jms.TopicConnection;import javax.jms.TopicConnectionFactory;import javax.jms.TopicPublisher;import javax.jms.TopicSession;import javax.ejb.CreateException;import javax.ejb.RemoveException;import javax.naming.Context;import javax.naming.InitialContext;import javax.naming.NamingException;import javax.rmi.PortableRemoteObject;/** * This class illustrates calling a Message-Driven bean and publishing * quotes on a topic. * * @author Copyright (c) 1998-2002 by BEA Systems, Inc. All Rights Reserved. */public class TestClient {  static private String TOPIC_NAME = "MDBDemo Topic";  private String m_url;  private Context m_context;  private TopicConnection m_topicConnection;  public TestClient(String url)    throws NamingException  {    m_url = url;    try {      //      // Create a context      //      m_context = getInitialContext();      //      // Create the connection and start it      //      TopicConnectionFactory cf =        (TopicConnectionFactory) m_context.lookup("MDBDemoCF");      m_topicConnection = cf.createTopicConnection();      m_topicConnection.start();    }    catch(Exception ex) {      ex.printStackTrace();    }  }  /**   * Runs this example from the command line. Example:   * <p>   * <tt>java examples.ejb20.message.Client "t3://localhost:7001"</tt>   * <p>   * The parameters are optional, but if any are supplied,   * they are interpreted in this order:   * <p>   * @param url               URL such as "t3://localhost:7001" of Server   */  public static void main(String[] args) throws Exception {    log("\nBeginning message.Client...\n");    String url       = "t3://localhost:7001";    TestClient client = null;    try {      client = new TestClient(url);    } catch (NamingException ne) {      System.exit(1);    }    try {      client.example();    }    catch (Exception e) {      log("There was an exception while creating and using the MDB.");      log("This indicates that there was a problem communicating with the server: "+e);      //e.printStackTrace();    }    log("\nEnd message.Client...\n");  }  /**   * Runs this example.   */  public void example()    throws RemoteException, JMSException, NamingException  {    Topic newTopic = null;    TopicSession session = null;    try {      session =        m_topicConnection.createTopicSession(false,   // non transacted                                             Session.AUTO_ACKNOWLEDGE);      newTopic = (Topic) m_context.lookup(TOPIC_NAME);    }    catch(NamingException ex) {      newTopic = session.createTopic(TOPIC_NAME);      m_context.bind(TOPIC_NAME, newTopic);    }    TopicPublisher sender = session.createPublisher(newTopic);    TextMessage tm = session.createTextMessage();    String[] quotes = new String[] {      "BEAS 40 1/8", "SUNW 79 1/2", "IBM 82 1/4", "Hello !"    };    for (int i = 0; i < quotes.length; i++) {      tm.setText(quotes[i]);      sender.publish(tm);    }  }  /**   * Using a Properties object will work on JDK 1.1.x and Java2   * clients   */  private Context getInitialContext() throws NamingException {    try {      // Get an InitialContext      Properties h = new Properties();      h.put(Context.INITIAL_CONTEXT_FACTORY,        "weblogic.jndi.WLInitialContextFactory");      h.put(Context.PROVIDER_URL, m_url);      return new InitialContext(h);    }    catch (NamingException ex) {      log("We were unable to get a connection to the WebLogic server at "+m_url);      log("Please make sure that the server is running.");      throw ex;    }  }  /**   * This is the Java2 version to get an InitialContext.   * This version relies on the existence of a jndi.properties file in   * the application's classpath.   *   *///    private static Context getInitialContext()//      throws NamingException//    {//      return new InitialContext();//    }  private static void log(String s) {    System.out.println(s);  }}///
    运行以后,在weblogic的dos窗口,就可以看到:have received message
    have received message
    have received message
    have received message
      

  11.   

    你在配置EJB的时候,在Message-Driven Bean标签里,Connection factory name需要将JMS的
    Connection factory name填进去吗?Resource References标签的JNDI name 是不是JMS的工厂JNDI name?我还是接受不到消息,苦闷啊!
      

  12.   

    我发现好像发消息的的时候也要指定发送的Queue,用send(queue,message)方法,但是老是不成功,抛出异常,为什么?有知道的吗?。现在问题还没有解决,解决了就结账
      

  13.   

    OK!问题全部解决了。对曾经给予我帮助的 neuhawk(hawk;hymarx(偷偷给我一点爱) ;请接受我真诚的感谢!我现在准备把这几天的收获分享给大家,我的宗旨是大家一起学习一起进步。我会重新贴出一个新的贴子。 kreven(天地无用恨离别) 你现在可以真正的了解MessageDirvenBen的机制了。好现在开始发分。
      

  14.   

    liuyu9806(羽翔) 
    请问是怎么解决的??我的程序运行时,可以接受,当队列空的时候,再加入消息,这回那个Listener就不管用了。