springboot2.0.3: Read and write separations, using AOP to dynamically switch data sources based on method names.

Source: Internet
Author: User

Springboot version: 2.0.3!!! Springboot version: 2.0.3!!! Springboot version: 2.0.3!!!

The environment I set up is: Springboot 2.0.3+mybatis

Approximate process:
Execute SQL before method execution, toggle data source

    • Cancel Single data source default configuration
@SpringBootApplication(exclude = {        DataSourceAutoConfiguration.class})public class PalletDemoApplication {    public static void main(String[] args) {        SpringApplication.run(PalletDemoApplication.class, args);    }}
    • Cut
@Aspect@Component@Lazy(false)@Order(0) //Order设定AOP执行顺序 使之在数据库事务上先执行public class SwitchDataSourceAOP {    //这里切到你的方法目录    @Before("execution(* com.zed.palletdemo.service.*.*(..))")    public void process(JoinPoint joinPoint) {        String methodName=joinPoint.getSignature().getName();        if (methodName.startsWith("get")                ||methodName.startsWith("count")                ||methodName.startsWith("find")                ||methodName.startsWith("list")                ||methodName.startsWith("select")                ||methodName.startsWith("check")){            DataSourceContextHolder.setDbType("selectDataSource");        }else {            //切换dataSource            DataSourceContextHolder.setDbType("updateDataSource");        }    }}
    • It uses a class: Datasourcecontextholder see how he wrote it.
@Component@Lazy(false)public class DataSourceContextHolder {    private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();    public static void setDbType(String dbType) {        contextHolder.set(dbType);    }    public static String getDbType() {        return contextHolder.get();    }    public static void clearDbType() {        contextHolder.remove();    }}
    • Configure two data source beans, one switch
@Configurationpublic class DataSourceConfig {    @Bean(name = "selectDataSource")    @ConfigurationProperties(prefix = "spring.datasource.select") // application.properteis中对应属性的前缀    public DataSource dataSource1() {        return DataSourceBuilder.create().build();    }        @Bean(name = "updateDataSource")    @ConfigurationProperties(prefix = "spring.datasource.update") // application.properteis中对应属性的前缀    public DataSource dataSource2() {        return DataSourceBuilder.create().build();    }}
    • Cut the main switch data source name, here formally effective
  @Component @primary//do not know what to use, without error public class Dynamicdatasource extends Abstractroutingdatasource {@    Autowired @Qualifier ("Selectdatasource") private DataSource Selectdatasource;    @Autowired @Qualifier ("Updatedatasource") private DataSource Updatedatasource; /** * This is the primary method that returns the data source name that is valid */@Override protected Object Determinecurrentlookupkey () {SYSTEM.OUT.PR        Intln ("Datasourcecontextholder:::" +datasourcecontextholder.getdbtype ());    return Datasourcecontextholder.getdbtype (); }/** * Always report what you do not specify the target set here, the default data source is Updatedatasource */@Override public void Afterpropertiesset ()        {map<object,object> Map = new hashmap<> ();        Map.put ("Selectdatasource", Selectdatasource);        Map.put ("Updatedatasource", Updatedatasource);        Settargetdatasources (map);        Setdefaulttargetdatasource (Updatedatasource);    Super.afterpropertiesset (); }}
    • Then the service layer method to notice the name, you can dynamically switch.
    • I'm with two data sources.
spring:  datasource:    select:      jdbc-url: jdbc:mysql://127.0.0.1:3306/test1      driver-class-name: com.mysql.jdbc.Driver      username: root      password: 123456    update:      jdbc-url: jdbc:mysql://127.0.0.1:3306/test2      driver-class-name: com.mysql.jdbc.Driver      username: root      password: 123456    type: com.alibaba.druid.pool.DruidDataSource
Problem
    • After always reported what can not find Jdbcurl, Online said springboot1.5 later changed, pit dad
      https://my.oschina.net/chinesedragon/blog/1647846

springboot2.0.3: Read and write separations, using AOP to dynamically switch data sources based on method names.

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.