Microsoft PowerPoint - 18-DataSource.ppt

Similar documents
rmi_박준용_final.PDF

Connection 8 22 UniSQLConnection / / 9 3 UniSQL OID SET

쉽게 풀어쓴 C 프로그래밊

Spring Boot/JDBC JdbcTemplate/CRUD 예제

J2EE Concepts

FileMaker ODBC and JDBC Guide

PowerPoint 프레젠테이션

Interstage5 SOAP서비스 설정 가이드

교육2 ? 그림

JMF2_심빈구.PDF

자바-11장N'1-502

신림프로그래머_클린코드.key

02 C h a p t e r Java

FileMaker 15 ODBC 및 JDBC 설명서

Microsoft PowerPoint - 04-UDP Programming.ppt

No Slide Title

歯JavaExceptionHandling.PDF

FileMaker ODBC 및 JDBC 가이드

JMF3_심빈구.PDF

Chap12

12-file.key

FileMaker ODBC and JDBC Guide

PowerPoint 프레젠테이션

10.ppt

Microsoft PowerPoint - Supplement-03-TCP Programming.ppt [호환 모드]

Microsoft PowerPoint - RMI.ppt

Network Programming

Microsoft PowerPoint - GUI _DB연동.ppt [호환 모드]

Analyze Connection Failover Options.ppt

PowerPoint 프레젠테이션

Microsoft PowerPoint - 03-TCP Programming.ppt

API STORE 키발급및 API 사용가이드 Document Information 문서명 : API STORE 언어별 Client 사용가이드작성자 : 작성일 : 업무영역 : 버전 : 1 st Draft. 서브시스템 : 문서번호 : 단계 : Docum

ilist.add(new Integer(1))과 같이 사용하지 않고 ilist.add(1)과 같이 사용한 것은 자바 5.0에 추가된 기본 자료형과 해당 객체 자료 형과의 오토박싱/언박싱 기능을 사용한 것으로 오토박싱이란 자바 컴파일러가 객체를 요구하는 곳에 기본 자료형

개요오라클과티베로에서 JDBC 를통해접속한세션을구분할수있도록 JDBC 접속시 ConnectionProperties 를통해구분자를넣어줄수있다. 하나의 Node 에다수의 WAS 가있을경우 DB 에서 Session Kill 등의동작수행시원하는 Session 을선택할수있다.

비긴쿡-자바 00앞부속

fundamentalOfCommandPattern_calmglow_pattern_jstorm_1.0_f…

PowerPoint Presentation

(Microsoft PowerPoint - Chapter17 RMI.ppt [\310\243\310\257 \270\360\265\345])

Spring Data JPA Many To Many 양방향 관계 예제

1

교육자료

09-interface.key

목차 BUG DEQUEUE 의 WAIT TIME 이 1 초미만인경우, 설정한시간만큼대기하지않는문제가있습니다... 3 BUG [qp-select-pvo] group by 표현식에있는컬럼을참조하는집합연산이존재하지않으면결괏값오류가발생할수있습니다... 4

05-class.key

제11장 프로세스와 쓰레드

MasoJava4_Dongbin.PDF

q 이장에서다룰내용 1 객체지향프로그래밍의이해 2 객체지향언어 : 자바 2

PowerPoint 프레젠테이션

<4D F736F F F696E74202D20C1A63235C0E520B3D7C6AEBFF6C5A920C7C1B7CEB1D7B7A1B9D628B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

단계

