在创建可以通过LDAP JNDI查找连接到IBM Websphere MQ的jms模板时需要帮助吗?

时间:2019-02-12 05:30:00

标签: java spring-boot ibm-mq jndi spring-jms

///我有一个独立的JAVA代码,可以通过JNDI查找连接到IBMMQ,并且可以发送或接收消息。我想通过Spring Boot实现相同的功能,但是无法配置jms模板?如果有人可以帮助我,我将不熟悉Spring Boot。

//这是有效的JAVA代码。

import java.security.Security;
import java.util.Hashtable;             //Imports for JNDI

import javax.jms.Connection;
import javax.jms.ConnectionFactory;     //Imports for JMS
import javax.jms.Destination;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.core.JmsTemplate;

import com.ibm.mq.MQException;          //Import for MQ Linked Exception

import net.bytebuddy.asm.Advice.This;

public class Jms11ListenerSample extends Thread implements MessageListener, ExceptionListener{

public void run() {
    //declaration of objects
    ConnectionFactory   jmsConnFactory  = null;     
    Destination         jmsDestination  = null;
    MessageConsumer     jmsConsumer     = null;

    jmsConnFactory = this.lookupCF();               
    jmsDestination = this.lookupDestination();      

    while (running) {
        try {
            if (!connected) {
                System.out.println("connecting to MQ...");
                //connect to MQ and start the connection:
                jmsConnection = jmsConnFactory.createConnection();
                jmsConnection.setExceptionListener(this);
                jmsConnection.start();
                jmsSession = jmsConnection.createSession(true, 0);  //Session.AUTO_ACKNOWLEDGE/CLIENT_ACKNOWLEDGE/DUPS_OK_ACKNOWLEDGE
                jmsConsumer = jmsSession.createConsumer(jmsDestination);

                jmsConsumer.setMessageListener(this);
                connected = true;
            }

            System.out.println("sleeping for " + DEFAULT_RECONNECT_PAUSE/1000 + " seconds ...");
            //Wait for onMSG / onExc
            try {Thread.sleep(DEFAULT_RECONNECT_PAUSE);} catch (Exception exc) {/*ignored*/}

        } catch (JMSException e) {
            onException(e);
        } //end try/catch
    } //end while 

    if (jmsConnection != null) {
        try {
            jmsConnection.close(); //this closes all sub-objects, too!
        } catch (JMSException e) {
            System.out.println("JMS Connection could not be closed: " + e);
            e.printStackTrace();
        }
    }
} //END RUN()


//This method is called from outside
public void onMessage(Message receiveMSG) {
    try {
        if (receiveMSG instanceof TextMessage) {
            System.out.println("Received a message: " + ((TextMessage)receiveMSG).getText());
        } else {
            System.out.println("Received a non-text message");
        }

        jmsSession.commit();

        DONE_MSGS++;
        if (DONE_MSGS >= MAX_MSGS) {running = false;}

    } catch (JMSException e) {
        onException(e);
    }
}


//This method is called when an exception occurs
public void onException(JMSException e) {
    if (jmsSession != null) {try {jmsSession.rollback();} catch (JMSException exc) {/*ignored*/}}

    //Print and analyse the error:
    System.out.println("JMS Exception: " + e);
    e.printStackTrace();
    //The linked exception is vital to errorhandling and cause determination. PRINT IT OUT!!!!
    MQException le = (MQException)e.getLinkedException();
    if (le != null) {
        int reasoncode = le.reasonCode;
        System.out.println("LINKED Exception:   " + le + " - REASON-CODE: " + reasoncode);
        if (reasoncode == MQException.MQRC_CONNECTION_BROKEN  ||  reasoncode == MQException.MQRC_Q_MGR_NOT_AVAILABLE) {
            System.out.println("Will have to reconnect!");
            connected=false;
            if (jmsConnection != null) {try {jmsConnection.close();} catch (JMSException exc) {/*ignored*/}}
            try {Thread.sleep(DEFAULT_RECONNECT_PAUSE);} catch (Exception exc) {/*ignored*/}
        } else {
            running = false;
        }

        //The cause is usually empty. In some cases (i.e. SSL) it might be set. PRINT IT OUT!!
        if (le.getCause() != null) {
            System.out.println("CAUSE of Linked Exception:  " + le.getCause());
        }
    }
}


//lookupCF() reads the ConnectionFactory from JNDI (LDAP). All threads use the same CF, therefore we do this only once.
private ConnectionFactory lookupCF() {
    //Synchronize so that not multiple threads try to overwrite 'theCF' !
    synchronized (this) {
        if (theCF != null) {
            return theCF;
        }

        InitialContext  ctx         = null;
        Hashtable       jndiContext = new Hashtable();
        jndiContext.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        jndiContext.put(Context.SECURITY_AUTHENTICATION, "none");
        jndiContext.put(Context.PROVIDER_URL, jndiLDAPserver);

        try {
            ctx     = new InitialContext(jndiContext);
            theCF   = (ConnectionFactory) ctx.lookup(jndiCFname);
            if (theCF == null) {
                System.out.println("FATAL ERROR: CF " + jndiCFname + " not found!");
                System.exit(1); //Quit because fatal error!
            }
            ctx.close();
        } catch (NamingException e) {
            e.printStackTrace(); System.exit(1); //Quit because fatal error!
        } catch(ClassCastException e) {
            e.printStackTrace(); System.exit(1); //Quit because fatal error!
        }

        return theCF;
    } //END synchonized
}//END lookupCF()


//lookupDestination() reads the Destination from JNDI (FILE). It is needed only once. 
private Destination lookupDestination() {

    Destination     destination = null;
    InitialContext  ctx         = null;
    Hashtable       jndiContext = new Hashtable();
    jndiContext.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
    jndiContext.put(Context.PROVIDER_URL, jndiDestinationFile);

    try {
        ctx         = new InitialContext(jndiContext);
        destination = (Destination) ctx.lookup(jndiDestinationName);
        if (destination == null) {
            System.out.println("FATAL ERROR: Destination " + jndiDestinationName + " not found!");
            System.exit(1);                 //Quit because fatal error
        }
        ctx.close();
    } catch (NamingException e) {
        e.printStackTrace(); System.exit(1); //Quit because fatal error
    } catch(ClassCastException e) {
        e.printStackTrace(); System.exit(1); //Quit because fatal error
    }
    return destination;
}//END OF lookupDestination()

private static  ConnectionFactory   theCF           = null; //Used for all threads

private         Session             jmsSession      = null;
private         Connection          jmsConnection   = null;
private         boolean             running         = true;
private         boolean             connected       = false;

private static String jndiLDAPserver                = "";
private static String jndiCFname                    = "";
private static String jndiDestinationFile           = "";
private static String jndiDestinationName           = "";

private final static int DEFAULT_RECEIVE_TIMEOUT    = 500;  //Milliseconds to wait for message if queue is empty!
private final static int DEFAULT_RECONNECT_PAUSE    = 5000; //Milliseconds to wait before next reconnect-try
private final static int DEFAULT_NUMBER_OF_THREADS  = 1;    //Milliseconds to wait before next reconnect-try
`enter code here`private final static int MAX_MSGS                  = 5;
private       static int DONE_MSGS                  = 0;


public static void main(String[] args) {
    System.out.println("starting application");

    //reading config
    if (args.length < 4) {
        System.out.println("Arguments missing.");
        System.out.println("LDAP-server&context  CF-name PathTo.bindings DestinationName");
        System.out.println("To force re-enabling SSLv3 enable support the property JMS11Sample.reenableSSLv3 must be <> NULL (check setup files for details)"); 
        System.exit(1);
    }

    jndiLDAPserver      = args[0];
    jndiCFname          = args[1];
    jndiDestinationFile = args[2];
    jndiDestinationName = args[3];

    if(System.getProperty("JMS11Sample.reenableSSLv3")!=null)
    {
        System.out.println("Force re-enabling SSLv3 support");
        String disabledAlgorithms = Security.getProperty("jdk.tls.disabledAlgorithms");
        Security.setProperty("jdk.tls.disabledAlgorithms", disabledAlgorithms .replace("SSLv3,", ""));
    }

    //Run the demo
    System.out.println("creating threads...");

    Jms11ListenerSample[]   myJMSthreads = new Jms11ListenerSample[DEFAULT_NUMBER_OF_THREADS];
    for (int i=0; i<DEFAULT_NUMBER_OF_THREADS; i++) {
        myJMSthreads[i] = new Jms11ListenerSample();
        myJMSthreads[i].start();
    }

    System.out.println("joining threads...");
    for (int i=0; i<DEFAULT_NUMBER_OF_THREADS; i++) {
        try {myJMSthreads[i].join();
        } catch (InterruptedException e) {
        }
    }

    System.out.println("application ended normally");
} //END MAIN()
 //END OF CLASS

///这是我在Spring Boot配置中尝试的-

@Configuration
@EnableJms
public class JmsConfig {
    @Value("${ibm.mq.queueManager}")
    private String queueManager;

