Druid는 Alibaba의 오픈 소스 데이터베이스 연결 풀으로 데이터베이스 작업에 대한 우수한 모니터링 기능을 제공합니다. 이 기사는 Druid를 SpringBoot 프로젝트에 통합하는 방법을 설명합니다.
이 기사는 JPA 기반 프로젝트에 따라 개발되었습니다. 먼저, 추가 드루이드 종속성이 POM 파일에 추가됩니다. POM 파일은 다음과 같습니다.
<? xml version = "1.0"encoding = "utf-8"?> <project xmlns = "http://maven.apache.org/pom/4.0.0"xmlns : xsi = "http://www.w3.org/2001/xmlschema-instance" xsi : schemalocation = "http://maven.apache.org/pom/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelversion> 4.0.0 </modelversion> <groupid> com.dalaoyang </groupid> <artifactid> springicid> <버전> 0.0.1-snapShot </version> <packaging> jar </packaging> <name> springboot_druid </name> <description> springboot_druid </descript> <perge> org.springframework.boot </groupid> <artifactid> spring-boot-starter-parent </artifactid> </artifactid> <RelativePath/> <!-리포지토리에서 부모를 조회합니다 .-> </parent> <properties> <proffice.build.sourceencoding> utf-8 </project.build.sourceencoding> <project.worting.outputencoding> utf-8 </project.reporting.outputencoding> <java.version> 1.8 </java.version> 1.8. </properties> <pectionilency> <pectinement> <groupId> org.springframework.boot </groupid> <artifactid> spring-boot-starter-data-jpa </artifactid> </dependency> <pelection> <groupid> org.springframework.boot </groupicid> spring-starter-starter-web </의존성> <pectionency> <groupId> org.springframework.boot </groupid> <artifactid> Spring-Boot-DevTools </artifactid> <Scope> 런타임 </scope> </fexendency> <groupId> mySQL </groupId> <artifactid> mysql-connect-</artifactid> </artifactid> <cope> runtime </scope> </fectionement> <pectionement> <groupid> org.springframework.boot </groupid> <artifactid> spring-boot-starter-test </artifactid> <scope> test </scope> </spectency> <groupid> com.alibaba </groupid> <artifactid> druid> druid> <버전> 1.0.28 </version> </dependency> </dependencies> <build> <grugins> <groupid> org.springframework.boot </groupid> <artifactid> spring-boot-maven-plugin </artifactid> </plugin> </build> </project>
Application.properties와 통합 JPA의 상반기는 전혀 변경되지 않았습니다. 일부 드루이드 구성이 아래에 추가되었습니다. 드루이드 구성을 이해하지 못하면 온라인으로 확인할 수 있습니다. (이 기사가 잘 쓰여졌다 고 생각합니다, 포털)
#Port Number Server.port = 8888 ## Hibernate가로드 될 때 유효성 검사를 받고 데이터베이스 테이블 구조 생성을 확인하십시오. ## Hibernate가로드 될 때마다 생성, 데이터베이스 테이블 구조를 재현 할 때마다 데이터베이스 테이블 데이터가 손실되는 이유입니다. ## hibernate가로드 될 때 생성 된 Create-Drop, Exit은 테이블 구조를 삭제하는 것입니다. ## 업데이트 HIBERNATE 업데이트 데이터베이스 구조를 자동으로 업데이트합니다 ## 시작시 테이블 구조 검증 및 테이블 구조 확인을 시작할 때 아무것도하지 않습니다. sqlspring.jpa.show-sql = true ## 데이터베이스 구성 ## 데이터베이스 주소 spring.datasource.url = jdbc : mysql : // localhost : 3306/test? testf8 & usessl = false = false ## database username spring.datasource.usernam e = root base password spring.datasource.password = root ## database driver spring.datasource.driver class-name = com.mysql.jdbc.driver#여기 다른#druid를 사용하는 경우 다른#을 구성해야합니다. # 연결 풀의 연결 정보 # 크기, 최소, 최대 Spring.datasource.InitialSize = 5 Spring.Datasource.MinIdle = 5 Spring.Datasource.MaxActive = 20 # 연결 시간 초과 Spring.datasource.MaxWait = 60000 # Dettect inter to the Detlet to the Dette in the Dette in the Dette in world wont to the deent to the deent to the dette in work a to the deent to the deent to the dettel Unit은 밀리 초입니다. Datasource.timebetweenevictionRunsmillis = 60000 # 수영장에서 생존하기위한 최소 시간 구성, 유닛은 밀리 초 스프링 스프링. spring.datasource.testonborring = false spring.datasource.testonreturn = false # 열린 pscache를 열고 각 연결에서 pscache 크기를 지정하고 spring.datasource.poolpreparedstatements = true spring.datasource.maxpoolpreparedstatementperconnectize = 20 # monspertistics stitics interceping. 제거 후 모니터링 인터페이스 SQL을 계산할 수 없습니다. '벽'은 방화벽 스프링 스프링에 사용됩니다 .Datasource.filters = STAT, WALL, LOG4J# ConnectProperties 속성을 사용하여 MERGESQL 함수를 열십시오. 느린 SQL 레코드
그런 다음 프로젝트에 druidconfig를 추가 하고이 구성 파일이 주로 Application.Properties의 구성을로드하고 코드는 다음과 같습니다.
패키지 com.dalaoyang.config; import java.sql.sqlexception; import javax.sql.datasource; import org.apache.log4j.logger; import org.springframework.beans.annotation.value; import org.springframework.contettation.bean; org.springframework.context.annotation.configuration; import org.springframework.context.annotation.primary; import com.alibaba.druid.pool.druiddatasource;/** * @author dalaoyang * @description * @prooyang * @package. @email [email protected] * @date 2018/4/12 */ @configurationPublic 클래스 druidconfig {private logger = logger.getLogger (this.getClass ()); @Value ( "$ {spring.datasource.url}") 개인 문자열 dburl; @Value ( "$ {spring.datasource.username}") 개인 문자열 사용자 이름; @Value ( "$ {spring.datasource.password}") 개인 문자열 비밀번호; @Value ( "$ {spring.datasource.driver class-name}") private String driver className; @Value ( "$ {spring.datasource.initialSize}") 개인 int 이니셜 크기; @Value ( "$ {spring.datasource.minidle}") 개인 int minidle; @Value ( "$ {spring.datasource.maxactive}") private int maxactive; @Value ( "$ {spring.datasource.maxwait}") 개인 int maxwait; @Value ( "$ {spring.datasource.timebetweenevictionRunsmillis}") private int timebetweenevictionRunsmillis; @Value ( "$ {spring.datasource.mineVictableDletimemillis}") private int minevictableDletimemillis; @Value ( "$ {spring.datasource.validationQuery}") private String validationQuery; @Value ( "$ {spring.datasource.testsThileIdle}") 개인 부울 테스트 WhileIdle; @Value ( "$ {spring.datasource.testonborrow}") 개인 부울 testonborrow; @Value ( "$ {spring.datasource.testonreturn}") 개인 부울 testonreturn; @Value ( "$ {spring.datasource.poolpreparedStatements}") 개인 부울 풀 프리 퍼드 스테이트; @Value ( "$ {spring.datasource.MaxPoolPrepRedStatementPerConnectionsize}") private int maxpoolprepedStatementPerConnectionsize; @Value ( "$ {spring.datasource.filters}") 개인 문자열 필터; @Value ( "{spring.datasource.connectionProperties}") 개인 문자열 ConnectionProperties; @bean @primary // 주요 데이터 소스 공개 데이터 소스 DataSource () {druiddatasource dataSource = 새로운 druiddatasource (); DataSource.seturl (this.dburl); DataSource.setusername (사용자 이름); DataSource.setpassword (비밀번호); DataSource.setDriverClassName (DriverClassName); // configuration dataSource.setInitialSize (이니셜 크기); DataSource.setminidle (Minidle); DataSource.setMaxActive (maxactive); DataSource.setmaxwait (Maxwait); DataSource.settimebetweenevictionRunsmillis (TimeBetweenevictionRunsmillis); DataSource.SetMineVictableIdleTimemillis (MineVictableDletimemillis); DataSource.setValidationQuery (ValidationQuery); DataSource.SetTestWhileIdle (테스트 whileIdle); DataSource.SetTestOnborrow (TestOnBorrow); DataSource.SetTestOnreturn (TreastonReturn); DataSource.setPoolpreparedStatements (poolpreparedStatements); DataSource.setMaxPoolPreparedStatementPerConnectionsize (MaxPoolPreparedStatemperConnectionsize); try {dataSource.setFilters (필터); } catch (sqlexception e) {logger.error ( "druid configuration exception", e); } dataSource.setConnectionProperties (ConnectionProperties); 반환 데이터 소스; }}
그런 다음 druidfilter를 만들면 코드는 다음과 같습니다.
package com.dalaoyang.filter; import javax.servlet.annotation.webfilter; import javax.servlet.annotation.webinitparam; import com.alibaba.druid.support.http.webstatfilter;/** @author dalaoyang * @Dalaoyang * @description com.dalaoyang.filter * @email [email protected] * @date 2018/4/12 */ @webfilter (filtername = "druidwebstatfilter", urlpatterns = "/ *", Initparams = { @webinitparam (이름 = "제외", value = "*.
새 Druidservlet을 만들고 Druid 모니터링 페이지, 화이트리스트 및 블랙리스트 구성에 로그인하는 계정 비밀번호를 구성하는 클래스 @webservlet에 주석을 추가하십시오. 코드는 다음과 같습니다.
패키지 com.dalaoyang.servlet; import javax.servlet.annotation.webinitparam; import javax.servlet.annotation.webservlet; import com.alibaba.druid.support.http.statviewservlet;/** * @author dalaoyang * @procto springnecate * @proctor dalaoyang * @description com.dalaoyang.servlet * @email [email protected] * @date 2018/4/12 */ @webservlet (urlpatterns = "/druid/ *", initparams = {@webinitparam (name = "allow", value = "), // IP Whitelistation이 없음) @webinitparam (이름 = "deny", value = ""), // ip blacklist (deny deeny postedence over sever) @webinitparam (name = "loginusername", value = "admin"), // 드루이드 관리 페이지에 로그인하는 페이지 username @webinitparam (loginpassword = "value ="Admin ")). druidservlet는 statviewservlet {}을 확장합니다.
그런 다음 주석 @ServletComponentScan을 시작 클래스에 추가하고 프로젝트를 서블릿으로 스캔하도록하십시오. 코드는 다음과 같습니다.
패키지 com.dalaoyang; import org.springframework.boot.springApplication; import org.springframework.boot.autoconfigure.springbootapplication; import org.springframework.boot.web.servlet.servlet.servletcomponentscan; @springbooteNtscan // startup claste 포함. 그렇지 않으면 주석, 그렇지 않으면 servlet@servletcomponentscan public class springbootdruidapplication {public static void main (string [] args) {springApplication.run (springbootdruidapplication.class, args); }}나머지는 동일한 엔티티 (엔티티 클래스), 저장소 (데이터 조작 계층), 컨트롤러 (테스트에 사용되는 컨트롤러)를 통합 JPA와 함께 코드를 직접 표시합니다.
도시
package com.dalaoyang.entity; import javax.persistence. *;/** * @author dalaoyang * @description * @project springboot_learn * @package com.dalaoyang.entity * @email [email protected] * @date 2018/4/7 */ @Table (Tame = "City"). @generatedValue (전략 = GenerationType.Auto) Private int CityId; 개인 문자열 CityName; 개인 문자열 CityIntroading; 공공 시티 (Int CityId, String CityName, String CityIntroction) {this.cityID = CityId; this.cityName = CityName; this.cityIntroading = CityIntRoading; } public City (String CityName, String CityIntroction) {this.cityName = CityName; this.cityIntroading = CityIntRoading; } public city () {} public int getCityId () {return cityId; } public void setCityId (int cityId) {this.cityId = cityId; } public String getCityName () {return cityName; } public void setCityName (String CityName) {this.cityName = CityName; } public String getCityIntroading () {return cityIntROIDGE; } public void setCityIntroading (String CityIntRoading) {this.cityIntroading = CityIntRoading; }}
Cityrepository
package com.dalaoyang.repository; import com.dalaoyang.entity.city; import org.sprameframework.data.jpa.repository.jparepository;/** * @author dalaoyang * @despression * @project springboot_lear_ * @package com.dalaoyang.repository * @Package.dalaoyang.repository @Date 2018/4/7 */public 인터페이스 CityRepository 확장 jparepository <city, integer> {}도시 컨트롤러
package com.dalaoyang.controller; import com.dalaoyang.entity.city; import com.dalaoyang.repository.cityrepository; import org.spramframework.beans.beans.annotation.autowired; import org.spramework.web.bind.annotation.getmapping; import org.springframework.web.bind.annotation.restcontroller;/** * @author dalaoyang * @description * @project springboot_learn * @package com.dalaoyang.controller * @email [email protected] * @date 2018/4/4/ @restcontrontcontrontrical restcontrontric and @Dalaoyang.controller @autowired Private CityRepository CityRepository; // http : // localhost : 8888/savecity? cityName = Beijing & CityIntroction = 중국의 자본 @getMapping (value = "savecity") 공개 문자열 Savecity (String CityName, String CityIntricch) {City City = New City (CityName, CityIntricud); CityRepository.save (City); "성공"을 반환합니다. } // http : // localhost : 8888/deletecity? cityId = 2 @getMapping (value = "deletecity") public String deletecity (int cityId) {cityRepository.delete (cityId); "성공"을 반환합니다. } // http : // localhost : 8888/updatecity? cityId = 3 & cityName = shenyang & cityIntROCTION = liaoning provincial @getmapping (value = "updatecity") 공개 문자열 updatecity (int cityid, string cityname, string cityintrood) {City = New City (CityId, CityName, CityName) CityRepository.save (City); "성공"을 반환합니다. } // http : // localhost : 8888/getCityById? cityId = 3 @getMapping (value = "getCityById") 공개 도시 GetCityById (int cityID) {City City = CityRepository.findone (CityID); 반환 도시; }}
그런 다음 프로젝트를 시작하면 콘솔이 도시 테이블을 만들었 음을 알 수 있습니다.
그런 다음 http : // localhost : 8888/druid를 방문하면 다음 그림을 볼 수 있습니다.
아래 그림과 같이 계정 비밀번호 관리자 admin을 입력하십시오.
그런 다음 현재 우리는 http : // localhost : 8888/savecity? cityname = Beijing & CityIntroction = 중국의 수도를 방문 할 수 있습니다
그런 다음 아래 그림과 같이 위의 SQL 모니터링을 클릭하십시오.
위 그림에서 프로젝트 제작 테이블을 시작한 SQL이 방금 실행되었음을 알 수 있습니다. 통합이 여기에서 완료되었습니다.
소스 코드 다운로드 : https://gitee.com/dalaoyang/springboot_learn
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.