spring實現讀寫分離aop註解方式

來源:互聯網
上載者:User

標籤:mysql   root   utf-8   resolved   rman   它的   for   nic   pac   

1.情境,實現資料庫的讀寫分離。

2.思路,既然是讀寫分離,那就是需要切換不同的資料來源,一種是靜態切換,就是提前配置好兩個待用資料庫資源,還有一種就是動態切換資源,這裡用到spring,那就要知道spring如何動態切換資料來源。

3.spring提供了動態切換資料來源介面AbstractRoutingDataSource,關於AbstractRoutingDataSource這個類我們可以看下它的源碼

protected DataSource determineTargetDataSource() {        Assert.notNull(this.resolvedDataSources, "DataSource router not initialized");        Object lookupKey = determineCurrentLookupKey();        DataSource dataSource = this.resolvedDataSources.get(lookupKey);        if (dataSource == null && (this.lenientFallback || lookupKey == null)) {            dataSource = this.resolvedDefaultDataSource;        }        if (dataSource == null) {            throw new IllegalStateException("Cannot determine target DataSource for lookup key [" + lookupKey + "]");        }        return dataSource;    }

可以看到會調用determineCurrentLookupKey()這個用方法去擷取key,然後根據key去擷取對應的資料來源,這個時候我們就可以整合這個重寫這個方法代碼如下:

public class DynamicDataSource extends AbstractRoutingDataSource{    @Override    protected Object determineCurrentLookupKey() {        // TODO Auto-generated method stub        return DynamicDataSourceHolder.getDataSource();    }}

DynamicDataSourceHolder類:

public class DynamicDataSourceHolder {        public final static ThreadLocal<String> holder = new ThreadLocal<String>();        public static void putDataSource(String name){        holder.set(name);    }        public static String getDataSource(){        return holder.get();    }}

使用ThreadLocal是為了防止並髮帶來的問題,保證每個線程用到的是自己的資料來源。

上面擷取key的方法會在下面會用。

 

3.解決了動態擷取資料來源下面就是,如何?當我調用讀方法時切換到讀資料來源,實現寫操作時切換到寫資料來源。

這裡就可以用到spring aop 面向切面編程,為了方便操作我們可以寫一個自定註解使用自訂的註解去註解那個方法是讀操作那個方法是寫操作

@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)public @interface DataSource {        String value();}

 

aop類:

@Component@Aspectpublic class DaoAspect {    @Pointcut("execution(* com.kedacom.aop.service.*.*(..))")    public void read(){}        @Before("read()")    public void beforeRead(JoinPoint point){                Object object = point.getTarget();                //擷取方法名稱        String methodName = point.getSignature().getName();        Class<?>[] parameterTypes = ((MethodSignature)point.getSignature()).getMethod().getParameterTypes();                try {            //擷取到方法            Method method = object.getClass().getMethod(methodName, parameterTypes);                        //擷取註解中的值            DataSource dataSource = method.getAnnotation(DataSource.class);                        //擷取主從資料庫的key以便切換資料庫            String dbKey = dataSource.value();                        DynamicDataSourceHolder.putDataSource(dbKey);                        System.out.println(dbKey);                    } catch (Exception e) {            // TODO: handle exception            e.printStackTrace();        }        }}

這裡使用 到aop的註解功能。

兩個服務了類:

@Service("readService")public class ReadService {    @Resource(name="userDao")    UserDao userDao;        @DataSource(value="slave")    public User readUser(String id){                return userDao.getUser(id);        }}
@Service("writeService")public class WriteService {    @Resource(name="userDao")    UserDao userDao;        @DataSource(value="master")    public void writeDb(User user){        userDao.save(user);    }}

測試代碼:

public static void main(String[] args) {        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");        //        PersonServer bean = (PersonServer)ctx.getBean("personServiceBean");//        bean.save("fasdfa");        WriteService ws = (WriteService)ctx.getBean("writeService");        User user = new User();        user.setId("123");        user.setName("xxx");        user.setPasswd("ok");                ws.writeDb(user);                ReadService rs = (ReadService)ctx.getBean("readService");        User u = rs.readUser("1");        System.out.println(u.getId()+"--"+u.getName()+"--"+u.getPasswd());    }

 

spring的配置:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"    xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr"    xmlns:dwra="http://www.directwebremoting.org/schema/spring-dwr-annotations"    xsi:schemaLocation="http://www.springframework.org/schema/beans                         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd                        http://www.springframework.org/schema/aop                        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd                        http://www.springframework.org/schema/context                        http://www.springframework.org/schema/context/spring-context-3.2.xsd                        http://www.springframework.org/schema/tx                        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd                        http://www.directwebremoting.org/schema/spring-dwr                        http://www.directwebremoting.org/schema/spring-dwr-3.0.xsd                        http://www.directwebremoting.org/schema/spring-dwr-annotations                              http://www.directwebremoting.org/schema/spring-dwr-annotations.xsd ">    <context:annotation-config />    <context:component-scan base-package="com.guo.*,com.kedacom.*" />    <aop:aspectj-autoproxy/>     <bean id="personServiceBean" class="com.guo.test.PersonServerBean"/>     <!-- <bean id="myInterceptor" class="com.guo.test.MyInterceptor"/>   -->        <!-- 主要資料庫源 -->    <bean id="masterDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">        <property name="url" value="jdbc:mysql://localhost:3306/maven?useUnicode=true&amp;characterEncoding=UTF-8"/>        <property name="username" value="root"/>        <property name="password" value="root"/>        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>    </bean>     <!-- 從資料庫源 -->    <bean id="slaveDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">        <property name="url" value="jdbc:mysql://localhost:3306/test_user?useUnicode=true&amp;characterEncoding=UTF-8"/>        <property name="username" value="root"/>        <property name="password" value="root"/>        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>    </bean>     <!-- 配置動態資料源 -->    <bean id="dataSource" class="com.kedacom.aop.DynamicDataSource">        <property name="targetDataSources">                <map key-type="java.lang.String">                    <!-- write -->                 <entry key="master" value-ref="masterDataSource"/>                   <!-- read -->                 <entry key="slave" value-ref="slaveDataSource"/>                </map>                       </property>          <!-- 預設資料來源 -->        <property name="defaultTargetDataSource" ref="masterDataSource"/>      </bean>        <bean id="daoJdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">        <property name="dataSource" ref="dataSource" />    </bean></beans>

 

spring實現讀寫分離aop註解方式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.