溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

springboot配置多數(shù)據(jù)源框架的示例分析

發(fā)布時(shí)間:2021-09-10 15:45:08 來源:億速云 閱讀:169 作者:柒染 欄目:開發(fā)技術(shù)

本篇文章為大家展示了springboot配置多數(shù)據(jù)源框架(dynamic-datasource-spring-boot-starter),內(nèi)容簡明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。

框架簡介

dynamic-datasource-spring-boot-starter 是一個(gè)基于 springboot 的快速集成多數(shù)據(jù)源的啟動(dòng)器

 框架說明

  • 本框架只做 切換數(shù)據(jù)源 這件核心的事情,并不限制你的具體操作,切換了數(shù)據(jù)源可以做任何 CRUD

  • 配置文件所有以下劃線 _ 分割的數(shù)據(jù)源 首部 即為組的名稱,相同組名稱的數(shù)據(jù)源會(huì)放在一個(gè)組下

  • 切換數(shù)據(jù)源可以是組名,也可以是具體數(shù)據(jù)源名稱。組名則切換時(shí)采用負(fù)載均衡算法切換

  • 默認(rèn)的數(shù)據(jù)源名稱為 master ,你可以通過 spring.datasource.dynamic.primary 修改

  • 方法上的注解優(yōu)先于類上注解

  • DS 支持繼承抽象類上的 DS,暫不支持繼承接口上的 DS

與 springboot 的整合

數(shù)據(jù)準(zhǔn)備
  •  springboot 版本:2.0.6.RELEASE

  • mysql 版本:5.7

分別創(chuàng)建數(shù)據(jù)庫 test1,test2,數(shù)據(jù)庫表均為 goods,數(shù)據(jù)不相同

