Springboot怎样实现根据用户ID切换动态数据源?

1. Springboot怎样实现根据用户ID切换动态数据源?

Springboot可以通过实现AbstractRoutingDataSource来实现动态数据源的路由。具体步骤如下:

1.首先在pom.xml中引入依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

2.实现AbstractRoutingDataSource类:

public class DynamicDataSource extends AbstractRoutingDataSource {

    @Override
    protected Object determineCurrentLookupKey() {
        return DataSourceContextHolder.getDataSourceType();
    }

}

3.定义数据源类型枚举类DataSourceType:

public enum DataSourceType {

    MASTER,

    SLAVE;

}

4.定义数据源上下文持有者类DataSourceContextHolder:

public class DataSourceContextHolder {

    private static final ThreadLocal<DataSourceType> contextHolder = new ThreadLocal<>();

    public static DataSourceType getDataSourceType() {
        return contextHolder.get();
    }

    public static void setDataSourceType(DataSourceType dataSourceType) {
        contextHolder.set(dataSourceType);
    }

    public static void clearDataSourceType() {
        contextHolder.remove();
    }

}

5.定义动态数据源切换切面DynamicDataSourceAspect:

@Aspect
@Component
public class DynamicDataSourceAspect {

    @Pointcut("execution(* com.example.demo.mapper.*.*(..))")
    public void pointCut() {}

    @Before("pointCut()")
    public void before(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Class<?> clazz = joinPoint.getTarget().getClass();
        DataSourceType dataSourceType = clazz.isAnnotationPresent(Master.class) ? DataSourceType.MASTER : DataSourceType.SLAVE;
        DataSourceContextHolder.setDataSourceType(dataSourceType);
    }

    @After("pointCut()")
    public void after() {
        DataSourceContextHolder.clearDataSourceType();
    }

}

6.给不同的Mapper类加上注解@Master或@Slave表示数据源类型:

@Mapper
@Master
public interface UserMapper {

    User getUserById(@Param("id") int id);

    int addUser(User user);

}

@Mapper
@Slave
public interface OrderMapper {

    List<Order> getOrderList(@Param("userId") int userId);

}

至此,根据用户ID切换动态数据源的功能就实现了。在使用Mapper类查询时,只需要在需要查询主库数据的地方给Mapper类加上@Master注解,在需要查询从库数据的地方给Mapper类加上@Slave注解即可。

类似文章

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注