SpringBoot Mybatis 读写分离配置

为什么需要读写分离

当项目越来越大和并发越来大的情况下,单个数据库服务器的压力肯定也是越来越大,最终演变成数据库成为性能的瓶颈,而且当数据越来越多时,查询也更加耗费时间,当然数据库数据过大时,可以采用数据库分库分表,同时数据库压力过大时,也可以采用Redis等缓存技术来降低压力,但是任何一种技术都不是万金油,很多时候都是通过多种技术搭配使用,而本文主要就是介绍通过读写分离来加快数据库读取速度

实现方式

读写分离实现的方式有多种,但是多种都需要配置数据库的主从复制,当然也许是有不需要配置的,只是我不知道而已

方式一

数据库中间件实现,如Mycat等数据库中间件,对于项目本身来说,只有一个数据源,就是链接到Mycat,再由mycat根据规则去选择从哪个库获取数据

方式二

代码中配置多数据源,通过代码控制使用哪个数据源,本文也是主要介绍这种方式

读写分离优劣

优点

1.降低数据库读取压力,尤其是有些需要大量计算的实时报表类应用
2.增强数据安全性,读写分离有个好处就是数据近乎实时备份,一旦某台服务器硬盘发生了损坏,从库的数据可以无限接近主库
3.可以实现高可用,当然只是配置了读写分离并不能实现搞可用,最多就是在Master(主库)宕机了还能进行查询操作,具体高可用还需要其他操作

缺点

1.增大成本,一台数据库服务器和多台数据库的成本肯定是不一样的
2.增大代码复杂度,不过这点还比较轻微吧,但是也的确会一定程度上加重
3.增大写入成本,虽然降低了读取成本,但是写入成本却是一点也没有降低,毕竟还有从库一直在向主库请求数据

MySQL主从复制配置

MySQL主从配置是实现读写分离的基本条件,具体实现MySQL主从复制可以参考我之前的文章MySQL主从复制搭建,基于日志(binlog)

数据源配置

spring:
  application:
    name: separate
  master:
    url: jdbc:mysql://192.168.1.126:3307/test?useUnicode=true&characterEncoding=utf8&emptyStringsConvertToZero=true
    username: root
    password: 123456
    driver_class_namel: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

    max-active: 20
    initial-size: 1
    min-idle: 3
    max-wait: 600
    time-between-eviction-runs-millis: 60000
    min-evictable-idle-time-millis: 300000
    test-while-idle: true
    test-on-borrow: false
    test-on-return: false
    poolPreparedStatements: true
  slave:
    url: jdbc:mysql://192.168.1.126:3309/test?useUnicode=true&characterEncoding=utf8&emptyStringsConvertToZero=true
    username: test
    password: 123456
    driver_class_namel: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

    max-active: 20
    initial-size: 1
    min-idle: 3
    max-wait: 600
    time-between-eviction-runs-millis: 60000
    min-evictable-idle-time-millis: 300000
    test-while-idle: true
    test-on-borrow: false
    test-on-return: false
    poolPreparedStatements: true

文件中配置了2个数据源,master是写库,slave是读库,为了防止向slave写入,slave的用户只有读取权限
因为代码中需要动态的设置数据源,所以数据源需要通过继承AbstractRoutingDataSource


/**
 * 动态数据源
 * @author Raye
 * @since 2016年10月25日15:20:40
 */
public class DynamicDataSource extends AbstractRoutingDataSource {
    private static final ThreadLocal<DatabaseType> contextHolder = new ThreadLocal<DatabaseType>();

    @Override
    protected Object determineCurrentLookupKey() {
        return contextHolder.get();
    }

    public static enum DatabaseType {
        Master, Slave
    }

    public static void master(){
        contextHolder.set(DatabaseType.Master);
    }


    public static void slave(){
        contextHolder.set(DatabaseType.Slave);
    }

    public static void setDatabaseType(DatabaseType type) {
        contextHolder.set(type);
    }

    public static DatabaseType getType(){
        return contextHolder.get();
    }
}

contextHolder 是线程变量,因为每个请求是一个线程,所以通过这样来区分使用哪个库
determineCurrentLookupKey是重写的AbstractRoutingDataSource的方法,主要是确定当前应该使用哪个数据源的key,因为AbstractRoutingDataSource 中保存的多个数据源是通过Map的方式保存的

实例化数据源
/**
 * Druid的DataResource配置类
 * @author Raye
 * @since 2016年10月7日14:14:18
 */
@Configuration
@EnableTransactionManagement
public class DataBaseConfiguration  implements EnvironmentAware {

