SpringBoot 整合shardingsphere + mybatisPlus 实现读写分离

SpringBoot 版本 2.2.2.RELEASE

项目结构

maven依赖

 <!--springboot web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--lombok插件-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--Mybatis-Plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.1</version>
        </dependency>
        <!--shardingsphere start-->
        <!-- for spring boot -->
        <dependency>
            <groupId>io.shardingsphere</groupId>
            <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
            <version>3.1.0</version>
        </dependency>
        <!-- for spring namespace -->
        <dependency>
            <groupId>io.shardingsphere</groupId>
            <artifactId>sharding-jdbc-spring-namespace</artifactId>
            <version>3.1.0</version>
        </dependency>
        <!--shardingsphere end-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--公共api组件-->
        <dependency>
            <groupId>com.gpdi.wireless</groupId>
            <artifactId>wireless-api-commons</artifactId>
            <version>${project.version}</version>
        </dependency>
        <!--alibaba 连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>${druid.verison}</version>
        </dependency>

yaml 配置文件

server:
  port: 8061

#mybatis-plus映射mapper文件
mybatis-plus:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.gpdi.wireless.domain

sharding:
  jdbc:
    datasource:
      names: master1,salve0 #主从数据源
      master1:
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver #数据库新的驱动,下面连接url一定要加区时
        url: jdbc:mysql://localhost:3306/master1?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowMultiQueries=true
        username: root
        password: 123456
      salve0:
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/salve0?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowMultiQueries=true
        username: root
        password: 123456
    config:  #读写分离配置
      masterslave:
        master-data-source-name: master1 #主数据库配置
        slave-data-source-names: salve0 #从数据库配置(多个以逗号隔开)
        load-balance-algorithm-type: round_robin # 提供轮询与随机(random),这里选择用轮询,
        name: ms
      props:
        sql:
          show: true #打印sql日志
spring:
  main:
    allow-bean-definition-overriding: true #设置为true,表示后发现的bean会覆盖之前相同名称的bean。
  application:
    name: sharing-sphere-server

MybatisPlusConfig 扫描mapper包
package com.gpdi.wireless.config;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Configuration;

/**
 * @Author Lxq
 * @Date 2020/5/4 20:59
 * @Version 1.0
 */
@Configuration
@MapperScan("com.gpdi.wireless.mapper")
public class MybatisPlusConfig {
}
UserController
package com.gpdi.wireless.controller;

import com.gpdi.wireless.domain.UserInfo;
import com.gpdi.wireless.entities.CommonResult;
import com.gpdi.wireless.entities.Payment;
import com.gpdi.wireless.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Author Lxq
 * @Date 2020/5/4 20:35
 * @Version 1.0
 */
@RestController
public class UserController {

    @Autowired
    private UserInfoService userService;

    @GetMapping("/select")
    public List<UserInfo> select() {
        return userService.getUserList();
    }

    @PostMapping("/insert")
    public int insert(UserInfo user) {
        return userService.save(user);
    }

    @GetMapping(value = "/getobj/{id}")
    public CommonResult<Payment> getStorage(@PathVariable("id") Integer id) {
        UserInfo userInfo = userService.selectById(id);
        return new CommonResult<>(200, "from serverPort" + userInfo.toString());
    }
}
UserInfo
package com.gpdi.wireless.domain;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @Author Lxq
 * @Date 2020/5/4 20:34
 * @Version 1.0
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("user_info")
public class UserInfo {

    @TableId(value = "id", type = IdType.AUTO)
    private int id;
    private String userName;
    private int age;
}
UserInfoMapper
package com.gpdi.wireless.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.gpdi.wireless.domain.UserInfo;
import org.springframework.stereotype.Repository;

/**
 * @Author Lxq
 * @Date 2020/5/4 20:38
 * @Version 1.0
 */
@Repository
public interface UserInfoMapper extends BaseMapper<UserInfo> {
    
}
UserInfoService
package com.gpdi.wireless.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.gpdi.wireless.domain.UserInfo;

import java.util.List;

/**
 * @Author Lxq
 * @Date 2020/5/4 20:36
 * @Version 1.0
 */
public interface  UserInfoService {

    /**
     * 保存用户信息
     * @param entity
     * @return
     */

    int save(UserInfo entity);

    /**
     * 查询所以用户信息
     * @return
     */
    List<UserInfo> getUserList();

    /**
     *
     * @param id
     * @return
     */
    UserInfo selectById(Integer id);
}
UserInfoServiceImpl
package com.gpdi.wireless.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gpdi.wireless.domain.UserInfo;
import com.gpdi.wireless.mapper.UserInfoMapper;
import com.gpdi.wireless.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author Lxq
 * @Date 2020/5/4 20:37
 * @Version 1.0
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {


    @Autowired
    private UserInfoMapper userInfoMapper;


    public int save(UserInfo entity) {
        return userInfoMapper.insert(entity);
    }

    @Override
    public List<UserInfo> getUserList() {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("*");
        return userInfoMapper.selectList(queryWrapper);
    }

    @Override
    public UserInfo selectById(Integer id) {
        return userInfoMapper.selectById(id);
    }
}
ShardingsphereMain
package com.gpdi.wireless;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @Author Lxq
 * @Date 2020/5/4 20:26
 * @Version 1.0
 */
