如果用AbstractRoutingDataSource实现Hikari呢
时间: 2023-12-29 17:23:57 浏览: 77
使用AbstractRoutingDataSource实现Hikari数据源切换,可以按照以下步骤进行:
1.在pom.xml文件中添加HikariCP和Spring JDBC依赖:
```xml
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.9</version>
</dependency>
```
2.创建HikariDataSource实例,并将其添加到AbstractRoutingDataSource中:
```java
@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource.master")
public DataSource masterDataSource() {
return new HikariDataSource();
}
@Bean
@ConfigurationProperties(prefix = "spring.datasource.slave")
public DataSource slaveDataSource() {
return new HikariDataSource();
}
@Bean
public AbstractRoutingDataSource routingDataSource() {
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put("master", masterDataSource());
targetDataSources.put("slave", slaveDataSource());
AbstractRoutingDataSource routingDataSource = new AbstractRoutingDataSource() {
@Override
protected Object determineCurrentLookupKey() {
return DataSourceContextHolder.getDataSource();
}
};
routingDataSource.setDefaultTargetDataSource(masterDataSource());
routingDataSource.setTargetDataSources(targetDataSources);
return routingDataSource;
}
}
```
3.创建一个DataSourceContextHolder类,用于存储当前线程使用的数据源:
```java
public class DataSourceContextHolder {
private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
public static void setDataSource(String dataSource) {
contextHolder.set(dataSource);
}
public static String getDataSource() {
return contextHolder.get();
}
public static void clearDataSource() {
contextHolder.remove();
}
}
```
4.创建一个AOP切面,用于在方法调用前设置当前线程使用的数据源:
```java
@Aspect
@Component
public class DataSourceAspect {
@Pointcut("@annotation(com.example.demo.annotation.DataSource)")
public void dataSourcePointCut() {
}
@Before("dataSourcePointCut()")
public void before(JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
DataSource dataSource = signature.getMethod().getAnnotation(DataSource.class);
if (dataSource == null) {
DataSourceContextHolder.setDataSource("master");
} else {
DataSourceContextHolder.setDataSource(dataSource.value());
}
}
@After("dataSourcePointCut()")
public void after(JoinPoint joinPoint) {
DataSourceContextHolder.clearDataSource();
}
}
```
5.在需要使用不同数据源的方法上添加@DataSource注解:
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
@DataSource("master")
public User getUserById(int id) {
return userDao.getUserById(id);
}
@Override
@DataSource("slave")
public List<User> getAllUsers() {
return userDao.getAllUsers();
}
}
```
阅读全文