Java Development druid Data Connection Pool maven Simple Configuration Process Example

  • 2021-11-29 06:47:46
  • OfStack

Directory 1. pom. xml file introduces druid and database connection jar package 2. jdbc. properties configuration 3. ibatis-config. xml parameter configuration for mybatis 4. spring-mybatis. xml consolidation file configuration 5. web. xml configuration detection access ip6. Configuration of various monitoring Spring-mvc. xml7. Optional secure encryption operation database encryption 8. Access mode

1. pom. xml file introduces druid and database connection jar package


<properties>
<druid.version>1.0.18</druid.version>
</properties>
<dependencies>
<!-- connection pool -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>${druid.version}</version>
		</dependency>
	<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.38</version>
		</dependency>
</dependencies>

2. jdbc. properties configuration


datasource.mysql.driverClassName=com.mysql.jdbc.Driver
datasource.mysql.url=jdbc:mysql://localhost:3306/ganlandoudata?useUnicode=true&characterEncoding=UTF-8&useSSL=false
datasource.mysql.username=root
datasource.mysql.password=
jdbc.pool.init=1    Number of connections initialized by connection pool 
jdbc.pool.minIdle=3   Minimum number of free connections in connection pool 
jdbc.pool.maxActive=20   Maximum active connections in connection pool 
datasource.validationQuery=select 1 from dual  Connection test 
datasource.testOnBorrow=true  <span style="font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 13px; background-color: rgb(254, 254, 242);"> Executed when requesting a connection validationQuery Check whether the connection is valid, which will degrade performance. </span>
datasource.testOnReturn=false  <span style="font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 13px; background-color: rgb(254, 254, 242);"> Executed when the connection is returned validationQuery Check whether the connection is valid, which will degrade performance </span>

3. ibatis-config. xml Parameter configuration for mybatis


<!--  Global parameter  -->
	<settings>
		<!--  Enable or disable caching for the global mapper.  -->
		<setting name="cacheEnabled" value="true"/>
		
		<!--  Delayed loading is enabled or disabled globally. When disabled, all associated objects are loaded immediately.  -->
		<setting name="lazyLoadingEnabled" value="true"/>
 
		<!--  When enabled, objects with delayed load properties will fully load any properties when they are called. Otherwise, each property will be loaded as needed.  -->
		<setting name="aggressiveLazyLoading" value="true"/>
 
		<!--  Whether to allow a single article sql  Returns multiple datasets   ( Depending on driver compatibility ) default:true -->
		<setting name="multipleResultSetsEnabled" value="true"/>
		
		<!--  Can I use an alias for a column  ( Depending on driver compatibility ) default:true -->
		<setting name="useColumnLabel" value="true"/>
		
		<!--  Allow JDBC  Generate the primary key. Drive support is required. If set to true This setting will force the use of the generated primary key, with the 1 Some drives are incompatible but can still be executed.   default:false  -->
		<setting name="useGeneratedKeys" value="true"/>
		
		<!--  Specify  MyBatis  How to map automatically   Columns of a base table  NONE : Not implicit PARTIAL: Part   FULL: All   -->  
		<setting name="autoMappingBehavior" value="FULL"/>
		
		<!--  This is the default execution type    ( SIMPLE:  Simple;  REUSE:  Actuators may be reused prepared statements Statement; BATCH:  Actuators can repeat statements and batch updates)   -->
		<setting name="defaultExecutorType" value="BATCH"/>
		
		<!--  Database exceeds 25000 Timeout if no response occurs in seconds    -->
        <setting name="defaultStatementTimeout" value="1000" /> 
		
		<!--  Convert fields using hump nomenclature.  -->
		<setting name="mapUnderscoreToCamelCase" value="true"/>
		
		<!--  Set the local cache scope  session: There will be data sharing   statement: Statement scope  ( In this way, there will be no data sharing  ) defalut:session -->
        <setting name="localCacheScope" value="SESSION"/>
		
        <!--  Set but JDBC When the type is empty , Some drivers   To specify a value ,default:OTHER You do not need to specify a type when inserting a null value  -->
        <setting name="jdbcTypeForNull" value="NULL"/>
		
	</settings>
	<!--  Type alias  -->
	<!-- <typeAliases>
		<typeAlias alias="Page" type="com.thinkgem.jeesite.common.persistence.Page" /> Paging  
	</typeAliases>
	 -->
	<!--  Plug-in configuration  -->
	<plugins>
		<plugin interceptor="com.hl.core.mybatis.plugin.OffsetLimitInterceptor">
			<property name="dialectClass" value="com.hl.core.mybatis.dialect.MySQLDialect"/>
		</plugin>
	</plugins> 
