个人制作一个网站的费用,怎么样免费做自己的网站,合肥市建设工程市场信息价网站,邢台网站改版怎么开发#x1f339;作者主页#xff1a;青花锁 #x1f339;简介#xff1a;Java领域优质创作者#x1f3c6;、Java微服务架构公号作者#x1f604; #x1f339;简历模板、学习资料、面试题库、技术互助 #x1f339;文末获取联系方式 #x1f4dd; 系列专栏目录
[Java项… 作者主页青花锁 简介Java领域优质创作者、Java微服务架构公号作者 简历模板、学习资料、面试题库、技术互助 文末获取联系方式 系列专栏目录
[Java项目实战] 介绍Java组件安装、使用手写框架等 [Aws服务器实战] Aws Linux服务器上操作nginx、git、JDK、Vue等 [Java微服务实战] Java 微服务实战Spring Cloud Netflix套件、Spring Cloud Alibaba套件、Seata、gateway、shadingjdbc等实战操作 [Java基础篇] Java基础闲聊已出HashMap、String、StringBuffer等源码分析JVM分析持续更新中 [Springboot篇] 从创建Springboot项目到加载数据库、静态资源、输出RestFul接口、跨越问题解决到统一返回、全局异常处理、Swagger文档 [Spring MVC篇] 从创建Spring MVC项目到加载数据库、静态资源、输出RestFul接口、跨越问题解决到统一返回 [华为云服务器实战] 华为云Linux服务器上操作nginx、git、JDK、Vue等以及使用宝塔运维操作添加Html网页、部署Springboot项目/Vue项目等 [Java爬虫] 通过JavaSeleniumGoogleWebDriver 模拟真人网页操作爬取花瓣网图片、bing搜索图片等 [Vue实战] 讲解Vue3的安装、环境配置基本语法、循环语句、生命周期、路由设置、组件、axios交互、Element-ui的使用等 [Spring] 讲解Spring(Bean)概念、IOC、AOP、集成jdbcTemplate/redis/事务等 前言
Apache ShardingSphere 是一款分布式的数据库生态系统 可以将任意数据库转换为分布式数据库并通过数据分片、弹性伸缩、加密等能力对原有数据库进行增强。
Apache ShardingSphere 设计哲学为 Database Plus旨在构建异构数据库上层的标准和生态。 它关注如何充分合理地利用数据库的计算和存储能力而并非实现一个全新的数据库。 它站在数据库的上层视角关注它们之间的协作多于数据库自身。
1、ShardingSphere-JDBC
ShardingSphere-JDBC 定位为轻量级 Java 框架在 Java 的 JDBC 层提供的额外服务。
1.1、应用场景
Apache ShardingSphere-JDBC 可以通过Java 和 YAML 这 2 种方式进行配置开发者可根据场景选择适合的配置方式。
数据库读写分离数据库分表分库
1.2、原理
Sharding-JDBC中的路由结果是通过分片字段和分片方法来确定的,如果查询条件中有 id 字段的情况还好查询将会落到某个具体的分片如果查询没有分片的字段会向所有的db或者是表都会查询一遍让后封装结果集给客户端。
1.3、spring boot整合
1.3.1、添加依赖
!-- 分表分库依赖 --
dependencygroupIdorg.apache.shardingsphere/groupIdartifactIdsharding-jdbc-spring-boot-starter/artifactIdversion4.1.1/version
/dependency1.3.2、添加配置
spring:main:# 一个实体类对应多张表覆盖allow-bean-definition-overriding: trueshardingsphere:datasource:ds0:#配置数据源具体内容包含连接池驱动地址用户名和密码driver-class-name: com.mysql.cj.jdbc.Driverjdbc-url: jdbc:mysql://127.0.0.1:3306/account?autoReconnecttrueallowMultiQueriestruepassword: roottype: com.zaxxer.hikari.HikariDataSourceusername: rootds1:driver-class-name: com.mysql.cj.jdbc.Driverjdbc-url: jdbc:mysql://127.0.0.1:3306/account?autoReconnecttrueallowMultiQueriestruepassword: roottype: com.zaxxer.hikari.HikariDataSourceusername: root# 配置数据源给数据源起名称names: ds0,ds1props:sql:show: truesharding:tables:user_info:#指定 user_info 表分布情况配置表在哪个数据库里面表名称都是什么actual-data-nodes: ds0.user_info_${0..9}database-strategy:standard:preciseAlgorithmClassName: com.xxxx.store.account.config.PreciseDBShardingAlgorithmrangeAlgorithmClassName: com.xxxx.store.account.config.RangeDBShardingAlgorithmsharding-column: idtable-strategy:standard:preciseAlgorithmClassName: com.xxxx.store.account.config.PreciseTablesShardingAlgorithmrangeAlgorithmClassName: com.xxxx.store.account.config.RangeTablesShardingAlgorithmsharding-column: id1.3.3、制定分片算法
1.3.3.1、精确分库算法
/*** 精确分库算法*/
public class PreciseDBShardingAlgorithm implements PreciseShardingAlgorithmLong {/**** param availableTargetNames 配置所有的列表* param preciseShardingValue 分片值* return*/Overridepublic String doSharding(CollectionString availableTargetNames, PreciseShardingValueLong preciseShardingValue) {Long value preciseShardingValue.getValue();//后缀 01String postfix String.valueOf(value % 2);for (String availableTargetName : availableTargetNames) {if(availableTargetName.endsWith(postfix)){return availableTargetName;}}throw new UnsupportedOperationException();}}1.3.3.2、范围分库算法
/*** 范围分库算法*/
public class RangeDBShardingAlgorithm implements RangeShardingAlgorithmLong {Overridepublic CollectionString doSharding(CollectionString collection, RangeShardingValueLong rangeShardingValue) {return collection;}
}1.3.3.3、精确分表算法
/*** 精确分表算法*/
public class PreciseTablesShardingAlgorithm implements PreciseShardingAlgorithmLong {/**** param availableTargetNames 配置所有的列表* param preciseShardingValue 分片值* return*/Overridepublic String doSharding(CollectionString availableTargetNames, PreciseShardingValueLong preciseShardingValue) {Long value preciseShardingValue.getValue();//后缀String postfix String.valueOf(value % 10);for (String availableTargetName : availableTargetNames) {if(availableTargetName.endsWith(postfix)){return availableTargetName;}}throw new UnsupportedOperationException();}}1.3.3.4、范围分表算法
/*** 范围分表算法*/
public class RangeTablesShardingAlgorithm implements RangeShardingAlgorithmLong {Overridepublic CollectionString doSharding(CollectionString collection, RangeShardingValueLong rangeShardingValue) {CollectionString result new ArrayList();RangeLong valueRange rangeShardingValue.getValueRange();Long start valueRange.lowerEndpoint();Long end valueRange.upperEndpoint();Long min start % 10;Long max end % 10;for (Long i min; i max 1; i) {Long finalI i;collection.forEach(e - {if(e.endsWith(String.valueOf(finalI))){result.add(e);}});}return result;}}1.3.4、数据库建表
DROP TABLE IF EXISTS user_info_0;
CREATE TABLE user_info_0 (id bigint(20) NOT NULL,account varchar(255) DEFAULT NULL,user_name varchar(255) DEFAULT NULL,pwd varchar(255) DEFAULT NULL,PRIMARY KEY (id)
) ENGINEInnoDB DEFAULT CHARSETutf8;
1.3.5、业务应用
1.3.5.1、定义实体类
Data
TableName(value user_info)
public class UserInfo {/*** 主键*/private Long id;/*** 账号*/private String account;/*** 用户名*/private String userName;/*** 密码*/private String pwd;}1.3.5.2、定义接口
public interface UserInfoService{/*** 保存* param userInfo* return*/public UserInfo saveUserInfo(UserInfo userInfo);public UserInfo getUserInfoById(Long id);public ListUserInfo listUserInfo();
}
1.3.5.3、实现类
Service
public class UserInfoServiceImpl extends ServiceImplUserInfoMapper, UserInfo implements UserInfoService {OverrideTransactionalpublic UserInfo saveUserInfo(UserInfo userInfo) {userInfo.setId(IdUtils.getId());this.save(userInfo);return userInfo;}Overridepublic UserInfo getUserInfoById(Long id) {return this.getById(id);}Overridepublic ListUserInfo listUserInfo() {QueryWrapperUserInfo userInfoQueryWrapper new QueryWrapper();userInfoQueryWrapper.between(id,1623695688380448768L,1623695688380448769L);return this.list(userInfoQueryWrapper);}
}1.3.6、生成ID - 雪花算法
package com.xxxx.tore.common.utils;import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;/*** 生成各种组件ID*/
public class IdUtils {/*** 雪花算法* return*/public static long getId(){Snowflake snowflake IdUtil.getSnowflake(0, 0);long id snowflake.nextId();return id;}
}
1.4、seata与sharding-jdbc整合
https://github.com/seata/seata-samples/tree/master/springcloud-seata-sharding-jdbc-mybatis-plus-samples
1.4.1、common中添加依赖
!--seata依赖--
dependencygroupIdcom.alibaba.cloud/groupIdartifactIdspring-cloud-starter-alibaba-seata/artifactIdversion2021.0.4.0/version
/dependency
!-- sharding-jdbc整合seata分布式事务--
dependencygroupIdorg.apache.shardingsphere/groupIdartifactIdsharding-transaction-base-seata-at/artifactIdversion4.1.1/version
/dependencydependencygroupIdcom.alibaba.cloud/groupIdartifactIdspring-cloud-starter-alibaba-nacos-discovery/artifactIdversion2021.0.4.0/versionexclusionsexclusiongroupIdcom.alibaba.nacos/groupIdartifactIdnacos-client/artifactId/exclusion/exclusions
/dependency
dependencygroupIdcom.alibaba.nacos/groupIdartifactIdnacos-client/artifactIdversion1.4.2/version
/dependency1.4.2、改造account-service服务
Service
public class AccountServiceImpl extends ServiceImplAccountMapper, Account implements AccountService {Autowiredprivate OrderService orderService;Autowiredprivate StorageService storageService;/*** 存放商品编码及其对应的价钱*/private static MapString,Integer map new HashMap();static {map.put(c001,3);map.put(c002,5);map.put(c003,10);map.put(c004,6);}OverrideTransactionalShardingTransactionType(TransactionType.BASE)public void debit(OrderDTO orderDTO) {//扣减账户余额int calculate this.calculate(orderDTO.getCommodityCode(), orderDTO.getCount());AccountDTO accountDTO new AccountDTO(orderDTO.getUserId(), calculate);QueryWrapperAccount objectQueryWrapper new QueryWrapper();objectQueryWrapper.eq(id,1);objectQueryWrapper.eq(accountDTO.getUserId() ! null,user_id,accountDTO.getUserId());Account account this.getOne(objectQueryWrapper);account.setMoney(account.getMoney() - accountDTO.getMoney());this.saveOrUpdate(account);//扣减库存this.storageService.deduct(new StorageDTO(null,orderDTO.getCommodityCode(),orderDTO.getCount()));//生成订单this.orderService.create(orderDTO); }/*** 计算购买商品的总价钱* param commodityCode* param orderCount* return*/private int calculate(String commodityCode, int orderCount){//商品价钱Integer price map.get(commodityCode) null ? 0 : map.get(commodityCode);return price * orderCount;}
}注意调单生成调用的逻辑修改减余额-减库存-生成订单。调用入口方法注解加上ShardingTransactionType(TransactionType.BASE)
1.4.3、修改business-service服务
Service
public class BusinessServiceImpl implements BusinessService {Autowiredprivate OrderService orderService;Autowiredprivate StorageService storageService;Autowiredprivate AccountService accountService;Overridepublic void purchase(OrderDTO orderDTO) {//扣减账号中的钱accountService.debit(orderDTO); }
}1.4.4、修改order-service服务
Service
public class OrderServiceImpl extends ServiceImplOrderMapper,Order implements OrderService {/*** 存放商品编码及其对应的价钱*/private static MapString,Integer map new HashMap();static {map.put(c001,3);map.put(c002,5);map.put(c003,10);map.put(c004,6);}OverrideTransactionalShardingTransactionType(TransactionType.BASE)public Order create(String userId, String commodityCode, int orderCount) {int orderMoney calculate(commodityCode, orderCount);Order order new Order();order.setUserId(userId);order.setCommodityCode(commodityCode);order.setCount(orderCount);order.setMoney(orderMoney);//保存订单this.save(order);try {TimeUnit.SECONDS.sleep(30);} catch (InterruptedException e) {e.printStackTrace();}if(true){throw new RuntimeException(回滚测试);}return order;}/*** 计算购买商品的总价钱* param commodityCode* param orderCount* return*/private int calculate(String commodityCode, int orderCount){//商品价钱Integer price map.get(commodityCode) null ? 0 : map.get(commodityCode);return price * orderCount;}
}1.4.5、配置文件参考
server:port: 8090spring:main:# 一个实体类对应多张表覆盖allow-bean-definition-overriding: trueshardingsphere:datasource:ds0:#配置数据源具体内容包含连接池驱动地址用户名和密码driver-class-name: com.mysql.cj.jdbc.Driverjdbc-url: jdbc:mysql://127.0.0.1:3306/account?autoReconnecttrueallowMultiQueriestruepassword: roottype: com.zaxxer.hikari.HikariDataSourceusername: rootds1:driver-class-name: com.mysql.cj.jdbc.Driverjdbc-url: jdbc:mysql://127.0.0.1:3306/account?autoReconnecttrueallowMultiQueriestruepassword: roottype: com.zaxxer.hikari.HikariDataSourceusername: root# 配置数据源给数据源起名称names: ds0,ds1props:sql:show: truesharding:tables:account_tbl:actual-data-nodes: ds0.account_tbl_${0..1}database-strategy:standard:preciseAlgorithmClassName: com.xxxx.store.account.config.PreciseDBExtShardingAlgorithm#rangeAlgorithmClassName: com.xxxx.store.account.config.RangeDBShardingAlgorithmsharding-column: idtable-strategy:standard:preciseAlgorithmClassName: com.xxxx.store.account.config.PreciseTablesExtShardingAlgorithm#rangeAlgorithmClassName: com.xxxx.store.account.config.RangeTablesShardingAlgorithmsharding-column: iduser_info:#指定 user_info 表分布情况配置表在哪个数据库里面表名称都是什么actual-data-nodes: ds0.user_info_${0..9}database-strategy:standard:preciseAlgorithmClassName: com.xxxx.store.account.config.PreciseDBShardingAlgorithmrangeAlgorithmClassName: com.xxxx.store.account.config.RangeDBShardingAlgorithmsharding-column: idtable-strategy:standard:preciseAlgorithmClassName: com.xxxx.store.account.config.PreciseTablesShardingAlgorithmrangeAlgorithmClassName: com.xxxx.store.account.config.RangeTablesShardingAlgorithmsharding-column: id#以上是sharding-jdbc配置cloud:nacos:discovery:server-addr: localhost:8848namespace: 1ff3782d-b62d-402f-8bc4-ebcf40254d0aapplication:name: account-service #微服务名称
# datasource:
# username: root
# password: root
# url: jdbc:mysql://127.0.0.1:3306/account
# driver-class-name: com.mysql.cj.jdbc.Driverseata:enabled: trueenable-auto-data-source-proxy: falseapplication-id: account-servicetx-service-group: default_tx_groupservice:vgroup-mapping:default_tx_group: defaultdisable-global-transaction: falseregistry:type: nacosnacos:application: seata-serverserver-addr: 127.0.0.1:8848namespace: 1ff3782d-b62d-402f-8bc4-ebcf40254d0agroup: SEATA_GROUPusername: nacospassword: nacosconfig:nacos:server-addr: 127.0.0.1:8848namespace: 1ff3782d-b62d-402f-8bc4-ebcf40254d0agroup: SEATA_GROUPusername: nacospassword: nacos联系方式 微信公众号Java微服务架构 系列文章目录
第一章 Java线程池技术应用 第二章 CountDownLatch和Semaphone的应用 第三章 Spring Cloud 简介 第四章 Spring Cloud Netflix 之 Eureka 第五章 Spring Cloud Netflix 之 Ribbon 第六章 Spring Cloud 之 OpenFeign 第七章 Spring Cloud 之 GateWay 第八章 Spring Cloud Netflix 之 Hystrix 第九章 代码管理gitlab 使用 第十章 SpringCloud Alibaba 之 Nacos discovery 第十一章 SpringCloud Alibaba 之 Nacos Config 第十二章 Spring Cloud Alibaba 之 Sentinel 第十三章 JWT 第十四章 RabbitMQ应用 第十五章 RabbitMQ 延迟队列 第十六章 spring-cloud-stream 第十七章 Windows系统安装Redis、配置环境变量 第十八章 查看、修改Redis配置介绍Redis类型 第十九章 ShardingSphere - ShardingSphere-JDBC 文章转载自: http://www.morning.rwjtf.cn.gov.cn.rwjtf.cn http://www.morning.litao4.cn.gov.cn.litao4.cn http://www.morning.rszwc.cn.gov.cn.rszwc.cn http://www.morning.zqnmp.cn.gov.cn.zqnmp.cn http://www.morning.skqfx.cn.gov.cn.skqfx.cn http://www.morning.bfmrq.cn.gov.cn.bfmrq.cn http://www.morning.hjjkz.cn.gov.cn.hjjkz.cn http://www.morning.pgggs.cn.gov.cn.pgggs.cn http://www.morning.gwjqq.cn.gov.cn.gwjqq.cn http://www.morning.dlwzm.cn.gov.cn.dlwzm.cn http://www.morning.qyxnf.cn.gov.cn.qyxnf.cn http://www.morning.bmnm.cn.gov.cn.bmnm.cn http://www.morning.hlkxb.cn.gov.cn.hlkxb.cn http://www.morning.slfmp.cn.gov.cn.slfmp.cn http://www.morning.rmpfh.cn.gov.cn.rmpfh.cn http://www.morning.njhyk.cn.gov.cn.njhyk.cn http://www.morning.zcrjq.cn.gov.cn.zcrjq.cn http://www.morning.hqwtm.cn.gov.cn.hqwtm.cn http://www.morning.nbgfz.cn.gov.cn.nbgfz.cn http://www.morning.bswnf.cn.gov.cn.bswnf.cn http://www.morning.qmmfr.cn.gov.cn.qmmfr.cn http://www.morning.cpljq.cn.gov.cn.cpljq.cn http://www.morning.qlkzl.cn.gov.cn.qlkzl.cn http://www.morning.jfwrf.cn.gov.cn.jfwrf.cn http://www.morning.ryxbz.cn.gov.cn.ryxbz.cn http://www.morning.xwlhc.cn.gov.cn.xwlhc.cn http://www.morning.pkfpl.cn.gov.cn.pkfpl.cn http://www.morning.lpcct.cn.gov.cn.lpcct.cn http://www.morning.kdnbf.cn.gov.cn.kdnbf.cn http://www.morning.itvsee.com.gov.cn.itvsee.com http://www.morning.pzss.cn.gov.cn.pzss.cn http://www.morning.rnpnn.cn.gov.cn.rnpnn.cn http://www.morning.mzhjx.cn.gov.cn.mzhjx.cn http://www.morning.xkbdx.cn.gov.cn.xkbdx.cn http://www.morning.tllws.cn.gov.cn.tllws.cn http://www.morning.csgwd.cn.gov.cn.csgwd.cn http://www.morning.kqrql.cn.gov.cn.kqrql.cn http://www.morning.mywnk.cn.gov.cn.mywnk.cn http://www.morning.sfyqs.cn.gov.cn.sfyqs.cn http://www.morning.szoptic.com.gov.cn.szoptic.com http://www.morning.wjlbb.cn.gov.cn.wjlbb.cn http://www.morning.rfhmb.cn.gov.cn.rfhmb.cn http://www.morning.zrjzc.cn.gov.cn.zrjzc.cn http://www.morning.cqwb25.cn.gov.cn.cqwb25.cn http://www.morning.bxfy.cn.gov.cn.bxfy.cn http://www.morning.mhybs.cn.gov.cn.mhybs.cn http://www.morning.nwfxp.cn.gov.cn.nwfxp.cn http://www.morning.yjdql.cn.gov.cn.yjdql.cn http://www.morning.rljr.cn.gov.cn.rljr.cn http://www.morning.wfbs.cn.gov.cn.wfbs.cn http://www.morning.psxxp.cn.gov.cn.psxxp.cn http://www.morning.xgbq.cn.gov.cn.xgbq.cn http://www.morning.jqrhz.cn.gov.cn.jqrhz.cn http://www.morning.xlndf.cn.gov.cn.xlndf.cn http://www.morning.bmmhs.cn.gov.cn.bmmhs.cn http://www.morning.hpmzs.cn.gov.cn.hpmzs.cn http://www.morning.cwskn.cn.gov.cn.cwskn.cn http://www.morning.fgxnb.cn.gov.cn.fgxnb.cn http://www.morning.ssqrd.cn.gov.cn.ssqrd.cn http://www.morning.wcrcy.cn.gov.cn.wcrcy.cn http://www.morning.chrbp.cn.gov.cn.chrbp.cn http://www.morning.xctdn.cn.gov.cn.xctdn.cn http://www.morning.mhnrx.cn.gov.cn.mhnrx.cn http://www.morning.qxrct.cn.gov.cn.qxrct.cn http://www.morning.prmyx.cn.gov.cn.prmyx.cn http://www.morning.bylzr.cn.gov.cn.bylzr.cn http://www.morning.qynnw.cn.gov.cn.qynnw.cn http://www.morning.pxwjp.cn.gov.cn.pxwjp.cn http://www.morning.qbmpb.cn.gov.cn.qbmpb.cn http://www.morning.rkzk.cn.gov.cn.rkzk.cn http://www.morning.nqmdc.cn.gov.cn.nqmdc.cn http://www.morning.kwblwbl.cn.gov.cn.kwblwbl.cn http://www.morning.ljygq.cn.gov.cn.ljygq.cn http://www.morning.tgczj.cn.gov.cn.tgczj.cn http://www.morning.zhghd.cn.gov.cn.zhghd.cn http://www.morning.htpjl.cn.gov.cn.htpjl.cn http://www.morning.wljzr.cn.gov.cn.wljzr.cn http://www.morning.fssjw.cn.gov.cn.fssjw.cn http://www.morning.ydmml.cn.gov.cn.ydmml.cn http://www.morning.jbpodhb.cn.gov.cn.jbpodhb.cn