SpringBoot2.0整合Sharding-Jdbc
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的更多相关文章
- 第二篇:SpringBoot2.0整合ActiveMQ
本篇开始将具体介绍SpringBoot如何整合其它项目. 如何创建SpringBoot项目 访问https://start.spring.io/. 依次选择构建工具Maven Project.语言ja ...
- SpringBoot2.0 整合 QuartJob ,实现定时器实时管理
一.QuartJob简介 1.一句话描述 Quartz是一个完全由java编写的开源作业调度框架,形式简易,功能强大. 2.核心API (1).Scheduler 代表一个 Quartz 的独立运行容 ...
- SpringBoot2.0 整合 Swagger2 ,构建接口管理界面
一.Swagger2简介 1.Swagger2优点 整合到Spring Boot中,构建强大RESTful API文档.省去接口文档管理工作,修改代码,自动更新,Swagger2也提供了强大的页面测试 ...
- SpringBoot2.0 整合 Dubbo框架 ,实现RPC服务远程调用
一.Dubbo框架简介 1.框架依赖 图例说明: 1)图中小方块 Protocol, Cluster, Proxy, Service, Container, Registry, Monitor 代表层 ...
- SpringBoot2.0 整合 Redis集群 ,实现消息队列场景
本文源码:GitHub·点这里 || GitEE·点这里 一.Redis集群简介 1.RedisCluster概念 Redis的分布式解决方案,在3.0版本后推出的方案,有效地解决了Redis分布式的 ...
- springboot2.0整合logback日志(详细)
<div class="post"> <h1 class="postTitle"> springboot2.0整合logback日志(详 ...
- SpringBoot2.0应用(三):SpringBoot2.0整合RabbitMQ
如何整合RabbitMQ 1.添加spring-boot-starter-amqp <dependency> <groupId>org.springframework.boot ...
- SpringBoot2.0整合fastjson的正确姿势
SpringBoot2.0如何集成fastjson?在网上查了一堆资料,但是各文章的说法不一,有些还是错的,可能只是简单测试一下就认为ok了,最后有没生效都不知道.恰逢公司项目需要将J ...
- Activiti工作流框架学习笔记(二)之springboot2.0整合工作流Activiti6.0
以前在工作当中做过不少与工作流Activiti有关的工作,当时都是spring集成activiti5.22的项目,现在回过头去看,其实版本已经稍微老了,因此,基于先前的工作经验,决定用较新版本的技术来 ...
随机推荐
- poj2046
Gap Time Limit: 5000MS Memory Limit: 65536K Total Submissions: 1829 Accepted: 829 Description Le ...
- 170214、mybatis一级和二级缓存
mybatis一级缓存是指在内存中开辟一块区域,用来保存用户对数据库的操作信息(sql)和数据库返回的数据,如果下一次用户再执行相同的请求, 那么直接从内存中读数数据而不是从数据库读取. 其中数据的生 ...
- Android Download机制详解(一)DocumentUI部分
在Android中Google为我们集成了一套十分便利的Download机制,用来下载网络上的资源文件.以此省去了我们编写和维护大量与Download相关的代码. 组成 Android中Downloa ...
- FineReport----查询功能 的知识点
1.设置日期控件,默认当前日期 2.默认不查询 选择参数:点击查询前不显示报表内容
- 【转】windows 下 goprotobuf 的安装与使用
1. 安装 在网上看了很多教程,都提到要安装 protoc 与 protoc-gen-go,但通过尝试之后并不能正确安装 protoc,一下记录能够顺利安装 protoc 与 protoc-gen-g ...
- table width 决定 td width
w td width 有无在chrome edge ff 均未影响td实际宽度,td接近等比分配table width. <!doctype html> <html lang=&qu ...
- Taylor's theorem
w https://en.wikipedia.org/wiki/Taylor_series
- dev grid 常用方法
绑定数据源 public void Data(){DataTable td = new DataTable();DataRow row = td.NewRow();foreach (GridColum ...
- Linux内核设计与实现——内核同步
内核同步 同步介绍 同步的概念 临界区:也称为临界段,就是訪问和操作共享数据的代码段. 竞争条件: 2个或2个以上线程在临界区里同一时候运行的时候,就构成了竞争条件. 所谓同步.事实上防止在临界区中形 ...
- Python3+Selenium3自动化测试-(三)
selenium键盘事件 #coding=utf-8 from selenium import webdriver import time from selenium.webdriver.common ...