springboot和dynamic和MySQL和SqlServer多数据源配置

springboot和dynamic和MySQL和SqlServer多数据源配置

配置
	spring:
	  datasource:
		dynamic://参考MyBatis-Plus官网
		  # 是否开启 SQL日志输出,生产环境建议关闭,有性能损耗
		  p6spy: true
		  hikari:
			connection-timeout: 30000
			max-lifetime: 1800000
			max-pool-size: 15
			min-idle: 5
			connection-test-query: select 1
			pool-name: FebsHikariCP
		  # 配置默认数据源
		  primary: primary
		  datasource:
			# 数据源-1,名称为 primary
			primary:
			  username: root
			  password: 123456
			  driver-class-name: com.mysql.cj.jdbc.Driver
			  url: jdbc:mysql://xx.xx.xx.xx:3306/bm_dev?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8
			oa:
			  username: root
			  password: 123456
			  driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
			  url: jdbc:sqlserver://xx.xx.xx.xx:1433;DatabaseName=oatest
			slave_1:
			  username: root
			  password: 123456
			  driver-class-name: com.mysql.jdbc.Driver
			  url: jdbc:mysql://xx.xx.xx.xx:3307/dynamic
			slave_2:
			  username: root
			  password: 123456
			  driver-class-name: com.mysql.jdbc.Driver
			  url: jdbc:mysql://xx.xx.xx.xx:3308/dynamic
		   #......省略
		   #以上会配置一个默认库master,一个组slave下有两个子库slave_1,slave_2
使用
	没有@DS  默认数据源
	@DS("dsName")	dsName可以为组名也可以为具体某个库的名称
	
	@Service
	@DS("slave")
	public class UserServiceImpl implements UserService {

	  @Autowired
	  private JdbcTemplate jdbcTemplate;

	  public List> selectAll() {
		return  jdbcTemplate.queryForList("select * from user");
	  }
	  @Override
	  @DS("slave_1")
	  public List> selectByCondition() {
		return  jdbcTemplate.queryForList("select * from user where age >10");
	  }
	}

dynamic-datasource-spring-boot-starter版本为2.5.7以上亲测2.5.1不行 另外service类上不可有事务相关的注解

你可能感兴趣的:(java)