spring mybatis多数据源切换(1)

阅读更多
项目中既要连接mysql数据库又要连接sever sql数据库,做了如下设置,实现数据库的连接。
1、在resource.properties中配置不同的数据库连接信息。
#连接mysql数据库
db.driverClass=com.mysql.jdbc.Driver
db.url=jdbc:mysql://127.0.0.1:3306/qyjx?useUnicode=true&characterEncoding=utf-8&useSSL=false
db.user=root
db.password=sa
db.validationQuery=select 1
#连接seversql数据库
msdb.driverClass=com.microsoft.sqlserver.jdbc.SQLServerDriver
msdb.url=jdbc:sqlserver://127.0.0.1:1433; DatabaseName=zjys1024
msdb.user=sa
msdb.password=Zgpt-svr
msdb.validationQuery=select GETDATE()

2、在mybaits.xml文件中进行多数据源的配置。


    

    
    
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        

    

    
    
        
        
        
        
        
        
        
        
        
        
        
        
    


    
        
            
                
                
            
        
        
        
    

    
    
        
            
        
    

    
    
        
        
        
    
    
    
        
    
    
    
        
    
    
    

    
    
        
            
            
            
            
            
            
            
        
    
    
        
        
    



3、写一个继承AbstractRoutingDataSource的类DynamicDataSource,和DataSourceContextHolder处理类。
DynamicDataSource代码如下:
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

/**
 * Created by TonyJ on 2019/6/5.
 */
public class DynamicDataSource extends AbstractRoutingDataSource {
    @Override
    protected Object determineCurrentLookupKey() {
        return DataSourceContextHolder.getDbType();
    }
}


DataSourceContextHolder代码如下:

/**
 * Created by TonyJ on 2019/6/5.
 */
public class DataSourceContextHolder {

    private static final ThreadLocal contextHolder = new ThreadLocal();

    public static void setDbType(String dbType) {
        contextHolder.set(dbType);
    }

    public static String getDbType() {
        return ((String) contextHolder.get());
    }

    public static void clearDbType() {
        contextHolder.remove();
    }
}


4、在实现代码中加入切换数据源的控制,在调用service之前。

/**
 * Created by TonyJ on 2019/6/5.
 */
@Controller
@RequestMapping("/test")
public class TestController extends AbstractController {

    @Autowired
    private SysLogService sysLogService;


    @RequestMapping(value = "list")
    public @ResponseBody
    Map list(@RequestMap MapAdapter mapAdapter, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map param= new HashMap();
        //注意这里在调用service前切换到dataSource2的数据源
        DataSourceContextHolder.setDbType("dataSource2");
        List dataList = sysLogService.querySyhjAllDatasByParams(param);
        return dataList.get(0);
    }
}


你可能感兴趣的:(spring mybatis多数据源切换(1))