Spring boot (quad) multiple data sources

Source: Internet
Author: User

Objective

In the previous article we created a single data source using spring Boot+mybatis, where a single data source does not need to be created by ourselves, and spring boot autoconfiguration creates a good data source for us when the program starts.

Preparatory work

Configuring the 4 properties of connection in APPLICATION.YML

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

  

Multi-Data Source creation method

1, multi-data source is the main need we manually to create DataSource, Sqlsessionfactory, Sqlsessiontemplate. Here we create a read-write detached data source based on the same library. The return values for both methods are javax.sql.DataSource.

@Configurationpublic 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, read and write separation of the configuration class. That is, the sqlsessionfactory and Sqlsessiontemplate are created separately.

 @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 Sqlsessionfactory        Bean=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=ne        W sqlsessiontemplate (Readsqlsessionfactory ());    return sqlsessiontemplate; }}

 @Configuration @mapperscan (basepackages = {"Com.zhangfei.dao.write"}, Sqlsessionfactoryref = "Writesqlsessionfactory") public class Mybatisdbbconfig {@Autowired @Qualifier ("Writedatasour    Ce ") private DataSource DataSource; @Bean public Sqlsessionfactory writesqlsessionfactory () throws exception{Sqlsessionfactorybean Sqlsessionfactor        Ybean=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=n        EW Sqlsessiontemplate (Writesqlsessionfactory ());    return sqlsessiontemplate; }}

3. The DAO interface under Read package

Public interface Studentreaddao {    list<student> getstudentlist ();    Student getById (long id);}

4. DAO interface under Wite package

Public interface Studentwritedao {    int delete (long id);    int Insert (Student Student);    int update (Student Student);}

5. Create a read-write mapper file respectively. I created it locally: 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. The above sections have been prepared for the separation of reads and writes, which can then be invoked in the controller. When the preparation is complete, it is important to exclude the data source provided by the Springboot automatic property at the entrance of the program @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 ();}    }

  

Summarize

Well, it's almost 3 minutes away. Springboot+mybatis Multi-data source or read-write separation work. So I don't know what you're not asking us. What are the specific types of datasource that we create manually? Here we only write the Javax.sql.DataSource interface here. My local use is Springboot 2.0.2, the current Datasourcebuilder only supports 3 types of data sources: Com.zaxxer.hikari.HikariDataSource, Org.apache.tomcat.jdbc.pool.DataSource, Org.apache.commons.dbcp2.BasicDataSource. You can see the relevant code in the Datasourcebuilder class. So now this is the case because we're referencing inline tomcat, so the type of data source we're returning here is Org.apache.tomcat.jdbc.pool.DataSource. You can use instanceof to verify the specific data source type.

Spring boot (quad) multiple data sources

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.