SpringMVC4+MyBatis+SQL Server2014 基于SqlSession实现读写分离(也可以实现主从分离)


前言

    上篇文章我觉的使用拦截器虽然方便快捷,但是在使用读串还是写串上你无法控制,我更希望我们像jdbc那样可以手动控制我使用读写串,那么这篇则在sqlsession的基础上实现读写分离, 这种方式则需要手动实现daoImpl。

项目结构

开发环境

  SpringMVC+MyBatis+SQL Server2014

实现读写分离

1、关键点是springmvc-servlet.xml中的配置,datasource、sqlsessionfactory、sqlsession

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:mvc="http://www.springframework.org/schema/mvc"
 5        xmlns:context="http://www.springframework.org/schema/context"
 6        xmlns:tx="http://www.springframework.org/schema/tx"
 7        xsi:schemaLocation="http://www.springframework.org/schema/beans
 8        http://www.springframework.org/schema/beans/spring-beans.xsd
 9        http://www.springframework.org/schema/context
10        http://www.springframework.org/schema/context/spring-context.xsd
11        http://www.springframework.org/schema/mvc
12        http://www.springframework.org/schema/mvc/spring-mvc.xsd
13        http://www.springframework.org/schema/tx
14        http://www.springframework.org/schema/tx/spring-tx.xsd">
15 
16     
17     <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
18         <property name="locations" value="classpath:config/jdbc.properties"/>
19         <property name="fileEncoding" value="UTF-8"/>
20     bean>
21 
22     
23     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
24         <property name="driverClassName" value="${sqlserver.driver}"/>
25         <property name="url" value="${sqlserver.url}"/>
26         <property name="username" value="${sqlserver.username}"/>
27         <property name="password" value="${sqlserver.password}"/>
28     bean>
29 
30 
31     
32     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
33         <property name="configLocation" value="classpath:springmvc-mybatis.xml"/>
34         <property name="dataSource" ref="dataSource"/>
35     bean>
36 
37     
38     <bean id="masterSqlSession" class="org.mybatis.spring.SqlSessionTemplate">
39         <constructor-arg index="0" ref="sqlSessionFactory"/>
40     bean>
41 
42     
43     <bean id="slaveSqlSession" class="org.mybatis.spring.SqlSessionTemplate">
44         <constructor-arg index="0" ref="sqlSessionFactory"/>
45     bean>
46 
47     
48     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
49         <property name="dataSource" ref="dataSource"/>
50     bean>
51 
52     
53     <tx:annotation-driven transaction-manager="transactionManager"/>
54 
55     
56     
57         
58     
59 
60     
61     <mvc:annotation-driven/>
62 
63 
64     <context:component-scan base-package="com.autohome.*"/>
65 
66     
67     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
68         <property name="prefix" value="/WEB-INF/views/"/>
69         <property name="suffix" value=".jsp"/>
70     bean>
71 
72 beans>

2、UserMapper.xml。 namespace不再和dao的包名保持一致

<?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="mapper.UserDao">
    <select id="listAllUser" resultType="User">
        select * from t_userinfo
    select>

    <select id="listPagedUser"   resultType="User">
        select top ${pageSize} * from t_userinfo where id not in (select top (${pageSize} * (${pageIndex} -1)) id from t_userinfo)
    select>

    <select id="count" resultType="int">
        select count(*) from t_userinfo
    select>

    <insert id="insertUser" parameterType="User">
        insert into t_userinfo(name,address) VALUES (#{name},#{address})
    insert>

    <update id="updateUser" parameterType="User">
        UPDATE  t_userinfo set name=#{name},address=#{address} where id=#{id}
    update>

    <delete id="deleteUser" parameterType="int">
        DELETE FROM t_userinfo where id=#{id}
    delete>

    <select id="getUserById" resultType="User" parameterType="int">
        select * from t_userinfo where id=#{id}
    select>

mapper>

3、UserDao 接口、UserDao实现

public interface UserDao {
    List listAllUser();
    int insertUser(User user);
    User getUserById(int id);
}
@Repository("userDaoImpl")
public class UserDaoImpl implements UserDao {

    @Autowired
    private SqlSession masterSqlSession;

    @Autowired
    private SqlSession slaveSqlSession;


    public List listAllUser() {
        System.out.println("===========slave==========");
        return slaveSqlSession.selectList("mapper.UserDao.listAllUser");
    }

    public int insertUser(User user) {
        System.out.println("===========master==========");
        return masterSqlSession.insert("mapper.UserDao.insertUser",user);
    }

    public User getUserById(int id) {
        System.out.println("===========slave==========");
        return slaveSqlSession.selectOne("mapper.UserDao.getUserById",id);
    }
}

4、Serivce

@Service
public class UserService {

    @Autowired
    @Qualifier("userDaoImpl")
    UserDao userDao;

    public List listAllUser() {

        return userDao.listAllUser();
    }

    @Transactional
    public int insertUser(User user) {
        return userDao.insertUser(user);
    }

    public User getUserById(int id) {
        return userDao.getUserById(id);
    }


}

总结

     在controller中调用service方法时则可以看出当前方法使用的连接串,而且不用去关心sqlsession的打开关闭问题。

补充

     一开始只站在demo的角度去想sqlsession主从分离或者读写分离,从实际应用角度的话从datasource就要分开,并且使用不同的读写连接串。那么针对如上的配置就是需要配置read-datasource、write-datasource、readsqlsessionfactory、writesqlsessionfactory、readsqlsession、writesqlsession。