最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

springboot 中 druid+jpa+MYSQL數(shù)據(jù)庫(kù)配置過(guò)程

 更新時(shí)間:2021年08月02日 14:21:26   作者:netsram  
這篇文章主要介紹了springboot 中 druid+jpa+MYSQL數(shù)據(jù)庫(kù)配置,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

Druid來(lái)自于阿里的一個(gè)開(kāi)源連接池能夠提供強(qiáng)大的監(jiān)控和擴(kuò)展功能,Spring Boot默認(rèn)不支持Druid和jpa,需要引入依賴(lài)。

1、引入依賴(lài)包

<!--druid-->
    <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.22</version>
    </dependency>
 
<!--jpa-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

2、配置application.properties

#druid配置-MYSQL
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test1?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=123456
 
# 初始化大小,最小,最大
spring.datasource.initialSize=5
spring.datasource.maxActive=20
spring.datasource.minIdle=5
# 配置獲取連接等待超時(shí)的時(shí)間
spring.datasource.max-wait=60000
# 配置間隔多久才進(jìn)行一次檢測(cè),檢測(cè)需要關(guān)閉的空閑連接,單位是毫秒
spring.datasource.time-between-eviction-runs-millis=60000
# 配置一個(gè)連接在池中最小生存的時(shí)間,單位是毫秒
spring.datasource.min-evictable-idle-time-millis=300000
#檢測(cè)連接是否有效的sql,要求是一個(gè)查詢(xún)語(yǔ)句,常用select 'x'.如果validationQuery為null,testOnBorrow,testOnBorrow,testOnReturn,testWhileIdle都不會(huì)起作用。這個(gè)可以不配置
spring.datasource.validation-query=SELECT 'x'
#檢測(cè)連接是否有效的超時(shí)時(shí)間。
spring.datasource.validation-query-timeout=60000
spring.datasource.test-while-idle=true
spring.datasource.test-on-borrow=false
spring.datasource.test-on-return=false
# 打開(kāi)PSCache,并且指定每個(gè)連接上PSCache的大小
spring.datasource.pool-prepared-statements=true
spring.datasource.max-pool-prepared-statement-per-connection-size=20
# 配置監(jiān)控統(tǒng)計(jì)攔截的filters,去掉后監(jiān)控界面sql無(wú)法統(tǒng)計(jì),'wall'用于防火墻,#別名方式,擴(kuò)展插件,監(jiān)控統(tǒng)計(jì)用的filter:stat,日志用的filter:log4j,防御sql注入的filter:wall
spring.datasource.filters=stat,wall,slf4j

3、Druid配置信息定制

@Configuration
public class DruidConfig {
    @Autowired
    private DruidDataSourceProperties properties;
 
    @Bean(name = "druidDataSource", initMethod = "init", destroyMethod = "close")
    @Qualifier("druidDataSource")
    public DataSource dataSource() throws Exception {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(properties.getUrl());
        druidDataSource.setUsername(properties.getUsername());
        druidDataSource.setPassword(properties.getPassword());
        druidDataSource.setDriverClassName(properties.getDriverClassName());
        druidDataSource.setInitialSize(properties.getInitialSize());
        druidDataSource.setMaxActive(properties.getMaxActive());
        druidDataSource.setMinIdle(properties.getMinIdle());
        druidDataSource.setMaxWait(properties.getMaxWait());
        druidDataSource.setTimeBetweenEvictionRunsMillis(properties
                .getTimeBetweenEvictionRunsMillis());
        druidDataSource.setMinEvictableIdleTimeMillis(properties
                .getMinEvictableIdleTimeMillis());
        druidDataSource.setValidationQuery(properties.getValidationQuery());
        druidDataSource.setTestWhileIdle(properties.isTestWhileIdle());
        druidDataSource.setTestOnBorrow(properties.isTestOnBorrow());
        druidDataSource.setTestOnReturn(properties.isTestOnReturn());
        druidDataSource.setPoolPreparedStatements(properties
                .isPoolPreparedStatements());
        druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(properties
                .getMaxPoolPreparedStatementPerConnectionSize());
        druidDataSource.setFilters(properties.getFilters());
 
        try {
            if (null != druidDataSource) {
                druidDataSource.setFilters("wall,stat");
                druidDataSource.setUseGlobalDataSourceStat(true);
//                Properties properties = new Properties();
//                properties.setProperty("decrypt", "true");
//                druidDataSource.setConnectProperties(properties);
                druidDataSource.init();
            }
        } catch (Exception e) {
            throw new RuntimeException(
                    "load datasource error, dbProperties is :", e);
        }
        return druidDataSource;
    }
}

