动态数据源使用 Druid 动态数据源

一、动态数据源配置 /src/main/resources/bootstrap.yml

datasource: datasource: master: url: jdbc:mysql://127.0.0.1:3306/nacos_config?characterEncoding=UTF-8&useUnicode=true&useSSL=false username: root password: root driver-class-name: com.mysql.jdbc.Driver slave: url: jdbc:mysql://localhost:3306/nacos_config?useUnicode=true&characterEncoding=utf8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true username: root password: root driver-class-name: com.mysql.jdbc.Driver

master 为主数据源,系统默认数据源 slave:自定义的第三方数据源,名字随便起

二、动态数据源使用 **

使用 @DS 切换数据源。 @DS 可以注解在方法上和类上,同时存在方法注解优先于类上注解。 1 2 **

注解在service实现或mapper接口方法上,但强烈不建议同时在service和mapper注解。 (可能会有问题)

没有加该注解@DS,使用默认数据源 @DS(“dsName”) dsName可以为组名也可以为具体某个库的名称 代码示例:

@Service @DS("slave") public class AmpServiceImpl implements AmpService {

@Autowired private JdbcTemplate jdbcTemplate;

public List<Map<String, Object>> selectAll() { return jdbcTemplate.queryForList("select * from user"); }

@Override @DS("slave2") public List<Map<String, Object>> selectByCondition() { return jdbcTemplate.queryForList("select * from user where age >10"); } }