电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

springboot 中 druid+jpa+MYSQL數據庫配置過程

瀏覽:2日期:2023-02-20 11:54:30

Druid來自于阿里的一個開源連接池能夠提供強大的監控和擴展功能,Spring Boot默認不支持Druid和jpa,需要引入依賴。

1、引入依賴包

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

3、Druid配置信息定制

@Configurationpublic 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的監控統計功能在配置代碼中加入以下代碼:

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

訪問地址:http://127.0.0.1:8080/druid, 使用配置的賬號密碼登錄即可查看數據源及SQL統計等監控信息。

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(); } /** * 指定需要掃描的實體包實現與數據庫關聯 * @param builder * @return */ @Bean(name = 'entityManagerFactory') @Primary public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder) {return builder.dataSource(druidDataSource).properties(getVendorProperties(druidDataSource)).packages('*.entity')//指定需要掃描的entity所在包.build(); } /** * 通過jpaProperties指定hibernate數據庫方言以及在控制臺打印sql語句 * @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; } /** * 創建事務管理 * @param builder * @return */ @Bean(name = 'transactionManager') @Primary PlatformTransactionManager transactionManager(EntityManagerFactoryBuilder builder) {return new JpaTransactionManager(entityManagerFactory(builder).getObject()); } }

到此這篇關于springboot 中 druid+jpa+MYSQL數據庫配置的文章就介紹到這了,更多相關springboot druid+jpa+MYSQL配置內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Spring
相關文章:
主站蜘蛛池模板: 安全光栅|射频导纳物位开关|音叉料位计|雷达液位计|两级跑偏开关|双向拉绳开关-山东卓信机械有限公司 | 建大仁科-温湿度变送器|温湿度传感器|温湿度记录仪_厂家_价格-山东仁科 | 山东钢衬塑罐_管道_反应釜厂家-淄博富邦滚塑防腐设备科技有限公司 | TwistDx恒温扩增-RAA等温-Jackson抗体-默瑞(上海)生物科技有限公司 | 首页-瓜尔胶系列-化工单体系列-油田压裂助剂-瓜尔胶厂家-山东广浦生物科技有限公司 | 爱佩恒温恒湿测试箱|高低温实验箱|高低温冲击试验箱|冷热冲击试验箱-您身边的模拟环境试验设备技术专家-合作热线:400-6727-800-广东爱佩试验设备有限公司 | 鑫铭东办公家具一站式定制采购-深圳办公家具厂家直销 | 东莞猎头公司_深圳猎头公司_广州猎头公司-广东万诚猎头提供企业中高端人才招聘服务 | 天津拓展_天津团建_天津趣味运动会_天津活动策划公司-天津华天拓展培训中心 | 网站建设-临朐爱采购-抖音运营-山东兆通网络科技 | 叉车电池-叉车电瓶-叉车蓄电池-铅酸蓄电池-电动叉车蓄电池生产厂家 | 无压烧结银_有压烧结银_导电银胶_导电油墨_导电胶-善仁(浙江)新材料 | 澳门精准正版免费大全,2025新澳门全年免费,新澳天天开奖免费资料大全最新,新澳2025今晚开奖资料,新澳马今天最快最新图库-首页-东莞市傲马网络科技有限公司 | 儋州在线-儋州招聘找工作、找房子、找对象,儋州综合生活信息门户! | 双能x射线骨密度检测仪_dxa骨密度仪_双能x线骨密度仪_品牌厂家【品源医疗】 | 起好名字_取个好名字_好名网免费取好名在线打分 | 宝元数控系统|对刀仪厂家|东莞机器人控制系统|东莞安川伺服-【鑫天驰智能科技】 | 安徽净化工程设计_无尘净化车间工程_合肥净化实验室_安徽创世环境科技有限公司 | 立式硫化罐-劳保用品硫化罐-厂家直销-山东鑫泰鑫硫化罐厂家 | 尊享蟹太太美味,大闸蟹礼卡|礼券|礼盒在线预订-蟹太太官网 | 武汉不干胶印刷_标签设计印刷_不干胶标签印刷厂 - 武汉不干胶标签印刷厂家 | 上海皓越真空设备有限公司官网-真空炉-真空热压烧结炉-sps放电等离子烧结炉 | 楼梯定制_楼梯设计施工厂家_楼梯扶手安装制作-北京凌步楼梯 | NBA直播_NBA直播免费观看直播在线_NBA直播免费高清无插件在线观看-24直播网 | 开云(中国)Kaiyun·官方网站-登录入口| 铸铝门厂家,别墅大门庭院大门,别墅铸铝门铜门[十大品牌厂家]军强门业 | 不锈钢丸厂家,铝丸,铸钢丸-淄博智源铸造材料有限公司 | 深圳美安可自动化设备有限公司,喷码机,定制喷码机,二维码喷码机,深圳喷码机,纸箱喷码机,东莞喷码机 UV喷码机,日期喷码机,鸡蛋喷码机,管芯喷码机,管内壁喷码机,喷码机厂家 | 小港信息港-鹤壁信息港 鹤壁老百姓便民生活信息网站 | 东莞喷砂机-喷砂机-喷砂机配件-喷砂器材-喷砂加工-东莞市协帆喷砂机械设备有限公司 | 谷歌关键词优化-外贸网站优化-Google SEO小语种推广-思亿欧外贸快车 | 巨野月嫂-家政公司-巨野县红墙安康母婴护理中心 | 至顶网| 深圳南财多媒体有限公司介绍| 电镀电源整流器_高频电解电源_单脉双脉冲电源 - 东阳市旭东电子科技 | 蒸汽吸附分析仪-进口水分活度仪|康宝百科 | 防堵吹扫装置-防堵风压测量装置-电动操作显示器-兴洲仪器 | 工装定制/做厂家/公司_工装订做/制价格/费用-北京圣达信工装 | 杭州中策电线|中策电缆|中策电线|杭州中策电缆|杭州中策电缆永通集团有限公司 | 熔体泵_熔体出料泵_高温熔体泵-郑州海科熔体泵有限公司 | 铝镁锰板_铝镁锰合金板_铝镁锰板厂家_铝镁锰金属屋面板_安徽建科 |