SpringBoot:多数据源配置——注解+AOP

2024-06-21 02:48

本文主要是介绍SpringBoot:多数据源配置——注解+AOP,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

* maven依赖

<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.1.RELEASE</version><relativePath/> <!-- lookup parent from repository -->
</parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- 整合freemarker --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-freemarker</artifactId></dependency><!-- log4j --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-log4j</artifactId></dependency><!-- aop --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency><!-- fastJson --><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.32</version></dependency><!-- lombok --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><!-- mybatis --><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.1.1</version></dependency><!-- mysql --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency>
</dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins>
</build>

一,多数据源配置——注解+AOP

    前一篇基于拆包配置维度对多数据源配置进行了简单实现。两种方式对比来看,拆包方式规范性更强,而注解方式更加注重灵活性。通过AOP方式,直接反射获取自定义注解,解析注解值进行数据源动态添加,实现多数据源配置。

二,基于AOP配置流程;相对拆包流程比较复杂,先对流程进行梳理,然后按照流程一步步实现

    * Java整体结构

    * 动态多数据源配置

        -- DataSourceConfig

    * 创建线程持有数据库上下文

        -- DynamicDataSourceHolder

    * 基于Spring提供的AbstractRoutingDataSource,动态添加数据源(事务下可能存在问题)

        -- DynamicDataSource

    * 自定义注解,标识数据源

        -- TargetDataSource

    * AOP前后置拦截解析类,对Mapper方法代用进行拦截

        -- DataSourceAspect

    * 三层代码架构处理

        -- DataSourceAOPController,DataSourceAOPService,DataSourceMapper

三,代码变现

0,application.properties

    * 不同于分数据源配置,单一数据源配置,jdbc-url为url

