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的项目,现在回过头去看,其实版本已经稍微老了,因此,基于先前的工作经验,决定用较新版本的技术来 ...
随机推荐
- hdu1814(2-SAT)
2-SAT 求出可能的解,但是这个解要是字典序最小的,所以只能采用2-SAT基本思想来解. 从小到大开始,对一个可能的点染色,染为1,然后dfs其所有能到达的点,如果其中出现一个已经标号为-1的话,那 ...
- 推荐一个CSS类库
animate.css 一个封装好的动画效果类
- JAVA 集合相关整理和学习
一.Set接口实现类 二.List接口实现类 三.Queue接口实现类 四.Map接口实现类 五.上面的图片截自附件: 附件列表
- 转!!关于java类初始化顺序
原文地址:http://www.cnblogs.com/luckygxf/p/4796955.html 1.没有继承 静态变量->静态初始化块->变量->变量初始化块->构造方 ...
- 在VMW里安装Ghost操作系统遇到的问题及解决的办法
条件:Ghost系列系统镜像文件 遇到的问题:1.导入镜像文件时提示“无法检测此光盘映像中的操作系统”: 2.分区时提示“ezboot kernel not found” 解决办法:1.直接先创建一个 ...
- Python爬虫之-Requests
Requests模块 Python标准库中提供了:urllib.urllib2.httplib等模块以供Http请求,但是,它的 API 太渣了. 它是为另一个时代.另一个互联网所创建的.它需要巨量的 ...
- 分别用request和socket给百多发送请求
1.方式1 import socket client = socket.socket() # 百度创建连接: 阻塞 client.connect(('www.baidu.com',80)) # 问百度 ...
- Linux上free命令的输出及其他
一.明确概念 A buffer is something that has yet to be "written" to disk. A cache is something t ...
- Keras网络层之卷积层
卷积层 Cov1D层 keras.layers.convolutional.Conv1D(filters, kernel_size, strides=1, padding='valid', dilat ...
- (4.3)ODBC/OLE DB/ADO概念与使用情况
一.ODBC ODBC的由来 1992年Microsoft和Sybase.Digital共同制定了ODBC标准接口,以单一的ODBC API来存取各种不同的数据库.随后ODBC便获得了许多数据库厂 ...