数据库的读写分离配置1

实现数据库的读写分离步骤如下:

读数据源配置

引用
<bean id="readDataSource" class="org.apache.commons.dbcp.BasicDataSource" parent="commonDatasource" destroy-method="close">
<property name="driverClassName" value="${query.jdbc.mysql.driver}" />
<property name="url" value="${query.jdbc.mysql.url}" />
<property name="username" value="${query.jdbc.mysql.userName}" />
<property name="password" value="${query.jdbc.mysql.password}" />

</bean>


写数据源配置

引用
<!-- 写数据源配置 -->
<bean id="writeDataSource" class="org.apache.commons.dbcp.BasicDataSource"  parent="commonDatasource" destroy-method="close">
<property name="driverClassName" value="${update.jdbc.mysql.driver}" />
<property name="url" value="${update.jdbc.mysql.url}" />
<property name="username" value="${update.jdbc.mysql.userName}" />
<property name="password" value="${update.jdbc.mysql.password}" />
</bean>



引用
<bean id="readSqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean" parent="commonSqlMapClient">
<property name="dataSource" ref="readDataSource" />
</bean>

<bean id="writeSqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean" parent="commonSqlMapClient">
<property name="dataSource" ref="writeDataSource" />
</bean>



java实现

引用
/**
* 用于写操作的Template
*/
private SqlMapClientTemplate writeTemplate;

/**
* 用于读操作的Template
*/
private SqlMapClientTemplate readTemplate;

/**
* @return the writeTemplate
*/
public SqlMapClientTemplate getWriteTemplate() {
return writeTemplate;
}

/**
* 需要在配置文件中配置id为writeSqlMapClient的bean
*
* @param sqlMapClient the SqlMapClient object to set
*/
@Resource(name="writeSqlMapClient")
public void setWriteSqlMapClient(SqlMapClient sqlMapClient) {
writeTemplate = new SqlMapClientTemplate(sqlMapClient);
}

/**
* @return the readTemplate
*/
public SqlMapClientTemplate getReadTemplate() {
return readTemplate;
}

/**
* 需要在配置文件中配置id为writeSqlMapClient的bean
*
* @param sqlMapClient the SqlMapClient object to set
*/
@Resource(name="readSqlMapClient")
public void setReadSqlMapClient(SqlMapClient sqlMapClient) {
readTemplate = new SqlMapClientTemplate(sqlMapClient);
}


/**
* 新增实体类
*
* @param statement
* @param entity
* @return
*/
protected DomainObject save(String statement, DomainObject entity) {
Integer entityId = (Integer)writeTemplate.insert(statement, entity);
if(entityId != null && entityId > 0) {
entity.setId(entityId);
}

return entity;
}


/**
* 新增
*
* @param statement
* @param entity
*/
protected void save(String statement, Object entity) {
writeTemplate.insert(statement, entity);
}



/**
* 根据参数取得<code>T</code>类型实体
*
* @param statement
* @param params
* @return
*/
@SuppressWarnings("unchecked")
protected T getEntity(String statement, Object params) {
return (T)readTemplate.queryForObject(statement, params);
}


/**
* 根据根据参数取得任意类型实体
*
* @param statement
* @param param
* @return
*/
protected Object getObject(String statement, Object param) {
return readTemplate.queryForObject(statement, param);
}



你可能感兴趣的:(bean)