Tomcat connection pool, WebService configuration, and log4j log output

Source: Internet
Author: User
Tags sendmsg

The WebService written in Java is used to establish a database connection because the WebService interface is intended for many users. In this case, if you write the database connection statement in our method called by the user, you can use the method before closing it. However, with the Tomcat connection pool, 25 connections can be applied for at most 50 (both 25 and 50 can be configured) at the beginning, saving a lot of time for creating and disabling connections, better compression capability. A more scientific usage is to use the Tomcat connection pool.

Configuration method:

1. Add the following code to the Tomcat server. xml file (the red part is to be added, and the purple font is to be modified according to the actual situation. If the program needs to connect both Oracle and sqlserver2005 ):

.....................

<Resource Name = "userdatabase" auth = "Container"
Type = "org. Apache. Catalina. userdatabase"
Description = "u4ser database that can be updated and saved"
Factory = "org. Apache. Catalina. Users. memoryuserdatabasefactory"
Pathname = "CONF/tomcat-users.xml"/>

<Resource Name = "datasourcesql" auth = "Container"
Type = "javax. SQL. datasource"
Username = "sa" Password = "PWD"
Driverclassname = "com. Microsoft. sqlserver. JDBC. sqlserverdriver"
Url = "JDBC: sqlserver: // 127.0.0.1: 8080; databasename = dbname" logabandoned = "true" maxactive = "50" maxidle = "25" maxwait = "20000"/>

<Resource Name = "ceceoracle" auth = "Container"
Type = "javax. SQL. datasource"
Username = "username" Password = "PWD"
Driverclassname = "oracle. JDBC. Driver. oracledriver"
Url = "JDBC: oracle: thin: @ 127.0.0.1: 8080: dbname" logabandoned = "true" maxactive = "50" maxidle = "25" maxwait = "20000"/>

</Globalnamingresources>
........................

<Connector Port = "8899" protocol = "HTTP/1.1"
Connectiontimeout = "20000"
Redirectport = "8483" uriencoding = "UTF-8"/>

 

<Host name = "localhost" appbase = "webapps"
Unpackwars = "true" autodeploy = "true"
Xmlvalidation = "false" xmlnamespaceaware = "false">
<Context Path = "/de_ws" docbase = "E: \ de_ws \ webroot" reloadable = "true" DEBUG = "0">
<Resourcelink global = "datasourcesql" name = "datasourcesql" type = "javax. SQL. datasource"/>
<Resourcelink global = "datasourceoracle" name = "datasourceoracle" type = "javax. SQL. datasource"/>
</Context>

(Note: when accessing the interface address, if the local Tomcat is started, it is

String url = "http: // localhost: 8899/de_ws/services/clientjk ";

Why is the access address? This is the path in green.

In the preceding

In the green font:

Webapps corresponds to the webapps folder in the Tomcat directory. If the following <Context
Path = "/de_ws" docbase = "E: \ de_ws \ webroot .. Tomcat will be found in the webapps directory.

<Context Path = "/de_ws" docbase = "E: \ de_ws \ webroot. Path = "/de_ws" is the path of the virtual directory, docbase = "E: \ de_ws \ webroot "is the actual physical address of the virtual directory (the address must be configured to the upper-level directory of the WEB-INF ). Because Path = "/de_ws" is configured here"
Therefore, add/de_ws after http: // localhost: 8899 during access. If Path = "" is configured, you only need to access the http: // localhost: 8899 and/services/clientjk after the access interface. /Services/is configured in the web. xml file of WebService. Clientjk is configured in the deploy. WSDD file.

Therefore, whether or not to add/de_ws to the access interface address depends on the path (virtual directory) configuration in <context Path = "/de_ws.

Maxactive = "50" maxidle = "25" maxwait = "20000"/means that the maximum number of connections in the connection pool is 50. When Tomcat is started, 25 connections will be applied, whether or not the 25 are used at the beginning, this saves the connection request time. 20000 means that when 50 connections are used up, wait for 20 s. If there is a released connection, use it. If not, Tomcat reports an error.

2. In the Java program, the code for connecting to the database is changed:

Import Java. SQL. connection; import javax. naming. namingexception; import javax. SQL. datasource; import Org. apache. commons. logging. log; import Org. apache. commons. logging. logfactory; public class connectionmanager {// connect to the Oracle class Private Static log logger = logfactory. getlog (connectionmanager. class); // print it to the log file. The path is configured in the log4j file. Private connection conn = NULL; public static connection getconnection () throws Exception {datasource DS = getdatasource (); Return Ds. getconnection ();} public static datasource getdatasource () throws exception {try {javax. naming. context CTX = new javax. naming. initialcontext (); object OBJ = NULL; OBJ = CTX. lookup ("Java: COMP/ENV/datasourceoracle"); // After Tomcat is configured in step 1, write the name in the configuration to datasource DS = (javax. SQL. datasource) OBJ; return Ds;} catch (namingexception ne) {logger. error ("context F AIl to lookup jndi1_cename! "+ NE. getmessage (); throw ne ;}// public static connection getconnection () throws exception {// connect to the database by reading the configuration file // properties P = new properties (); // inputstream is = connectionmanager. class. getresourceasstream ("/config/other/init. properties "); // P. load (is); // class. forname (P. getproperty ("JDBC. driver "); // return drivermanager. getconnection (P. getproperty ("JDBC. URL "), P //. getproperty ("JDBC. username "), P. getproperty ("JDBC. password "));//}}

 

Package COM. tools; import Java. SQL. connection; import javax. naming. namingexception; import javax. SQL. datasource; import Org. apache. commons. logging. log; import Org. apache. commons. logging. logfactory; public class basedao {// connect to the sqlserver2005 database // public connection getconn () throws exception {// connect to the database by reading the configuration file // connection conn = NULL; // properties P = new properties (); // inputstream is = connectionmanager. class/ /. Getresourceasstream ("/config/other/init_sql2005.properties"); // P. load (is); // class. forname (P. getproperty ("JDBC. driver "); // conn = drivermanager. getconnection (P. getproperty ("JDBC. URL "), P //. getproperty ("JDBC. username "), P. getproperty ("JDBC. password "); // return conn; //} Private Static log logger = logfactory. getlog (connectionmanager. class); Private connection conn = NULL; public static connection GETC ONN () throws exception {datasource DS = getdatasource (); Return Ds. getconnection ();} public static datasource getdatasource () throws exception {try {javax. naming. context CTX = new javax. naming. initialcontext (); object OBJ = NULL; OBJ = CTX. lookup ("Java: COMP/ENV/datasourcesql"); datasource DS = (javax. SQL. datasource) OBJ; return Ds;} catch (namingexception ne) {logger. error ("context fail to lookup jndida Tasourcename! "+ NE. getmessage (); throw ne ;}}}

If you use the read configuration file to connect to the database (that is, the comment-out method, the configuration file content is as follows ):

Init. Properties

#created by Apusic#Thu Nov 10 14:48:52 CST 2011gis.ip=..paging.number.per=10jdbc.password=pwdsms.ip=...jdbc.maxActive=50jdbc.url=jdbc\:oracle\:thin\:@192.168.1.1\:1521\:dbnamevaluelisthandlerclass=oraclejdbc.maxWait=50000jdbc.driver=oracle.jdbc.driver.OracleDriverjdbc.username=usernamepci.ip=...

 

 

3. WebService code is called in the program:

Public class testclient {public static void main (string [] ARGs) {string url = "http: // 192.168.1.1: 8080/de_ws/services/clientjk "; // clientjk is the interface name. Why should I add the/de_ws directory during access? In process 1, we will detail service = new service (); call = NULL; try {call = (CALL) service. createcall (); call. settargetendpointaddress (new URL (URL); call. setoperationname ("sendmsg"); // sendmsg is the method name provided by the interface string myname = (string) Call. invoke (new object [] {"parameter 1", "parameter 2", "parameter 3", "parameter 4", "parameter 5"}); system. out. println ("myname:" + myname);} catch (serviceexception e) {e. printstacktrace ();} catch (malformedurlexception e) {e. printstacktrace ();} catch (RemoteException e) {e. printstacktrace ();}}}

4. digress. Log4j log output method (package to be imported ):

Import Org. apache. commons. logging. log; import Org. apache. commons. logging. logfactory ;.... private log logger = logfactory. getlog (sendthread. class );.... long starttime = system. currenttimemillis (); // ------------------- get start time long endtime = system. currenttimemillis (); // ------------------------ obtain the end time logger.info ("transaction time consumed in the thread:" + (endtime-starttime) // output to the log file + "Ms ");..... try {ps2.close (); PS2 = NULL;} catch (sqlexception e) {logger. error (E. getmessage (); // output to the log file}

 

Log4j. properties configuration file:

Log4j. rootlogger = info, a1, a2 // info indicates that the Tomcat startup mode is Info (II), debug (I), warn (III), and error (IV ). A1 is output to the terminal, A2 is output to the log file log4j. appender. a1 = org. apache. log4j. leleappenderlog4j. appender. a1.layout = org. apache. log4j. patternlayoutlog4j. appender. a1.layout. conversionpattern = % 5 p (% F % m: % L)-% m % N log4j. appender. a2 = org. apache. log4j. dailyrollingfileappenderlog4j. appender. a2.file = C:/logs/XXX/info. log // the path of the configuration log file. The directory should be created in advance, info. you do not need to create log4j for the log file. appender. a2.datepattern = '('yyyy-mm-dd')' log4j. appender. a2.layout = org. apache. log4j. patternlayoutlog4j. appender. a2.layout. conversionpattern = % d [% P] % C-line: % L-% m % nlog4j.logger.org. apache. commons = offlog4j.logger.org. apache. struts = offlog4j.logger.org. springframework = offlog4j.logger.com. ysoft = off

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.