springboot 5 -整合多数据源(aop,自定义注解实现)

通过自定义注解,利用aop来实现对指定数据源操作。

1、数据库配置

server:
  port: 10000

spring:
  datasource:
    initialize: false
    name: MySQL
    druid:
       first:
          url: jdbc:mysql://192.168.199.86:3306/aoshop?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
          username: ddb_dev
          password: 123456
       second:
          url: jdbc:mysql://192.168.199.45:3306/aoshop?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
          username: test_all
          password: 123456
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    initialSize: 5
    maxActive: 1000
    minIdle: 5
    maxWait: 10000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 30000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    maxPoolPreparedStatementPerConnectionSize: 20
    filters: stat,wall,log4j
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
    logSlowSql: true
    

swagger:
    host: 127.0.0.1:9000
    enable: true
logging:
    config: classpath:logs.xml
    level:
         com.jinglitong.shop.mapper: debug	



# 体验卡skuId
tiyancard.skuid : feaed821bbd74ce69ad9cabfee4d3468

level.member: hehuoren
level.date: 2099-06-20 23:59:59

2、首先写一个注解

『元注解』是用于修饰注解的注解,通常用在注解的定义上

@Target:注解的作用目标

@Retention:注解的生命周期

@Documented:注解是否应当被包含在 JavaDoc 文档中

@Inherited:是否允许子类继承该注解

@Target 用于指明被修饰的注解最终可以作用的目标是谁,也就是指明,你的注解到底是用来修饰方法的?修饰类的?还是用来修饰字段属性的

@Retention 用于指明当前注解的生命周期,它的基本定义如下:

  • ElementType.TYPE:允许被修饰的注解作用在类、接口和枚举上
  • ElementType.FIELD:允许作用在属性字段上
  • ElementType.METHOD:允许作用在方法上
  • ElementType.PARAMETER:允许作用在方法参数上
  • ElementType.CONSTRUCTOR:允许作用在构造器上
  • ElementType.LOCAL_VARIABLE:允许作用在本地局部变量上
  • ElementType.ANNOTATION_TYPE:允许作用在注解上
  • ElementType.PACKAGE:允许作用在包上

这里的 RetentionPolicy 依然是一个枚举类型,它有以下几个枚举值可取:

@Documented 注解修饰的注解,当我们执行 JavaDoc 文档打包时会被保存进 doc 文档,反之将在打包时丢弃。

@Inherited 注解修饰的注解是具有可继承性的,也就说我们的注解修饰了一个类,而该类的子类将自动继承父类的该注解。 

  • RetentionPolicy.SOURCE:当前注解编译期可见,不会写入 class 文件
  • RetentionPolicy.CLASS:类加载阶段丢弃,会写入 class 文件
  • RetentionPolicy.RUNTIME:永久保存,可以反射获取

JDK5.0加入了下面三个内置注解:

1. @Override:表示当前的方法定义将覆盖父类中的方法
2. @Deprecated:表示代码被弃用,如果使用了被@Deprecated注解的代码则编译器将发出警告
3. @SuppressWarnings:表示关闭编译器警告信息

package com.jinglitong.shop.datasource;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataSource {

	String name() default "";
}

2、配置数据源

package com.jinglitong.shop.datasource;

public interface DataSourceNames {

	String FIRST = "first";
    String SECOND = "second"; 
}

3、动态数据源加载

package com.jinglitong.shop.datasource;

import java.util.Map;

import javax.sql.DataSource;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

public class DynamicDataSource extends AbstractRoutingDataSource {

    //用来保存数据源与获取数据源
	private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
	
	public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {
        super.setDefaultTargetDataSource(defaultTargetDataSource);
        super.setTargetDataSources(targetDataSources);
        super.afterPropertiesSet();
    }
	
	@Override
	protected Object determineCurrentLookupKey() {
		return getDataSource();
	}

	public static void setDataSource(String dataSource) {
        contextHolder.set(dataSource);
    }
 
    public static String getDataSource() {
        return contextHolder.get();
    }
 
    public static void clearDataSource() {
        contextHolder.remove();
    }
}

AbstractRoutingDataSource这个类 

可以看到AbstractRoutingDataSource获取数据源之前会先调用determineCurrentLookupKey方法查找当前的lookupKey,这个lookupKey就是数据源标识。因此通过重写这个查找数据源标识的方法就可以让spring切换到指定的数据源了。 

4、把信息加载到配置中

package com.jinglitong.shop.datasource;

import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;

import tk.mybatis.spring.annotation.MapperScan;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;


@Configuration
@MapperScan("com.jinglitong.shop.mapper")
public class DynamicDataSourceConfig {

	@Bean
    @ConfigurationProperties("spring.datasource.druid.first")
    public DataSource firstDataSource(){
        return DruidDataSourceBuilder.create().build();
    }
 
    @Bean
    @ConfigurationProperties("spring.datasource.druid.second")
    public DataSource secondDataSource(){
        return DruidDataSourceBuilder.create().build();
    }
 
    @Bean
    @Primary
    public DynamicDataSource dataSource(DataSource firstDataSource, DataSource secondDataSource) {
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceNames.FIRST, firstDataSource);
        targetDataSources.put(DataSourceNames.SECOND, secondDataSource);
        return new DynamicDataSource(firstDataSource, targetDataSources);
    }
}

 5、aop代理一下

package com.jinglitong.shop.datasource;

import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

/**
 * 多数据源,切面处理类 处理带有注解的方法类
 * Copyright (c) 2019, 井立通
 * All rights reserved.
 * 文件名称: DataSourceAspect.java
 * 作        者: yxl 2019年7月30日
 * 创建时间: 2019年7月30日
 * 功能说明:
 */
@Aspect
@Component
public class DataSourceAspect implements Ordered{

	 protected Logger logger = LoggerFactory.getLogger(getClass());
	 
	    @Pointcut("@annotation(com.jinglitong.shop.datasource.DataSource)")//这个注解DataSource的包名
	    public void dataSourcePointCut() {
	 
	    }
	 
	    @Around("dataSourcePointCut()")
	    public Object around(ProceedingJoinPoint point) throws Throwable {
	        MethodSignature signature = (MethodSignature) point.getSignature();
	        Method method = signature.getMethod();
	 
	        DataSource ds = method.getAnnotation(DataSource.class);
	        if(ds == null){
	            DynamicDataSource.setDataSource(DataSourceNames.FIRST);
	            System.out.println("FIRST");
	            logger.debug("set datasource is " + DataSourceNames.FIRST);
	        }else {
	        	System.out.println(ds.name());
	            DynamicDataSource.setDataSource(ds.name());
	            logger.debug("set datasource is " + ds.name());
	        }
	 
	        try {
	            return point.proceed();
	        } finally {
	            DynamicDataSource.clearDataSource();
	            logger.debug("clean datasource");
	        }
	    }
	 
	    @Override
	    public int getOrder() {
	        return 1;
	    }
}

6、在service层使用自定义注解

7、启动类

启动执行结果:

 https://github.com/lombook/shop-test-aop-datasource.git

package com.jinglitong.shop.reflect;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;

@Table(value = "it_user")
class User {
	@ProPerty(value = "it_id", leng = 10)
	private String id;
	@ProPerty(value = "it_name", leng = 10)
	private String name;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}
@Target(value = ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Table {
	String value();
}
@Retention(RetentionPolicy.RUNTIME)
@interface ProPerty {
	String value();
	int leng();
}
public class ReflectTable {
	public static void main(String[] args) throws ClassNotFoundException {
		Class<?> forName = Class.forName("com.jinglitong.shop.reflect.User");
		StringBuffer sf = new StringBuffer();
		sf.append(" select ");
		// 获取当前的所有的属性
		Field[] declaredFields = forName.getDeclaredFields();
		for (int i = 0; i < declaredFields.length; i++) {
			Field field = declaredFields[i];
			ProPerty proPertyAnnota = field.getDeclaredAnnotation(ProPerty.class);
			String proPertyName = proPertyAnnota.value();
			sf.append(" " + proPertyName);
			if (i < declaredFields.length - 1) {
				sf.append(" , ");
			}
		}
		Table tableAnnota = forName.getDeclaredAnnotation(Table.class);
		// 表的名称
		String tableName = tableAnnota.value();
		sf.append(" from " + tableName);
		System.out.println(sf.toString());
	}
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值