CREATE TABLE `goods` (
  `goodsId` bigint(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
  `goodsName` varchar(500) NOT NULL DEFAULT '' COMMENT 'name',
  `subject` varchar(200) NOT NULL DEFAULT '' COMMENT '標(biāo)題',
  `price` decimal(15,2) NOT NULL DEFAULT '0.00' COMMENT '價(jià)格',
  `stock` int(11) NOT NULL DEFAULT '0' COMMENT 'stock',
  PRIMARY KEY (`goodsId`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COMMENT='商品表';

test1 數(shù)據(jù)庫數(shù)據(jù)如下

springboot配置多數(shù)據(jù)源框架的示例分析

test2 數(shù)據(jù)庫數(shù)據(jù)如下

springboot配置多數(shù)據(jù)源框架的示例分析

引入依賴

至于其他依賴,不再贅述

<dependency>
	<groupId>com.baomidou</groupId>
	<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
	<version>3.3.2</version>
</dependency>
springboot 配置文件

配置文件詳情可以參考官方文檔

server.port=8080

#設(shè)置test1為主數(shù)據(jù)源
spring.datasource.dynamic.primary=master
#test1主數(shù)據(jù)源配置
spring.datasource.dynamic.datasource.master.url=jdbc:mysql://127.0.0.1:3306/test1?characterEncoding=utf8&useSSL=false&autoReconnect=true&serverTimezone=UTC
spring.datasource.dynamic.datasource.master.username=root
spring.datasource.dynamic.datasource.master.password=123456
spring.datasource.dynamic.datasource.master.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.dynamic.datasource.master.type=com.alibaba.druid.pool.DruidDataSource
#druid連接池配置
spring.datasource.dynamic.datasource.master.druid.initial-size=5
spring.datasource.dynamic.datasource.master.druid.max-active=20
spring.datasource.dynamic.datasource.master.druid.min-idle=5
spring.datasource.dynamic.datasource.master.druid.max-wait=60000

#test2從數(shù)據(jù)源配置
spring.datasource.dynamic.datasource.slave.url=jdbc:mysql://127.0.0.1:3306/test2?characterEncoding=utf8&useSSL=false&autoReconnect=true&serverTimezone=UTC
spring.datasource.dynamic.datasource.slave.username=root
spring.datasource.dynamic.datasource.slave.password=123456
spring.datasource.dynamic.datasource.slave.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.dynamic.datasource.slave.type=com.alibaba.druid.pool.DruidDataSource
#druid連接池配置
spring.datasource.dynamic.datasource.slave.druid.initial-size=5
spring.datasource.dynamic.datasource.slave.druid.max-active=20
spring.datasource.dynamic.datasource.slave.druid.min-idle=5
spring.datasource.dynamic.datasource.slave.druid.max-wait=60000

#mybatis配置
mybatis.mapper-locations=classpath:org/example/mapper/*.xml
mybatis.configuration.cache-enabled=true
#開啟駝峰命名
mybatis.configuration.map-underscore-to-camel-case=true
#打印SQL
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

啟動(dòng)類

需要排除掉 DruidDataSourceAutoConfigure 類,不然啟動(dòng)會(huì)報(bào)錯(cuò)找不到配置的 url

@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class)
@Slf4j
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
        log.info("------springboot running-----");
    }
}

實(shí)體類

@Data
@ApiModel
public class Goods implements Serializable {

    @ApiModelProperty(value = "商品id")
    private Long goodsid;

    @ApiModelProperty(value = "商品名稱")
    @NotBlank(message = "商品名稱不能為空")
    private String goodsname;

    @ApiModelProperty(value = "商品描述")
    @NotBlank(message = "商品描述不能為空")
    private String subject;

    @ApiModelProperty(value = "商品價(jià)格")
    @NotNull(message = "商品價(jià)格不能為空")
    private BigDecimal price;

    @ApiModelProperty(value = "商品庫存", example = "0")
    @NotNull(message = "商品庫存不能為空")
    private Integer stock;
}

service

至于 dao 層,使用的是 mybatis-generator 插件自動(dòng)生成

@Service
public class GoodServiceImpl implements GoodService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    public Goods selectOneGoods(Long goodsid) {
        return goodsMapper.selectByPrimaryKey(goodsid);
    }

    @Override
    public int addGoods(Goods goods) {
        return goodsMapper.insertSelective(goods);
    }
}

controller

@Controller
@RequestMapping(path = "/goods")
@Api(tags = "商品管理相關(guān)接口")
@Slf4j
public class GoodsController {

    @Autowired
    private GoodService goodService;

    @GetMapping(path = "/selectOne")
    @ResponseBody
    @ApiOperation(value = "查詢商品接口")
    @ApiImplicitParam(name = "id", value = "商品id", required = true)
    public ResultMap selectOne(@RequestParam(name = "id", defaultValue = "3") Long goodsid) {
        Goods goods = goodService.selectOneGoods(goodsid);
        log.info("查詢到的商品數(shù)據(jù):" + goods.toString());
        if (StringUtils.isEmpty(goods)) {
            return new ResultMap().fail().message("查詢失敗,沒有您要的數(shù)據(jù)");
        }
        return new ResultMap().success().message("查詢成功").data(goods);
    }

    @PostMapping(path = "/addGoods")
    @ResponseBody
    @ApiOperation(value = "添加商品的接口")
    public ResultMap addGoods(@Valid Goods goods, @NotNull BindingResult bindingResult) {
        if (bindingResult.hasErrors()){
            String defaultMessage = Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage();
            return new ResultMap().fail().message(defaultMessage);
        }
        int i = goodService.addGoods(goods);
        if (i > 0) {
            return new ResultMap().success().message("添加成功");
        }
        return new ResultMap().fail().message("添加失敗");
    }
}

測試 service 層方法上都沒有注解 @DS

使用 postman 測試第一個(gè)接口

springboot配置多數(shù)據(jù)源框架的示例分析

使用 postman 測試第二個(gè)接口

springboot配置多數(shù)據(jù)源框架的示例分析
springboot配置多數(shù)據(jù)源框架的示例分析

以上兩個(gè)接口測試說明:它們都默認(rèn)操作的是主數(shù)據(jù)源 test1,證明我們配置文件中配置的主數(shù)據(jù)源 test1 是配置正確的,已經(jīng)生效

service 層方法上加上注解 @DS 再測試

@Service
public class GoodServiceImpl implements GoodService {

    @Autowired
    private GoodsMapper goodsMapper;

    @DS(value = "slave")// 切換數(shù)據(jù)源,并指定要訪問的數(shù)據(jù)庫名稱
    @Override
    public Goods selectOneGoods(Long goodsid) {
        return goodsMapper.selectByPrimaryKey(goodsid);
    }

    @Override
    public int addGoods(Goods goods) {
        return goodsMapper.insertSelective(goods);
    }
}

使用 postman 測試第一個(gè)接口

springboot配置多數(shù)據(jù)源框架的示例分析

此時(shí) @DS 注解已生效,發(fā)生了數(shù)據(jù)源的動(dòng)態(tài)切換

使用 postman 測試第二個(gè)接口

springboot配置多數(shù)據(jù)源框架的示例分析

springboot配置多數(shù)據(jù)源框架的示例分析

由于該接口沒有 @DS 注解,所以沒有發(fā)生數(shù)據(jù)源的切換,依然操作的是 test1 默認(rèn)數(shù)據(jù)源

@DS 注解說明

注解結(jié)果
沒有@DS默認(rèn)數(shù)據(jù)源
@DS("dsName")dsName可以為組名也可以為具體某個(gè)庫的名稱
  • @DS 可以注解在方法上或類上,同時(shí)存在就近原則 方法上注解 優(yōu)先于 類上注解

  • @DS 官方建議使用在 service 層的方法上

上述內(nèi)容就是springboot配置多數(shù)據(jù)源框架(dynamic-datasource-spring-boot-starter)的示例分析,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI