【问题标题】:Calling webservice should be same thread or separate thread?调用 webservice 应该是同一个线程还是单独的线程?
【发布时间】:2015-10-29 16:38:04
【问题描述】:

下面我有一个socket程序代码sn-p。如果有数据,我首先要做什么,然后我在使用 dbconn1 的第一部分进行处理。之后,根据收到的数据,我得到了一个变量 callWebService,如果将其设置为 callWebService=1,那么我有一个 if 语句来建立另一个新连接并调用外部 Web 服务。由于有时 Web 服务关闭并且失败导致我的整个第一部分停止,我将它们拆分。我不确定这是正确的方法还是应该将部分部分完全分成一个单独的线程?哪个处理起来更有效,因为我注意到当 web 服务关闭时,它会导致我的资源上升,导致数据库连接被挂起

BufferedWriter writer1 = null; 
Connection dbconn1 = null;  
Connection dbconn2 = null;  
    public void run() { // etc
    writer1 = null;
    String message="";
    BufferedReader reader1 = null; 
    try { 

        writer1 =  new BufferedWriter(new OutputStreamWriter(receivedSocketConn1.getOutputStream()));
        reader1 = new BufferedReader(new InputStreamReader(receivedSocketConn1.getInputStream()));
        receivedSocketConn1.setSoTimeout(60000);
        int nextChar=0;
        int callWebService=0;
        while ((nextChar=reader1.read()) != -1) {    
            message += (char) nextChar; 
            if (nextChar == '*'){

                try{   
                   System.out.println("\n\n Trying establish a new db connection ");
                   dbconn1 = connectionPool.getConnection();
                   dbconn1.setAutoCommit(false);
                   System.out.println("\n\n Checking db connection status "+dbconn1.isClosed());
                   if ((dbconn1 == null) || dbconn1.isClosed()) {
                        System.out.println("\n\n db connection status is closed");
                        dbconn1 = connectionPool.getConnection();
                        dbconn1.setAutoCommit(false);
//other codes follow here.

                        // e.g. the callWebService=1;
                        dbconn1.commit();
                   }
                }
                catch (SQLException ex){ 
                  System.out.println("Error SQL Exception : "+ex.toString());
                  ex.printStackTrace(System.out);
                  try{    
                    dbconn1.rollback();  
                  } 
                   catch (Exception rollback) {    
                    System.out.println("\nRollback dbconn1 :");  
                    rollback.printStackTrace(System.out);
                  }
               }
               catch (Exception e){
                  System.out.println("\nSQL Error here :");
                  e.printStackTrace(System.out);
                 try{    
                  dbconn1.rollback();  
                 } 
                 catch (Exception rollback) {    
                   System.out.println("\nRollback dbconn1 :");  
                   rollback.printStackTrace(System.out);
                 }
               }
               finally{
                  try {

                  if ( dbconn1 != null ) {
                    dbconn1.close();
                    System.out.println("\n\n dbConn1 is being closed");
                 }

                 }
                catch(SQLException ex){
                  System.out.println("SQLException has been caught for dbConn1 close");
                  ex.printStackTrace();
              }

             if(callWebService==1){

                 try{   
                     System.out.println("\n\n Trying establish a new db connection ");
                     dbconn2 = connectionPool.getConnection();
                     dbconn2.setAutoCommit(false);
                     sendIncomingData(dataID, dataString) 
                     dbconn2.commit();
                  }
                  catch (SQLException ex){ 
                     System.out.println("Error SQL Exception : "+ex.toString());
                     ex.printStackTrace(System.out);
                     try{    
                       dbconn2.rollback();  
                     } 
                      catch (Exception rollback) {    
                       System.out.println("\nRollback dbconn2 :");  
                       rollback.printStackTrace(System.out);
                     }
                  }
                  catch (Exception e){
                     System.out.println("\nSQL Error here :");
                     e.printStackTrace(System.out);
                    try{    
                     dbconn2.rollback();  
                    } 
                    catch (Exception rollback) {    
                      System.out.println("\nRollback dbconn2 :");  
                      rollback.printStackTrace(System.out);
                    }
                  }
                  finally{
                     try {

                     if ( dbconn2 != null ) {
                       dbconn2.close();
                       System.out.println("\n\n dbConn2 is being closed");
                    }

                    }
                   catch(SQLException ex){
                     System.out.println("SQLException has been caught for dbConn1 close");
                     ex.printStackTrace();
                 }
             }



            } 

          }
      }


     }
     catch (SocketTimeoutException ex){ 
          System.out.println("SocketTimeoutException has been caught ");
          ex.printStackTrace();
     }  
     catch (IOException ex) { 
          System.out.println("IOException has been caught ");
          ex.printStackTrace();
     }  
     catch (Exception ex) { 

          System.out.println("Exception has been caught");
          ex.printStackTrace(System.out);
     }      
     finally{

       try {
           if (writer1 != null ) {
               writer1.close();
           }               
       }
       catch(IOException ex){
          System.out.println("IOException has been caught for finally");
          ex.printStackTrace(System.out);
       }
     }
}

void sendIncomingData(int dataID, String dataString) throws Exception {

        try{
            SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
            SOAPConnection soapConnection = soapConnectionFactory.createConnection();
            String url = "http://**********/webservice.asmx?WSDL";
            SOAPMessage soapACK = soapConnection.call(soapCalling(dataID,dataString), url);
            printSOAP(soapACK,dataID); //do some sql insert/update in this function
           }
           catch (Exception e){
                 e.printStackTrace();
                 System.err.println(e.toString());
                 throw e;
           }

}
SOAPMessage createSOAPIncoming(int dataID,String dataString) throws Exception {
          MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();
        SOAPPart soapPart = soapMessage.getSOAPPart();

        String serverURI = "http://*******";

        // SOAP Envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        SOAPBody body = envelope.getBody();
        SOAPBodyElement element = body.addBodyElement(envelope.createName("*******"));
        element.addChildElement("dataID").addTextNode(dataID);
        element.addChildElement("dataString").addTextNode(dataString);
        MimeHeaders headers = soapMessage.getMimeHeaders();
        soapMessage.saveChanges();

        /* Print the request message */
        System.out.print("\n\n Request SOAP Message To ACK FOR  = ");
        soapMessage.writeTo(System.out);
        System.out.print("\n\n After Print  = ");
        System.out.println();

        return soapMessage;
}

如果网络服务关闭,我经常会从网络服务中收到此错误。

SEVERE: SAAJ0537: Invalid Content-Type. Could be an error message instead of a SOAP message
com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Invalid Content-Type:text/html. Is this an error message instead of a SOAP response?
at com.sun.xml.internal.messaging.saaj.client.p2p.HttpSOAPConnection.call(HttpSOAPConnection.java:148)
at sk1$ConnectionHandler.sendIncomingData(sk1.java:2753)
at sk1$ConnectionHandler.run(sk1.java:2057)
at java.lang.Thread.run(Thread.java:722)
Caused by: com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Invalid Content-Type:text/html. Is this an error message instead of a SOAP response?
at com.sun.xml.internal.messaging.saaj.soap.MessageImpl.identifyContentType(MessageImpl.java:649)
at com.sun.xml.internal.messaging.saaj.soap.MessageFactoryImpl.createMessage(MessageFactoryImpl.java:85)
at com.sun.xml.internal.messaging.saaj.client.p2p.HttpSOAPConnection.post(HttpSOAPConnection.java:327)
at com.sun.xml.internal.messaging.saaj.client.p2p.HttpSOAPConnection.call(HttpSOAPConnection.java:144)

【问题讨论】:

    标签: java multithreading web-services


    【解决方案1】:

    解决问题的方法不是多线程,而是业务逻辑的正确实现。

    • 如果您正在执行的 Web 服务调用和 DB 内容在功能上是独立的,那么您可以将功能分成独立的块并释放连接或在另一个线程中实现该功能。
    • 如果 web 服务的调用和 DB 的东西是相互依赖的,那么你必须想办法抓住 web 服务停机的情况来处理这种情况并释放连接。

    【讨论】:

    • 我的问题是相互依赖的,我不得不打破它们的原因是网络服务链接的不确定性。那么你对捕捉网络服务宕机情况的建议是什么处理情况并释放连接?
    • 我已经用来自网络服务的经常出现的错误消息更新了我的问题?所以我设置了网络服务调用的超时时间?连接.setConnectTimeout (30 * 1000); connection.setReadTimeout (30 * 1000);
    猜你喜欢
    • 1970-01-01
    • 2014-10-12
    • 2019-08-16
    • 2019-03-09
    • 2021-12-06
    • 1970-01-01
    • 2018-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多