SpringBoot学习之SpringBoot动态切换数据源

新建实体类User

package org.hx.springboot_dynamic_demo29.model;

public class User {
    private Integer id;
    private String username;


    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}

新建UserMapper接口和UserMapper.xml文件

package org.hx.springboot_dynamic_demo29.mapper;

import org.apache.ibatis.annotations.Mapper;
import org.hx.springboot_dynamic_demo29.model.User;

import java.util.List;
@Mapper
public interface UserMapper {
    Integer addUser(User user);
    List<User> getAllUsers();
}

<?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="org.hx.springboot_dynamic_demo29.mapper.UserMapper">
    <insert id="addUser">
        insert into user (username) values (#{username});
    </insert>
    <select id="getAllUsers" resultType="org.hx.springboot_dynamic_demo29.model.User">
        select * from user;
    </select>
</mapper>

新建UserService类

package org.hx.springboot_dynamic_demo29.service;

import com.baomidou.dynamic.datasource.annotation.DS;
import org.hx.springboot_dynamic_demo29.mapper.UserMapper;
import org.hx.springboot_dynamic_demo29.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {
    @Autowired
    UserMapper userMapper;
    @DS("master")
    public Integer addUser(User user){
        return userMapper.addUser(user);
    }
    @DS("slave")
    public List<User> getAllUsers(){
        return userMapper.getAllUsers();
    }
}

在pom.xml中配置扫描xml文件

  <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
</resources>

在resources目录下新建application.yaml文件

spring:
  datasource:
    dynamic:
      primary: master #设置默认的数据源或者数据源组,默认值即为master
      strict: false #设置严格模式,默认false不启动. 启动后在未匹配到指定数据源时候会抛出异常,不启动则使用默认数据源
      datasource:
        master:
          url: jdbc:mysql://192.168.133.8:33061/hxdb
          username: root
          password: 123
          driver-class-name: com.mysql.jdbc.Driver
        slave:
          url: jdbc:mysql://192.168.133.8:33062/hxdb
          username: root
          password: 123
          driver-class-name: com.mysql.jdbc.Driver

在测试类中进行测试

package org.hx.springboot_dynamic_demo29;

import org.hx.springboot_dynamic_demo29.model.User;
import org.hx.springboot_dynamic_demo29.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
class SpringbootDynamicDemo29ApplicationTests {

    @Autowired
    UserService userService;
    @Test
    void contextLoads() {
        User user = new User();
        user.setUsername("zhangsan");
        userService.addUser(user);
    }
    @Test
    void test(){
        List<User> userList = userService.getAllUsers();
        System.out.println("UserList: "+userList);
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Springboot中使用MongoDB多数据源动态切换,可以通过以下步骤实现: 1. 添加MongoDB的依赖 在pom.xml文件中加入对spring-boot-starter-data-mongodb和mongodb-driver的依赖。 2. 配置多数据源 在application.yml或application.properties中配置多个数据源,如下所示: ``` spring: data: mongodb: uri: mongodb://localhost:27017/test1 database: test1 seconddata: mongodb: uri: mongodb://localhost:27017/test2 database: test2 ``` 其中第一个数据源是默认的数据源,第二个数据源是自定义的数据源。 3. 配置数据源切换组件 在Springboot中使用MongoDB多数据源需要使用MongoDbFactory和MongoTemplate两个组件。我们可以通过自定义MongoTemplate的方式来实现数据源切换。具体实现可以参考以下代码: ```java @Configuration public class MultipleMongoConfig { @Bean(name = "firstMongoTemplate") @Primary public MongoTemplate firstMongoTemplate() throws Exception { return new MongoTemplate(firstFactory()); } @Bean(name = "secondMongoTemplate") public MongoTemplate secondMongoTemplate() throws Exception { return new MongoTemplate(secondFactory()); } @Bean @Primary public MongoDbFactory firstFactory() throws Exception { return new SimpleMongoDbFactory(new MongoClientURI( env.getProperty("spring.data.mongodb.uri"))); } @Bean public MongoDbFactory secondFactory() throws Exception { return new SimpleMongoDbFactory(new MongoClientURI( env.getProperty("seconddata.mongodb.uri"))); } } ``` 4. 动态切换数据源 在需要切换数据源的地方,可以通过注入MongoTemplate来实现。具体实现可以参考以下代码: ```java @Service public class UserServiceImpl implements UserService { @Autowired @Qualifier("firstMongoTemplate") private MongoTemplate firstMongoTemplate; @Autowired @Qualifier("secondMongoTemplate") private MongoTemplate secondMongoTemplate; public void save(User user) { if (user.isUseSecondDataSource()) { secondMongoTemplate.save(user); } else { firstMongoTemplate.save(user); } } public User findById(String id, boolean useSecondDataSource) { if (useSecondDataSource) { return secondMongoTemplate.findById(id, User.class); } else { return firstMongoTemplate.findById(id, User.class); } } } ``` 在上面的示例中,我们可以通过isUseSecondDataSource()方法来判断是否需要使用第二个数据源。如果需要使用第二个数据源,则使用secondMongoTemplate;否则使用firstMongoTemplate。 以上就是在Springboot中使用MongoDB多数据源动态切换的全部步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值