SpringBoot+MyBatisPlus+Druid从单数据源到多数据源动态切换1-单数据源

系列文章

1. SpringBoot+MyBatisPlus+Druid从单数据源到多数据源动态切换1-单数据源

2. SpringBoot+MyBatisPlus+Druid从单数据源到多数据源动态切换2-基于AbstractRoutingDataSource实现多数据源

3. SpringBoot+MyBatisPlus+Druid从单数据源到多数据源动态切换3-基于dynamic-datasource实现多数据源 


1.简介

MyBatis-Plus (简称 MP)是一个 MyBatis的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

2.引入依赖

<!--mybatis-plus mybatis增强工具 -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>${mybatis-plus-boot-starter.version}</version>
</dependency>

 3. 在application.yml中添加配置

mybatis-plus:
  #MyBatis Mapper 所对应的 XML 文件位置,Maven 多模块项目的扫描路径需以 classpath*: 开头 (即加载多个 jar 包下的 XML 文件)
  mapper-locations: classpath:mapper/**/*Mapper.xml
  configuration:
    #在控制台打印SQL日志
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  global-config:
    db-config:
      field-strategy: NOT_NULL
      id-type: auto #全局默认主键类型,设置后,即可省略实体对象中的@TableId(type = IdType.AUTO)配置
      db-type: mysql
    banner: false #是否控制台 print mybatis-plus 的 LOGO

4.使用

entity

@Data
@Accessors(chain = true)
@TableName("tb_user")
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    @TableField("name")
    private String name;

    @TableField("age")
    private Integer age;
    
}

mapper:继承com.baomidou.mybatisplus.core.mapper.BaseMapper<T>

@Mapper
public interface UserMapper extends BaseMapper<User> {

}
<?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="com.doit.mapper.UserMapper">

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.doit.entity.User">
        <id column="id" property="id" />
        <result column="name" property="name" />
        <result column="age" property="age" />
    </resultMap>

    <!-- 通用查询结果列 -->
    <sql id="Base_Column_List">
        id, name, age
    </sql>

</mapper>

service:继承com.baomidou.mybatisplus.extension.service.IService<T>

public interface UserService extends IService<User> {

}

 serviceImpl:继承com.baomidou.mybatisplus.extension.service.impl.ServiceImpl<XXMapper,T>

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

}

controller

@RestController
@RequestMapping("/user")
public class UserController extends BaseController{
    @Autowired
    private UserService userService;

    @GetMapping("/list")
    public TableDataInfo list(){
        List<User> list = userService.list();
        return getDataTable(list);
    }

}

BaseController:自定义Controller基类,提供一些响应封装方法

public class BaseController
{
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());



    /**
     * 响应请求分页数据
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    protected TableDataInfo getDataTable(List<?> list)
    {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }

    /**
     * 返回成功
     */
    public AjaxResult success()
    {
        return AjaxResult.success();
    }

    /**
     * 返回失败消息
     */
    public AjaxResult error()
    {
        return AjaxResult.error();
    }

    /**
     * 返回成功消息
     */
    public AjaxResult success(String message)
    {
        return AjaxResult.success(message);
    }

    /**
     * 返回失败消息
     */
    public AjaxResult error(String message)
    {
        return AjaxResult.error(message);
    }

    /**
     * 响应返回结果
     * 
     * @param rows 影响行数
     * @return 操作结果
     */
    protected AjaxResult toAjax(int rows)
    {
        return rows > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 响应返回结果
     * 
     * @param result 结果
     * @return 操作结果
     */
    protected AjaxResult toAjax(boolean result)
    {
        return result ? success() : error();
    }

}

二、Druid是什么

1.简介

Druid是Java语言中最好的数据库连接池。Druid能够提供强大的监控和扩展功能。

2.引入依赖

<!-- 阿里数据库连接池 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>${druid.version}</version>
</dependency>

 3. 在application.yml中添加配置(单数据源)

# 单数据源配置
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://localhost:3306/db-master?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
    username: root
    password: root
    druid:
      # 初始连接数
      initialSize: 5
      # 最小连接池数量
      minIdle: 10
      # 最大连接池数量
      maxActive: 20
      # 配置获取连接等待超时的时间
      maxWait: 60000
      # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
      timeBetweenEvictionRunsMillis: 60000
      # 配置一个连接在池中最小生存的时间,单位是毫秒
      minEvictableIdleTimeMillis: 300000
      # 配置一个连接在池中最大生存的时间,单位是毫秒
      maxEvictableIdleTimeMillis: 900000
      # 配置检测连接是否有效
      validationQuery: SELECT 1 FROM DUAL
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      # 用于采集web-jdbc关联监控的数据
      webStatFilter:
        enabled: true
      # 用于展示Druid的统计信息(提供监控信息展示的html页面+提供监控信息的JSON Api)
      statViewServlet:
        enabled: true
        # 设置ip白名单(逗号隔开),不填则允许所有访问
        allow:
        # ip黑名单(优先于allow)
        deny:
        # 监控页面的url
        url-pattern: /druid/*
        # 控制台管理用户名和密码
        login-username: ruoyi
        login-password: 123456
      filter:
        # 用于统计监控信息
        stat:
          enabled: true
          # 慢SQL记录
          log-slow-sql: true
          # 慢sql标准,单位毫秒
          slow-sql-millis: 1000
          # 合并sql
          merge-sql: true
        wall:
          config:
            # 是否允许一次执行多条语句,默认关闭
            multi-statement-allow: true

 三、启动测试

1.项目端口上下文路径配置

server:
  port: 9999
  servlet:
    context-path: /single-datasource-demo

2.启动类

@SpringBootApplication
public class SingleDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(SingleDemoApplication.class, args);
    }
}

3.启动项目,使用测试工具insomnia访问接口

 控制台打印出sql语句:


 数据库连接访问成功,接口测试成功。

4.访问Druid监控页面

 使用statViewServlet下配置的login-username和login-password登录可以看到上面的页面,成功。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值