2014년 1월 2일 목요일

Oracle 10g Connection Cache Callback Sample[재직자무료교육/프로그래머교육/구로디지털IT교육,오라클/자바/닷넷/C#/iOS/안드로이드/아이폰교육]

Oracle 10g Connection Cache Callback Sample[재직자무료교육/프로그래머교육/구로디지털IT교육,오라클/자바/닷넷/C#/iOS/안드로이드/아이폰교육]

10g Connection Cache Callback Sample
 
묵시적인 Connection Cache는 데이터베이스 Connection이 캐시로부터 리턴 될 수 있는 기능을 제공 합니다. Callback OracleConnection에 등록되면 Connection Cache Connection이 재 요구되기 전에 callback handleAbandonedConnection() 메소드를 호출 합니다. 만약 return값이 true라면 해당 Connection객체가 재 사용되어 지는 것입니다.
 
아래의 예제를 보시면서 이해하도록 하겠습니다.  [OTN 자료]
 
---------------------------
CacheManager.java
---------------------------
 
/**
   * @author  Shrinivas Bhat
   * @version 1.0
   *
   * Development Environment        :  Oracle JDeveloper 10g
   * Name of the Application        :  CacheManager.java
   * Creation/Modification History  :
   *
   *    Shrinivas       18-Jun-2004      Created
   *
   * Overview of Application        : This class is used to create and maintain
   * a connection cache.
   **/
  
  package oracle.otnsamples.jdbc10g;
 
  // Java IO Exception class
  import java.io.IOException;
 
  // Java Utility classes
  import java.util.Enumeration;
  import java.util.Properties;
  import java.util.ResourceBundle;
 
  // Java SQL classes
  import java.sql.Connection;
  import java.sql.SQLException;
 
  // Oracle JDBC classes
  import oracle.jdbc.pool.OracleConnectionCacheManager;
  import oracle.jdbc.pool.OracleDataSource;
 
  /**
   * This class is used to create and manage the connection cache.
   */
  public class CacheManager  {
   
    // OracleDataSource object
    private static OracleDataSource ods = null;
    // Connection cache name
    public static final String CACHE_NAME = "ConnectionCacheSample";
 
    /**
     * Default constructor
     */
    public CacheManager() {
      try {
        // Create OracleDataSource object if it is not null
        if( ods == null ) {
          ods = new OracleDataSource();     
          // Configure the datasource
          configureDataSource();
        }
      } catch(SQLException sqlEx )  {
        sqlEx.printStackTrace();
      } catch(IOException ioEx)  {
        ioEx.printStackTrace();
      }
 
    }
 
    /**
     * This method configures the Datasource with appropriate values of Host
     * Name, User Name, Password etc. Note that the configuration parameters are
     * stored in Connection.properties file.
     *
     */
    private void configureDataSource() throws SQLException, IOException  {
       // Load the properties file to get the connection information
       // from the Connection.properties file
       Properties prop = this.loadParams("Connection");
      
       // Set the database properties
       ods.setUser(prop.getProperty("UserName"));
       ods.setPassword(prop.getProperty("Password"));
       ods.setServerName(prop.getProperty("HostName"));
       ods.setDatabaseName( prop.getProperty("SID") );
       ods.setPortNumber(Integer.parseInt( prop.getProperty("Port") ) );
       ods.setDriverType("thin");    
            
       // Enable implicit connection cache
       ods.setConnectionCachingEnabled(true);
      
       // Cache properties
       Properties cacheProperties = new Properties();
 
       // Set Max Limit for the Cache
       cacheProperties.setProperty("MaxLimit", "4");
 
       // Set the PropertyCheckInterval for 2 seconds
       cacheProperties.setProperty("PropertyCheckInterval", "2");        
      
       // Set the AbandonedConnectionTimeout for 2 seconds
       cacheProperties.setProperty("AbandonedConnectionTimeout", "2");        
 
       // Set the LowerThresholdLimit property to 25 percent (of the MaxLimit)
       cacheProperties.setProperty("LowerThresholdLimit", "25");        
 
       // Get the OracleConnectionCacheManager instance      
       OracleConnectionCacheManager connMgr =
              OracleConnectionCacheManager.getConnectionCacheManagerInstance();
      
       // Create the cache      
       connMgr.createCache(CACHE_NAME,ods,cacheProperties);          
    }
   
    /**
     * This method reads a properties file, which is passed as the parameter 
     * and loads it into a java Properties object and returns the object.
     *
     * @param file - File name
     *
     * @return Properties object
     *
     * @throws IOException
     */
    private Properties loadParams(String file)  throws  IOException {
      // Loads a ResourceBundle and creates Properties from it
      Properties prop = new Properties();
      ResourceBundle bundle = ResourceBundle.getBundle(file);
      Enumeration enum = bundle.getKeys();
      String key = null;
   
      while (enum.hasMoreElements()) {
        key = (String) enum.nextElement();
        prop.put(key, bundle.getObject(key) );
      }
      // Return  properties
      return prop;
    }
   
    /**
     * This method returns a connection from the cache.
     * @return Connection - Connection object
     * @throws java.sql.SQLException - SQL Exception
     */
    public Connection getConnection() throws SQLException {
      return ods.getConnection();
    }
  }
 
 
------------------------
CallbackHandler.java
------------------------
 
/**
 * @author  Shrinivas Bhat
 * @version 1.0
 *
 * Development Environment        :  Oracle JDeveloper 10g
 * Name of the Application        :  CallbackHandler.java
 * Creation/Modification History  :
 *
 *    Shrinivas       18-Jun-2004      Created
 *
 * Overview of Application        : This class implements the
 * OracleConnectionCacheCallback interface.
 **/
 
package oracle.otnsamples.jdbc10g;
 
// Oracle JDBC imports
import oracle.jdbc.OracleConnection;
import oracle.jdbc.pool.OracleConnectionCacheCallback;
 
public class CallbackHandler  implements OracleConnectionCacheCallback  {
 
  /**
   * When the release connection callback is registered on a connection, and the
   * cache from which the connection was retrieved is empty, then instead of
   * the default behavior to wait for connections to be returned to the cache,
   * this method is called by the cache.
   * @param conn - OracleConnection object
   * @param obj - Any Java object that needs to be processed in this method
   */
  public void releaseConnection(OracleConnection conn, Object obj) {
    try  {
      System.out.print("\nReleasing connection from thread \"");
      System.out.println(((EmpManager)obj).getThreadName()+"\"");
      // Release the connection
      if (conn != null)  {
        conn.close();            
      }
    } catch (Exception ex)  {
      ex.printStackTrace();
    }
  }
 
  /**
   * When the handle abandoned connection callback is registered, the
   * connection cache calls this method when a connection needs to be
   * reclaimed.
   * @param conn - OracleConnection object
   * @param obj - Any Java object that needs to be processed in this method
   * @return - true of false
   */
  public boolean handleAbandonedConnection(OracleConnection conn, Object obj)  {
    try  {
       // Close the connection
       if ( conn != null )  {
         conn.close();
       }
       // Set a flag in the application to indicate the connection closure
      if ( obj != null )  {
        ((EmpManager)obj).isActive = false;
      }
    } catch (Exception ex)  {
      ex.printStackTrace();
    }
    return true;
  }
}
 
 
--------------------------
Emp.java
--------------------------
 
/**
   * @author  Shrinivas Bhat
   * @version 1.0
   *
   * Development Environment        :  Oracle JDeveloper 10g
   * Name of the Application        :  EmpManager.java
   * Creation/Modification History  :
   *
   *    Shrinivas       18-Jun-2004      Created
   *
   * Overview of Application        : This class connects to the database and
   * displays the contents in the EMP table. This class makes use of CacheManager
   * class to access the connection cache.
   **/
package oracle.otnsamples.jdbc10g;
 
// Java SQL imports
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
 
// Oracle JDBC imports
import oracle.jdbc.OracleConnection;
import oracle.jdbc.OracleResultSet;
import oracle.jdbc.OracleStatement;
import oracle.jdbc.pool.OracleConnectionCacheManager;
import oracle.jdbc.rowset.OracleCachedRowSet;
 
  /**
   * This class is used to connect to the database and print the results.
   * This extends the java.lang.Thread class and implements the run method. When
   * the thread is started it calls the display() method which displays the
   * contents from the emp table.
   */
  public class Emp extends Thread  {
    // OracleConnection conn = null;
    CacheManager cacheManager = null;
    // OracleConnectionCacheManager object
    OracleConnectionCacheManager connMgr = null;
    // Thread name
    String name = null;
    // Boolean field that indicates whether the connection is active or not
    boolean isActive = true;
    // Connection cache name
    public static final String CACHE_NAME = "ConnectionCacheSample";
 
    /**
     * Constructor.
     * @param name - Name of the thread
     */
    public Emp(String name) {
     super(name);
     this.name = name;
     try  {
      if (cacheManager == null) {
        cacheManager= new CacheManager();
        connMgr = OracleConnectionCacheManager.getConnectionCacheManagerInstance();
        // Start the thread
        this.start();
      }
     } catch (Exception ex)  {
      ex.printStackTrace();
     }
    }
 
    /**
     * The run method of the thread.
     */
    public void run() {
        System.out.println(" Starting thread " + name );
     try  {
       this.display();
     } catch (Exception ex)  {
       ex.printStackTrace();
     }
 
    }
 



  • JAVA
  • ORACLE
  • iPhone/Android
  • .NET
  • 표준웹/HTML5
  • 채용/취업무료교육
  • 초보자(재학생)코스

  • 댓글 없음:

    댓글 쓰기