springboot整合多數據源

在一個項目中存在會員模塊,訂單,支付模塊,不算是分佈式項目,只算是分包 分模塊項目

分佈式項目是將一個大的項目拆分成N個不同的子項目,子項目之間採用rpc遠程調用技術。

假設一個項目有三大模塊,每個模塊分別對應着一個數據庫,存在三個不同的jdbc,多數據庫要如何定位自己的數據源。

  • 分包名

原理使用根據包名,加載不同的數據源

com.xyt.member--會員數據庫

com.xyt.pay--支付數據庫

com.xyt.order--訂單數據庫

  • 註解式

在Service方法或者在類上加上自定義的註解@DataSource("要連接的數據庫"),這種方式用起來比較麻煩,建議少用

 

pom.xml

 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <!-- 測試 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>
        <!-- mysql 依賴 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- springboot-web組件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

application.yml配置文件

###springboot2.0名稱url在多數據源的情況下變成jdbc-url,否則出現debug
###準備兩個數據庫連接:mumber/order
spring:
  datasource:
    member:
      jdbc-url: jdbc:mysql://localhost:3306/user
      username: root
      password: 123123
      driver-class-name: com.mysql.jdbc.Driver
    order:
      jdbc-url: jdbc:mysql://localhost:3306/order
      username: root
      password: 123123
      driver-class-name: com.mysql.jdbc.Driver
      

創建兩個配置文件分別:MemberDatasourceConfig.java/OrderDatasourceConfig.java

package com.xyt.springboot.config.member;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
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.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.xyt.springboot.member",sqlSessionFactoryRef ="memberSqlSessionFactory")
public class MemberDatasourceConfig {
    /**
     * 創建我們的datasource
     *
     * @return
     */
    @Bean("memberDataSource")//spring容器注入
    @ConfigurationProperties(prefix = "spring.datasource.member")//查找數據庫配置
    public DataSource memberDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "memberSqlSessionFactory")
    public SqlSessionFactory memberSqlSessionFactory(@Qualifier("memberDataSource") DataSource dataSource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        // bean.setMapperLocations(
        // new
        // PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test2/*.xml"));
        return bean.getObject();
    }

    /**
     * 事務管理
     *
     * @param dataSource
     * @return
     */
    @Bean(name = "memberTransactionManager")
    public DataSourceTransactionManager memberTransactionManager(@Qualifier("memberDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "memberSqlSessionTemplate")
    public SqlSessionTemplate memberSqlSessionTemplate(
            @Qualifier("memberSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
package com.xyt.springboot.config.order;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
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.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration//@Configuration等同於OrderDatasourceConfig.xml
@MapperScan(basePackages = "com.xyt.springboot.order", sqlSessionFactoryRef = "orderSqlSessionFactory")
public class OrderDatasourceConfig {

    /**
     * 創建我們的datasource
     *
     * @return
     */
    @Bean("orderDataSource")//spring容器注入
    @ConfigurationProperties(prefix = "spring.datasource.order")//查找數據庫配置
    public DataSource orderDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "orderSqlSessionFactory")
    public SqlSessionFactory orderSqlSessionFactory(@Qualifier("orderDataSource") DataSource dataSource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        // bean.setMapperLocations(
        // new
        // PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test2/*.xml"));
        return bean.getObject();
    }

    /**
     * 事務管理
     *
     * @param dataSource
     * @return
     */
    @Bean(name = "orderTransactionManager")
    public DataSourceTransactionManager orderTransactionManager(@Qualifier("orderDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "orderSqlSessionTemplate")
    public SqlSessionTemplate orderSqlSessionTemplate(
            @Qualifier("orderSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

接口代碼UserMapper.java/OrderMapper.java

package com.xyt.springboot.member;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;

public interface UserMapper {
	@Insert("insert into users values(null,#{name},#{age});")
	public int addUser(@Param("name") String name, @Param("age") Integer age);
}
package com.xyt.springboot.order;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;

public interface OrderMapper {
	@Insert("insert into orders values(null,#{order_no});")
	public int addOrder(@Param("order_no") String order_no);
}

controller控制器代碼

package com.xyt.springboot.controller;
import com.xyt.springboot.member.UserMapper;
import com.xyt.springboot.order.OrderMapper;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.xml.transform.Result;

@RestController
public class UserController {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderMapper orderMapper;

    /**
     * 調用User數據庫
     *
     * @param name
     * @param age
     * @return
     */
    @RequestMapping("/addUser")
    public String addUser(String name, int age) {
        return userMapper.addUser(name, age) > 0 ? "success" : "fail";
    }

    /**
     * 調用Order數據庫
     *
     * @param order_no
     * @return
     */
    @RequestMapping("/addOrder")
    public String addOrder(String order_no) {
        return orderMapper.addOrder(order_no) > 0 ? "success" : "fail";
    }
}

springboot啓動代碼

package com.xyt.springboot;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.xyt.springboot.mapper")
public class AppSpringBootMybatis {
    public static void main(String[] args) {
        SpringApplication.run(AppSpringBootMybatis.class, args);
    }
}

 

發佈了31 篇原創文章 · 獲贊 1 · 訪問量 6531
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章