@OneToOne(cascade = = "addr_id") private Addr addr; public Emp(String ename, Addr addr) { this.ename = ename; this.a

07 자바의 다양한 클래스.key

.

Chap7.PDF

PowerPoint Presentation

<4D F736F F F696E74202D20C1A63038C0E520C5ACB7A1BDBABFCD20B0B4C3BC4928B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

파일로입출력하기II - 파일출력클래스중에는데이터를일정한형태로출력하는기능을가지고있다. - PrintWriter와 PrintStream을사용해서원하는형태로출력할수있다. - PrintStream은구버전으로가능하면 PrintWriter 클래스를사용한다. PrintWriter

Microsoft PowerPoint - Java7.pptx

PowerPoint Presentation

Application 에서 Parameter 값을받아 JDBC Interface 로보내게되면적절한 JDBC Driver 를통해 SQL 을 Database 로보내주게되고결과를받아서사용자에게보여주게된다. 2-2 JDBC Interface JDBC 의핵심 Interface

Cluster management software

untitled

자바 프로그래밍

<C0CCBCBCBFB52DC1A4B4EBBFF82DBCAEBBE7B3EDB9AE2D D382E687770>

Chapter 1

PWR PWR HDD HDD USB USB Quick Network Setup Guide xdsl/cable Modem PC DVR 1~3 1.. DVR DVR IP xdsl Cable xdsl Cable PC PC DDNS (

PowerPoint Presentation

슬라이드 1

Connection pool 엑셈컨설팅본부 /APM 팀박종현 Connection pool 이란? 사용자의요청에따라 Connection을생성하다보면많은수의연결이발생했을때서버에과부하가걸리게된다. 이러한상황을방지하기위해미리일정수의 Connection을만들어 pool에담아뒀다

PowerPoint Presentation

1. 자바프로그램기초 및개발환경 2 장 & 3 장. 자바개발도구 충남대학교 컴퓨터공학과

* Factory class for query and DML clause creation * tiwe * */ public class JPAQueryFactory implements JPQLQueryFactory private f

JAVA PROGRAMMING 실습 09. 예외처리

13주-14주proc.PDF

Secure Programming Lecture1 : Introduction

PowerPoint Presentation

Spring Boot

NoSQL

목차 INDEX JSON? - JSON 개요 - JSONObject - JSONArray 서울시공공데이터 API 살펴보기 - 요청인자살펴보기 - Result Code - 출력값 HttpClient - HttpHelper 클래스작성 - JSONParser 클래스작성 공공

歯Writing_Enterprise_Applications_2_JunoYoon.PDF

PowerPoint Presentation

Portal_9iAS.ppt [읽기 전용]

USB USB DV25 DV25 REC SRN-475S REC SRN-475S LAN POWER LAN POWER Quick Network Setup Guide xdsl/cable Modem PC DVR 1~3 1.. DVR DVR IP xdsl Cable xdsl C

<4D F736F F F696E74202D20C1A63234C0E520C0D4C3E2B7C228B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

Analytics > Log & Crash Search > Unity ios SDK [Deprecated] Log & Crash Unity ios SDK. TOAST SDK. Log & Crash Unity SDK Log & Crash Search. Log & Cras

PowerPoint Presentation

PowerPoint 프레젠테이션

Microsoft PowerPoint - java1-lab5-ImageProcessorTestOOP.pptx

Interstage4 설치가이드

DocsPin_Korean.pages

웹연동 } 웹 (Web) 환경에서데이터베이스시스템을연동하는방법은다음과같다 } Server Client 구조의통신 (2-Tier) } Server Middleware Client 구조의통신 (3-Tier) 2

PowerPoint 프레젠테이션

JAVA PROGRAMMING 실습 08.다형성

01-OOPConcepts(2).PDF

11 템플릿적용 - Java Program Performance Tuning (김명호기술이사)

8 장데이터베이스 8.1 기본개념 - 데이터베이스 : 데이터를조직적으로구조화한집합 (cf. 엑셀파일 ) - 테이블 : 데이터의기록형식 (cf. 엑셀시트의첫줄 ) - 필드 : 같은종류의데이터 (cf. 엑셀시트의각칸 ) - 레코드 : 데이터내용 (cf. 엑셀시트의한줄 )

5장.key

PowerPoint 프레젠테이션

untitled

³»Áö¼öÁ¤

Transcription:

18 장 : JDBC DataSource DataSource JDBC 2.0의 javax.sql 패키지에포함되어도입됨 DataSource 인터페이스는데이터베이스커넥션을만들거나사용하는데좀더유연한아키텍처를제공하기위해도입됨 DataSource를이용할경우, 클라이언트코드는한줄도바꾸지않고서도다른데이터베이스에접속할수있도록해줌 즉 DataSource 는커넥션상세사항들을캡슐화 DataSource 인터페이스구현방식에따른클래스타입들 기본적인 DataSource 클래스 javax.sql.datasource 인터페이스를구현함 커넥션풀링기능을갖추고있는 DataSource 클래스 javax.sql.connectionpooldatasource 인터페이스를구현함 분산트랜잭션을지원하는 DataSource 클래스 ( 14 장 ) javax.sql.xadatasource 인터페이스를구현함 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 1/38 Standalone DataSource 사용하기 1 Standalone DataSource 객체사용하기 (Oracle) DriverManager보다는 DataSource사용을권장함 DataSource 사용하여 Connection 객체생성하기 ( datasource/datasourcetestoracle.java)... import oracle.jdbc.pool.oracledatasource; OracleDataSource ds = new OracleDataSource(); ds.seturl("jdbc:oracle:thin:@xtreme.hanbat.ac.kr:1521:xtrm"); ds.setuser("student"); ds.setpassword("xxxx"); // Connect to the local database Connection conn = ds.getconnection(); // Query the employee names Statement stmt = conn.createstatement();... DriverManager Class.forName("jdbc.driver.OracleDriver"); String url = "jdbc:oracle:thin:@xtreme.hanbat.ac.kr:1521:xtrm"; String user = "student"; Stirng password = "xxxx"; Connection conn = DriverManager.getConnection(url, user, password); Statement stmt = conn.createstatement(); 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 2/38