### mapper存储路径_AOP
mybatis.mapper-locations=classpath:com.gupao.springboot.*.mapper/*.xml### MYSQL_First数据源配置
spring.datasource.first.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.first.jdbc-url=jdbc:mysql://localhost:3306/first?characterEncoding=utf-8&serverTimezone=GMT%2B8
spring.datasource.first.username=root
spring.datasource.first.password=123456### MYSQL_First数据源配置
spring.datasource.second.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.second.jdbc-url=jdbc:mysql://localhost:3306/second?characterEncoding=utf-8&serverTimezone=GMT%2B8
spring.datasource.second.username=root
spring.datasource.second.password=123456

1,动态多数据源配置

package com.gupao.springboot.datasourceaop.config;import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;/*** 配置数据源* @author pj_zhang* @create 2018-12-28 12:03**/
@Configuration
public class DataSourceConfig {/*** First数据源* @return*/@Bean(name = "firstAopDataSource")@ConfigurationProperties(prefix = "spring.datasource.first")public DataSource firstDataSource() {return DataSourceBuilder.create().build();}/*** Second数据源* @return*/@Bean(name = "secondAopDataSource")@ConfigurationProperties(prefix = "spring.datasource.second")public DataSource secondDataSource() {return DataSourceBuilder.create().build();}/*** 获取动态数据源* @return*/@Bean(name = "dynamicDataSource")@Primarypublic DataSource dynamicDataSource() {DynamicDataSource dynamicDataSource = new DynamicDataSource();// 设置默认数据源为first数据源dynamicDataSource.setDefaultTargetDataSource(firstDataSource());// 配置多数据源, // 添加数据源标识和DataSource引用到目标源映射Map<Object, Object> dataSourceMap = new HashMap<>();dataSourceMap.put("firstAopDataSource", firstDataSource());dataSourceMap.put("secondAopDataSource", secondDataSource());dynamicDataSource.setTargetDataSources(dataSourceMap);return dynamicDataSource;}@Beanpublic PlatformTransactionManager transactionManager() {return new DataSourceTransactionManager(dynamicDataSource());}}

2,创建线程持有数据库上下文,添加数据源到ThreadLocal中

package com.gupao.springboot.datasourceaop.context;/*** 线程持有数据源上下文** @author pj_zhang* @create 2018-12-28 12:00**/
public class DynamicDataSourceHolder {private static final ThreadLocal<String> THREAD_LOCAL = new ThreadLocal<String>();/*** 设置线程持有的DataSource, 底层以map形式呈现, key为当前线程** @param dataSource*/public static void setDataSource(String dataSource) {THREAD_LOCAL.set(dataSource);}/*** 获取线程持有的当前数据源** @return*/public static String getDataSource() {return THREAD_LOCAL.get();}/*** 清除数据源*/public static void clear() {THREAD_LOCAL.remove();}}

3,基于Spring提供的AbstractRoutingDataSource,动态添加数据源(事务下可能存在问题)

package com.gupao.springboot.datasourceaop.config;import com.gupao.springboot.datasourceaop.context.DynamicDataSourceHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;/*** spring为我们提供了AbstractRoutingDataSource,即带路由的数据源。* 继承后我们需要实现它的determineCurrentLookupKey(),* 该方法用于自定义实际数据源名称的路由选择方法,* 由于我们将信息保存到了ThreadLocal中,所以只需要从中拿出来即可。* @author pj_zhang* @create 2018-12-28 12:04**/
@Slf4j
public class DynamicDataSource extends AbstractRoutingDataSource  {@Overrideprotected Object determineCurrentLookupKey() {// 直接从ThreadLocal中获取拿到的数据源log.info("DynamicDataSource.determineCurrentLookupKey curr data source :" + DynamicDataSourceHolder.getDataSource());return DynamicDataSourceHolder.getDataSource();}
}

4,自定义注解,标识数据源

package com.gupao.springboot.datasourceaop.annotations;import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;/*** @author pj_zhang* @create 2018-12-28 12:13**/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface TargetDataSource {// 数据源名称String value() default "";
}

5,AOP前后置拦截解析类,对Mapper方法代用进行拦截

package com.gupao.springboot.datasourceaop.aspect;import com.gupao.springboot.datasourceaop.annotations.TargetDataSource;
import com.gupao.springboot.datasourceaop.context.DynamicDataSourceHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;import java.lang.reflect.Method;/*** 多数据源配置, 拦截器配置* @author pj_zhang* @create 2018-12-28 12:15**/
@Aspect
@Component
@Slf4j
// 优先级, 1标识最先执行
@Order(1)
public class DataSourceAspect {private final String DEFAULT_DATA_SOURCE = "firstAopDataSource";@Pointcut("execution(public * com.gupao.springboot.*.mapper.*.*(..))")public void dataSourcePoint() {}@Before("dataSourcePoint()")public void before(JoinPoint joinPoint) {Object target = joinPoint.getTarget();MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();// 执行方法名String methodName = methodSignature.getName();// 方法参数Class[] parameterTypes = methodSignature.getParameterTypes();try {// 获取方法, 直接getClass获取对象可能为代理对象Method method = target.getClass().getInterfaces()[0].getMethod(methodName, parameterTypes);// 添加默认数据源String dataSource = DEFAULT_DATA_SOURCE;if (null != method && method.isAnnotationPresent(TargetDataSource.class)) {TargetDataSource targetDataSource = method.getAnnotation(TargetDataSource.class);dataSource = targetDataSource.value();}// 此处添加线程对应的数据源到上下文// 在AbstractRoutingDataSource子类中拿到数据源, 加载后进行配置DynamicDataSourceHolder.setDataSource(dataSource);log.info("generate data source : " + dataSource);} catch (Exception e) {log.info("error", e);}}/*** 清除数据源, 方法执行完成后, 清除数据源*/@After("dataSourcePoint()")public void after(JoinPoint joinPoint) {DynamicDataSourceHolder.clear();}}

6,Controller层

package com.gupao.springboot.datasourceaop.controller;import com.gupao.springboot.datasourceaop.service.IDataSourceAOPService;
import com.gupao.springboot.entitys.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.List;/*** @author pj_zhang* @create 2018-12-28 10:42**/
@Slf4j
@RestController
public class DataSourceAOPController {@Autowiredprivate IDataSourceAOPService dataSourceAOPService;@RequestMapping("/firstAOPInsert")public Integer firstInsert(String userName, String password) {UserVO userVO = new UserVO();userVO.setUserName(userName);userVO.setPassword(password);return dataSourceAOPService.insertFirstUserLst(userVO);}@RequestMapping("/secondAOPInsert")public Integer secondInsert(String userName, String password) {UserVO userVO = new UserVO();userVO.setUserName(userName);userVO.setPassword(password);return dataSourceAOPService.insertSecondUserLst(userVO);}@RequestMapping("/firstAOPSelect")public List<UserVO> findFirstData() {return dataSourceAOPService.findFirstData();}@RequestMapping("/secondAOPSelect")public List<UserVO> findSecondData() {return dataSourceAOPService.findSecondData();}@RequestMapping("/insertFirstAndSecond")public Integer insertFirstAndSecond(String userName, String password) {UserVO userVO = new UserVO();userVO.setUserName(userName);userVO.setPassword(password);return dataSourceAOPService.insertFirstAndSecond(userVO);}}

7,Service层

