springBoot学习笔记(六)切换数据源

springBoot学习笔记(六)切换数据源

  • 切换数据源
    • 代码实现
      • 实体bean
      • ProductMapper
      • ProductService
      • ProductController
      • 配置文件
      • MyDataSourceConfiguratioin
      • RoutingDataSource
      • RoutingDataSourceContext
      • DruidConfig
      • RoutingAspect
      • RoutingWith
      • Springboot03DataaccessApplication

切换数据源

代码实现

实体bean

package com.lagou.pojo;

import lombok.Data;

@Data
public class Product {
	private Integer id;
	private String name;
	private double price;

}

ProductMapper

public interface ProductMapper {
	@Select("select * from product")
	public List findAllMaster();
	@Select("select * from product")
	public List findAllSlave();
}

ProductService

@Service
public class ProductService {
	@Autowired
	ProductMapper productMapper;
	public void findAllM(){
		List allMaster = productMapper.findAllMaster();
		for (Product product : allMaster) {
			System.out.println(product);
		}
	}
	public void findAllS(){
		List allMaster = productMapper.findAllSlave();
		for (Product product : allMaster) {
			System.out.println(product);
		}
	}
}

ProductController

@RestController
public class ProductController {
	@Autowired
	ProductService productService;
	@RequestMapping("findAllM")
	@RoutingWith("master")
	public String findAllProM(){
//		RoutingDataSourceContext master = new RoutingDataSourceContext("master");
		productService.findAllM();
		return "master";
	}
	@RequestMapping("findAllS")
	@RoutingWith("slave")
	public String findAllProS(){
//		RoutingDataSourceContext master = new RoutingDataSourceContext("slave");
		productService.findAllS();
		return "slave";
	}
}

配置文件

# 数据库连接配置
spring.datasource.master.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.master.jdbc-url=jdbc:mysql:///product_master? useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
spring.datasource.master.username=root
spring.datasource.master.password=root

spring.datasource.slave.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.slave.jdbc-url=jdbc:mysql:///product_slave?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
spring.datasource.slave.username=root
spring.datasource.slave.password=root

MyDataSourceConfiguratioin

@Configuration
public class MyDataSourceAutoConfiguration {
	Logger logger = LoggerFactory.getLogger(MyDataSourceAutoConfiguration.class);
	//master
	@Bean
	@ConfigurationProperties(prefix = "spring.datasource.master")
	public DataSource masterDataSource(){
		logger.info("master ................... dataSource");
		return DataSourceBuilder.create().build();
	}
	//slave
	@Bean
	@ConfigurationProperties(prefix = "spring.datasource.slave")
	public DataSource slaveDataSource(){
		logger.info("slave ................... dataSource");
		return DataSourceBuilder.create().build();
	}

	@Bean
	@Primary
	public DataSource primaryDataSource(
			@Autowired @Qualifier("masterDataSource")DataSource masterDataSource,
			@Autowired @Qualifier("slaveDataSource")DataSource slaveDataSource
	){
		RoutingDataSource routingDataSource = new RoutingDataSource();
		Map map = new HashMap<>();
		map.put("master",masterDataSource);
		map.put("slave",slaveDataSource);
		routingDataSource.setTargetDataSources(map);
		return routingDataSource;
	}
}

RoutingDataSource

public class RoutingDataSource extends AbstractRoutingDataSource {
	@Override
	protected Object determineCurrentLookupKey() {
		return RoutingDataSourceContext.getDataSourceRoutingKey();
	}
}

RoutingDataSourceContext

public class RoutingDataSourceContext {
	static final ThreadLocal threadLocal=new ThreadLocal<>();
	//指定数据源类型
	public RoutingDataSourceContext(String key) {
		threadLocal.set(key);
	}

	public static String getDataSourceRoutingKey(){
		String s = threadLocal.get();
		return s==null?"master":s;
	}
	public void close(){
		threadLocal.remove();
	}
}

DruidConfig

@Configuration
public class DruidConfig {
	@Bean
	@ConfigurationProperties(prefix = "spring.datasource")
	public DataSource dataSource(){
		return new DruidDataSource();
	}
}

RoutingAspect

@Aspect
@Component
public class RoutingAspect {
	@Around("@annotation(routingWith)")
	public Object routingDataSource(ProceedingJoinPoint joinPoint,RoutingWith routingWith) throws Throwable {
		String value = routingWith.value();
		RoutingDataSourceContext master = new RoutingDataSourceContext(value);
		return joinPoint.proceed();
	}
}

RoutingWith

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RoutingWith {
	String value() default "master";
}

Springboot03DataaccessApplication

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@MapperScan("com.lagou.mapper")
public class Springboot03DataaccessApplication {

	public static void main(String[] args) {
		SpringApplication.run(Springboot03DataaccessApplication.class, args);
	}

}

你可能感兴趣的:(java,数据库)