Standalone DataSource 사용하기 2 Standalone DataSource 객체사용하기 (Derby) DriverManager보다는 DataSource사용을권장함 DataSource 사용하여 Connection 객체생성하기 ( datasource/datasourcetestderby.java)... import org.apache.derby.jdbc.embeddeddatasource; EmbeddedDataSource ds = new EmbeddedDataSource(); ds.setdatabasename( d:/derby/databases/wrox4370.db"); // Connect to the local database Connection conn = ds.getconnection(); // Query the employee names Statement stmt = conn.createstatement();... DriverManager Class.forName("org.apache.derby.jdbc.EmbeddedDriver"); String url = "jdbc:derby:d:/derby/databases/wrox4370.db"; Connection conn = DriverManager.getConnection(url); Statement stmt = conn.createstatement(); 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 3/38 Client/Server DataSource 객체의작동방식 context.bind( MusicStore, oracledatasource) DataSource ds = (DataSource) context.lookup( MusicStore ) LDAP Server Client Connection conn = ds.getconnection(); Oracle DBMS 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 4/38

Client/Server DataSource 사용하기 ( 서버측 ) 준비사항 DataSource 객체를생성해서디렉토리에바인딩해야함 이런일들은대개데이터베이스관리자가하게됨 Hashtable<String,String> env = new Hashtable<String,String>(); env.put( Context.INITIAL_CONTEXT_FACTORY, com.sun.jndi.fscontext.reffscontextfactory ); env.put( Context.PROVIDER_URL, file:/d:/java/jndi/derby ); Context ctx = new InitialContext(env); EmbeddedDataSource ds = new EmbeddedDataSource(); ds.setdatabasename( d:/derby/databases/wrox4370.db ); ctx.rebind( jdbc/musicstore, ds); ( 클라이언트측 ) 사용방법 Hashtable<String,String> env = new Hashtable<String,String>(); env.put( Context.INITIAL_CONTEXT_FACTORY, com.sun.jndi.fscontext.reffscontextfactory ); env.put( Context.PROVIDER_URL, file:/d:/java/jndi/derby ); Context ctx = new InitialContext(env); DataSource ds = (DataSource) ctx.lookup( jdbc/musicstore ); Connection connection = ds.getconnection(); 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 5/38 디렉토리 (Directory) 디렉토리개요 DataSource는대개컨텍스트 (context) 안에서룩업 (lookup) 을실행해서얻어내는경우가많음 컨텍스트는이름과자원을결합시킨다는뜻임 컨텍스트예 : 디렉토리 LDAP (Lightweight Directory Access Protocol) Active Directory X.500 File System ( 서버관점 ) DataSource 객체를생성한다음, 그객체를디렉토리에바인드 (bind) 함 바인드한다는것 (binding) 은디렉토리에게특정한이름을특정한자원과결합하라고명령하는행동임 전화디렉토리 ( 전화번호부 ): 어떤사람의주소와전화번호에대한정보를그사람의이름과바인드함 파일시스템 : Store01.java라는파일을생성하는경우, 파일내용에해당하는수많은바이트들을하드디스크에기록한다음, Store01.java라는이름과바인드하는것임 JDBC가 DBMS 중립적인인터페이스를제공하듯이 JNDI(Java Naming and Directory Interface) 는디렉토리서버중립적인인터페이스를제공함 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 6/38

실습해보기 DataSource 를사용하기위해셋팅하기 필요한라이브러리 JDKv1.4 이상 JNDI 와아래와같은 4 개의서비스제공자를기본적으로포함하고있음 ( 즉 jndi1_2_1.zip 를설치할필요가없음 ) LDAP Server Provider COS Naming Service Provider RMI Registry Service Provider DNS Service Provider JDKv1.3 JNDI 와아래와같은 3 개의서비스제공자를기본적으로포함하고있음 ( 즉 jndi1_2_1.zip 를설치할필요가없음 ) LDAP Server Provider COS Naming Service Provider RMI Registry Service Provider JDKv1.2 JNDI 와아래와같은 1 개의서비스제공자를기본적으로포함하고있음 ( 즉 jndi1_2_1.zip 를설치할필요가없음 ) COS Naming Service Provider ( 사용할경우 ) 필요한라이브러리 File System Service Provider (fscontext1_2beta3.zip)» Lib 폴더밑의 fscontext.jar, providerutil.jar 를 c:\java\lib 로복사한다. 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 7/38 실습해보기 FileSystem-Oracle 용 DataSource 만들기 DataSource 객체를저장 / 사용하기위한디렉토리서버 File System (JNDI File System Service Provider) DBMS Oracle 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 8/38

실습해보기 FileSystem-Oracle 용서버측프로퍼티파일 DataSource-FileSystem-Oracle.properties 871 page # DataSource-FileSystem-Oracle.properties # Oracle # drvname = "oracle.jdbc.driver.oracledriver" # srcurl = "jdbc:oracle:thin:@xtreme.hanbat.ac.kr:1521:xtrm" datasource.factory=com.sun.jndi.fscontext.reffscontextfactory datasource.url=file:/d:/java/jndi/oracle datasource.bindname=jdbc/musicstore datasource.username=student 자신의오라클계정이름 datasource.password=xxxxxx 자신의오라클패스워드 datasource.server=xtreme.hanbat.ac.kr datasource.port=1521 datasource.drivertype=thin datasource.netprotocol=tcp datasource.databasename=xtrm 준비작업 d:\java\jndi\oracle 디렉토리를생성함 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 9/38 실습해보기 FileSystem-Oracle 용 DataSourceServer 1 DataSourceFileSystemOracle.java (1/2) 874-875 page package datasource; import java.sql.*; import javax.sql.*; import javax.naming.*; import java.util.*; import oracle.jdbc.pool.oracledatasource; public class DataSourceFileSystemOracle { static ResourceBundle bundle = ResourceBundle.getBundle( datasource.datasource-filesystem-oracle ); public static void main(string[] args) { try { // create and store parameters which are used to create the context Hashtable<String,String> env = new Hashtable<String,String>(); env.put(context.initial_context_factory, bundle.getstring("datasource.factory")); env.put(context.provider_url, bundle.getstring("datasource.url")); // create the context Context context = new InitialContext(env); 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 10/38

실습해보기 FileSystem-Oracle 용 DataSourceServer 2 DataSourceFileServerOracle.java (2/2) // Create a DataSource object OracleDataSource datasource = new OracleDataSource(); // set the connection parameters String s; s = bundle.getstring("datasource.username"); datasource.setuser(s); s = bundle.getstring("datasource.password"); datasource.setpassword(s); s = bundle.getstring("datasource.drivertype"); datasource.setdrivertype(s); s = bundle.getstring("datasource.netprotocol"); datasource.setnetworkprotocol(s); s = bundle.getstring("datasource.server"); datasource.setservername(s); s = bundle.getstring("datasource.databasename"); datasource.setdatabasename(s); datasource.setportnumber(getport()); String bindname = bundle.getstring("datasource.bindname"); context.rebind(bindname, datasource); System.out.println("DataSource completed"); catch (Exception e) { e.printstacktrace(); static int getport() throws NumberFormatException { String s = bundle.getstring("datasource.port"); return Integer.parseInt(s); 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 11/38 실습해보기 FileSystem-Oracle 용 DataSourceServer 3 DataSourceFileSystemOracle.java 컴파일하기 d:> cd d:\begjavadb\ch18 d:> javac datasource/datasourcefilesystemoracle.java DataSourceFileSytemOracle 실행하기 d:> cd d:\begjavadb\ch18 d:> java datasource.datasourcefilesystemoracle d:\java\jndi\oracle 폴더밑에만들어진.bindings 파일을 notepad로열어내용확인 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 12/38

실습해보기 클라이언트측프로퍼티파일 MusicStore-FileSystem-Oracle.properties 879 page # MusicStore-FileSystem-Oracle.properties datasource.factory=com.sun.jndi.fscontext.reffscontextfactory datasource.url=file:/d:/java/jndi/oracle datasource.bindname=jdbc/musicstore 준비작업 d:\begjavadb\ch18\datasource 에서아래명령을수행함 copy MusicStore-FileSystem-oracle.properties MusicStore.properties 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 13/38 실습해보기 DataSourceClient DataSourceClient.java ( 교재에있는소스를다음과같이수정하는것이필요함 ) 878 page package datasource; import java.sql.*; import javax.sql.*; import javax.naming.*; import java.util.*; public class DataSourceClient { private static ResourceBundle bundle = ResourceBundle.getBundle( datasource.musicstore ); private DataSource datasource; public DataSourceClient() { Context context; try { Hashtable<String,String> env = new Hashtable<String,String>(); env.put(context.initial_context_factory, bundle.getstring("datasource.factory")); env.put(context.provider_url, bundle.getstring("datasource.url")); context = new InitialContext(env); String bindname = bundle.getstring("datasource.bindname"); datasource = (DataSource) context.lookup(bindname); catch (Exception e) { e.printstacktrace(); public Connection getconnection() throws SQLException { return datasource.getconnection(); 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 14/38

실습해보기 DataSourceClient 컴파일하기 DataSourceClient.java 컴파일하기 앞의소스파일을 d:\begjavadb\ch18\datasource\datasourceclient.java 파일로저장 d:> cd d:\begjavadb\ch18 d:> javac datasource/datasourceclient.java DataSourceClient 실행하기 d:> cd d:\begjavadb\ch18 d:> java datasource.datasourceclient 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 15/38 실습해보기 Store 클래스와함께 DataSource 이용하기 connections/storeds.java 881-884 pages... import datasource.*;... DataSourceClient ds = new DataSourceClient(); Connection conn = ds.getconnection();... connections/storeds.java 컴파일하기 소스파일을 d:\begjavadb\ch18\connections\storeds.java 파일로저장 d:> cd d:\begjavadb\ch18 d:> javac connections/storeds.java 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 16/38

실습해보기 TestStoreDS 1 connections/teststoreds.java 884 page package connections; public class TestStoreDS { public static void main(string[] args) { String id = "4"; StoreDS store = new StoreDS(); boolean result = store.findbyprimarykey(id); if (result) { System.out.println("Store retrieved"); System.out.println("Store details: n" + store.tostring()); else { System.out.println("Store NOT retrieved"); 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 17/38 실습해보기 TestStoreDS 2 connections/teststoreds.java 컴파일하기한후실행하기 소스파일을 d:\begjavadb\ch18\connections\teststoreds.java 파일로저장 d:> cd d:\begjavadb\ch18 d:> javac connections/teststoreds.java d:> java connections.teststoreds 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 18/38

FileSystem-Derby 에맞도록변경하기 DataSource 객체를저장 / 사용하기위한디렉토리서버 File System (JNDI File System Service Provider) DBMS Derby 서버측 ( 변경필요 ) DataSource-FileSystem-Derby.properties ( 새로작성 ) DataSourceFileServerDerby.java ( 새로작성 ) 클라이언트측 ( 변경불필요 ) MustsicStore-FileSystem-Derby.properties MusicStore.properties DataSourceClient.java ( 무변경 ) StoreDS.java ( 무변경 ) TestStoreDS.java ( 무변경 ) 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 19/38 DataSourceFileServerDerby datasource/datasourcefileserverderby.java 887-889 pages package datasource; import java.sql.*; import javax.sql.*; import javax.naming.*; import java.util.*; import org.apache.derby.jdbc.embeddeddatasource; public class DataSourceFileSystemDerby { static ResourceBundle bundle = ResourceBundle.getBundle( datasource.datasource-filesystem-derby ); static String s; public static void main(string[] args) { try { //create and store parameters which are used to create the context Hashtable<String,String> env = new Hashtable<String,String>(); env.put(context.initial_context_factory, bundle.getstring("datasource.factory")); env.put(context.provider_url, bundle.getstring("datasource.url")); //create the context Context context = new InitialContext(env); EmbeddedDataSource csdatasource = new EmbeddedDataSource(); s = bundle.getstring("datasource.databasename"); csdatasource.setdatabasename(s); String bindname = bundle.getstring("datasource.bindname"); context.rebind(bindname, csdatasource); System.out.println("DataSource completed"); catch (Exception e) { e.printstacktrace(); 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 20/38

실습해보기 FileSystem-Derby 실습하기 datasource/datasourcefilesystemderby.java 컴파일하고실행하기 소스파일을 d:\begjavadb\ch18\datasource에저장 d:> cd d:\begjavadb\ch18 d:> javac datasource/datasourcefileserverderby.java d:> java datasource.datasourcefileserverderby ( d:\java\jndi\derby\.bindings 이변경됨 ) connections/teststoreds.java 실행하기 ( 전혀수정없이 ) d:> cd d:\begjavadb\ch18 d:> java connections.teststoreds 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 21/38 File System 대신 LDAP 서버를사용하도록변경하기 DataSource 객체를저장 / 사용하기위한디렉토리서버 Fedora Directory Server (JNDI LDAP Service Provider) DBMS Oracle 서버측 ( 변경필요 ) DataSource-LDAP-Oracle.properties ( 새로작성 ) DataSourceLDAPServerOracle.java ( 새로작성 ) 클라이언트측 ( 변경불필요 ) MusicStore-LDAP-Oracle.properties MusicStore.properties DataSourceClient.java ( 무변경 ) StoreDS.java ( 무변경 ) TestStoreDS.java ( 무변경 ) 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 22/38

변경 1 : DataSource-LDAP-Oracle.properties DataSource-LDAP-Oracle.properties 887 page # DataSource-LDAP-Oracle.properties # Oracle # clsname = "oracle.jdbc.driver.oracledriver" # url = "jdbc:oracle:thin:@xtreme.hanbat.ac.kr:1521:xtrm" datasource.factory=com.sun.jndi.ldap.ldapctxfactory datasource.url=ldap://embedded.hanbat.ac.kr/dc=hanbat,dc=ac,dc=kr datasource.bindname=cn=oracle_musicstore,ou=datasources datasource.username=student 자신의오라클계정이름 datasource.password=xxxxxx 자신의오라클패스워드 datasource.server=xtreme.hanbat.ac.kr datasource.port=1521 datasource.drivertype=thin datasource.netprotocol=tcp datasource.databasename=xtrm 준비작업 embedded.hanbat.ac.kr 에 FDS 서버실행 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 23/38 변경 2 : DataSourceLDAPServerOracle 클래스구현하기 1 DataSourceLDAPServerOracle.java (1/3) package datasource; import java.util.*; import java.sql.*; import javax.sql.*; import javax.naming.*; import javax.naming.directory.*; import oracle.jdbc.pool.oracledatasource; public class DataSourceLDAPServerOracle { final static String rootdn = "cn=directory Manager"; final static String rootpass = "xxxx"; // DataSource Parameter final static ResourceBundle bundle = ResourceBundle.getBundle( datasource.datasource"); public static void main( String[] args ) { // set up environment to access the server Hashtable<String,String> env = new Hashtable<String,String>(); env.put( Context.INITIAL_CONTEXT_FACTORY, bundle.getstring("datasource.factory")); env.put( Context.PROVIDER_URL, bundle.getstring("datasource.url")); env.put( Context.SECURITY_PRINCIPAL, rootdn ); env.put( Context.SECURITY_CREDENTIALS, rootpass ); 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 24/38

변경 2 : DataSourceLDAPServerOracle 클래스구현하기 2 DataSourceLDAPServerOracle.java (2/3) try { // obtain initial directory context using the environment DirContext ctx = new InitialDirContext( env ); // create a DataSource object to add to the directory OracleDataSource datasource = new OracleDataSource(); // set the connection parameters String s; s = bundle.getstring("datasource.username"); datasource.setuser(s); s = bundle.getstring("datasource.password"); datasource.setpassword(s); s = bundle.getstring("datasource.drivertype"); datasource.setdrivertype(s); s = bundle.getstring("datasource.netprotocol"); datasource.setnetworkprotocol(s); s = bundle.getstring("datasource.server"); datasource.setservername(s); s = bundle.getstring("datasource.databasename"); datasource.setdatabasename(s); datasource.setportnumber(getport()); 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 25/38 변경 2 : DataSourceLDAPServerOracle 클래스구현하기 3 DataSourceLDAPServerOracle.java (3/3) // get the name String bindname = bundle.getstring("datasource.bindname"); // bind the DataSource with the name ctx.rebind( bindname, datasource ); System.out.println("DataSource completed"); catch ( NameAlreadyBoundException nabe ) { System.err.println( "value has already been bound!" ); catch ( Exception e ) { System.err.println( e ); static int getport() throws NumberFormatException { String s = bundle.getstring("datasource.port"); return Integer.parseInt(s); 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 26/38

변경 3 : MusicStore-LDAP-oracle.properties MusicStore-LDAP-Oracle.properties # MusicStore-LDAP-Oracle.properties datasource.factory=com.sun.jndi.ldap.ldapctxfactory datasource.url=ldap://embedded.hanbat.ac.kr/dc=hanbat,dc=ac,dc=kr datasource.bindname=cn=oracle_musicstore,ou=datasources 준비작업 d:\begjavadb\ch18> copy MusicStore-LDAP-oracle.properties MusicStore.properties 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 27/38 실습해보기 TestStoreDS connections/teststoreds.java 실행하기 d:> cd d:\begjavadb\ch18 d:> java connections.teststoreds 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 28/38

Connection Pooling : Profiler.java profiler/profiler.java 891 page package profiler; import static java.lang.system.out; public class Profiler { private long m_starttime; private long m_stoptime; private String m_routinename; public void Start(String routinename) { m_starttime = System.currentTimeMillis(); m_routinename = routinename; public void Stop() { m_stoptime = System.currentTimeMillis(); out.printf( Routine [%s] took %d msecs to execute. n, m_routinename, (m_stoptime - m_starttime) ); 컴파일하기 C:\BegJavaDB\Ch18> javac profiler\profiler.java 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 29/38 Connection Pooling : ProfilerTest.java profiler/profilertest.java 893 page package profiler; import static java.lang.system.out; public class ProfilerTest { public static void main(string args[]) { Profiler p = new Profiler(); // Start the profiler p.start("a routine"); for (long ncounter = 0; ncounter < 100; ncounter++) { out.printf( %2d n, ncounter); p.stop(); 컴파일및실행하기 d:\begjavadb\ch18> javac profiler\profilertest.java d:\begjavadb\ch18> java profiler.profilertest 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 30/38

Connection Pooling : DataSourceConnectionPool.java pooling/datasourceconnectionpool.java (1/3) 894-895 pages package pooling; import java.sql.*; import java.util.*; import datasource.*; public class DataSourceConnectionPool { private Vector connections; private String url, username, password; private boolean inuse[]; final private int poolsize = 10; private DataSourceClient client; public DataSourceConnectionPool() throws SQLException { connections = new Vector(poolsize); inuse = new boolean[poolsize]; try { SetupConnectionsPool(); catch (Exception e) { e.printstacktrace(); 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 31/38 Connection Pooling : DataSourceConnectionPool.java 2 pooling/datasourceconnectionpool.java (2/3) 894-895 pages private void SetupConnectionsPool() throws SQLException { for (int i = 0; i < poolsize; i++) { Connection conn = new DataSourceClient().getConnection(); connections.addelement(conn); inuse[i] = false; public void freeconnection(int connectionidx) { inuse[connectionidx] = false; public Connection getconnection() { Connection c = null; for (int idx = 0; idx < connections.size(); idx++) { if (inuse[idx] == false) { c = (Connection) connections.elementat(idx); inuse[idx] = true; return c; 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 32/38

Connection Pooling : DataSourceConnectionPool.java 3 pooling/datasourceconnectionpool.java (3/3) 894-895 pages public void dumpconnectionstatus() { System.out.println(" nconnection Pool Status"); System.out.println(" npool Size is " + connections.size()); for (int i = 0; i < connections.size(); i++) { System.out.println("Pool Index [" + i + "] In Use status = " + inuse[i]); 컴파일하기 d:\begjavadb\ch18> set CLASSPATH=.;d:\java\lib\fscontext.jar;d:\java\lib\providerutil.jar d:\begjavadb\ch18> javac pooling\datasourceconnectionpool.java 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 33/38 Connection Pooling : NonPoolTest.java pooling/nonpooltest.java package pooling; import java.sql.*; import profiler.profiler; import datasource.datasourceclient; public class NonPoolTest { private static ConnectionPool pool; public static void main(string args[]) { Profiler p = new Profiler(); try { Connection c[] = new Connection[10]; p.start("main() in NON PoolTest"); for (int i = 0; i < 10; i++) { c[i] = new DataSourceClient().getConnection(); p.stop(); catch (Exception e) { e.printstacktrace(); 컴파일하기 d:\begjavadb\ch18> javac pooling\nonpooltest.java d:\begjavadb\ch18> java pooling.nonpooltest 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 34/38

Connection Pooling : DataSourcePoolTest.java pooling/datasourcepooltest.java 899-900 pages package pooling; import java.sql.*; import profiler.profiler; public class DataSourcePoolTest { private static DataSourceConnectionPool pool; private static String url = "jdbc:cloudscape:c:/begjavadb/wrox4370.db"; private static String username = ""; private static String password = ""; public static void main(string args[]) { Profiler p = new Profiler(); try { System.out.println("Establish a connection [" + url + "]"); p.start("creating a pool of 10 connections"); pool = new DataSourceConnectionPool(); Connection c[] = new Connection[10]; p.stop(); p.start("main() in PoolTest"); for (int i = 0; i < 10; i++) { c[i] = pool.getconnection(); p.stop(); catch (Exception e) { e.printstacktrace(); 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 35/38 Connection Pooling : DataSourcePoolTest.java 실행하기 실행하기 d:\begjavadb\ch18> javac pooling\datasourcepooltest.java d:\begjavadb\ch18> java pooling.datasourcepooltest 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 36/38

Connection Pooling : 기업형환경에서사용하기 Enterprise JavaBean 에서벤더가제공하는커넥션풀링사용예 import java.sql.*; import javax.sql.*; import javax.naming.*; import java.util.*; public MyEJB ejbcreate() { ConnectionPoolDataSource ds; PooledConnection pc; try { // create and store parameters which are used to create the context context = new InitialContext(env); ds = (ConnectionPoolDataSource) context.lookup(bindname); pc = ds.getpooledconnection(); conn = pc.getconnection(); // // 데이타베이스조작하는코드 // conn.close(); catch (Exception e) { e.printstacktrace(); 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 37/38 Connection Pooling : Oracle 의 ConnectionPool 사용 datasource/connectionpooldatasourceldapserver.java datasource/connectionpooldatasourceclient.java 한밭대학교정보통신 - 컴퓨터공학부김영찬교수 38/38