简介:对于分布式架构项目,A服务想访问B服务中的数据,有2种方式,第1种是通过B服务提供的开放的restapi,第2种就是直接连B服务数据库,本文实现第2种方式。
方式一、自定义多数据源
application.properties
# sso数据库配置
spring.datasource.sso.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.sso.username=root
spring.datasource.sso.password=root
spring.datasource.sso.url=jdbc:mysql://127.0.0.1:3306/miqu_sso?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true&useSSL=false
# server数据库配置
spring.datasource.server.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.server.username=root
spring.datasource.server.password=root
spring.datasource.server.url=jdbc:mysql://127.0.0.1:3306/miqu_server?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true&useSSL=false
自定义数据源配置
通过application.properties不同的数据源参数,构建不同的DataSource数据源对象,再通过不同的数据源对象构建SqlSessionFactory工厂
package com.cong.miqu.sso.config; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import javax.sql.DataSource; /** * @Author zhangyc * @Date 2022/10/24 23:29 * @PackageName:com.cong.miqu.sso.config * @ClassName: ServerDataSourceConfig * @Description: TODO * @Version 1.0 */ @Configuration @MapperScan(basePackages = "com.cong.miqu.sso.dao.mapper.server",sqlSessionFactoryRef = "serverSqlSessionFactory") public class ServerDataSourceConfig { @Primary @Bean(name = "serverDataSource") @ConfigurationProperties(prefix = "spring.datasource.server") public DataSource ssoDataSource(){ return DataSourceBuilder.create().build(); } @Bean(name = "serverSqlSessionFactory") public SqlSessionFactory sqlSessionFactory(@Qualifier(value = "serverDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean(); sessionFactoryBean.setDataSource(dataSource); sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver() .getResources("classpath:com/cong/miqu/sso/dao/mapper/server/*.xml")); return sessionFactoryBean.getObject(); } }
package com.cong.miqu.sso.config;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.MybatisXMLLanguageDriver;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.handlers.MybatisEnumTypeHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.EnumTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.aop.interceptor.PerformanceMonitorInterceptor;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;
/**
* ssodata源配置
*
* @Author zhangyc
* @Date 2022/10/24 23:28
* @PackageName:com.cong.miqu.sso.config
* @ClassName: SSODataSourceConfig
* @Description: TODO
* @Version 1.0
*/
@Configuration
@MapperScan(basePackages = "com.cong.miqu.sso.dao.mapper.sso",sqlSessionFactoryRef = "ssoSqlSessionFactory")
public class SSODataSourceConfig {
@Primary
@Bean(name = "ssoDataSource")
@ConfigurationProperties(prefix = "spring.datasource.sso")
public DataSource ssoDataSource(){
return DataSourceBuilder.create().build();
}
@Bean(name = "ssoSqlSessionFactory")
public SqlSessionFactory sqlSessionFactory(@Qualifier(value = "ssoDataSource") DataSource dataSource) throws Exception {
MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
MybatisConfiguration configuration = new MybatisConfiguration();
configuration.setDefaultEnumTypeHandler(MybatisEnumTypeHandler.class);
configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
configuration.setJdbcTypeForNull(JdbcType.NULL);
sqlSessionFactoryBean.setConfiguration(configuration);
sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath:com/cong/miqu/sso/dao/mapper/sso/*.xml"));
sqlSessionFactoryBean.setGlobalConfig(new GlobalConfig().setBanner(false));
return sqlSessionFactoryBean.getObject();
}
}
目录结构
方式二、引入dynamic-datasource-spring-boot-starter(推荐)
mybatis-plus官网推荐的扩展
- 本框架只做 切换数据源 这件核心的事情,并不限制你的具体操作,切换了数据源可以做任何CRUD。
- 配置文件所有以下划线
_
分割的数据源 首部 即为组的名称,相同组名称的数据源会放在一个组下。- 切换数据源可以是组名,也可以是具体数据源名称。组名则切换时采用负载均衡算法切换。
- 默认的数据源名称为 master ,你可以通过
spring.datasource.dynamic.primary
修改。- 方法上的注解优先于类上注解。
- DS支持继承抽象类上的DS,暂不支持继承接口上的DS
多数据源 | MyBatis-Plus
引入依赖,注意版本要与mybatis-plus版本保持一致
com.baomidou
dynamic-datasource-spring-boot-starter
application.properties
# sso数据库配置
spring.datasource.dynamic.primary=sso
spring.datasource.dynamic.strict=false
spring.datasource.dynamic.datasource.sso.url=jdbc:mysql://127.0.0.1:3306/miqu_sso?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true&useSSL=false
spring.datasource.dynamic.datasource.sso.username=root
spring.datasource.dynamic.datasource.sso.password=root
spring.datasource.dynamic.datasource.sso.driverClassName=com.mysql.jdbc.Driver
# server数据库配置
spring.datasource.dynamic.datasource.server.driverClassName=com.mysql.jdbc.Driver
spring.datasource.dynamic.datasource.server.username=root
spring.datasource.dynamic.datasource.server.url=jdbc:mysql://127.0.0.1:3306/miqu_server?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true&useSSL=false
spring.datasource.dynamic.datasource.server.password=root
@DS注解使用
package com.cong.miqu.server.service;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cong.miqu.server.dao.mapper.UserInfoMapper;
import com.cong.miqu.server.dao.pojo.UserInfo;
import org.springframework.stereotype.Service;
import java.util.Set;
/**
* 用户信息服务
*
* @author zhangyc
* @date 2022/10/24
*/
@Service
@DS(value = "sso")
public class UserInfoService extends ServiceImpl {
public IPage page(int page, int pageSize, String keyword, Set friendsUserIds) {
IPage iPage = new Page<>(page, pageSize);
LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>();
wrapper.in(UserInfo::getUserId, friendsUserIds).like(StrUtil.isNotEmpty(keyword), UserInfo::getNickName, keyword);
iPage = this.page(iPage, wrapper);
return iPage;
}
}
测试验证
说明:查询好友列表是B服务模块中的功能,用户注册以及完善身份信息是在A服务中完成的,好友列表需要到A数据库查询用户的一些基础信息