Druid ist ein Open -Source -Datenbankverbindungspool von Alibaba, der hervorragende Überwachungsfunktionen für Datenbankvorgänge bietet. In diesem Artikel wird erläutert, wie Druid in das Springboot -Projekt integriert wird.
Dieser Artikel wird im Rahmen eines JPA-basierten Projekts entwickelt. Zunächst werden der POM -Datei zusätzliche Druidenabhängigkeiten hinzugefügt. Die POM -Datei lautet wie folgt:
<? 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> SpringBoot_druid </artifactId> <version> 0.0.1-Snapshot </Version> <Packages> jar </packaging> <name> Springboot_druid </name> <beschreibung> SpringBoot_druid </Beschreibung <artifactid> Spring-Boot-Starter-Parent </artifactId> <version> 1.5.12.Release </Version> <RelativePath/> <!-SOOKUP PLOTTER aus Repository-> </parent> <Proporties> <projekts.build.SourceCoding> utf-8 </project.build.surecoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </abhängig> <depeopcy> <GroupId> org.springframework </abhängig> <depeopecy> <GroupId> Mysql </GroupID> <artifactId> mysql-connector-java </artifactId> <scope> runtime </scope> </abhängig> <abhängigkeit> <gruppeId> org.springFramework <Scope> test </scope> </abhängig> <abhängigkeit> <gruppe> com.alibaba </GroupId> <artifactId> druid </artifactid> <version> 1.0.28 </Version> </abhängig> </abhängig> <build> <plogins> <gruppe> borg.springframework.boot </GroupId> <artifactid> Spring-Boot-Maven-Plugin </artifactId> </plugin> </plugins> </build> </project>
Die erste Hälfte von Anwendungen.Properties und der integrierte JPA haben sich überhaupt nicht geändert. Einige Druidenkonfigurationen wurden unten hinzugefügt. Wenn Sie die Konfiguration von Druid nicht verstehen, können Sie sie online überprüfen. (Ich denke, dieser Artikel ist gut geschrieben, Portal)
#Port number Server.port = 8888 ## Validieren Sie beim Laden von Hibernate, überprüfen Sie die Erstellung der Datenbanktabellenstruktur ## CREATE Jedes Mal, wenn der Hibernate geladen wird, und die Datenbanktabellenstruktur neu erstellen, was der Grund für den Verlust der Datenbanktabellendaten ist. ## Erstellen Sie beim Laden von Hibernate die Tabellenstruktur. ## Aktualisieren Sie das Laden von Hibernate automatisch die Datenbankstruktur. sqlspring.jpa.show-sql = true ## Datenbankkonfiguration ## Datenbankadresse Spring.datasource.url = JDBC: MySQL: // localhost: 3306/test? Spring.DataSource.Password = Root ## Datenbanktreiber Spring.Datasource.Driver-Class-Name = com.mysql.jdbc.driver#Hier sind unterschiedlich#Wenn Sie druid verwenden, müssen Sie eine weitere Eigenschaft Spring.DataSource.type.datasource.type = com.aliBabaSource.datource.datourcacacacace.al.aliBabaSource.dataSourceSourceconconconconconconconconconconconce.dataSource.datource.alceconconconconconconconce.dataSource-. Informationen zum Verbindungspool # Initialisieren Sie Größe, minimaler, maximaler Spring. Spring.DataSource.TimeBetweenevictionRunsmillis = 60000 # Konfigurieren Sie die Mindestzeit für eine Verbindung, um im Pool zu überleben. Spring.DataSource.TestonBorrow = false Spring.datasource.TestonReturn = Falsch # Öffnen Sie PSCache und geben Sie die Größe von PSCache auf jeder Verbindung Spring.DataSource.PoolPreparedStatements = True Spring.DataSource.MaxpoolPoParedSripeSizeSize = 20 # 20 # -DataSource für Überwachungsstatistiken. Nach dem Entfernen kann die Überwachungsschnittstelle SQL nicht gezählt werden. 'Wall' wird für Firewall Spring verwendet. Langsame SQL -Aufzeichnungen
Fügen Sie dann DruidConfig zum Projekt hinzu und erklären Sie kurz, dass diese Konfigurationsdatei die Konfiguration von Application.Properties hauptsächlich lädt und der Code wie folgt lautet:
Paket com.dalaoyang.config; import Java.sql.sqlexception; import javax.sql.dataSource; import org.apache.log4j.logger; org.springframework.context.annotation.configuration; import org.springframework.context.annotation @email [email protected] * @date 2018/4/12 */ @configurationPublic class druidconfig {private logger logger = logger.getLogger (this.getClass ()); @Value ("$ {spring.datasource.url}") private String dburl; @Value ("$ {spring.datasource.username}") privater String -Benutzername; @Value ("$ {Spring.DataSource.Password}") privates Zeichenfolge Passwort; @Value ("$ {spring.datasource.driver-class-name}") private String-Treiberklassename; @Value ("$ {spring.datasource.initialSize}") private init initialSize; @Value ("$ {spring.datasource.minidle}") Private int Minidle; @Value ("$ {spring.datasource.maxactive}") private int maxactive; @Value ("$ {spring.datasource.maxwait}") private int maxwait; @Value ("$ {Spring.DataSource.TimeBetweenevictionRunsmillis}") Private int timeBetweenevictionRunsmillis; @Value ("$ {Spring.DataSource.MineVictableIdletImemillis}") Private int mineVictableIdletImemillis; @Value ("$ {Spring.DataSource.ValidationQuery}") private String validationQuery; @Value ("$ {Spring.DataSource.TestIDEIDLE}") privater boolescher Test, während Idle; @Value ("$ {Spring.DataSource.TestonBorrow}") Private boolean testonborrow; @Value ("$ {Spring.DataSource.TestonReturn}") Private boolean testonReturn; @Value ("$ {spring.datasource.poolpreparedStatements}") Private boolean PoolpreparedStatements; @Value ("$ {spring.datasource.maxpoolpoolpreparedStatementPerConnectionSize}") private int maxpoolProparedStatementPerconConnectionSize; @Value ("$ {spring.datasource.filters}") private String -Filter; @Value ("{Spring.DataSource.ConnectionProperties}") Private String ConnectionProperties; @Bean @Primary // Hauptdatenquelle public DataSource dataSource () {druidDataSource dataSource = new DruidDataSource (); DataSource.seturl (this.dburl); DataSource.Setusername (Benutzername); DataSource.SetPassword (Passwort); DataSource.SetDriverClassName (TRAVERCLASSNAME); // configuration dataSource.setInitialSize (InitialSize); DataSource.SetMinidle (Minidle); DataSource.SetMaxActive (maxActive); DataSource.SetMaxwait (maxwait); DataSource.SettimeBetweenevictionRunsmillis (TimeBetweenevictionRunsmillis); DataSource.SetMineVictableIdletImemillis (minevictableIdletImemillis); DataSource.setValidationQuery (ValidationQuery); dataSource.settest -idle (test während der IDLE); DataSource.settestonborrow (testonborrow); DataSource.settestonReturn (testonReturn); DataSource.setPoolPreparedStatements (PoolpreparedStatements); DataSource.setMaxPoolProparedStatementPerConnectionSize (maxpoolPreparedStatementPerConnectionSize); try {dataSource.setFilters (Filter); } catch (sqlexception e) {logger.Error ("Druid -Konfigurationsausnahme", e); } dataSource.setConnectionProperties (ConnectionProperties); DataSource zurückgeben; }}
Erstellen Sie dann einen Druidfilter, der Code lautet wie folgt:
Paket com.dalaoyang.filter; import javax.servlet.annotation.webfilter; import javax.servlet.annotation com.dalaoyang.filter * @email [email protected] * @date 2018/4/12 */ @webilter (filtername = "druidwebstatfilter", urlpatterns = "/ *", initparams = {{{{{{ @WebinitParam (name = "exklusions", value = "*. Js,*. Gif,*. Jpg,*. Bmp,*.
Erstellen Sie ein neues DruidServlet, fügen Sie der Klasse @Webservlet Annotation hinzu, die das Kontokennwort für die Anmeldung zur Druid -Überwachungsseite, die Whitelist und die Blacklist -Konfigurationen konfiguriert, der Code ist wie folgt:
Paket com.dalaoyang.servlet; import javax.servlet.annotation.webinitparam; import javax.servlet.annotation.webservlet; com.dalaoyang.servlet * @email [email protected] * @date 2018/4/12 */ @webservlet (urlpatterns = "/druid/ *", initparams = {@webinitparam (name = "zugelassen", value = "), // ip Whitelist (ip whitelist (ip Whitelist @WebinitParam (name = "Deny", value = ""), // ip Blacklist (Deny hat Vorrang vorzulassen) @WebinitParam (name = "loginUnername", value = "admin"), // Anmeldung bei der DRUID -Verwaltungsseite username @WebinitParam (name = "loginpassword", value = "). DruidServlet erweitert statViewServlet {}
Fügen Sie dann die Annotation @ServletComponentscan in die Startklasse hinzu und lassen Sie das Projekt in das Servlet scannen. Der Code ist wie folgt:
Paket com.dalaoyang; import org.springframework.boot.springapplication; import org.springframework Annotation, ansonsten kann sie nicht auf servlet@servletComponentscan Class SpringbootdruidApplication {public static void main (String [] args) {SpringApplication.run (SpringbootdruidApplication.Class, Args) gescannt werden. }}Der Rest ist dieselbe Entität (Entitätsklasse), Repository (Data Operation Layer), Controller (Controller für das Testen) wie integrierte JPA, auf dem der Code direkt angezeigt wird.
Stadt
Paket com.dalaoyang.entity; Import Javax.Persistence. @GeneratedValue (Strategie = GenerationType.auto) Private int CityId; private String CityName; private String CityInTroducucucucucucucucucuce; Public City (int CityId, String CityName, String CityInTroducuce) {this.cityId = CityId; this.cityName = CityName; this.cityInTroducuce = CityIntroduc; } public City (String CityName, String CityInTroduce) {this.cityName = CityName; this.cityInTroducuce = CityIntroduc; } 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 getCityInTroduce () {return CityInTroducuce; } public void setCityInTroducu (String CityInTroducuce) {this.cityInTroDucuce = CityInTroducuce; }}CityRepository
Paket com.dalaoyang.repository; import com.dalaoyang.entity.city; import org.springframework.data.jpa.repository.jparepository;/** * @Author Dalaoyang * @Description * @Project.Learn * @package com.dalaoyang.repository * @package com.dalaoyang.repository * | [email protected] * @date 2018/4/7 */public interface CityRepository erweitert JParepository <City, Integer> {}
CityController
Paket com.dalaoyang.controller; import com.dalaoyang.entity.city; import com.dalaoyang.repository.cityrepository; import org.springframework.bean.factory.Annotation.Autowired; org.springframework.web.bind.annotation.restcontroller;/** * @Author Dalaoyang * @Description * @project SpringBoot_Learn * @package com.dalaoang.controller * @email [email protected] * @date 2018/7/7/7/. {@Autowired Private CityRepository CityRepository; // http: // localhost: 8888/Savecity? CityName = Beijing & CityInTroduce = China's Capital @getmapping (value = "Savecity") öffentliche String -Savigkeit (String CityName, String CityInTroducu) {City City = New City (CityName, CityInRepyNtroduce); CityRepository.save (Stadt); zurück "Erfolg"; } // http: // localhost: 8888/deletecity? CityId = 2 @getmapping (value = "deletecity") public String deletecity (int CityId) {CityRepository.Delete (CityId); zurück "Erfolg"; } //http://localhost:8888/updateCity?cityId=3&cityName=Shenyang&cityIntroduce=Liaoning Provincial Capital @GetMapping(value = "updateCity") public String updateCity(int cityId,String cityName,String cityIntroduce){ City city = new City(cityId,cityName,cityIntroduce); CityRepository.save (Stadt); zurück "Erfolg"; } // http: // localhost: 8888/getCityById? CityId = 3 @getMapping (value = "getCityById") Public City getCityById (int CityId) {City City = CityRepository.Findone (CityId); Stadt zurückkehren; }}
Dann starten Sie das Projekt und Sie können sehen, dass die Konsole den Stadttisch erstellt hat.
Besuchen Sie dann http: // localhost: 8888/druid und Sie können die folgende Abbildung sehen:
Geben Sie den Account Password Admin, Admin, wie in der folgenden Abbildung ein
Dann können wir zu diesem Zeitpunkt http: // localhost: 8888/Savecity? CityName = Beijing & CityInTroducy = Chinas Hauptstadt besuchen
Klicken Sie dann auf die SQL -Überwachung oben (siehe Abbildung unten).
Aus der obigen Abbildung können Sie sehen, dass die SQL, die die Projekterstellungstabelle begann, gerade ausgeführt wurde. Die Integration wurde hier abgeschlossen.
Quellcode herunterladen: https://gitee.com/dalaoyang/springboot_learn
Das obige ist der gesamte Inhalt dieses Artikels. Ich hoffe, es wird für das Lernen aller hilfreich sein und ich hoffe, jeder wird Wulin.com mehr unterstützen.