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的项目,现在回过头去看,其实版本已经稍微老了,因此,基于先前的工作经验,决定用较新版本的技术来 ...
随机推荐
- Manacher模板,kmp,扩展kmp,最小表示法模板
*N]; //储存临时串 *N];//中间记录 int Manacher(char tmp[]) { int len=strlen(tmp); ; ;i<len;i++) { s[cnt++]= ...
- 网络虚拟化之FlowVisor:网络虚拟层(上)
概念解释:切片:虚拟网络的一个实例 一. 网络虚拟化(虚拟网络) 人类社会的发展在很大方面得益于自然界,飞机受益于鸟,雷达受益于蝙蝠等等,所以专门有个学科为仿生学就是研究和模仿生物的特殊本质,利用生物 ...
- java的奇技淫巧--意外行为与特性(译文)
Java是一种非常成熟的编程语言 - 事实上,它已经走过21年了,如果它是一个人,它可以在美国随便混!随着年龄的增长,智慧也在增长,而至少有时候,有些东西会变得很怪异.在本文中,我将介绍Java语言的 ...
- 02、微信小程序的数据绑定
02.微信小程序的数据绑定 目录结构: 模板内容: 使用bindtap绑定事件 <!--index.wxml--> <view class="container" ...
- jQuery获取textarea中的文本
今天出了一个bug,用$("#textareaid").text()获取textarea中的信息在IE下没问题,在火狐中居然获取不到信息,经过查阅资料才发现,应该用$(" ...
- 使用synergyc共享键鼠
通常情况下我们经常同时操作两台或者多台电脑, 这样就会存在多个键盘鼠标来回切换的问题. 那么我们主要的目标就是怎么在多个电脑上共享一套键盘鼠标,而且可以轻松的来回切换呢. 网上有很多的解决方案,这里我 ...
- [转载]js复制内容加版权声明代码
转自:https://www.cnblogs.com/zdz8207/p/js-oncopy.html var ua = navigator.userAgent.toLowerCase(); if( ...
- 解决 apt-get the following packages has unmet dependencies 问题
安装vpn遇到以下问题: 显示flinux print util和openconnect存在依赖库的冲突 此时尝试安装新的tk.vpnc-scripts.libopenconnect5,尝试apt-g ...
- 我的Android进阶之旅------>解决:debug-stripped.ap_' specified for property 'resourceFile' does not exist.
1.错误描述 更新Android Studio到2.0版本后,出现了编译失败的问题,我clean project然后重新编译还是出现抑郁的问题,问题具体描述如下所示: Error:A problem ...
- pandas数据分析第二天
一:汇总和计算描述统计 pandas对象拥有一组常用的数据和统计方法,用于从Series中提取单个值(sum,mean)或者从DataFrame的行或者列中提取一个Series对应的Numpy数组方法 ...