    @Value("${ibm.mq.port}")
    private int port;

    @Value("${spring.jms.jndi-cf-name}")
    private String jndiCfName;

    @Value("${spring.jms.jndi-LDAP-Server}")
    private String jndiLdapServer;

    @Bean
    public ConnectionFactory getConnection(){
        ConnectionFactory connFactory = null;
        InitialContext  ctx         = null;
        Hashtable jndiContext   = new Hashtable();
        jndiContext.put(Context.INITIAL_CONTEXT_FACTORY, 
        "com.sun.jndi.ldap.LdapCtxFactory");
        jndiContext.put(Context.SECURITY_AUTHENTICATION, "none");
        jndiContext.put(Context.PROVIDER_URL, jndiLdapServer);
        try {
            ctx     = new InitialContext(jndiContext);
            connFactory = (ConnectionFactory) ctx.lookup(jndiCfName);
            if (connFactory == null) {
                System.out.println("FATAL ERROR: CF " + jndiCfName);
                System.exit(1);
            }
            ctx.close();
        } catch (NamingException e) {
            e.printStackTrace(); System.exit(1); 
        } catch(ClassCastException e) {
            e.printStackTrace(); System.exit(1); 
        }
        return connFactory;
    }
    @Bean
    public JmsTemplate jmsTemplate(){
    return new JmsTemplate(getConnection());
    }
}

0 个答案:

没有答案