前言: 首先准备三台机,分别装了mysql,主(192.168.1.132),从1(192.168.1.133),从2(192.168.1.134)
springboot的项目结构如下:
1、pom.xml
4.0.0 org.springframework.boot spring-boot-starter-parent 2.1.5.RELEASE com.example springboot-rw-sharejdbc 0.0.1-SNAPSHOT springboot-rw-sharejdbc share-jdbc project for Spring Boot 1.8 org.springframework.boot spring-boot-starter-web org.projectlombok lombok true com.baomidou mybatis-plus-boot-starter 3.0-beta io.shardingjdbc sharding-jdbc-core 2.0.3 mysql mysql-connector-java org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-maven-plugin src/main/resources true jdbc.properties mail.properties src/main/resources false jdbc.properties mail.properties
2、application.yml
mybatis-plus: mapper-locations: classpath*:/mapper/*.xml global-config: db-config: column-underline: true configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #开启sql日志 #shardingjdbc配置 sharding: jdbc: data-sources: ###配置第一个从数据库 ds_slave_0: password: Aa123456 jdbc-url: jdbc:mysql://192.168.1.133:3306/world?useUnicode=true&characterEncoding=utf-8&useSSL=false driver-class-name: com.mysql.jdbc.Driver username: root ds_slave_1: password: Aa123456 jdbc-url: jdbc:mysql://192.168.1.134:3306/world?useUnicode=true&characterEncoding=utf-8&useSSL=false driver-class-name: com.mysql.jdbc.Driver username: root ###主数据库配置 ds_master: password: Aa123456 jdbc-url: jdbc:mysql://192.168.1.132:3306/world?useUnicode=true&characterEncoding=utf-8&useSSL=false driver-class-name: com.mysql.jdbc.Driver username: root ###配置读写分离 master-slave-rule: ###配置从库选择策略,提供轮询与随机,这里选择用轮询 load-balance-algorithm-type: round_robin ####指定从数据库 slave-data-source-names: ds_slave_0,ds_slave_1 name: ds_ms ####指定主数据库 master-data-source-name: ds_master config: sharding: props: sql.show: true #仅仅开启读写分离时,不打印sql
3、 配置文件类
(1)、ShardingDataSourceConfig
package com.example.config; import com.google.common.collect.Maps; import io.shardingjdbc.core.api.MasterSlaveDataSourceFactory; import lombok.extern.log4j.Log4j2; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; import java.sql.SQLException; import java.util.Map; @Configuration @EnableConfigurationProperties(ShardingMasterSlaveConfig.class) @Log4j2 // 读取ds_master主数据源和读写分离配置 @ConditionalOnProperty({ "sharding.jdbc.data-sources.ds_master.jdbc-url", "sharding.jdbc.master-slave-rule.master-data-source-name" }) public class ShardingDataSourceConfig { @Autowired private ShardingMasterSlaveConfig shardingMasterSlaveConfig; @Bean public DataSource masterSlaveDataSource() throws SQLException { final MapdataSourceMap = Maps.newHashMap(); dataSourceMap.putAll(shardingMasterSlaveConfig.getDataSources()); final Map newHashMap = Maps.newHashMap(); // 创建 MasterSlave数据源 DataSource dataSource = MasterSlaveDataSourceFactory.createDataSource(dataSourceMap, shardingMasterSlaveConfig.getMasterSlaveRule(), newHashMap); log.info("masterSlaveDataSource config complete"); return dataSource; } }
(2)ShardingMasterSlaveConfig
package com.example.config; import com.zaxxer.hikari.HikariDataSource; import io.shardingjdbc.core.api.config.MasterSlaveRuleConfiguration; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import java.util.HashMap; import java.util.Map; @Data @ConfigurationProperties(prefix = "sharding.jdbc") public class ShardingMasterSlaveConfig { // 存放本地多个数据源 private MapdataSources = new HashMap<>(); private MasterSlaveRuleConfiguration masterSlaveRule; }
4、mapper
(1)、UserMapper.class
package com.example.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.example.entity.User; import org.apache.ibatis.annotations.Param; public interface UserMapper extends BaseMapper{ User queryById(@Param("id") Long id); }
(2)、UserMapper.xml
5、service
package com.example.service; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.toolkit.IdWorker; import com.example.entity.User; import com.example.mapper.UserMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class UserService { @Autowired private UserMapper userMapper; // 使用读的数据源 public ListfindUser() { QueryWrapper queryWrapper = new QueryWrapper<>(); return userMapper.selectList(queryWrapper); } public User queryById(Long id) { return userMapper.queryById(id); } public Boolean insert(Long id){ User user = new User(); id = IdWorker.getId(); user.setId(id); user.setName(id.toString()); return userMapper.insert(user) > 0; } }
6、entity
User.class
package com.example.entity; public class User { private Long id; public Long getId() { return id; } public void setId(Long id) { this.id = id; } private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
7、controller
package com.example.controller; import com.example.entity.User; import com.example.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController public class UserController { @Autowired private UserService userService; @RequestMapping("/findUser") public ListfindUser() { return userService.findUser(); } @RequestMapping("/user") public User queryById(String userName) { return userService.queryById(16L); } @RequestMapping("/user/insert") public Boolean insertUser(String userName) { return userService.insert(16L); } }