3、獲取Properties中配置信息

@Configuration
@ConfigurationProperties(prefix = "spring.datasource")
public class DruidDataSourceProperties {
	
	private String url;
 
	private String username;
 
	private String password;
 
	private String driverClassName;
 
	private int initialSize;
 
	private int maxActive;
 
	private int minIdle;
 
	private int maxWait;
 
	private long timeBetweenEvictionRunsMillis;
 
	private long minEvictableIdleTimeMillis;
 
	private String validationQuery;
 
	private boolean testWhileIdle;
 
	private boolean testOnBorrow;
 
	private boolean testOnReturn;
 
	private boolean poolPreparedStatements;
 
	private int maxPoolPreparedStatementPerConnectionSize;
 
	private String filters;
 
	public String getUrl() {
		return url;
	}
 
	public void setUrl(String url) {
		this.url = url;
	}
 
	public String getUsername() {
		return username;
	}
 
	public void setUsername(String username) {
		this.username = username;
	}
 
	public String getPassword() {
		return password;
	}
 
	public void setPassword(String password) {
		this.password = password;
	}
 
	public String getDriverClassName() {
		return driverClassName;
	}
 
	public void setDriverClassName(String driverClassName) {
		this.driverClassName = driverClassName;
	}
 
	public int getInitialSize() {
		return initialSize;
	}
 
	public void setInitialSize(int initialSize) {
		this.initialSize = initialSize;
	}
 
	public int getMaxActive() {
		return maxActive;
	}
 
	public void setMaxActive(int maxActive) {
		this.maxActive = maxActive;
	}
 
	public int getMinIdle() {
		return minIdle;
	}
 
	public void setMinIdle(int minIdle) {
		this.minIdle = minIdle;
	}
 
	public int getMaxWait() {
		return maxWait;
	}
 
	public void setMaxWait(int maxWait) {
		this.maxWait = maxWait;
	}
 
	public long getTimeBetweenEvictionRunsMillis() {
		return timeBetweenEvictionRunsMillis;
	}
 
	public void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) {
		this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
	}
 
	public long getMinEvictableIdleTimeMillis() {
		return minEvictableIdleTimeMillis;
	}
 
	public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) {
		this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
	}
 
	public String getValidationQuery() {
		return validationQuery;
	}
 
	public void setValidationQuery(String validationQuery) {
		this.validationQuery = validationQuery;
	}
 
	public boolean isTestWhileIdle() {
		return testWhileIdle;
	}
 
	public void setTestWhileIdle(boolean testWhileIdle) {
		this.testWhileIdle = testWhileIdle;
	}
 
	public boolean isTestOnBorrow() {
		return testOnBorrow;
	}
 
	public void setTestOnBorrow(boolean testOnBorrow) {
		this.testOnBorrow = testOnBorrow;
	}
 
	public boolean isTestOnReturn() {
		return testOnReturn;
	}
 
	public void setTestOnReturn(boolean testOnReturn) {
		this.testOnReturn = testOnReturn;
	}
 
	public boolean isPoolPreparedStatements() {
		return poolPreparedStatements;
	}
 
	public void setPoolPreparedStatements(boolean poolPreparedStatements) {
		this.poolPreparedStatements = poolPreparedStatements;
	}
 
	public int getMaxPoolPreparedStatementPerConnectionSize() {
		return maxPoolPreparedStatementPerConnectionSize;
	}
 
	public void setMaxPoolPreparedStatementPerConnectionSize(
			int maxPoolPreparedStatementPerConnectionSize) {
		this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize;
	}
 
	public String getFilters() {
		return filters;
	}
 
	public void setFilters(String filters) {
		this.filters = filters;
	}
 
	public DruidDataSourceProperties() {
		// TODO Auto-generated constructor stub
	}
 
	public DruidDataSourceProperties(String url, String username,
									 String password, String driverClassName, int initialSize,
									 int maxActive, int minIdle, int maxWait,
									 long timeBetweenEvictionRunsMillis,
									 long minEvictableIdleTimeMillis, String validationQuery,
									 boolean testWhileIdle, boolean testOnBorrow, boolean testOnReturn,
									 boolean poolPreparedStatements,
									 int maxPoolPreparedStatementPerConnectionSize, String filters) {
		this.url = url;
		this.username = username;
		this.password = password;
		this.driverClassName = driverClassName;
		this.initialSize = initialSize;
		this.maxActive = maxActive;
		this.minIdle = minIdle;
		this.maxWait = maxWait;
		this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
		this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
		this.validationQuery = validationQuery;
		this.testWhileIdle = testWhileIdle;
		this.testOnBorrow = testOnBorrow;
		this.testOnReturn = testOnReturn;
		this.poolPreparedStatements = poolPreparedStatements;
		this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize;
		this.filters = filters;
	}
	
}

