澳门新萄京官方网站-www.8455.com-澳门新萄京赌场网址

澳门新萄京官方网站数据源切换时报错,多数据

2019-11-16 作者:数据库网络   |   浏览(153)

在进行数据源切换时spring.datasource.type类型依照源码所给的私下认可值改正后依然报错

springboot整合篇

前言

        前风流倜傥篇中大家采用spring boot mybatis创制了纯粹数据源,个中单纯数据源不供给大家团结手动创造,spring boot自动配置在前后相继运行时会替大家创立好数据源。

(1卡塔 尔(英语:State of Qatar)在pom.xml中增加正视包;

  • 先看源码:标色部分 ,  正是springboot所给的数据源 ,  符合规律的话只要在安排文件中改善type值就能够  ,然则本人开掘那多少个依旧报错

    @ConditionalOnClass(org.apache.tomcat.jdbc.pool.DataSource.class)

    @ConditionalOnProperty(name = "spring.datasource.type", havingValue = "org.apache.tomcat.jdbc.pool.DataSource", matchIfMissing = true)
    static class Tomcat extends DataSourceConfiguration {
    
        @Bean
        @ConfigurationProperties(prefix = "spring.datasource.tomcat")
        public org.apache.tomcat.jdbc.pool.DataSource dataSource(
                DataSourceProperties properties) {
            org.apache.tomcat.jdbc.pool.DataSource dataSource = createDataSource(
                    properties, org.apache.tomcat.jdbc.pool.DataSource.class);
            DatabaseDriver databaseDriver = DatabaseDriver
                    .fromJdbcUrl(properties.determineUrl());
            String validationQuery = databaseDriver.getValidationQuery();
            if (validationQuery != null) {
                dataSource.setTestOnBorrow(true);
                dataSource.setValidationQuery(validationQuery);
            }
            return dataSource;
        }
    
    }
    
    /**
     * Hikari DataSource configuration.
     */
    @ConditionalOnClass(HikariDataSource.class)
    @ConditionalOnProperty(name = "spring.datasource.type", havingValue = "com.zaxxer.hikari.HikariDataSource", matchIfMissing = true)
    static class Hikari extends DataSourceConfiguration {
    
        @Bean
        @ConfigurationProperties(prefix = "spring.datasource.hikari")
        public HikariDataSource dataSource(DataSourceProperties properties) {
            HikariDataSource dataSource = createDataSource(properties,
                    HikariDataSource.class);
            if (StringUtils.hasText(properties.getName())) {
                dataSource.setPoolName(properties.getName());
            }
            return dataSource;
        }
    
    }
    
    /**
     * DBCP DataSource configuration.
     */
    @ConditionalOnClass(org.apache.commons.dbcp2.BasicDataSource.class)
    @ConditionalOnProperty(name = "spring.datasource.type", havingValue = "org.apache.commons.dbcp2.BasicDataSource", matchIfMissing = true)
    static class Dbcp2 extends DataSourceConfiguration {
    
        @Bean
        @ConfigurationProperties(prefix = "spring.datasource.dbcp2")
        public org.apache.commons.dbcp2.BasicDataSource dataSource(
                DataSourceProperties properties) {
            return createDataSource(properties,
                    org.apache.commons.dbcp2.BasicDataSource.class);
        }
    
    }
    
  • 错误新闻:澳门新萄京官方网站数据源切换时报错,多数据源搭建。其大器晚成错好五人付出的答案是让编辑器自动提醒  而不协调写 就不会冒出(鲜明十三分的卡塔 尔(英语:State of Qatar),value值是springboot源码上自带的,因此也不会错,可是为何会报错呢?

    Description:

    Failed to bind properties under 'spring.datasource.type' to java.lang.Class:

    Property: spring.datasource.type
    Value: org.apache.commons.dbcp2.BasicDataSource
    Origin: class path resource [application.yml]:7:11
    Reason: No converter found capable of converting from type [java.lang.String] to type [java.lang.Class<javax.sql.DataSource>]
    

    Action:

    Update your application's configuration

  • 原因:

前言

预备干活

       application.yml中配置connection的4个属性

spring:
  datasource:
    read:
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://192.168.80.129:3306/test
      username: root
      password: 123456
    write:
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://192.168.80.129:3306/test
      username: root
      password: 123456

  

(2卡塔 尔(英语:State of Qatar)编写运营类App.java那Ritter别要小心@Import({DynamicDataSourceRegister.class}卡塔尔不然运行不了会报找找不到数据源,这里注意一下这些DynamicDataSourceRegister须求本人到自己源码找配置文件,把具备配置文件复制一下就行啊,其余不用改。

在导入druid数据源时,也便是表面数据源,大家必须要导入相关信任,因而笔者尝试将springboot默许数据源的连带重视也导入

对于数据访问层,无论是Sql依然NoSql,SpringBoot私下认可使用整合SpringData的格局展开联合保管,增多大量的电动配置,屏蔽了成千上万装置。引进了种种XxxTemplate和XxxRepository来简化我们队数据访谈层的操作。

相当多据源创制方法

      1、许多据源首借使内需我们手动来创立DataSource、SqlSessionFactory、SqlSessionTemplate。这里我们根据同二个库来创制读写分离的数据源。这里多个措施的重返值都是javax.sql.DataSource。

   

@Configuration
public class DataSourceConfig {


    @Primary
    @Bean(name="readDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.read")
    public DataSource readDataSource(){
        return DataSourceBuilder.create().build();
    }



    @Bean(name="writeDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.write")
    public DataSource writeDataSource(){
        return DataSourceBuilder.create().build();
    }


}

 2、读写分离的配置类。也正是独家创制读写的SqlSessionFactory和SqlSessionTemplate

@Configuration
@MapperScan(basePackages = {"com.zhangfei.dao.read"},sqlSessionFactoryRef = "readSqlSessionFactory")
public class MyBatisDbAConfig {

    @Autowired
    @Qualifier("readDataSource")
    private DataSource dataSource;


    @Bean
    public SqlSessionFactory readSqlSessionFactory() throws Exception{
        SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resource=resolver.getResources("classpath:mybatis/read/*.xml");
        sqlSessionFactoryBean.setMapperLocations(resource);

        return sqlSessionFactoryBean.getObject();
    }

    @Bean
    public SqlSessionTemplate readSqlSession() throws Exception{
        SqlSessionTemplate sqlSessionTemplate=new SqlSessionTemplate(readSqlSessionFactory());

        return sqlSessionTemplate;
    }
}

  

@Configuration
@MapperScan(basePackages = {"com.zhangfei.dao.write"},sqlSessionFactoryRef = "writeSqlSessionFactory")
public class MyBatisDbBConfig {

    @Autowired
    @Qualifier("writeDataSource")
    private DataSource dataSource;


    @Bean
    public SqlSessionFactory writeSqlSessionFactory() throws Exception{
        SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resource=resolver.getResources("classpath:mybatis/write/*.xml");
        sqlSessionFactoryBean.setMapperLocations(resource);

        return sqlSessionFactoryBean.getObject();
    }

    @Bean
    public SqlSessionTemplate writeSqlSession() throws Exception{
        SqlSessionTemplate sqlSessionTemplate=new SqlSessionTemplate(writeSqlSessionFactory());

        return sqlSessionTemplate;
    }

}

澳门新萄京官方网站,  3、read包下的dao接口

public interface StudentReadDao {

    List<Student> getStudentList();

    Student getById(long id);

}

 4、wite包下的dao接口

public interface StudentWriteDao {

    int delete(long id);

    int insert(Student student);

    int update(Student student);


}

 5、分别创制读写的mapper文件。我本地分别创立了:resources/mybatis/read/studentdao.xml、/resources/mybatis/write/studentdao.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhangfei.dao.read.StudentReadDao">
    <select id="getStudentList" resultType="com.zhangfei.entity.Student">
        select * from student;
    </select>

    <select id="getById" resultType="com.zhangfei.entity.Student">
        select * from student where id=#{id};
    </select>


</mapper>

  

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhangfei.dao.write.StudentWriteDao">

    <insert id="insert" parameterType="com.zhangfei.entity.Student">
        insert into student (name,age) values (#{name},#{age})
    </insert>

    <update id="update" parameterType="com.zhangfei.entity.Student">
        update student set name=#{name},age=#{age} where id=#{id}
    </update>

    <delete id="delete" parameterType="long">
        delete from student where id=#{id}
    </delete>
</mapper>

  OK。以上几部就消除了读写剥离的备选专门的学问,接着就足以在controller里调用了。 构思干活到位后,还也许有主要的一些正是急需在程序入口处消除springboot自动属性提供的数码源  @SpringBootApplication(exclude = DataSourceAutoConfiguration.class)

 

@RestController
@RequestMapping("/student")
public class StudentController {


    @Autowired
    StudentReadDao studentDao;

    @GetMapping("/getbyid/{id}/")
    public Student getById(@PathVariable("id")long id){

        Student student=studentDao.getById(id);
        return student;
    }


    @GetMapping("/all/")
    public List<Student> getAll(){
        return studentDao.getStudentList();
    }


}

  

 

(3卡塔尔编写配置文件application.properties;

  • 引入(maven):

    org.apache.commons commons-dbcp2 2.2.0

springboot2.0默许是用com.zaxxer.hikari.HikariDataSource作为数据源。

总结

       好了,基本上又是3分钟就消除了SpringBoot MyBatis大多据源也许叫做读写分离的行事。那么不领悟您又未有反问大家手动创造的DataSource具体项目是何许吗? 这里大家在这里地只写了javax.sql.DataSource接口。 笔者本地用的是springboot 2.0.2 ,当前 DataSourceBuilder 只辅助3种档期的顺序的数据源: com.zaxxer.hikari.HikariDataSource、org.apache.tomcat.jdbc.pool.DataSource、org.apache.commons.dbcp2.BasicDataSource。能够在DataSourceBuilder类中来六柱预测关代码。那么未来这种场地因为大家援用的内嵌tomcat,所以大家这里重临的多少源类型是org.apache.tomcat.jdbc.pool.DataSource。 能够用instanceof验证一下切实可行的多寡源类型。

 

(4卡塔尔国测量检验类测量检验钦命数据源;(这里自个儿节约了广大布局文件,会留下源码卡塔 尔(英语:State of Qatar)

 

2.0以下暗许使用的是org.apache.tomcat.jdbc.pool.DataSource作为数据源。

(5卡塔尔国访谈页面

  • 结果:看调节台出口---nice(解决)

Hikari的官网:

                         

澳门新萄京官方网站 1

Hikari号称JAVA领域中最快的多寡连接池,你可去点总是进去看看,第后生可畏行正是他本身多么厉害,秒杀什么什么的,但是再快笔者也认为未有Alibaba贡献给apache的Druid好,因为Alibaba的服务全面,里面有监察和控制中心,能够帮助大家迅速牢固慢sql等。

(1卡塔尔国在pom.xml中增添信赖包;

澳门新萄京官方网站 2

 

Druid官方网站:

(2)启动类

importcom.neil.config.DynamicDataSourceRegister;

importorg.springframework.boot.SpringApplication;

importorg.springframework.boot.autoconfigure.SpringBootApplication;

importorg.springframework.context.annotation.Import;

/ **

*

* @ authorAngel(QQ:412887952)

*@versionv.0.1

* /

@SpringBootApplication

//注册动态许多据源

@Import({DynamicDataSourceRegister.class})

public classApp {

public static voidmain(String[] args) {

SpringApplication.run(App.class,args);

}

}

  • 再有正是springboot2.0.2.RELEASE版本暗许的数据源而不是org.apache.tomcat.jdbc.pool.DataSource,而是:com.zaxxer.hikari.HikariDataSource

怎么HikariCP被可以称作为品质最佳的Java数据库连接池,怎么样安插利用参照他事他说加以考查那篇博客:点击

(3卡塔尔国编写配置文件application.properties;

########################################################

###安插文件包含1个主数据源和七个数据源,

###当中主数据源在Spring中的beanName默以为dataSource,

###除此以外多少个数据源的beanName分包为:ds1、ds2、ab

###个中datasource的type属性能够切切实实钦赐到大家必要的数据源上面,

###不钦命情状下默感觉:org.apache.tomcat.jdbc.pool.DataSource

###理所必然你也得以把这么些数据源配置到主dataSource数据库中,然后读取数据库生成好些个据源。当然如此做的供给性并相当的小,难不成数据源还只怕会平常变吗。

########################################################

# 主数据源,暗许的

#spring.datasource.type=com.zaxxer.hikari.HikariDataSource

spring.datasource.driverClassName=com.mysql.jdbc.Driver

spring.datasource.url=jdbc:mysql://localhost:3306/test

spring.datasource.username=root

spring.datasource.password=1234

# 越来越多数据源

custom.datasource.names=ds1,ds2,ab

#custom.datasource.ds1.type=com.zaxxer.hikari.HikariDataSource

custom.datasource.ds1.driverClassName=com.mysql.jdbc.Driver

custom.datasource.ds1.url=jdbc:mysql://localhost:3306/test1

custom.datasource.ds1.username=root

custom.datasource.ds1.password=1234

#custom.datasource.ds2.type=com.zaxxer.hikari.HikariDataSource

custom.datasource.ds2.driverClassName=com.mysql.jdbc.Driver

custom.datasource.ds2.url=jdbc:mysql://localhost:3306/test

custom.datasource.ds2.username=root

custom.datasource.ds2.password=1234

#custom.datasource.ab.type=com.zaxxer.hikari.HikariDataSource

custom.datasource.ab.driverClassName=com.mysql.jdbc.Driver

custom.datasource.ab.url=jdbc:mysql://localhost:3306/test3

custom.datasource.ab.username=root

custom.datasource.ab.password=1234

# 上面为连接池的添补设置,应用到上边装有数据源中

spring.datasource.maximum-pool-size=100

spring.datasource.max-idle=10

spring.datasource.max-wait=10000

spring.datasource.min-idle=5

spring.datasource.initial-size=5

spring.datasource.validation-query=SELECT 1

spring.datasource.test-on-borrow=false

spring.datasource.test-while-idle=true

spring.datasource.time-between-eviction-runs-millis=18800

########################################################

### Java Persistence Api

########################################################

# Specify the DBMS

spring.jpa.database=MYSQL

# Show or not log for each sql query

spring.jpa.show-sql=true

# Hibernate ddl auto (create, create-drop, update)

spring.jpa.hibernate.ddl-auto=update

# Naming strategy

#[org.hibernate.cfg.ImprovedNamingStrategy  #org.hibernate.cfg.DefaultNamingStrategy]

spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.DefaultNamingStrategy

# stripped before adding them to the entity manager)

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

为此除了com.zaxxer.hikari.HikariDataSource不用额外引进信任,其余的数据源都要引入注重

注意事项:暗许意况下行使com.zaxxer.hikari.HikariDataSource获取数据源时会抛出三个非常。说时区不对,须要大家校正mysql的时区:

(4卡塔 尔(阿拉伯语:قطر‎测验类测量试验钦赐数据源,我这里剩了重重配备文件,笔者会留下源码;

澳门新萄京官方网站 3

  • http://mvnrepository.com:在这里个网站中输入要引入的重视,粘贴到pom中就ok了

SHOWVARIABLESLIKE'%time_zone%'SETGLOBALtime_zone=" 8:00"

(5卡塔 尔(英语:State of Qatar)测量试验运维并测量检验结果

澳门新萄京官方网站 4

那边极其提示:多数据源是不曾工作的       

数码源A和B都开展了扩张或删除

 A假诺出错,B是不会回滚的

 反过来也相符

 同贰个数目源有事务

使用Druid数据源

源码链接能够一向测量试验然而这里没提供数据库本身创设二个,

Apache Druid(Incubating卡塔 尔(阿拉伯语:قطر‎ - 面向列的布满式数据存储,特别相符为人机联作式应用程序提供重力

个中就五个属性 id 和name就能够 :

尽管HikariDataSource性能相当的高,可是Ali的druid数据源配有一切的数据源管理软件,开拓中运用的更加的多。

昔日大家都以向来引入Druid的信赖:

com.alibabadruid1.1.12

但是面前境遇那样刚烈的springboot并未直接对Druid的运维器而是供给大家和衷共济组合,apache中7个月前早就出了风度翩翩套康健扶助springboot的方案所以说咱俩不选用方面包车型大巴依据而是使用:

源码下载:

com.alibabadruid-spring-boot-starter1.1.10

配置YML文件,具体的参数配置能够去官方网址看看:

spring: datasource:# 数据源基本配备 username:root password:root driver-class-name:com.mysql.jdbc.Driver url:jdbc:mysql://localhost:3306/duid type:com.alibaba.druid.pool.DruidDataSource# 数据源其余安排initialSize:5 minIdle:5 maxActive:20 maxWait:60000 timeBetweenEvictionRunsMillis:60000 minEvictableIdleTimeMillis:300000 validationQuery:SELECT1FROMDUAL testWhileIdle:true testOnBorrow:false testOnReturn:false poolPreparedStatements:true# 配置监察和控制总括拦截的filters,去掉后监督分界面sql不能总结,'wall'用于防火墙 filters:stat,wall maxPoolPreparedStatementPerConnectionSize:20 useGlobalDataSourceStat:true connectionProperties:druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

纵然如此大家布置了druid连接池的其他性质,可是不会卓有效能。因为暗许是采纳的java.sql.Datasource的类来赢得属性的,有个别属性datasource未有。借使大家想让配置生效,须求手动成立Druid的安顿文件。

@ConfigurationProperties(prefix ="spring.datasource")@BeanpublicDruidDataSourcedruidDataSource(){returnnewDruidDataSource();}

Druid的最强盛之处在于它有着强大的监控,能够监察和控制大家发送到数据库的富有sql语句。方便大家前期排插错误。

我们随后在DruidDataSource里面配备监察和控制中央:

/** * 配置监察和控制服务器 *@return重回监控注册的servlet对象 *@authorSimpleWu */@BeanpublicServletRegistrationBeanstatViewServlet(){ ServletRegistrationBean servletRegistrationBean =newServletRegistrationBean(newStatViewServlet(),"/druid/*");// 增多IP白名单servletRegistrationBean.addInitParameter("allow","127.0.0.1");// 增加IP黑名单,当白名单和黑名单重复时,黑名单优先级更加高servletRegistrationBean.addInitParameter("deny","127.0.0.1");// 增加调控台管理客户servletRegistrationBean.addInitParameter("loginUsername","SimpleWu"); servletRegistrationBean.addInitParameter("loginPassword","123456");// 是还是不是能够重新复苏设置数据servletRegistrationBean.addInitParameter("resetEnable","false");returnservletRegistrationBean; }/** * 配置服务过滤器 * *@return重回过滤器配置对象 */@BeanpublicFilterRegistrationBeanstatFilter(){ FilterRegistrationBean filterRegistrationBean =newFilterRegistrationBean(newWebStatFilter;// 增加过滤法则filterRegistrationBean.addUrlPatterns;// 忽视过滤格式filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*,");returnfilterRegistrationBean; }

配置完后大家运营springboot程序访谈:

就能够过来大家的记名页面面便是大家地方增添的调整台管理客商,大家能够在地点很好的观望运维意况,图片就不贴了截图挺麻烦的。

多谢您的读书,假如您认为阅读本文对你有援助,请点一下“推荐”按键。本文招待各位转发,不过转载作品以往总得在篇章页面中付出小编和原作连接

学学是学则不固的。

本文由澳门新萄京官方网站发布于数据库网络,转载请注明出处:澳门新萄京官方网站数据源切换时报错,多数据

关键词: