SpringMVC + Spring + JdbcTemplate配置读写分离

环境:SpringMVC + Spring + JdbcTemplate、MySQL5.6.12

jdbc.properties:

#主数据库
jdbcM.url=jdbc:mysql://192.168.1.1:3306/test?useUnicode=true&characterEncoding=UTF-8
jdbcM.username=root
jdbcM.password=123456

#从数据库
jdbcS.url=jdbc:mysql://192.168.1.2:3306/test?useUnicode=true&characterEncoding=UTF-8
jdbcS.username=root
jdbcS.password=123456

spring-context.xml:



    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    




    
    
    

  


    
    
    




    
    
        
            
        
    




    
        
    




    

    


    
        
    

自定义类:DataSourceAspect:

public class DynamicDataSource extends AbstractRoutingDataSource {

    private DataSource master;
    private List slaves;

    private AtomicLong slaveCount = new AtomicLong();
    private int slaveSize = 0;

    private Map dataSources = new HashMap();

    private static final ThreadLocal> TARGET_DATA_SOURCE = new ThreadLocal>() {
        @Override
        protected LinkedList initialValue() {
            return new LinkedList();
        }
    };

    private static final String DEFAULT = "master";// 主数据库的Key
    private static final String SLAVE = "slave";// 从数据库的Key

    /**
     * 初始化
     */
    @Override
    public void afterPropertiesSet() {

        if (null == master) {
            throw new IllegalArgumentException("主数据库加载失败!");
        }

        dataSources.put(DEFAULT, master);

        if (slaves != null && !slaves.isEmpty()) {
            for (int i = 0; i < slaves.size(); i++) {
                dataSources.put(SLAVE + (i + 1), slaves.get(i));
            }
        }
        slaveSize = slaves.size();

        this.setDefaultTargetDataSource(master);
        this.setTargetDataSources(dataSources);

        super.afterPropertiesSet();

    }

    /**
     * 选择使用主库,并把选择放到当前ThreadLocal的栈顶
     * */
    public static void useMaster() {

        LinkedList m = TARGET_DATA_SOURCE.get();
        m.offerFirst(DEFAULT);

    }

    /**
     * 选择使用从库,并把选择放到当前ThreadLocal的栈顶
     * */
    public static void useSlave() {

        LinkedList m = TARGET_DATA_SOURCE.get();
        m.offerFirst(SLAVE);

    }

    /**
     * 重置当前栈
     * */
    public static void reset() {

        LinkedList m = TARGET_DATA_SOURCE.get();

        if (!m.isEmpty()) {
            m.poll();
        }

    }

    /**
     * 如果是选择使用从库,且从库的数量大于1,则通过取模来控制从库的负载 
* 计算结果返回AbstractRoutingDataSource */ @Override protected Object determineCurrentLookupKey() { LinkedList m = TARGET_DATA_SOURCE.get(); String key = m.peekFirst() == null ? "" : m.peekFirst(); if (key == null) { return null; } if (DEFAULT.equals(key)) { return key; } else if (SLAVE.equals(key)) { if (slaveSize > 1) { long c = slaveCount.incrementAndGet(); c = c % slaveSize; return SLAVE + (c + 1); } else { return SLAVE + "1"; } } return null; } public DataSource getMaster() { return master; } public void setMaster(DataSource master) { this.master = master; } public List getSlaves() { return slaves; } public void setSlaves(List slaves) { this.slaves = slaves; } }

自定义注解 DataSourceChange:

@Inherited
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DataSourceChange {
    boolean slave() default false;
}

Spring AOP切面 DataSourceAspect:
该类一定要注册,@Component注解式或者在spring配置文件配置,选一种就可以了



@Aspect
@Component
public class DataSourceAspect {

    @Pointcut("@annotation(com.su.util.DataSourceChange)")
    public void changeDS() {
    }

    @Around(value = "changeDS()", argNames = "pjp")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {

        Object retVal = null;
        MethodSignature ms = (MethodSignature) pjp.getSignature();
        Method method = ms.getMethod();
        DataSourceChange annotation = method
                .getAnnotation(DataSourceChange.class);
        boolean selectedDataSource = false;
        try {
            if (annotation != null) {
                selectedDataSource = true;
                if (annotation.slave()) {
                    DynamicDataSource.useSlave();
                } else {
                    DynamicDataSource.useMaster();
                }
            }
            retVal = pjp.proceed();
        } catch (Throwable e) {
            throw e;
        } finally {
            if (selectedDataSource) {
                DynamicDataSource.reset();
            }
        }
        return retVal;

    }

}

如果以上都配置正确,有{@DataSourceChange}注解的方法,调用时会切换到指定的数据源。

你可能感兴趣的:(SpringMVC + Spring + JdbcTemplate配置读写分离)