我们在开发项目的时候,会遇到一些问题。比如在某个数据库实现读数据,某个数据库实现写数据。所以这个时候就需要使用多数据源的读写。所以使用dynamic-datasource来实现。接下来我们就介绍下如何使用。
1:引入jar包
com.baomidou dynamic-datasource-spring-boot-starter3.4.1
2:在application.properties中添加相应的数据源
下面是比较简单的配置,复杂的可以参考参考链接。
### datasource begin ### ##设置默认的数据源或者数据源组,默认值为master spring.datasource.dynamic.primary=master #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源 spring.datasource.dynamic.strict=false ###主库设置 spring.datasource.dynamic.datasource.master.url=jdbc:mysql://localhost:3306/mfwow?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC spring.datasource.dynamic.datasource.master.username=root spring.datasource.dynamic.datasource.master.password= spring.datasource.dynamic.datasource.master.driver-class-name=com.mysql.jdbc.Driver ###从库设置 spring.datasource.dynamic.datasource.slave.url=jdbc:mysql://172.31.3.226:3306/Knowdege?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8&useSSL=false spring.datasource.dynamic.datasource.slave.username=root spring.datasource.dynamic.datasource.slave.password=YydhTest2019!226 spring.datasource.dynamic.datasource.slave.driver-class-name=com.mysql.jdbc.Driver ### datasource end ###
3:在启动类@SpringBootApplication注解中,添加排除原生Druid的配置类。
@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class)
public class Bootstrap {
private static Logger log= LoggerFactory.getLogger(Bootstrap.class);
public static void main(String[] args)throws Exception {
ConfigurableApplicationContext application = SpringApplication.run(Bootstrap.class, args);
Environment env = application.getEnvironment();
String ip = InetAddress.getLocalHost().getHostAddress();
String port = env.getProperty("server.port");
String path = env.getProperty("server.servlet.context-path");
log.info("n----------------------------------------------------------nt" +
"Application dynamicTest is running! Access URLs:nt" +
"Local: tthttp://localhost:" + port + path +"/swagger-ui.html"+ "nt" +
"Inner: thttp://" + ip + ":" + port + path +"/swagger-ui.html"+ "nt" +
"----------------------------------------------------------");
}
}
在此说明下:为什么要排除DruidDataSourceAutoConfigure ?
DruidDataSourceAutoConfigure会注入一个DataSourceWrapper,其会在原生的spring.datasource下找url,username,password等。而我们动态数据源的配置路径是变化的。
4:使用@DS切换数据源
在此说明下@DS只能在service和dao层使用,最好不要在controller层。如果没有标注,则是从master里操作数据。
Service层中添加@DS
@Service
public class SysUserService {
@Autowired
private JdbcTemplate jdbcTemplate;
public List
dao层
@Mapper
@DS("slave")
public interface SysUserMapper {
@Insert("insert into user(`name`) values(#{name})")
boolean addUser(@Param("name") String name);
@Update("update user set name=#{name} where id=#{id}")
boolean updateUser(@Param("id") Integer id, @Param("name") String name);
@Delete("delete from user where id=#{id}")
boolean deleteUser(@Param("id")Integer id);
@Select(value = "select * from USER")
List selectUser();
}
参考:Spring boot整合dynamic-datasource实现多数据源的读写分离
一个基于springboot的快速集成多数据源的启动器