</configuration>

4. spring-mybatis. xml consolidation file configuration


	<!--  Automatic scanning  , Under the specified package mapper-->
	<context:component-scan base-package="com.hl" />

	<!-- Introduce jdbc.properties Configuration file -->
	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location" value="classpath:jdbc.properties" />
	</bean>
 
	<!-- MyBatis begin -->

	<!--sqlsession Configure -->
 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
	
	  <!--  Injection dataSource That references the defined id For  dataSource Adj. bean-->
 <property name="dataSource" ref="dataSource" />

		<!--  Entity class  -->
		<property name="typeAliasesPackage" value="com.hl.manage.*.entity.*" />
		<!-- Parent class inherited by entity class -->
		<property name="typeAliasesSuperType" value="com.hl.core.base.BaseEntity" />
		<!--mapper.xml Configuration file -->
 <property name="mapperLocations" value="classpath:com/hl/**/mapper/*Mapper.xml" />

		<!--myBatis Configuration file -->
 <property name="configLocation" value="classpath:ibatis-config.xml"></property></bean><!--  Scanning basePackage Under all Dao Interface of  --><bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="sqlSessionFactoryBeanName"
 value="sqlSessionFactory" /><property name="basePackage" value="com.hl" /></bean><!--  Defining Transactions  --><bean id="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource" /></bean><!--  Configure 
 Annotation  Drive, scan @Transactional The annotated class defines the transaction  --><tx:annotation-driven transaction-manager="transactionManager"proxy-target-class="true" /><!-- MyBatis end --><!--  Data source configuration ,  Use  druid Database connection pool  --><bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"init-method="init"
 destroy-method="close"><!--  The data source driver class does not write, Druid By default, it will be automatically based on the URL Recognition DriverClass --><property name="driverClassName" value="${datasource.mysql.driverClassName}" /><!--  Basic attribute  url , user , password --><property name="url" value="${datasource.mysql.url}" /><property name="username"
 value="${datasource.mysql.username}" /><property name="password" value="${datasource.mysql.password}" /><!--  Configure initialization size, minimum, maximum  --><property name="initialSize" value="${jdbc.pool.init}" /><property name="minIdle" value="${jdbc.pool.minIdle}" /><property name="maxActive"
 value="${jdbc.pool.maxActive}" /><!--  Configure the time to get the connection wait timeout  --><property name="maxWait" value="60000" /><!--  How long does the configuration interval take place 1 Detects idle connections that need to be closed, in milliseconds  --><property name="timeBetweenEvictionRunsMillis" value="60000" /><!--  Configure 1 The minimum time, in milliseconds, for a connection to live in the pool  --><property name="minEvictableIdleTimeMillis"
 value="300000" /><!-- <property name="validationQuery" value="${jdbc.testSql}" /> --><property name="testWhileIdle" value="true" /><property name="testOnBorrow" value="false" /><property name="testOnReturn" value="false" /><!--  Open PSCache And specifies that on each connection PSCache The size of the ( Oracle Use) 
 <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> --><!--  Configure the for monitoring statistics interception filters , Note that this configuration is selected as needed --><property name="filters" value="stat,wall,config" />

		## If only monitoring is required, configure it to <property name="filters" value="stat" />  
		<!-- Configure config Add this configuration when -->
    		<property name="ConnectionProperties" value="config.decrypt=true;config.decrypt.key=${publickey}" />
		<!--  Defense SQL Injection attack  -->
		<!-- <property name="filters" value="wall"/> -->
		<!--  Database password decryption configuration  -->
		<!--  <property name="filters" value="config" /> -->
	</bean>
 
	<!--  Data source configuration ,  Do not use connection pooling  <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
		<property name="driverClassName" value="${jdbc.driver}" /> <property name="url" 
		value="${jdbc.url}" /> <property name="username" value="${jdbc.username}"/> 
		<property name="password" value="${jdbc.password}"/> </bean> -->
