maven:

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0-beta</version>
</dependency>
<dependency>
<groupId>io.shardingjdbc</groupId>
<artifactId>sharding-jdbc-core</artifactId>
<version>2.0.3</version>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins> </build>

yml:

mybatis-plus:
# mapper-locations: classpath*:/mapper/*.xml
global-config:
db-config:
column-underline: true
#shardingjdbc配置
sharding:
jdbc:
data-sources:
###配置第一个从数据库 名称随便起
ds_slave_0:
password: root
jdbc-url: jdbc:mysql://192.168.91.9:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true
driver-class-name: com.mysql.jdbc.Driver
username: root
###主数据库配置 名称随便起
ds_master:
password: root
jdbc-url: jdbc:mysql://192.168.91.8:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true
driver-class-name: com.mysql.jdbc.Driver
username: root
###配置读写分离
master-slave-rule:
###配置从库选择策略,提供轮询与随机,这里选择用轮询 如果从做了集群 查询时候做轮训查询
load-balance-algorithm-type: round_robin
####指定从数据库 如果多个从 用逗号隔开
slave-data-source-names: ds_slave_0
name: ds_ms
####指定主数据库
master-data-source-name: ds_master

config配置:

import java.sql.SQLException;
import java.util.Map; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import com.google.common.collect.Maps; import io.shardingjdbc.core.api.MasterSlaveDataSourceFactory;
import lombok.extern.log4j.Log4j2; @Configuration
@EnableConfigurationProperties(ShardingMasterSlaveConfig.class)
@Log4j2
// 读取ds_master主数据源和读写分离配置
@ConditionalOnProperty({ "sharding.jdbc.data-sources.ds_master.jdbc-url",
"sharding.jdbc.master-slave-rule.master-data-source-name" })
public class ShardingDataSourceConfig { @Autowired
private ShardingMasterSlaveConfig shardingMasterSlaveConfig; @Bean
public DataSource masterSlaveDataSource() throws SQLException {
final Map<String, DataSource> dataSourceMap = Maps.newHashMap();
dataSourceMap.putAll(shardingMasterSlaveConfig.getDataSources());
final Map<String, Object> newHashMap = Maps.newHashMap();
// 创建 MasterSlave数据源
DataSource dataSource = MasterSlaveDataSourceFactory.createDataSource(dataSourceMap,
shardingMasterSlaveConfig.getMasterSlaveRule(), newHashMap);
log.info("masterSlaveDataSource config complete");
return dataSource;
} }
import java.util.HashMap;
import java.util.Map; import org.springframework.boot.context.properties.ConfigurationProperties; import com.zaxxer.hikari.HikariDataSource; import io.shardingjdbc.core.api.config.MasterSlaveRuleConfiguration;
import lombok.Data; @Data //表示读取本底配置文件 前缀sharding.jdbc
@ConfigurationProperties(prefix = "sharding.jdbc")
public class ShardingMasterSlaveConfig { // 存放本地多个数据源 最终放在map集合中 key为yml配置的 ds_slave_0
private Map<String, HikariDataSource> dataSources = new HashMap<>(); private MasterSlaveRuleConfiguration masterSlaveRule;
}

上面为核心代码

下面是辅助的:

Controller:

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import com.mayikt.entity.UserEntity;
import com.mayikt.service.UserService; @RestController
public class UserController { @Autowired
private UserService userService; @RequestMapping("/findUser")
public List<UserEntity> findUser() {
return userService.findUser();
} @RequestMapping("/insertUser")
public String insertUser(String userName) {
return userService.insertUser(userName) > 0 ? "success" : "fail";
} }

entity:

public class UserEntity {

    private String userName;

    public String getUserName() {
return userName;
} public void setUserName(String userName) {
this.userName = userName;
} }

service:

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import com.mayikt.entity.UserEntity;
import com.mayikt.mapper.UserMapper; @Service
public class UserService {
@Autowired
private UserMapper userMapper; // 使用读的数据源
public List<UserEntity> findUser() {
return userMapper.findUser();
} // 使用写的数据源
public int insertUser(String userName) {
return userMapper.insertUser(userName);
} }

mapper:

import java.util.List;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select; import com.mayikt.entity.UserEntity; public interface UserMapper {
@Select("SELECT * FROM user_info ")
public List<UserEntity> findUser(); @Insert("insert into user_info values (#{userName}); ")
public int insertUser(@Param("userName") String userName);
}

启动类:

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
@MapperScan("com.toov5.mapper")
public class AppMbatis {
public static void main(String[] args) { SpringApplication.run(AppMbatis.class, args);
}
}

SpringBoot2.0整合Sharding-Jdbc的更多相关文章

  1. 第二篇:SpringBoot2.0整合ActiveMQ

    本篇开始将具体介绍SpringBoot如何整合其它项目. 如何创建SpringBoot项目 访问https://start.spring.io/. 依次选择构建工具Maven Project.语言ja ...

  2. SpringBoot2.0 整合 QuartJob ,实现定时器实时管理

    一.QuartJob简介 1.一句话描述 Quartz是一个完全由java编写的开源作业调度框架,形式简易,功能强大. 2.核心API (1).Scheduler 代表一个 Quartz 的独立运行容 ...

  3. SpringBoot2.0 整合 Swagger2 ,构建接口管理界面

    一.Swagger2简介 1.Swagger2优点 整合到Spring Boot中,构建强大RESTful API文档.省去接口文档管理工作,修改代码,自动更新,Swagger2也提供了强大的页面测试 ...

  4. SpringBoot2.0 整合 Dubbo框架 ,实现RPC服务远程调用

    一.Dubbo框架简介 1.框架依赖 图例说明: 1)图中小方块 Protocol, Cluster, Proxy, Service, Container, Registry, Monitor 代表层 ...

  5. SpringBoot2.0 整合 Redis集群 ,实现消息队列场景

    本文源码:GitHub·点这里 || GitEE·点这里 一.Redis集群简介 1.RedisCluster概念 Redis的分布式解决方案,在3.0版本后推出的方案,有效地解决了Redis分布式的 ...

  6. springboot2.0整合logback日志(详细)

    <div class="post"> <h1 class="postTitle"> springboot2.0整合logback日志(详 ...

  7. SpringBoot2.0应用(三):SpringBoot2.0整合RabbitMQ

    如何整合RabbitMQ 1.添加spring-boot-starter-amqp <dependency> <groupId>org.springframework.boot ...

  8. SpringBoot2.0整合fastjson的正确姿势

            SpringBoot2.0如何集成fastjson?在网上查了一堆资料,但是各文章的说法不一,有些还是错的,可能只是简单测试一下就认为ok了,最后有没生效都不知道.恰逢公司项目需要将J ...

  9. Activiti工作流框架学习笔记(二)之springboot2.0整合工作流Activiti6.0

    以前在工作当中做过不少与工作流Activiti有关的工作,当时都是spring集成activiti5.22的项目,现在回过头去看,其实版本已经稍微老了,因此,基于先前的工作经验,决定用较新版本的技术来 ...

随机推荐

  1. SQL系统函数——系统信息

    1.查看信息1.1.查看编号和名称select @@SERVERNAME--SQL SERVER服务器的连接字符串,如:computername\instancenameselect @@SERVIC ...

  2. oracle的row_number() OVER (ORDER BY COL2 asc)和row_number() OVER (PARTITION BY COL1 ORDER BY COL2)的用法

    转自:https://jingyan.baidu.com/article/9989c74604a644f648ecfef3.html SELECT ROW_NUMBER() OVER(PARTITIO ...

  3. css3动画效果:2 简易动画

    1. transition动画:鼠标移上去  旋转放大 关键点--  :hover  \ transform: scale(*)  rotate(*deg) cards 2.关键帧动画: 位移动画 t ...

  4. 【Python之路】第二十四篇--爬虫

    网络爬虫(又被称为网页蜘蛛,网络机器人,在FOAF社区中间,更经常的称为网页追逐者),是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本.另外一些不常使用的名字还有蚂蚁.自动索引.模拟程序或者蠕 ...

  5. mysql replace 使用注意,update的时候 删除从表数据

    使用REPLACE插入一条记录时,如果不重复,REPLACE就和INSERT的功能一样,如果有重复记录,REPLACE就使用新记录的值来替换原来的记录值. 使用REPLACE的最大好处就是可以将DEL ...

  6. Java 语言基础之数组应用

    什么时候使用数组呢? 如果数据出现了对应关系, 而且对应关系的一方是有序的数字编号, 并作为角标使用. 这时,就必须要想到数组的使用. 也就是将这些数据存储到数组中, 根据运算的结果作为角标, 直接去 ...

  7. Mysql实现企业级日志管理、备份与恢复

    数据备份形式 文件备份: 通过Linux的备份命令把文件统一打个包存起来,可存在本地和远程服务器,等到要恢复时,再用这些文件恢复到指定位置. 数据库数据备份: 在一些对数据可靠性要求很高的行业如银行. ...

  8. 基本数据类型补充、set集合、深浅拷贝

    一.基本数据类型补充 1,关于int和str在之前的学习中已经介绍了80%以上了,现在再补充一个字符串的基本操作 str.join(可迭代对象): li = ['李嘉诚','何炅','海峰','刘嘉玲 ...

  9. 代码艺术 CountDownTimer

    /** * Schedule a countdown until a time in the future, with regular notifications on intervals along ...

  10. redis的安装与配置(一)

    1. 介绍 Redis is an open source (BSD licensed), in-memory data structure store, used as database, cach ...