@SpringBootApplication
public class ShardingsphereMain {
    public static void main(String[] args) {
        SpringApplication.run(ShardingsphereMain.class, args);
    }
}

 数据源初始化成功,用postman 测试,我这里主从没有配置,只是单独用两个数据库来测试,自己可以先配置主从后测试效果更好。

 

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现读写分离可以利用 SpringBootMybatisPlus 和 Druid 进行配置。下面是一个简单的实现过程: 1. 添加 MybatisPlus 和 Druid 的 Maven 依赖。 ```xml <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.0</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.6</version> </dependency> ``` 2. 在配置文件中添加 Druid 数据源相关配置。 ```yaml spring: datasource: username: root password: 123456 url: jdbc:mysql://localhost:3306/db_name?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai driver-class-name: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource druid: initialSize: 5 maxActive: 10 minIdle: 5 maxWait: 60000 timeBetweenEvictionRunsMillis: 60000 validationQuery: SELECT 1 FROM DUAL testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true maxPoolPreparedStatementPerConnectionSize: 20 filters: stat,wall,log4j connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 ``` 3. 配置 MybatisPlus 的多数据源功能。 ```java @Configuration public class DataSourceConfig { @Bean @ConfigurationProperties(prefix = "spring.datasource.master") public DataSource masterDataSource() { return DruidDataSourceBuilder.create().build(); } @Bean @ConfigurationProperties(prefix = "spring.datasource.slave") public DataSource slaveDataSource() { return DruidDataSourceBuilder.create().build(); } @Bean public DynamicDataSource dynamicDataSource(@Qualifier("masterDataSource") DataSource masterDataSource, @Qualifier("slaveDataSource") DataSource slaveDataSource) { Map<Object, Object> targetDataSources = new HashMap<>(); targetDataSources.put(DataSourceType.MASTER.getType(), masterDataSource); targetDataSources.put(DataSourceType.SLAVE.getType(), slaveDataSource); return new DynamicDataSource(masterDataSource, targetDataSources); } } ``` 4. 创建一个 DataSourceHolder 类,用于保存当前线程的数据源类型。 ```java public class DataSourceHolder { private static final ThreadLocal<String> HOLDER = new ThreadLocal<>(); public static String getDataSource() { return HOLDER.get(); } public static void setDataSource(String dataSource) { HOLDER.set(dataSource); } public static void clearDataSource() { HOLDER.remove(); } } ``` 5. 创建一个枚举类型 DataSourceType,用于表示数据源类型。 ```java public enum DataSourceType { MASTER("master"), SLAVE("slave"); private final String type; DataSourceType(String type) { this.type = type; } public String getType() { return type; } } ``` 6. 创建一个 DynamicDataSource 类,继承 AbstractRoutingDataSource,用于动态切换数据源。 ```java public class DynamicDataSource extends AbstractRoutingDataSource { private final Map<Object, Object> targetDataSources; public DynamicDataSource(DataSource defaultDataSource, Map<Object, Object> targetDataSources) { super.setDefaultTargetDataSource(defaultDataSource); this.targetDataSources = targetDataSources; super.setTargetDataSources(targetDataSources); super.afterPropertiesSet(); } @Override protected Object determineCurrentLookupKey() { return DataSourceHolder.getDataSource(); } @Override public void setTargetDataSources(Map<Object, Object> targetDataSources) { this.targetDataSources.putAll(targetDataSources); super.setTargetDataSources(this.targetDataSources); super.afterPropertiesSet(); } @Override public void addTargetDataSource(Object key, Object dataSource) { this.targetDataSources.put(key, dataSource); super.setTargetDataSources(this.targetDataSources); super.afterPropertiesSet(); } } ``` 7. 创建一个 AopDataSourceConfig 类,用于配置切面,实现动态切换数据源。 ```java @Configuration public class AopDataSourceConfig { @Bean public DataSourceAspect dataSourceAspect() { return new DataSourceAspect(); } } ``` ```java @Aspect public class DataSourceAspect { @Pointcut("@annotation(com.example.demo.annotation.Master) " + "|| execution(* com.example.demo.service..*.select*(..)) " + "|| execution(* com.example.demo.service..*.get*(..)) " + "|| execution(* com.example.demo.service..*.query*(..)) " + "|| execution(* com.example.demo.service..*.find*(..)) " + "|| execution(* com.example.demo.service..*.count*(..))") public void read() { } @Pointcut("execution(* com.example.demo.service..*.insert*(..)) " + "|| execution(* com.example.demo.service..*.update*(..)) " + "|| execution(* com.example.demo.service..*.delete*(..))") public void write() { } @Around("read()") public Object read(ProceedingJoinPoint joinPoint) throws Throwable { try { DataSourceHolder.setDataSource(DataSourceType.SLAVE.getType()); return joinPoint.proceed(); } finally { DataSourceHolder.clearDataSource(); } } @Around("write()") public Object write(ProceedingJoinPoint joinPoint) throws Throwable { try { DataSourceHolder.setDataSource(DataSourceType.MASTER.getType()); return joinPoint.proceed(); } finally { DataSourceHolder.clearDataSource(); } } } ``` 8. 在 Service 层的方法上使用 @Master 注解,表示强制使用主库。 ```java @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { @Override @Master public boolean save(User user) { return super.save(user); } } ``` 这样就实现读写分离功能。需要注意的是,在使用 MybatisPlus 进行 CRUD 操作时,需要使用对应的 Service 方法,例如 selectList、selectPage、insert、updateById、deleteById,而不是直接调用 Mapper 方法。否则,数据源切换将不会生效。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值