1. 程式人生 > >SpringBoot和Mycat動態數據源項目整合

SpringBoot和Mycat動態數據源項目整合

sco turn style 是否 mic adl iba 需要 one

SpringBoot項目整合動態數據源(讀寫分離)

1.配置多個數據源,根據業務需求訪問不同的數據,指定對應的策略:增加,刪除,修改操作訪問對應數據,查詢訪問對應數據,不同數據庫做好的數據一致性的處理。由於此方法相對易懂,簡單,不做過多介紹。
2. 動態切換數據源,根據配置的文件,業務動態切換訪問的數據庫:此方案通過Spring的AOP,AspactJ來實現動態織入,通過編程繼承實現Spring中的AbstractRoutingDataSource,來實現數據庫訪問的動態切換,不僅可以方便擴展,不影響現有程序,而且對於此功能的增刪也比較容易。
3. 通過mycat來實現讀寫分離:使用mycat提供的讀寫分離功能,mycat連接多個數據庫,數據源只需要連接mycat,對於開發人員而言他還是連接了一個數據庫(實際是mysql的mycat中間件),而且也不需要根據不同 業務來選擇不同的庫,這樣就不會有多余的代碼產生。
詳細參考配置

動態數據源核心配置
在Spring 2.0.1中引入了AbstractRoutingDataSource, 該類充當了DataSource的路由中介, 能有在運行時, 根據某種key值來動態切換到真正的DataSource上。

1.項目中需要集成多個數據源分別為讀和寫的數據源,綁定不同的key。
2.采用AOP技術進行攔截業務邏輯層方法,判斷方法的前綴是否需要寫或者讀的操作
3.如果方法的前綴是寫的操作的時候,直接切換為寫的數據源,反之切換為讀的數據源
也可以自己定義註解進行封裝

項目中有兩個數據源 分別為讀和寫的數據源

使用AOP技術判斷業務邏輯方法的前綴,如果前綴為比如select get find等。直接走RoutingDataSource

如果是寫的話,傳遞一個key給RoutingDataSource指明使用寫的數據源

下面是兩個數據源,讀的數據源和寫的數據源。都需要設置一個key。然後註冊存放到RoutingDataSource。

使用AOP技術攔截業務邏輯層的方法,判斷方法的前綴是否為讀或者寫的操作

如果是寫的操作,會給RoutingDataSource傳遞一個key 哈哈懂得了吧

技術分享圖片

環境配置:

1.創建讀和寫的數據源

2.將讀和寫的數據源註冊到RoutiongDataSource

3.使用AOP技術攔截業務邏輯層,判斷方法的前綴是否需要做讀或者寫

pom:

<parent
> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.4.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.23</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>

配置代碼:

通過ThreadLocal 保存本地多數據源

import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;

@Component
@Primary
public class DynamicDataSource extends AbstractRoutingDataSource {
    @Autowired
    @Qualifier("selectDataSource")   //獲取讀的數據源
    private DataSource selectDataSource;

    @Autowired  
    @Qualifier("updateDataSource")  //獲取寫的數據源
    private DataSource updateDataSource;

    /**
     * 這個是主要的方法,返回的是生效的數據源名稱
     */
    @Override
    protected Object determineCurrentLookupKey() {
        System.out.println("DataSourceContextHolder:::" + DataSourceContextHolder.getDbType());
        return DataSourceContextHolder.getDbType();
    }

    /**
     * 配置數據源信息   註冊數據源的操作 最終註入到datasource數據源中
     */
    @Override
    public void afterPropertiesSet() {
        Map<Object, Object> map = new HashMap<>();
        map.put("selectDataSource", selectDataSource);
        map.put("updateDataSource", updateDataSource);
        setTargetDataSources(map);
        setDefaultTargetDataSource(updateDataSource);
        super.afterPropertiesSet();
    }
}

配置多個數據源:

import javax.sql.DataSource;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/*
 * 配置多個數據源
 */

@Configuration
public 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();
    }

}

將數據源註冊到RoutingDataSource中

import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;

@Component
@Primary
public class DynamicDataSource extends AbstractRoutingDataSource {
    @Autowired
    @Qualifier("selectDataSource")   //獲取讀的數據源
    private DataSource selectDataSource;

    @Autowired  
    @Qualifier("updateDataSource")  //獲取寫的數據源
    private DataSource updateDataSource;

    /**
     * 這個是主要的方法,返回的是生效的數據源名稱
     */
    @Override
    protected Object determineCurrentLookupKey() {
        System.out.println("DataSourceContextHolder:::" + DataSourceContextHolder.getDbType());
        return DataSourceContextHolder.getDbType();
    }

    /**
     * 配置數據源信息   註冊數據源的操作 最終註入到datasource數據源中
     */
    @Override
    public void afterPropertiesSet() {
        Map<Object, Object> map = new HashMap<>();
        map.put("selectDataSource", selectDataSource);
        map.put("updateDataSource", updateDataSource);
        setTargetDataSources(map);
        setDefaultTargetDataSource(updateDataSource);
        super.afterPropertiesSet();
    }
}

然後對於AOP的編寫配置:

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.mayikt.config.DataSourceContextHolder;

@Aspect
@Component
@Lazy(false)
@Order(0) // Order設定AOP執行順序 使之在數據庫事務上先執行  動態數據源事務先執行的
public class SwitchDataSourceAOP {
    // 這裏切到你的方法目錄
    @Before("execution(* com.mayikt.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");
        }
    }
}

啟動:

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan(basePackages = "com.toov5.mapper")
public class AppMybatis {

    public static void main(String[] args) {
        SpringApplication.run(AppMybatis.class, args);
    }

}

yml:

spring:
  datasource:
    ###可讀數據源
    select:
      jdbc-url: jdbc:mysql://192.168.91.7:8066/mycat_testdb
      driver-class-name: com.mysql.jdbc.Driver
      username: user
      password: user
    ####可寫數據源  
    update:
      jdbc-url: jdbc:mysql://192.168.91.7:8066/mycat_testdb
      driver-class-name: com.mysql.jdbc.Driver
      username: root
      password: 123456
    type: com.alibaba.druid.pool.DruidDataSource

註意數據源的配置:是MyCat的域名和端口

Controller:

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.mayikt.entity.UserEntity;
import com.mayikt.service.UserService;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/findUser")
    public List<UserEntity> findUser() {
        return userService.findUser();
    }

    @RequestMapping("/insertUser")
    public List<UserEntity> insertUser(String userName) {
        return userService.insertUser(userName);
    }

}

entity:

public class UserEntity {

    private String userName;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

}

service:

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mayikt.entity.UserEntity;
import com.mayikt.mapper.UserMapper;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public List<UserEntity> findUser() {
        return userMapper.findUser();
    }

    public List<UserEntity> insertUser(String userName) {
        return userMapper.insertUser(userName);
    }

}

mapper:

import java.util.List;

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import com.mayikt.entity.UserEntity;

public interface UserMapper {
    @Select("SELECT * FROM  user_info ")
    public List<UserEntity> findUser();

    @Select("insert into user_info values (null,#{userName}); ")
    public List<UserEntity> insertUser(@Param("userName") String userName);
}

SpringBoot和Mycat動態數據源項目整合