如果需要Druid的監(jiān)控統(tǒng)計(jì)功能在配置代碼中加入以下代碼:

@Bean
	public ServletRegistrationBean druidServlet() {
		ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
		// IP白名單 (沒(méi)有配置或者為空,則允許所有訪問(wèn))
		servletRegistrationBean.addInitParameter("allow", "127.0.0.1");
		// IP黑名單(共同存在時(shí),deny優(yōu)先于allow)
		//servletRegistrationBean.addInitParameter("deny", "");
		//控制臺(tái)管理用戶(hù)
		servletRegistrationBean.addInitParameter("loginUsername", "admin");
		servletRegistrationBean.addInitParameter("loginPassword", "admin");
		//是否能夠重置數(shù)據(jù) 禁用HTML頁(yè)面上的“Reset All”功能
		servletRegistrationBean.addInitParameter("resetEnable", "false");
		return servletRegistrationBean;
	}
 
	@Bean
	public FilterRegistrationBean filterRegistrationBean() {
		FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
		filterRegistrationBean.addUrlPatterns("/*");
		filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
		return filterRegistrationBean;
	}

訪問(wèn)地址:http://127.0.0.1:8080/druid, 使用配置的賬號(hào)密碼登錄即可查看數(shù)據(jù)源及SQL統(tǒng)計(jì)等監(jiān)控信息。

4、jpa配置

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactory",
        transactionManagerRef = "transactionManager",
        basePackages = {"*.dao"})//指定需要掃描的dao所在包
public class RepositoryConfig {
 
    @Autowired
    private JpaProperties jpaProperties;
 
    @Autowired
    @Qualifier("druidDataSource")
    private DataSource druidDataSource;
 
    @Bean(name = "entityManager")
    @Primary
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return entityManagerFactory(builder).getObject().createEntityManager();
    }
 
    /**
     * 指定需要掃描的實(shí)體包實(shí)現(xiàn)與數(shù)據(jù)庫(kù)關(guān)聯(lián)
     * @param builder
     * @return
     */
    @Bean(name = "entityManagerFactory")
    @Primary
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(druidDataSource)
                .properties(getVendorProperties(druidDataSource))
                .packages("*.entity")//指定需要掃描的entity所在包
                .build();
    }
 
    /**
     * 通過(guò)jpaProperties指定hibernate數(shù)據(jù)庫(kù)方言以及在控制臺(tái)打印sql語(yǔ)句
     * @param dataSource
     * @return
     */
    private Map<String, String> getVendorProperties(DataSource dataSource) {
        Map<String, String> map = jpaProperties.getProperties();
        map.put("hibernate.dialect", "org.hibernate.dialect.MySQL8Dialect");
        map.put("hibernate.show_sql", "true");
        return map;
    }
 
    /**
     * 創(chuàng)建事務(wù)管理
     * @param builder
     * @return
     */
    @Bean(name = "transactionManager")
    @Primary
    PlatformTransactionManager transactionManager(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactory(builder).getObject());
    }
 
}

到此這篇關(guān)于springboot 中 druid+jpa+MYSQL數(shù)據(jù)庫(kù)配置的文章就介紹到這了,更多相關(guān)springboot druid+jpa+MYSQL配置內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 基于Java設(shè)計(jì)一個(gè)高并發(fā)的秒殺系統(tǒng)

    基于Java設(shè)計(jì)一個(gè)高并發(fā)的秒殺系統(tǒng)

    這篇文章主要為大家詳細(xì)介紹了如何基于Java設(shè)計(jì)一個(gè)高并發(fā)的秒殺系統(tǒng),文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,有需要的小伙伴可以參考下
    2023-10-10
  • 深入java垃圾回收的詳解

    深入java垃圾回收的詳解

    本篇文章是對(duì)java垃圾回收進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下
    2013-06-06
  • Java如何實(shí)現(xiàn)判斷并輸出文件大小

    Java如何實(shí)現(xiàn)判斷并輸出文件大小

    這篇文章主要介紹了Java如何實(shí)現(xiàn)判斷并輸出文件大小問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-04-04
  • 一文詳解java閉包的用途是什么

    一文詳解java閉包的用途是什么

    閉包的價(jià)值在于可以作為函數(shù)對(duì)象或者匿名函數(shù),持有上下文數(shù)據(jù),作為第一級(jí)對(duì)象進(jìn)行傳遞和保存,下面這篇文章主要給大家介紹了關(guān)于java閉包的用途是什么,需要的朋友可以參考下
    2024-03-03
  • 解決IDEA使用maven創(chuàng)建Web項(xiàng)目,出現(xiàn)500錯(cuò)誤的問(wèn)題

    解決IDEA使用maven創(chuàng)建Web項(xiàng)目,出現(xiàn)500錯(cuò)誤的問(wèn)題

    本文主要介紹了在使用Maven創(chuàng)建項(xiàng)目并導(dǎo)入依賴(lài)寫(xiě)完測(cè)試代碼后運(yùn)行出現(xiàn)500錯(cuò)誤的解決步驟,這種問(wèn)題的根本原因是Tomcat啟動(dòng)后缺少某些支持的jar包,導(dǎo)致運(yùn)行出錯(cuò),解決方法是在項(xiàng)目結(jié)構(gòu)中找到Artifacts,點(diǎn)擊要編輯的項(xiàng)目
    2024-10-10
  • ZooKeeper Java API編程實(shí)例分析

    ZooKeeper Java API編程實(shí)例分析

    本文主要通過(guò)實(shí)例給大家詳細(xì)分析了ZooKeeper用JAVA實(shí)現(xiàn)API編程的知識(shí)要點(diǎn)。
    2017-11-11
  • spring+maven實(shí)現(xiàn)發(fā)送郵件功能

    spring+maven實(shí)現(xiàn)發(fā)送郵件功能

    這篇文章主要為大家詳細(xì)介紹了spring+maven實(shí)現(xiàn)發(fā)送郵件功能,利用spring提供的郵件工具來(lái)發(fā)送郵件,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-07-07
  • Java中使用注解獲取和改變Bean的指定變量值

    Java中使用注解獲取和改變Bean的指定變量值

    Java有時(shí)需要通過(guò)自定義注解,獲取某Bean的某變量的值,根據(jù)業(yè)務(wù)要求處理數(shù)據(jù),然后再把新值設(shè)置回Bean的同一變量中,這篇文章介紹了使用注解獲取和改變Bean變量值的過(guò)程,感興趣想要詳細(xì)了解可以參考下文
    2023-05-05
  • 為什么Java volatile++不是原子性的詳解

    為什么Java volatile++不是原子性的詳解

    這篇文章主要給大家介紹了關(guān)于為什么Java volatile++不是原子性的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2021-02-02
  • Struts2之Action接收請(qǐng)求參數(shù)和攔截器詳解

    Struts2之Action接收請(qǐng)求參數(shù)和攔截器詳解

    這篇文章主要介紹了Struts2之Action接收請(qǐng)求參數(shù)和攔截器詳解,非常具有實(shí)用價(jià)值,需要的朋友可以參考下
    2017-05-05

最新評(píng)論

深圳市| 望都县| 通海县| 宽城| 广宗县| 蒙城县| 乌拉特中旗| 乃东县| 大港区| 定远县| 阿拉善盟| 汕尾市| 雷山县| 灵台县| 朔州市| 陵川县| 济宁市| 延庆县| 高台县| 乌拉特中旗| 双江| 马龙县| 永定县| 诸城市| 东光县| 尼玛县| 新平| 金门县| 华容县| 华池县| 文昌市| 九台市| 邹城市| 芜湖县| 高青县| 云梦县| 沧源| 武安市| 麦盖提县| 普陀区| 察哈|