    * Service接口

package com.gupao.springboot.datasourceaop.service;import com.gupao.springboot.entitys.UserVO;import java.util.List;/*** @author pj_zhang* @create 2018-12-28 10:50**/
public interface IDataSourceAOPService {/*** 新增用户到FIRST* @param userVO* @return*/Integer insertFirstUserLst(UserVO userVO);/*** 新增用户到SECEND* @param userVO* @return*/Integer insertSecondUserLst(UserVO userVO);/*** 查找数据FIRST* @return*/List<UserVO> findFirstData();/*** 查找数据SECOND* @return*/List<UserVO> findSecondData();/*** 新增数据到FIRST_SECOND* @param userVO* @return*/Integer insertFirstAndSecond(UserVO userVO);
}

    * Service.Impl

package com.gupao.springboot.datasourceaop.service.impl;import com.gupao.springboot.datasourceaop.mapper.DataSourceMapper;
import com.gupao.springboot.datasourceaop.service.IDataSourceAOPService;
import com.gupao.springboot.entitys.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;/*** @author pj_zhang* @create 2018-12-28 10:43**/
@Slf4j
@Service
public class DataSourceAOPService implements IDataSourceAOPService {@Autowiredprivate DataSourceMapper dataSourceMapper;@Overridepublic Integer insertFirstUserLst(UserVO userVO) {return dataSourceMapper.insertFirstUser(userVO);}@Overridepublic Integer insertSecondUserLst(UserVO userVO) {return dataSourceMapper.insertSecondUser(userVO);}@Overridepublic List<UserVO> findFirstData() {return dataSourceMapper.findFirstData();}@Overridepublic List<UserVO> findSecondData() {return dataSourceMapper.findSecondData();}@Overridepublic Integer insertFirstAndSecond(UserVO userVO) {dataSourceMapper.insertFirstUser(userVO);dataSourceMapper.insertSecondUser(userVO);return 1;}}

8,Mapper层

package com.gupao.springboot.datasourceaop.mapper;import com.gupao.springboot.datasourceaop.annotations.TargetDataSource;
import com.gupao.springboot.entitys.UserVO;
import org.apache.ibatis.annotations.Mapper;import java.util.List;/*** 动态加载数据源* value值为DataSource源数据配置map映射的key值* @author pj_zhang* @create 2018-12-28 10:43**/
@Mapper
public interface DataSourceMapper {/*** 注解为FIRST数据库* @param userVO* @return*/@TargetDataSource("firstAopDataSource")Integer insertFirstUser(UserVO userVO);/*** 注解为SECOND数据库* @param userVO* @return*/@TargetDataSource("secondAopDataSource")Integer insertSecondUser(UserVO userVO);@TargetDataSource("firstAopDataSource")List<UserVO> findFirstData();@TargetDataSource("secondAopDataSource")List<UserVO> findSecondData();
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" ><mapper namespace="com.gupao.springboot.datasourceaop.mapper.DataSourceMapper"><insert id="insertFirstUser" parameterType="com.gupao.springboot.entitys.UserVO">INSERT INTOUSER_T(USER, PASSWORD)VALUES (#{userName, jdbcType=VARCHAR},#{password, jdbcType=VARCHAR})</insert><insert id="insertSecondUser" parameterType="com.gupao.springboot.entitys.UserVO">INSERT INTOUSER_T(USER, PASSWORD)VALUES (#{userName, jdbcType=VARCHAR},#{password, jdbcType=VARCHAR})</insert><select id="findFirstData" resultType="com.gupao.springboot.entitys.UserVO">SELECTuser as userName,password as passwordfromUSER_T</select><select id="findSecondData" resultType="com.gupao.springboot.entitys.UserVO">SELECTuser as userName,password as passwordfromUSER_T</select></mapper>

9,启动入库

package com.gupao.springboot;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
// 去除SpringBoot自动配置, 采用自定义数据源配置
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class GupaoSpringbootApplication {public static void main(String[] args) {SpringApplication.run(GupaoSpringbootApplication.class, args);}}

10,测试

    * FIRST入库数据

    * 注意两条日志打印顺序;先通过AOP变更了数据源,再通过实现类进行数据源加载,后续同!

    * SECOND入库数据

    * FIRST+SECOND入库数据

    * FIRST查询数据

    * SECOND查询数据

11,数据库数据

    * FIRST

    * SECOND

四,存在问题

1,踩过的一个坑,数据库连接错误,非正常错误

    error :java.sql.SQLException: The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone val

    这个问题可能是数据库时区问题导致的,具体解决措施在jdbc-url后面加上参数,如下

    spring.datasource.first.jdbc-url=jdbc:mysql://localhost:3306/first?characterEncoding=utf-8&serverTimezone=GMT%2B8

2,AOP配置引起的数据源加载问题

