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 <http://www.w3.org/2001 xsi:schemalocation = "http://maven.apache.org/pom/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.0.sdsd"> <modeleversion> 4.0.0 </modelversion> <グループ> com.dalayang </groupid> <artifactid> springboot_druid </artifactid> <バージョン> 0.0.1-snapshot </version> <packaging> jar </packaging> <name> springboot_druid </name> <説明> springboot_druid </description> <parent> <parent> <proupid> org.springframework.boot </groupid> <artifactid> spring-boot-starter-parent </artifactid> <version> 1.5.12.release </version> <relativepath/> <! - lookup parent from repository-> </parent> <properties> <build.sourceencoding> utf-8 </project.build.sourceencoding> <project.reporting.outputencoding> utf-8 </project.reporting.outputencoding> <java.version> 1.8 </java.version> </properties> <dependencies> <shiplencys> <seglonce> </dependency> <dependency> groupid> org.springframework.boot </groupid> <artifactid> spring-boot-starter-web </artifactid> </dependency> <redency> <groupid> org.springframework.boot </groupid> <artifactid </scope> </scopetid> </dependency> <dependency> groupid> mysql </groupid> <artifactid> mysql-connector-java </artifactid> <scope> runtime </scope> </dependency> <seplency> <shiptency> org.springframework.boot </groupid> spring-boot-stortertetid> <scope> test </scope> </dependency> <dependency> groupid> com.alibaba </groupid> <artifactid> druid </artifactid> <バージョン> 1.0.28 </version> </dependency> </dependencies> <build> <プラグイン> <groupid> org.springframework.boot </groupid> <artifactid> spring-boot-maven-plugin </artifactid> </plugin> </plugins> </build> </project>
Application.Propertiesの前半と統合JPAはまったく変更されていません。一部のドルイド構成は以下に追加されています。ドルイドの構成がわからない場合は、オンラインで確認できます。 (この記事はよく書かれていると思います、ポータル)
#port number server.port = 8888 ## hibernateが読み込まれたときに検証し、データベーステーブル構造の作成を確認します## hibernateがロードされるたびに作成し、データベーステーブル構造を再作成します。これがデータベーステーブルデータの損失の理由です。 hibernateがロードされたときに作成された作成ドロップの作成、exitはテーブル構造を削除するためです##更新hibernateはデータベース構造を自動的に更新します##起動時にテーブルの構造を検証しますsqlspring.jpa.show-sql = true ##データベース構成##データベースアドレスspring.datasource.url = jdbc:mysql:// localhost:3306/testencoding = utf8&usessl = fals ## fals ##データベースspring.datasosorce.usernam e spring.datasource.password = root ##データベースドライバーspring.datasource.datasource.datasource.datasource.datasourclass-name = com.mysql.jdbc.driver#druidを使用する場合は、spring.datasource.typespring.datasource.type = com.alibaba.datasource.tappe #接続プールの構成情報#サイズの初期化、最小、最大spring.datasource.initialsize = 5 spring.datasource.minidle = 5 spring.datasource.maxactive = 20#spring.datasource.maxwait = 60000#configure configure configure configure configure configure configure configure configure configure configure waiting timeout spring.datasource.maxwait = 60000 milliseconds spring.datasource.timebetweenevictionrunsmillis = 60000#プールで生存する接続の最小時間を構成します。 spring.datasource.testonborrow = false spring.datasource.testonreturn = false#pscacheを開いて、各接続でpscacheのサイズを指定しますspring.datasource.poolpreparedstatements = true spring.datasource.datasource.maxpoolpeardestatementperconnectionsizes = 20#統計学的な統計のためのフィルターを構成します。削除した後、監視インターフェイスSQLをカウントできません。 「ウォール」はファイアウォールに使用されますspring.datasource.filters = stat、wall、log4j#connectpropertiesプロパティを使用してmergesql関数を開きます。遅いSQLレコード
次に、DruidConfigをプロジェクトに追加し、この構成ファイルが主にApplication.Propertiesの構成をロードすると、コードが次のとおりであることを簡単に説明します。
パッケージcom.dalaoyang.config;インポートjava.sql.sqlexception; Import javax.sql.datasource; Import org.apache.log4j.logger; Import org.springframework.beans.factory.annotation.value; Import org.springframework.context.context.annotation.bean; org.springframework.annotation.configuration; Import org.springframework.context.annotation.primary; Import com.alibaba.druid.druiddatasource; @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}")private string username; @value( "$ {spring.datasource.password}")private string password; @value( "$ {spring.datasource.driver-class-name}")private string driverclassname; @value( "$ {spring.datasource.initialsize}")private int hientize; @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 balidationquery; @value( "$ {spring.datasource.testhileidle}")private boolean testhiledle; @value( "$ {spring.datasource.testonborrow}")private boolean testonborrow; @value( "$ {spring.datasource.testonreturn}")private boolean testonreturn; @value( "$ {spring.datasource.poolpreparedStatements}")private boolean poolpreparedStatements; @value( "$ {spring.datasource.maxpoolpreparedstatementperconnectionsize}")private int maxpoolpreparedstatementperconnectionsize; @value( "$ {spring.datasource.filters}")プライベート文字列フィルター。 @value( "{spring.datasource.connectionProperties}")private string connectionProperties; @bean @primary //メインデータソースpublic datasource datasource(){druiddatasource datasource = new Druiddatasource(); dataSource.seturl(this.dburl); DataSource.setUsername(username); dataSource.setPassWord(パスワード); DataSource.setDriverClassName(DriverClassName); //構成DataSource.setInitialSize(hientsize); DataSource.setMinidle(Minidle); DataSource.setMaxactive(maxactive); DataSource.setMaxWait(MaxWait); dataSource.settimebetweenevictionrunsmillis(timevethictionrunsmillis); dataSource.setMineVictableIdletimemillis(minevictableidletimemillis); dataSource.setValidationQuery(ValidationQuery); dataSource.settestwhileidle(testhiledle); dataSource.settestonborrow(testonborrow); DataSource.SetteStonreturn(TestOnreturn); DataSource.setPoolPreparedStatements(PoolPreparedStatements); DataSource.setMaxPoolPreparedStatementPerConnectionSize(MaxPoolPreparedStatementPerConnectionSize); try {dataSource.setFilters(フィルター); } catch(sqlexception e){logger.error( "Druid Configuration Exception"、e); } dataSource.setConnectionProperties(ConnectionProperties); DataSourceを返します。 }}
次に、DruidFilterを作成します。コードは次のとおりです。
パッケージcom.dalaoyang.filter; import javax.servlet.annotation.webfilter; Import javax.servlet.annotation.webinitparam; Import com.alibaba.druid.support.http.webstatfilter;/** * @author dalaonang * @descripation * @descripution * @descripution * @pagej com.dalaoyang.filter * @email [email protected] * @date 2018/4/12 */ @webfilter(filtername = "druidwebstatfilter"、urlpatterns = "/ *"、initparams = { @webinitparam(name = "除外"、value = "*。js、*。gif、*。jpg、*。bmp、*。png、*。
新しいDruidServletを作成し、クラス@webservletに注釈を追加します。これは、Druid監視ページ、ホワイトリスト、ブラックリストの構成にログインのアカウントパスワードを構成します。コードは次のとおりです。
com.dalaoyang.servlet; Import javax.servlet.annotation.webinitparam; import javax.servlet.annotation.websert.http.statviewservlet;/** * @author dalaang * @descripation * @pruedbed_projed * @pruej com.dalaoyang.servlet * @email [email protected] * @date 2018/4/12 */ @webservlet(urlpatterns = "/druid/ *"、initparams = {@webinitparam(name = "、loce"、value = "") @webinitparam(name = "deny"、value = "")、// ip blacklist(denyは許可を優先します)@webinitparam(name = "loginusername"、value = "admin")、// druid管理ページusername @webinitparam(name = "loginpassword"、value = "" druidservletはstatviewservletを拡張します{}
次に、annotation @servletcomponentscanをスタートアップクラスに追加し、プロジェクトをサーブレットにスキャンします。コードは次のとおりです。
パッケージcom.dalaoyang; Import org.springframework.boot.springApplication; Import org.springframework.boot.autoconfigure.springframework.springframework.boot.web.servletcomponentscan;アノテーション、それ以外の場合は、servlet@servletcomponentscan public class springbootdruidapplicationにスキャンすることはできません{public static void main(string [] args){springapplication.run(springbootdruidapplication.class、args); }}残りは、コードを直接表示する統合JPAとして同じエンティティ(エンティティクラス)、リポジトリ(データ操作レイヤー)、コントローラー(テストに使用されるコントローラー)です。
市
パッケージcom.dalaoyang.entity; import javax.persistence。 *;/** * @author dalaoyang * @description * @project springboot_learn * @package com.dalaoyang.entity @generatedValue(Strategy = GenerationType.auto)private int Cityid;プライベートストリングシティ名; Private String CityIntroduce;パブリックシティ(Int CityID、String CityName、String CityIntroduce){this.cityid = cityid; this.cityname = cityName; this.cityintroduce = cityintroduce; } public City(String CityName、String CityIntroduce){this.CityName = CityName; this.cityintroduce = cityintroduce; } 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 cityintroduce; } public void setCityIntroduce(string cityintroduce){this.cityintroduce = cityintroduce; }}CityRepository
パッケージcom.dalaoyang.repository; Import com.dalaoyang.entity.city; Import org.springframework.data.jpa.repository.jparepository;/** * @author dalaoyang * @description * @project springboot_lealen [email protected] * @date 2018/4/7 */public interface cityRepository拡張jparepository <city、integer> {}
CityController
パッケージcom.dalaoyang.controller; Import com.dalaoyang.entity.city; Import com.dalaoyang.repository.cityrepository; Import org.springframework.beans.factory.annotation.Autowired; Import org.springframework.web.bind.annotation; impateMapping; org.springframework.web.bind.annotation.restcontroller;/** * @author dalaoyang * @description * @project springboot_learn * @package com.dalaoyang.controller * @email [email protected] @Autowired Private CityRepository CityRepository; // http:// localhost:8888/savecity?cityname = beijing&cityintroduce = chinaのcapital @getmapping(value = "savecity")public string savecity(string cityname、string cityintroduce){city city = new City(CityName、CityIntroduce); 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&cityintroduce = liaoning provincial capital @getmapping(bule = "updatecity")public string updatecity(int Cityid、String CityName、String CityIntroduce) CityRepository.Save(City); 「成功」を返します。 } // http:// localhost:8888/getCityById?cityId = 3 @getMapping(value = "getCityByid")Public City getCityid(int Cityid){city city = cityRepository.findone(CityID);帰りの都市; }}
次に、プロジェクトを開始すると、コンソールが都市テーブルを作成したことがわかります。
次に、http:// localhost:8888/druidにアクセスすると、次の数字を確認できます。
次の図に示すように、アカウントのパスワード管理者、管理者を入力してください
その後、この時点でhttp:// localhost:8888/savecity?cityname = beijing&cityintroduce =中国の首都にアクセスできます
次に、下の図に示すように、上記のSQL監視をクリックします。
上記の図から、プロジェクト作成テーブルを開始したSQLが実行されたばかりであることがわかります。統合はここで完了しました。
ソースコードのダウンロード:https://gitee.com/dalaoyang/springboot_learn
上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。