日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

Spring Boot 中使用 MyBatis 整合 Druid 多数据源

發(fā)布時間:2024/1/17 javascript 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Spring Boot 中使用 MyBatis 整合 Druid 多数据源 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

本文將講述 spring boot + mybatis + druid 多數(shù)據(jù)源配置方案。

環(huán)境

CentOs7.3 安裝 MySQL 5.7.19 二進制版本

Github 代碼

代碼我已放到 Github ,導(dǎo)入spring-boot-mybatis 項目

github https://github.com/souyunku/spring-boot-examples/tree/master/spring-boot-mybatis

添加依賴

在項目中添加 mybatis,druid 依賴

點擊預(yù)覽 pom.xml

<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId> </dependency> <dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId> </dependency> 省略 更多

基礎(chǔ)數(shù)據(jù)源

@Configuration @EnableConfigurationProperties(DruidDbProperties.class) @Import({DruidMonitConfig.class}) public abstract class AbstractDruidDBConfig {private Logger logger = LoggerFactory.getLogger(AbstractDruidDBConfig.class);@Resourceprivate DruidDbProperties druidDbProperties;public DruidDataSource createDataSource(String url, String username, String password) {if (StringUtils.isEmpty(url)) {System.out.println("Your database connection pool configuration is incorrect!" + " Please check your Spring profile");throw new ApplicationContextException("Database connection pool is not configured correctly");}DruidDataSource datasource = new DruidDataSource();datasource.setUrl(url);datasource.setUsername(username);datasource.setPassword(password);// datasource.setDriverClassName(// StringUtils.isEmpty(driverClassName) ?// druidDbProperties.getDriverClassName() : driverClassName);datasource.setInitialSize(druidDbProperties.getInitialSize());datasource.setMinIdle(druidDbProperties.getMinIdle());datasource.setMaxActive(druidDbProperties.getMaxActive());datasource.setMaxWait(druidDbProperties.getMaxWait());datasource.setTimeBetweenEvictionRunsMillis(druidDbProperties.getTimeBetweenEvictionRunsMillis());datasource.setMinEvictableIdleTimeMillis(druidDbProperties.getMinEvictableIdleTimeMillis());datasource.setValidationQuery(druidDbProperties.getValidationQuery());datasource.setTestWhileIdle(druidDbProperties.isTestWhileIdle());datasource.setTestOnBorrow(druidDbProperties.isTestOnBorrow());datasource.setTestOnReturn(druidDbProperties.isTestOnReturn());try {datasource.setFilters(druidDbProperties.getFilters());} catch (SQLException e) {logger.error("druid configuration initialization filter", e);}datasource.setConnectionProperties(druidDbProperties.getConnectionProperties());return datasource;}/*** 加載默認(rèn)mybatis xml配置文件,并初始化分頁插件** @param dataSource* @return* @throws Exception*/public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {return createSqlSessionFactory(dataSource, "classpath:mybatis/**/*.xml");}/*** 加載mybatis xml配置文件,并初始化分頁插件** @param dataSource 數(shù)據(jù)源* @param mapperLocations 自定義xml配置路徑* @return* @throws Exception*/public SqlSessionFactory sqlSessionFactory(DataSource dataSource, String mapperLocations) throws Exception {return createSqlSessionFactory(dataSource, mapperLocations);}private SqlSessionFactory createSqlSessionFactory(DataSource dataSource, String mapperLocations) throws Exception {SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();sqlSessionFactoryBean.setDataSource(dataSource);// mybatis分頁PageHelper pageHelper = new PageHelper();Properties props = new Properties();props.setProperty("dialect", "mysql");props.setProperty("reasonable", "true");props.setProperty("supportMethodsArguments", "true");props.setProperty("returnPageInfo", "check");props.setProperty("params", "count=countSql");pageHelper.setProperties(props); // 添加插件sqlSessionFactoryBean.setPlugins(new Interceptor[]{pageHelper});PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();sqlSessionFactoryBean.setMapperLocations(resolver.getResources(mapperLocations));return sqlSessionFactoryBean.getObject();} }

Druid 監(jiān)控配置

@EnableConfigurationProperties(DruidDbProperties.class) @EnableAspectJAutoProxy(proxyTargetClass = true) public class DruidMonitConfig {@Resourceprivate DruidDbProperties druidDbProperties;@Beanpublic ServletRegistrationBean druidServlet() {ServletRegistrationBean reg = new ServletRegistrationBean();reg.setServlet(new StatViewServlet());reg.addUrlMappings("/druid/*");if (!StringUtils.isEmpty(druidDbProperties.getAllow())) {reg.addInitParameter("allow", druidDbProperties.getAllow()); // 白名單}if (!StringUtils.isEmpty(druidDbProperties.getDeny())) {reg.addInitParameter("deny", druidDbProperties.getDeny()); // 黑名單}reg.addInitParameter("loginUsername", druidDbProperties.getUsername());reg.addInitParameter("loginPassword", druidDbProperties.getPassword());return reg;}@Beanpublic FilterRegistrationBean filterRegistrationBean() {FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();filterRegistrationBean.setFilter(new WebStatFilter());filterRegistrationBean.addUrlPatterns("/*");filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");return filterRegistrationBean;}/*** 監(jiān)聽Spring 1.定義攔截器 2.定義切入點 3.定義通知類** @return*/@Beanpublic DruidStatInterceptor druidStatInterceptor() {return new DruidStatInterceptor();}@Beanpublic JdkRegexpMethodPointcut druidStatPointcut() {JdkRegexpMethodPointcut druidStatPointcut = new JdkRegexpMethodPointcut();String patterns = "io.ymq.mybatis*";druidStatPointcut.setPatterns(patterns);return druidStatPointcut;}@Beanpublic Advisor druidStatAdvisor() {return new DefaultPointcutAdvisor(druidStatPointcut(), druidStatInterceptor());} }

Druid 監(jiān)控參數(shù)

@ConfigurationProperties(prefix = "druid") public class DruidDbProperties {private String driverClassName = "com.mysql.jdbc.Driver";/*** 初始化時建立物理連接的個數(shù)。初始化發(fā)生在顯示調(diào)用init方法,或者第一次getConnection時*/private int initialSize = 10;/*** 最小連接池數(shù)量*/private int minIdle = 50;/*** 最大連接池數(shù)量*/private int maxActive = 300;/*** 獲取連接時最大等待時間,單位毫秒。配置了maxWait之后,缺省啟用公平鎖,并發(fā)效率會有所下降,如果需要可以通過配置useUnfairLock屬性為true使用非公平鎖。*/private int maxWait = 60000;/*** 有兩個含義: 1)* Destroy線程會檢測連接的間隔時間,如果連接空閑時間大于等于minEvictableIdleTimeMillis則關(guān)閉物理連接。 2)* testWhileIdle的判斷依據(jù),詳細(xì)看testWhileIdle屬性的說明*/private int timeBetweenEvictionRunsMillis = 60000;/*** 連接保持空閑而不被驅(qū)逐的最長時間*/private int minEvictableIdleTimeMillis = 3600000;/*** 用來檢測連接是否有效的sql,要求是一個查詢語句,常用select* 'x'。如果validationQuery為null,testOnBorrow、testOnReturn、testWhileIdle都不會其作用。*/private String validationQuery = "SELECT USER()";/*** 建議配置為true,不影響性能,并且保證安全性。申請連接的時候檢測,如果空閑時間大于timeBetweenEvictionRunsMillis,執(zhí)行validationQuery檢測連接是否有效。*/private boolean testWhileIdle = true;/*** 申請連接時執(zhí)行validationQuery檢測連接是否有效,做了這個配置會降低性能。*/private boolean testOnBorrow = false;/*** 歸還連接時執(zhí)行validationQuery檢測連接是否有效,做了這個配置會降低性能。*/private boolean testOnReturn = false;/*** 屬性類型是字符串,通過別名的方式配置擴展插件,常用的插件有: 監(jiān)控統(tǒng)計用的filter:stat 日志用的filter:log4j* 防御sql注入的filter:wall*/private String filters = "mergeStat,config,wall";private String connectionProperties;/*** 白名單*/private String allow;/*** 黑名單*/private String deny;private String username = "admin";private String password = "admin";省略 get set }

配置數(shù)據(jù)源 one

@Configuration @EnableTransactionManagement public class DBOneConfiguration extends AbstractDruidDBConfig {@Value("${ymq.one.datasource.url}")private String url;@Value("${ymq.one.datasource.username}")private String username;@Value("${ymq.one.datasource.password}")private String password;// 注冊 datasourceOne@Bean(name = "datasourceOne", initMethod = "init", destroyMethod = "close")public DruidDataSource dataSource() {return super.createDataSource(url, username, password);}@Bean(name = "sqlSessionFactorYmqOne")public SqlSessionFactory sqlSessionFactory() throws Exception {return super.sqlSessionFactory(dataSource());}@Beanpublic PlatformTransactionManager transactionManager() throws SQLException {return new DataSourceTransactionManager(dataSource());} }

配置數(shù)據(jù)源 two

@Configuration @EnableTransactionManagement public class DBOneConfiguration extends AbstractDruidDBConfig {@Value("${ymq.one.datasource.url}")private String url;@Value("${ymq.one.datasource.username}")private String username;@Value("${ymq.one.datasource.password}")private String password;// 注冊 datasourceOne@Bean(name = "datasourceOne", initMethod = "init", destroyMethod = "close")public DruidDataSource dataSource() {return super.createDataSource(url, username, password);}@Bean(name = "sqlSessionFactorYmqOne")public SqlSessionFactory sqlSessionFactory() throws Exception {return super.sqlSessionFactory(dataSource());}@Beanpublic PlatformTransactionManager transactionManager() throws SQLException {return new DataSourceTransactionManager(dataSource());} }

BaseDao one

@Repository public class YmqOneBaseDao extends BaseDao {@Resourcepublic void setSqlSessionFactorYmqOne(SqlSessionFactory sqlSessionFactory) {super.setSqlSessionFactory(sqlSessionFactory);} }

BaseDao two

@Repository public class YmqTwoBaseDao extends BaseDao {@Resourcepublic void setSqlSessionFactorYmqTwo(SqlSessionFactory sqlSessionFactory) {super.setSqlSessionFactory(sqlSessionFactory);} }

測試 Controller

@RestController public class IndexController {private static final Logger LOG = LoggerFactory.getLogger(IndexController.class);@Autowiredprivate YmqOneBaseDao ymqOneBaseDao;@Autowiredprivate YmqTwoBaseDao ymqTwoBaseDao;@RequestMapping("/")public String index() throws Exception {List<TestOnePo> testOnePoList = null;testOnePoList = ymqOneBaseDao.selectList(new TestOnePo());for (TestOnePo item : testOnePoList) {LOG.info("數(shù)據(jù)源 ymqOneBaseDao :查詢結(jié)果:{}", JSONObject.toJSONString(item));}List<TestTwoPo> testTwoPoList = null;testTwoPoList = ymqTwoBaseDao.selectList(new TestTwoPo());for (TestTwoPo item : testTwoPoList) {LOG.info("數(shù)據(jù)源 ymqTwoBaseDao:查詢結(jié)果:{}", JSONObject.toJSONString(item));}String onePoList = JSONObject.toJSONString(testOnePoList);String twoPoList = JSONObject.toJSONString(testTwoPoList);return "數(shù)據(jù)源 ymqOneBaseDao :查詢結(jié)果:" + onePoList + "<br/> 數(shù)據(jù)源 ymqTwoBaseDao :查詢結(jié)果:" + twoPoList;} }

參數(shù)配置

application.properties

#############SERVER CONFIG############ spring.application.name=ymq-mybatis-spring-boot#數(shù)據(jù)源 one ymq.one.datasource.url=jdbc:mysql://10.4.82.6:3306/ymq_one?useUnicode=true&characterEncoding=UTF-8 ymq.one.datasource.username=root ymq.one.datasource.password=123456#數(shù)據(jù)源 two ymq.two.datasource.url=jdbc:mysql://10.4.82.6:3306/ymq_two?useUnicode=true&characterEncoding=UTF-8 ymq.two.datasource.username=root ymq.two.datasource.password=123456server.port=80 server.tomcat.max-threads=1000 server.tomcat.max-connections=2000

啟動服務(wù)

@SpringBootApplication @ComponentScan(value = {"io.ymq.mybatis"}) public class Startup {public static void main(String[] args) {SpringApplication.run(Startup.class, args);} }

在頁面上輸入 http://localhost/ 可以看到 Controller 執(zhí)行情況:

數(shù)據(jù)源 ymqOneBaseDao :查詢結(jié)果:[{"id":1,"name":"測試","remark":"這是測試 ymq_one 數(shù)據(jù)庫"}] 數(shù)據(jù)源 ymqTwoBaseDao :查詢結(jié)果:[{"id":1,"name":"測試","remark":"這是測試 ymq_two 數(shù)據(jù)庫"}]

在頁面上輸入 http://localhost/druid/ 可以看到監(jiān)控到的sql語句執(zhí)行情況:

代碼我已放到 Github ,導(dǎo)入spring-boot-mybatis 項目

github https://github.com/souyunku/spring-boot-examples/tree/master/spring-boot-mybatis

Contact

  • 作者:鵬磊
  • 出處:http://www.ymq.io
  • Email:admin@souyunku.com
  • 版權(quán)歸作者所有,轉(zhuǎn)載請注明出處
  • Wechat:關(guān)注公眾號,搜云庫,專注于開發(fā)技術(shù)的研究與知識分享

總結(jié)

以上是生活随笔為你收集整理的Spring Boot 中使用 MyBatis 整合 Druid 多数据源的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。