    * 基于AbstractRoutingDataSource实现类配置的数据源动态加载,依赖于程序的执行顺序。先通过Mapper方法调用变更DynamicDataSourceHolder上下文持有的DataSource再进行数据源加载时,此时配置没有任何问题;

    * 但是单纯添加了声明式事务后,因为事务执行流程影响,AbstractRoutingDataSource实现类会先于Mapper方法执行,此时DynamicDataSourceHolder上下文并不持有数据源,则数据源为DataSourceConfig中配置的默认数据源;

    * 鉴于上面存在的问题,有的配置方式不基于AbstractRoutingDataSource实现类去动态加载数据源,而是在AOP前置拦截方法中,拦截到注解的数据源后,直接从Spring容器中获取DataSource并进行更改,直接跳过执行顺序可能存在的影响,该配置后续会继续完善在后面!

这篇关于SpringBoot:多数据源配置——注解+AOP的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1079997

相关文章

Spring Boot中的路径变量示例详解

《SpringBoot中的路径变量示例详解》SpringBoot中PathVariable通过@PathVariable注解实现URL参数与方法参数绑定,支持多参数接收、类型转换、可选参数、默认值及... 目录一. 基本用法与参数映射1.路径定义2.参数绑定&nhttp://www.chinasem.cnbs

JAVA中安装多个JDK的方法

《JAVA中安装多个JDK的方法》文章介绍了在Windows系统上安装多个JDK版本的方法,包括下载、安装路径修改、环境变量配置(JAVA_HOME和Path),并说明如何通过调整JAVA_HOME在... 首先去oracle官网下载好两个版本不同的jdk(需要登录Oracle账号,没有可以免费注册)下载完

Spring StateMachine实现状态机使用示例详解

《SpringStateMachine实现状态机使用示例详解》本文介绍SpringStateMachine实现状态机的步骤,包括依赖导入、枚举定义、状态转移规则配置、上下文管理及服务调用示例,重点解... 目录什么是状态机使用示例什么是状态机状态机是计算机科学中的​​核心建模工具​​,用于描述对象在其生命

Spring Boot 结合 WxJava 实现文章上传微信公众号草稿箱与群发

《SpringBoot结合WxJava实现文章上传微信公众号草稿箱与群发》本文将详细介绍如何使用SpringBoot框架结合WxJava开发工具包,实现文章上传到微信公众号草稿箱以及群发功能,... 目录一、项目环境准备1.1 开发环境1.2 微信公众号准备二、Spring Boot 项目搭建2.1 创建

Java中Integer128陷阱

《Java中Integer128陷阱》本文主要介绍了Java中Integer与int的区别及装箱拆箱机制,重点指出-128至127范围内的Integer值会复用缓存对象,导致==比较结果为true,下... 目录一、Integer和int的联系1.1 Integer和int的区别1.2 Integer和in

SpringSecurity整合redission序列化问题小结(最新整理)

《SpringSecurity整合redission序列化问题小结(最新整理)》文章详解SpringSecurity整合Redisson时的序列化问题,指出需排除官方Jackson依赖,通过自定义反序... 目录1. 前言2. Redission配置2.1 RedissonProperties2.2 Red

IntelliJ IDEA2025创建SpringBoot项目的实现步骤

《IntelliJIDEA2025创建SpringBoot项目的实现步骤》本文主要介绍了IntelliJIDEA2025创建SpringBoot项目的实现步骤,文中通过示例代码介绍的非常详细,对大家... 目录一、创建 Spring Boot 项目1. 新建项目2. 基础配置3. 选择依赖4. 生成项目5.

nginx 负载均衡配置及如何解决重复登录问题

《nginx负载均衡配置及如何解决重复登录问题》文章详解Nginx源码安装与Docker部署,介绍四层/七层代理区别及负载均衡策略,通过ip_hash解决重复登录问题,对nginx负载均衡配置及如何... 目录一:源码安装:1.配置编译参数2.编译3.编译安装 二,四层代理和七层代理区别1.二者混合使用举例

JSONArray在Java中的应用操作实例

《JSONArray在Java中的应用操作实例》JSONArray是org.json库用于处理JSON数组的类,可将Java对象(Map/List)转换为JSON格式,提供增删改查等操作,适用于前后端... 目录1. jsONArray定义与功能1.1 JSONArray概念阐释1.1.1 什么是JSONA

Java JDK1.8 安装和环境配置教程详解

《JavaJDK1.8安装和环境配置教程详解》文章简要介绍了JDK1.8的安装流程,包括官网下载对应系统版本、安装时选择非系统盘路径、配置JAVA_HOME、CLASSPATH和Path环境变量,... 目录1.下载JDK2.安装JDK3.配置环境变量4.检验JDK官网下载地址:Java Downloads