</beans> 


     

     

5. web. xml configuration detection access


<!-- DruidStatView -->
	<servlet>
		<servlet-name>DruidStatView</servlet-name>
		<servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
	<init-param>
			<!--  Allow statistics to be emptied  -->
			<param-name>resetEnable</param-name>
			<param-value>true</param-value>
		</init-param>
		<init-param>
			<!--  User name  -->
			<param-name>loginUsername</param-name>
			<param-value>admin</param-value>
		</init-param>
		<init-param>
			<!--  Password for access druid Monitoring interface  -->
			<param-name>loginPassword</param-name>
			<param-value>ganlandou123456</param-value>
		</init-param>
	<!--  Allow access ip

<init-param>
  	<param-name>allow</param-name>
  	<param-value>128.242.127.1/24,128.242.128.1</param-value>
</init-param>

ip with forbidden access


<init-param>
  		<param-name>deny</param-name>
  		<param-value>128.242.127.4</param-value>
  	</init-param> -->
	</servlet>
	<servlet-mapping>
		<servlet-name>DruidStatView</servlet-name>
		<url-pattern>/druid/*</url-pattern>
	</servlet-mapping>

6. Configure all kinds of monitoring Spring-mvc. xml as required


      <!-- druid web Monitoring  -->
	<filter>
		<filter-name>DruidWebStatFilter</filter-name>
		<filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class>
		<init-param>
			<param-name>exclusions</param-name>
			<param-value>*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*</param-value>
		</init-param>
		<!--  Monitor single url Called sql List  -->
		<init-param>
			<param-name>profileEnable</param-name>
			<param-value>true</param-value>
		</init-param>
		<!--  Obtained session Adj. name, According to name Get the stored value  -->
 <init-param><param-name>principalSessionName</param-name>
<param-value>user</param-value>
<param-value>agtCompany</param-value>
<param-value>cusUser</param-value></init-param>
<!-- Whether to turn it on session Monitoring, if it is turned on, it can obtain the service delivery session Information  -->
<init-param><param-name>sessionStatEnable</param-name>
<param-value>true</param-value></init-param></filter>
<filter-mapping><filter-name>DruidWebStatFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping>

    <!--  Association Spring Monitoring  -->
</bean>
		<bean id="druid-stat-interceptor"
		class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor">
	</bean>
 
	<bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut"
		scope="prototype">
		<property name="patterns">
			<list>
	<!-- Interception monitoring based on method -->
				<value>com.hl.manage.*.service.*.*</value>	
			</list>
		</property>
	</bean>
 
	<aop:config>
		<aop:advisor advice-ref="druid-stat-interceptor"
			pointcut-ref="druid-stat-pointcut" />
	</aop:config>






7. Optional Secure Encryption

Database encryption


datasource.mysql.driverClassName=com.mysql.jdbc.Driver
datasource.mysql.url=jdbc:mysql://localhost:3306/ganlandoudata?useUnicode=true&characterEncoding=UTF-8&useSSL=false
datasource.mysql.username=root
datasource.mysql.password=
jdbc.pool.init=1    Number of connections initialized by connection pool 
jdbc.pool.minIdle=3   Minimum number of free connections in connection pool 
jdbc.pool.maxActive=20   Maximum active connections in connection pool 
datasource.validationQuery=select 1 from dual  Connection test 
datasource.testOnBorrow=true  <span style="font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 13px; background-color: rgb(254, 254, 242);"> Executed when requesting a connection validationQuery Check whether the connection is valid, which will degrade performance. </span>
datasource.testOnReturn=false  <span style="font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 13px; background-color: rgb(254, 254, 242);"> Executed when the connection is returned validationQuery Check whether the connection is valid, which will degrade performance </span>
0

8. Access method

Ip: Port number/project name/druid

The above is Java development druid data connection pool maven simple configuration process example details, more information about druid data connection pool maven configuration please pay attention to other related articles on this site!


Related articles: