PackageCom.creditcore.services.common.dataSource;Importjava.sql.SQLException;ImportJava.util.HashMap;Importjava.util.List;ImportJava.util.Map;ImportJavax.sql.DataSource;Importorg.apache.ibatis.session.SqlSessionFactory;ImportOrg.mybatis.spring.SqlSessionFactoryBean;ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.beans.factory.annotation.Qualifier;ImportOrg.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;Importorg.springframework.boot.context.properties.EnableConfigurationProperties;ImportOrg.springframework.boot.web.servlet.FilterRegistrationBean;ImportOrg.springframework.boot.web.servlet.ServletRegistrationBean;ImportOrg.springframework.context.annotation.Bean;Importorg.springframework.context.annotation.Configuration;Importorg.springframework.context.annotation.Primary;ImportOrg.springframework.core.io.support.PathMatchingResourcePatternResolver;ImportOrg.springframework.jdbc.datasource.DataSourceTransactionManager;ImportCom.alibaba.druid.pool.DruidDataSource;ImportCom.alibaba.druid.support.http.StatViewServlet;ImportCom.alibaba.druid.support.http.WebStatFilter;/*** Springboot Integrated mybatis Basic Portal * 1) Create a data source (not required if you are using the default TOMCAT-JDBC data source) * 2) Create Sqlsessionfactory * 3) Configure the transaction manager, unless you need to use a transaction, Otherwise, do not configure*/@Configuration//This annotation is similar to the spring configuration file//@MapperScan (basepackages = "Com.xxx.firstboot.mapper")@EnableConfigurationProperties (datasourceconfiguration.class) Public classMybatisconfig {Private Static FinalLogger Logger = Loggerfactory.getlogger (mybatisconfig.class); //@Autowired//private Environment env; //@Value ("${info.build.name:hello Default}")//private String projectName;@AutowiredPrivatedatasourceconfiguration datasourceconfiguration; //mybaits Mapper XML search Path Private Static FinalString mapper_location = "Classpath:mapper/*.xml"; //read configuration information from Cloud Config, generate data source map definition Bean:d atasources@Bean @Primary @ConditionalOnMissingBean (name= "DataSources") PublicMap<string, datasource>datasources () {//System.out.println (projectName);list<map<string, string>> configlist =datasourceconfiguration.getconfiglist (); Map<string, datasource> DsMap =NewHashmap<string, datasource>(); //Configure information about a data source for(Map<string, string>configmap:configlist) {Druiddatasource DataSource=NewDruiddatasource (); Datasource.setdriverclassname (Configmap.get ("Driverclassname")); Datasource.seturl (Configmap.get ("url")); Datasource.setusername (Configmap.get ("Username")); Datasource.setpassword (Configmap.get ("Password")); //Configure initialization size, minimum, maximumDatasource.setinitialsize (Integer.parseint (Configmap.get ("InitialSize"))); Datasource.setminidle (Integer.parseint (Configmap.get ("Minidle"))); Datasource.setmaxactive (Integer.parseint (Configmap.get ("Maxactive"))); //Configure the time to get the connection wait timeoutDatasource.setmaxwait (Integer.parseint (Configmap.get ("maxwait"))); //How often the configuration interval is detected to detect idle connections that need to be closed, in millisecondsDatasource.settimebetweenevictionrunsmillis (Integer.parseint (Configmap.get ("Timebetweenevictionrunsmillis"))); //configures the minimum lifetime of a connection in a pool, in millisecondsDatasource.setminevictableidletimemillis (Integer.parseint (Configmap.get ("Minevictableidletimemillis"))); Datasource.setvalidationquery (Configmap.get ("Validationquery")); Datasource.settestwhileidle (Boolean.parseboolean (Configmap.get ("Testwhileidle"))); Datasource.settestonborrow (Boolean.parseboolean (Configmap.get ("Testonborrow"))); Datasource.settestonreturn (Boolean.parseboolean (Configmap.get ("Testonreturn"))); //Open PscacheDatasource.setpoolpreparedstatements (Boolean.parseboolean (Configmap.get ("Poolpreparedstatements"))); //Specify the size of the Pscache on each connectionDatasource.setmaxpoolpreparedstatementperconnectionsize (Integer.parseint (Configmap.get (" Maxpoolpreparedstatementperconnectionsize "))); Try { //Configure monitoring Statistics interception filters, remove post-monitoring interface SQL cannot be counted, ' wall ' for firewallsDatasource.setfilters (Configmap.get ("Filters")); } Catch(SQLException e) {logger.error ("Druid Configuration Initialization Filter", E); } //Open the Mergesql function with the Connectproperties property; slow SQL RecordsDatasource.setconnectionproperties (Configmap.get ("ConnectionProperties")); //merging monitoring data from multiple DruiddatasourceDatasource.setuseglobaldatasourcestat (true); Dsmap.put (Configmap.get ("Key"), DataSource); } returnDsMap; } /*** @Primary The note indicates which of the default options are selected when multiple implementation classes of the same interface can be injected, rather than having the @autowire annotations error * @Qualifier injected by name, usually in an injection of instances with the same multiple types (e.g. Instances of multiple datasource types)*/ //define Bean:datasource//the value of datasources is derived from the datasources defined above@Bean @Primary PublicDynamicdatasource DataSource (@Qualifier ("datasources") map<string, datasource>datasources) {Map<object, object> targetdatasources =NewHashmap<>(); for(String key:dataSources.keySet ()) {Targetdatasources.put (key, Datasources.get (key)); } Dynamicdatasource DataSource=NewDynamicdatasource (); Datasource.settargetdatasources (targetdatasources);//This method is a method of AbstractroutingdatasourceDatasource.setdefaulttargetdatasource (Targetdatasources.get ("Default"));//The default DataSource setting is Mytestdbdatasource returnDataSource; } /*** Create sqlsessionfactory based on data source*/ //define Bean:sqlsessionfactory//The value of DataSource is derived from the datasource defined above@Bean PublicSqlsessionfactory sqlsessionfactory (Dynamicdatasource dataSource)throwsException {Sqlsessionfactorybean fb=NewSqlsessionfactorybean (); Fb.setdatasource (DataSource);//Specify the data source (this must be, otherwise an error)//The following two sentences are only for the *.xml file, if the entire persistence layer operation does not need to use the XML file (only with annotations can be done), then does not add//Fb.settypealiasespackage (Env.getproperty ("Mybatis.typealiasespackage"));// //specifying a base package Try{fb.setmapperlocations (NewPathmatchingresourcepatternresolver (). Getresources (mapper_location));//}Catch(Exception e) {//Some projects do not need to operate the DB without mapper files, to prevent the start errorE.printstacktrace (); } returnFb.getobject (); } /*** Configure transaction manager*/@Bean PublicDatasourcetransactionmanager TransactionManager (Dynamicdatasource dataSource)throwsException {return NewDatasourcetransactionmanager (DataSource); } @Bean PublicServletregistrationbean Druidservlet () {Servletregistrationbean Servletregistrationbean=NewServletregistrationbean (NewStatviewservlet (), "/druid/*"); //White list:Servletregistrationbean.addinitparameter ("Allow", "" "); //IP blacklist (when common, deny takes precedence over allow): If Deny is satisfied: Sorry, you is not permitted to view the this page.Servletregistrationbean.addinitparameter ("Deny", "192.168.1.73"); //Log in to view the account password of the information.Servletregistrationbean.addinitparameter ("Loginusername", "admin"); Servletregistrationbean.addinitparameter ("Loginpassword", "123456"); //whether the data can be reset.Servletregistrationbean.addinitparameter ("Resetenable", "false"); returnServletregistrationbean; } @Bean PublicFilterregistrationbean Filterregistrationbean () {Filterregistrationbean Filterregistrationbean=NewFilterregistrationbean (); Filterregistrationbean.setfilter (NewWebstatfilter ()); Filterregistrationbean.addurlpatterns ("/*"); Filterregistrationbean.addinitparameter ("Exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); returnFilterregistrationbean; }}
Springboot Dynamic Data source Druid and monitoring configuration