springBoot学习笔记切换数据源

Posted 拐柒

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springBoot学习笔记切换数据源相关的知识,希望对你有一定的参考价值。

切换数据源

代码实现

实体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<Product> findAllMaster();
	@Select("select * from product")
	public List<Product> findAllSlave();
}

ProductService

@Service
public class ProductService {
	@Autowired
	ProductMapper productMapper;
	public void findAllM(){
		List<Product> allMaster = productMapper.findAllMaster();
		for (Product product : allMaster) {
			System.out.println(product);
		}
	}
	public void findAllS(){
		List<Product> 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<Object, Object> 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<String> 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);
	}

}

以上是关于springBoot学习笔记切换数据源的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot学习笔记——Thymeleaf

SpringBoot学习笔记——Web开发探究

SpringBoot学习笔记——自动配置原理

学习笔记:python3,代码片段(2017)

SpringBoot学习笔记.pdf,这个太全了!

SpringBoot学习笔记.pdf,这个太全了!