    private RelaxedPropertyResolver propertyResolver1;
    private RelaxedPropertyResolver propertyResolver2;

    public DataBaseConfiguration(){
        System.out.println("####################  DataBaseConfiguration");
    }
    public void setEnvironment(Environment env) {
        this.propertyResolver1 = new RelaxedPropertyResolver(env, "spring.master.");
        this.propertyResolver2 = new RelaxedPropertyResolver(env, "spring.slave.");
    }

    public DataSource master() {
        System.out.println("注入Master druid!!!");
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(propertyResolver1.getProperty("url"));
        datasource.setDriverClassName(propertyResolver1.getProperty("driver-class-name"));
        datasource.setUsername(propertyResolver1.getProperty("username"));
        datasource.setPassword(propertyResolver1.getProperty("password"));
        datasource.setInitialSize(Integer.valueOf(propertyResolver1.getProperty("initial-size")));
        datasource.setMinIdle(Integer.valueOf(propertyResolver1.getProperty("min-idle")));
        datasource.setMaxWait(Long.valueOf(propertyResolver1.getProperty("max-wait")));
        datasource.setMaxActive(Integer.valueOf(propertyResolver1.getProperty("max-active")));
        datasource.setMinEvictableIdleTimeMillis(Long.valueOf(propertyResolver1.getProperty("min-evictable-idle-time-millis")));
        try {
            datasource.setFilters("stat,wall");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return datasource;
    }

    public DataSource slave() {
        System.out.println("Slave druid!!!");
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(propertyResolver2.getProperty("url"));
        datasource.setDriverClassName(propertyResolver2.getProperty("driver-class-name"));
        datasource.setUsername(propertyResolver2.getProperty("username"));
        datasource.setPassword(propertyResolver2.getProperty("password"));
        datasource.setInitialSize(Integer.valueOf(propertyResolver2.getProperty("initial-size")));
        datasource.setMinIdle(Integer.valueOf(propertyResolver2.getProperty("min-idle")));
        datasource.setMaxWait(Long.valueOf(propertyResolver2.getProperty("max-wait")));
        datasource.setMaxActive(Integer.valueOf(propertyResolver2.getProperty("max-active")));
        datasource.setMinEvictableIdleTimeMillis(Long.valueOf(propertyResolver2.getProperty("min-evictable-idle-time-millis")));
        try {
            datasource.setFilters("stat,wall");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return datasource;
    }
    
    @Bean
    public DynamicDataSource dynamicDataSource() {
        DataSource master = master();
        DataSource slave = slave();
        Map<Object, Object> targetDataSources = new HashMap<Object, Object>();
        targetDataSources.put(DynamicDataSource.DatabaseType.Master, master);
        targetDataSources.put(DynamicDataSource.DatabaseType.Slave, slave);

        DynamicDataSource dataSource = new DynamicDataSource();
        dataSource.setTargetDataSources(targetDataSources);// 该方法是AbstractRoutingDataSource的方法
        dataSource.setDefaultTargetDataSource(master);
        return dataSource;
    }


}

一共有3个数据源,一个master,一个slave,一个是动态数据源,保存在master和slave,为了防止spring注入异常,所以master和slave都是主动实例化的,并不是交给spring管理

dataSource.setDefaultTargetDataSource(master);

是配置的如果没有配置当前使用哪个数据源的默认数据源,本来是打算配置slave,但是因为事物问题,所以配置的master

Mybatis配置
/**
 * MyBatis的配置类
 * 
 * @author Raye
 * @since 2016年10月7日14:13:39
 */
@Configuration
@AutoConfigureAfter({ DataBaseConfiguration.class })
@Slf4j
public class MybatisConfiguration {

    @Bean(name = "sqlSessionFactory")
    @Autowired
    public SqlSessionFactory sqlSessionFactory(DynamicDataSource dynamicDataSource) {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dynamicDataSource);
        try {

            SqlSessionFactory session = bean.getObject();
            MapperHelper mapperHelper = new MapperHelper();
            //特殊配置

            Config config = new Config();
            //具体支持的参数看后面的文档

            config.setNotEmpty(true);
            //设置配置

            mapperHelper.setConfig(config);
            // 注册自己项目中使用的通用Mapper接口,这里没有默认值,必须手动注册

            mapperHelper.registerMapper(Mapper.class);
            //配置完成后,执行下面的操作

            mapperHelper.processConfiguration(session.getConfiguration());
            return session;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Bean(name = "sqlSessionTemplate")
    @Autowired
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean
    public MapperScannerConfigurer scannerConfigurer(){
        MapperScannerConfigurer configurer = new MapperScannerConfigurer();
        configurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        configurer.setSqlSessionTemplateBeanName("sqlSessionTemplate");
        configurer.setBasePackage("wang.raye.**.mapper");
        configurer.setMarkerInterface(Mapper.class);
        return configurer;
    }
}

MybatisConfiguration 主要是配置的sqlSessionFactory和sqlSessionTemplate,以及Mybatis的扩展框架Mapper的配置,如果不需要Mapper,可以不用配置scannerConfigurer

事物配置

@Configuration
@EnableTransactionManagement
@Slf4j
@AutoConfigureAfter({ MybatisConfiguration.class })
public class TransactionConfiguration extends DataSourceTransactionManagerAutoConfiguration {

    @Bean
    @Autowired
    public DataSourceTransactionManager transactionManager(DynamicDataSource dynamicDataSource) {
        log.info("事物配置");
        return new DataSourceTransactionManager(dynamicDataSource);
    }
}

事物配置这里有一个坑就是,一旦开启了事物,好像就会切换线程执行,所以并不会使用当前配置的数据源,而会取到默认的数据源,所以只能通过将默认数据源设置为master

AOP切入设置数据源

/**
 * 数据源的切入面
 *
 */
@Aspect
@Component
@Slf4j
public class DataSourceAOP {

    @Before("execution(* wang.raye.separate.service..*.select*(..)) || execution(* wang.raye.separate.service..*.get*(..))")
    public void setReadDataSourceType() {
        DynamicDataSource.slave();
        log.info("dataSource切换到:slave");
    }

    @Before("execution(* wang.raye.separate.service..*.insert*(..)) || execution(* wang.raye.separate.service..*.update*(..)) || execution(* wang.raye.separate.service..*.delete*(..)) || execution(* wang.raye.separate.service..*.add*(..))")
    public void setWriteDataSourceType() {
        DynamicDataSource.master();
        log.info("dataSource切换到:master");
    }

}

这样的配置是根据方法名来的,可以根据自己的情况配置

也可以使用注解来主动切换,创建两个注解类,一个Master,一个Slave
Master.class

/**
 * 使用主库的注解
 */
public @interface Master {
}

Slave.class

/**
 * 使用读库的注解
 */
public @interface Slave {
}

AOP切入修改

/**
 * 数据源的切入面
 *
 */
@Aspect
@Component
@Slf4j
public class DataSourceAOP {

    @Before("(@annotation(wang.raye.separate.annotation.Master) || execution(* wang.raye.separate.service..*.insert*(..)) || " +
            "execution(* wang.raye.separate.service..*.update*(..)) || execution(* wang.raye.separate.service..*.delete*(..)) || " +
            "execution(* wang.raye.separate.service..*.add*(..))) && !@annotation(wang.raye.separate.annotation.Slave) -")
    public void setWriteDataSourceType() {
        DynamicDataSource.master();
        log.info("dataSource切换到:master");
    }

    @Before("(@annotation(wang.raye.separate.annotation.Slave) || execution(* wang.raye.separate.service..*.select*(..)) || execution(* wang.raye.separate.service..*.get*(..))) && !@annotation(wang.raye.separate.annotation.Master)")
    public void setReadDataSourceType() {
        DynamicDataSource.slave();
        log.info("dataSource切换到:slave");
    }


}

注:这个AOP切入规则只是包含基本的规格,如果要正常使用,需要扩展规则
简单的service层代码

/**
 * 用户相关业务接口实现类
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper mapper;

    @Master
    @Override
    public List<User> selectAll() {
        return mapper.selectAll();
    }

    @Override
    public boolean addUser(User user) {
        return mapper.insertSelective(user) > 0;
    }

    @Override
    public boolean updateUser(User user) {
        return mapper.updateByPrimaryKey(user) > 0;
    }

    @Override
    public boolean deleteByid(int id) {
        return mapper.deleteByPrimaryKey(id) > 0;
    }

    @Transactional(rollbackFor = Exception.class )
    @Override
    public boolean insertAndUpdate(User user){
        log.info("当前key:"+ DynamicDataSource.getType().name());
        int count = 0;
        count += mapper.insertSelective(user);
        user = null;
        user.getId();
        count += mapper.updateByPrimaryKey(user);
        return count > 1;
    }
}

这里所有方法会使用master源,如果去掉selectAll的Master注解,那么selectAll就会使用slave数据源,insertAndUpdate方法主要是测试使用事物的情况下是否是向Master数据源写入以及是否正常回滚

源码

具体代码可以直接看我的demo项目读写分离demo

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容