shardingsphere-proxy 实现postgresql的单库分表

news2024/11/18 6:04:05

1、docker 安装zookeeper

1、拉取镜像

docker pull zookeeper

2、运行容器

docker run -d -e TZ="Asia/Shanghai"  -p 2181:2181 -v /home/sunyuhua/docker/zookeeper:/data --name zookeeper --restart always zookeeper

3、查看容器是不是运行成功

docker exec -it zookeeper bash

./bin/zkCli.sh

2、docker 安装 shardingsphere-proxy

1、获取镜像中的配置

docker run -d --name tmp --entrypoint=bash apache/shardingsphere-proxy

docker cp tmp:/opt/shardingsphere-proxy/conf /home/sunyuhua/docker/shardingsphere-proxy/conf

docker rm tmp

2、启动shardingsphere-proxy

docker run -d -v /home/sunyuhua/docker/shardingsphere-proxy/conf:/opt/shardingsphere-proxy/conf -v /home/sunyuhua/docker/shardingsphere-proxy/ext-lib:/opt/shardingsphere-proxy/ext-lib -v /home/sunyuhua/docker/shardingsphere-proxy/logs:/opt/shardingsphere-proxy/logs -p3307:3307  --name sharding-proxy  --restart always  --network sharding-network  apache/shardingsphere-proxy:5.2.1

3、检查shardingsphere-proxy是否启动成功

docker logs sharding-proxy

3、docker 安装 postgresql13

1、拉取镜像

docker pull postgres:13

2、运行镜像

docker run -d --name postgres -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=postgres  -v /home/sunyuhua/docker/postgresql/data:/var/lib/postgresql/data -v /etc/localtime:/etc/localtime --restart=always  -p 5432:5432 postgres:13

3、进入docker容器检查是否成功

docker exec -it postgres /bin/bash

4、创建查询用户,并赋值权限

psql -U postgres


CREATE ROLE sa WITH SUPERUSER LOGIN PASSWORD 'boKYLXIERWnzB0gX';


grant all PRIVILEGES on database postgres to sa;

grant all PRIVILEGES on all tables in schema public TO sa;

ALTER ROLE sa CREATEROLE SUPERUSER;

4、准备数据库的表结构

CREATE DATABASE demo_ds_3;

\c demo_ds_3;

CREATE TABLE t_order_0 (
  order_id BIGINT NOT NULL,
  user_id BIGINT NOT NULL,
  total_money INT NOT NULL,
  PRIMARY KEY (order_id)
);

CREATE INDEX idx_user_id_0 ON t_order_0 (user_id);


CREATE TABLE t_order_1 (
  order_id BIGINT NOT NULL,
  user_id BIGINT NOT NULL,
  total_money INT NOT NULL,
  PRIMARY KEY (order_id)
);

CREATE INDEX idx_user_id_1 ON t_order_1 (user_id);



CREATE TABLE t_order_item_0 (
  order_item_id BIGINT NOT NULL,
  order_id BIGINT NOT NULL,
  user_id BIGINT NOT NULL,
  money INT NOT NULL,
  PRIMARY KEY (order_item_id)
);

CREATE INDEX idx_order_id_0 ON t_order_item_0 (order_id);
CREATE INDEX idx_user_id_0 ON t_order_item_0 (user_id);



CREATE TABLE t_order_item_1 (
  order_item_id BIGINT NOT NULL,
  order_id BIGINT NOT NULL,
  user_id BIGINT NOT NULL,
  money INT NOT NULL,
  PRIMARY KEY (order_item_id)
);

CREATE INDEX idx_order_id_1 ON t_order_item_1 (order_id);
CREATE INDEX idx_user_id_1 ON t_order_item_1 (user_id);


5、配置shardingsphere-proxy单库分表的策略

修改server.xml文件,文件地址:/home/sunyuhua/docker/shardingsphere-proxy/conf

mode:
  type: Cluster
  repository:
    type: ZooKeeper
    props:
      namespace: governance_ds
      server-lists: host.docker.internal:2181
      retryIntervalMilliseconds: 500
      timeToLiveSeconds: 60
      maxRetries: 3
      operationTimeoutMilliseconds: 500
#  overwrite: false
#
rules:
  - !AUTHORITY
    users:
      - root@%:root
      - sharding@:sharding
    provider:
      type: ALL_PRIVILEGES_PERMITTED
#  - !TRANSACTION
#    defaultType: XA
#    providerType: Atomikos

props:
#  max-connections-size-per-query: 1
#  kernel-executor-size: 16  # Infinite by default.
#  proxy-frontend-flush-threshold: 128  # The default value is 128.
#  proxy-opentracing-enabled: false
#  proxy-hint-enabled: false
  sql-show: true
#  check-table-metadata-enabled: false
#  show-process-list-enabled: false
#    # Proxy backend query fetch size. A larger value may increase the memory usage of ShardingSphere Proxy.
#    # The default value is -1, which means set the minimum value for different JDBC drivers.
#  proxy-backend-query-fetch-size: -1
#  check-duplicate-table-enabled: false
#  sql-comment-parse-enabled: false
#  proxy-frontend-executor-size: 0 # Proxy frontend executor size. The default value is 0, which means let Netty decide.
#    # Available options of proxy backend executor suitable: OLAP(default), OLTP. The OLTP option may reduce time cost of writing packets to client, but it may increase the latency of SQL execution
#    # if client connections are more than proxy-frontend-netty-executor-size, especially executing slow SQL.
#  proxy-backend-executor-suitable: OLAP
#  proxy-frontend-max-connections: 0 # Less than or equal to 0 means no limitation.
#  sql-federation-enabled: false

修改config-sharding.yaml 文件,文件地址/home/sunyuhua/docker/shardingsphere-proxy/conf



schemaName: sharding_db_postgres_single

dataSources:
 ds_3:
   url: jdbc:postgresql://host.docker.internal:5432/demo_ds_3
   username: sa
   password: boKYLXIERWnzB0gX
   connectionTimeoutMilliseconds: 30000
   idleTimeoutMilliseconds: 60000
   maxLifetimeMilliseconds: 1800000
   maxPoolSize: 50
   minPoolSize: 1

rules:
- !SHARDING
 tables:
   t_order:
     actualDataNodes: ds_3.t_order_${0..1}
     tableStrategy:
       standard:
         shardingColumn: order_id
         shardingAlgorithmName: t_order_inline
     keyGenerateStrategy:
         column: order_id
         keyGeneratorName: snowflake
   t_order_item:
     actualDataNodes: ds_3.t_order_item_${0..1}
     tableStrategy:
       standard:
         shardingColumn: order_id
         shardingAlgorithmName: t_order_item_inline
     keyGenerateStrategy:
       column: order_item_id
       keyGeneratorName: snowflake
 bindingTables:
   - t_order,t_order_item
 defaultDatabaseStrategy:
   none:
 defaultTableStrategy:
   none:
 
 shardingAlgorithms:
   t_order_inline:
     type: INLINE
     props:
       algorithm-expression: t_order_${order_id % 2}
   t_order_item_inline:
     type: INLINE
     props:
       algorithm-expression: t_order_item_${order_id % 2}
 
 keyGenerators:
   snowflake:
     type: SNOWFLAKE
     props:
       worker-id: 123

重新启动shardingsphere

docker restart sharding-proxy

检查shardingsphere-proxy是不是启动

docker logs sharding-proxy

或者查看日志

 /opt/shardingsphere-proxy/logs/stdout.log

[INFO ] 2023-06-28 05:46:54.015 [main-SendThread(host.docker.internal:2181)] org.apache.zookeeper.ClientCnxn - Session establishment complete on server host.docker.internal/192.168.65.2:2181, session id = 0x100000045ca0001, negotiated timeout = 40000
[INFO ] 2023-06-28 05:46:54.024 [main-EventThread] o.a.c.f.state.ConnectionStateManager - State change: CONNECTED
[INFO ] 2023-06-28 05:46:54.052 [main-EventThread] o.a.c.framework.imps.EnsembleTracker - New config event received: {}
[INFO ] 2023-06-28 05:46:54.052 [main-EventThread] o.a.c.framework.imps.EnsembleTracker - New config event received: {}
Thanks for using Atomikos! Evaluate http://www.atomikos.com/Main/ExtremeTransactions for advanced features and professional support
or register at http://www.atomikos.com/Main/RegisterYourDownload to disable this message and receive FREE tips & advice
[INFO ] 2023-06-28 05:46:56.075 [main] o.apache.curator.utils.Compatibility - Using org.apache.zookeeper.server.quorum.MultipleAddresses
[INFO ] 2023-06-28 05:46:56.093 [main] o.a.s.p.i.BootstrapInitializer - Database name is `MySQL`, version is `5.7.42-log`
[INFO ] 2023-06-28 05:46:56.283 [main] o.a.s.p.frontend.ShardingSphereProxy - ShardingSphere-Proxy start success

6、插入和查询数据,检查分库分表策略是不是生效

在这里插入图片描述

7、检查物理库是不是已经插入成功

在这里插入图片描述

常见错误

1、postgresql 客户端DBeaver 出现进行 SSL 连线时发生错误。 解决办法:降低shardingsphere-proxy到5.2.1版本即可

[ERROR] 2023-06-30 07:28:39.479 [epollEventLoopGroup-3-3] o.a.s.p.f.n.FrontendChannelInboundHandler - Exception occur: 
java.lang.IndexOutOfBoundsException: readerIndex(1) + length(4) exceeds writerIndex(1): PooledSlicedByteBuf(ridx: 1, widx: 1, cap: 1/1, unwrapped: PooledUnsafeDirectByteBuf(ridx: 4, widx: 8, cap: 2048))
        at io.netty.buffer.AbstractByteBuf.checkReadableBytes0(AbstractByteBuf.java:1442)
        at io.netty.buffer.AbstractByteBuf.readIntLE(AbstractByteBuf.java:817)
        at org.apache.shardingsphere.db.protocol.mysql.payload.MySQLPacketPayload.readInt4(MySQLPacketPayload.java:115)
        at org.apache.shardingsphere.db.protocol.mysql.packet.handshake.MySQLHandshakeResponse41Packet.<init>(MySQLHandshakeResponse41Packet.java:56)
        at org.apache.shardingsphere.proxy.frontend.mysql.authentication.MySQLAuthenticationEngine.authPhaseFastPath(MySQLAuthenticationEngine.java:86)
        at org.apache.shardingsphere.proxy.frontend.mysql.authentication.MySQLAuthenticationEngine.authenticate(MySQLAuthenticationEngine.java:73)
        at org.apache.shardingsphere.proxy.frontend.netty.FrontendChannelInboundHandler.authenticate(FrontendChannelInboundHandler.java:80)
        at org.apache.shardingsphere.proxy.frontend.netty.FrontendChannelInboundHandler.channelRead(FrontendChannelInboundHandler.java:72)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
        at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357)
        at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:324)
        at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:311)
        at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:432)
        at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:276)
        at io.netty.handler.codec.ByteToMessageCodec.channelRead(ByteToMessageCodec.java:103)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
        at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357)
        at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
        at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919)
        at io.netty.channel.epoll.AbstractEpollStreamChannel$EpollStreamUnsafe.epollInReady(AbstractEpollStreamChannel.java:795)
        at io.netty.channel.epoll.EpollEventLoop.processReady(EpollEventLoop.java:480)
        at io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:378)
        at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:986)
        at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
        at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
        at java.lang.Thread.run(Thread.java:748)

2、DBeaver出现SQL 错误 [22023]: ERROR: No value specified for parameter 1. 解决方法:更换Navicat for postgresql

[ERROR] 2023-06-30 08:47:23.424 [Connection-23-ThreadExecutor] o.a.s.p.f.c.CommandExecutorTask - Exception occur: 
org.postgresql.util.PSQLException: No value specified for parameter 1.
        at org.postgresql.core.v3.SimpleParameterList.checkAllParametersSet(SimpleParameterList.java:284)
        at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:340)
        at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:490)
        at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:408)
        at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:181)
        at org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:133)
        at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52)
        at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java)
        at org.apache.shardingsphere.proxy.backend.handler.admin.executor.AbstractDatabaseMetadataExecutor$DefaultDatabaseMetadataExecutor.getSourceData(AbstractDatabaseMetadataExecutor.java:216)
        at org.apache.shardingsphere.proxy.backend.handler.admin.executor.AbstractDatabaseMetadataExecutor.execute(AbstractDatabaseMetadataExecutor.java:76)
        at org.apache.shardingsphere.proxy.backend.handler.admin.DatabaseAdminQueryBackendHandler.execute(DatabaseAdminQueryBackendHandler.java:56)
        at org.apache.shardingsphere.proxy.frontend.postgresql.command.query.extended.JDBCPortal.bind(JDBCPortal.java:113)
        at org.apache.shardingsphere.proxy.frontend.postgresql.command.query.extended.bind.PostgreSQLComBindExecutor.execute(PostgreSQLComBindExecutor.java:53)
        at org.apache.shardingsphere.proxy.frontend.postgresql.command.query.extended.PostgreSQLAggregatedCommandExecutor.execute(PostgreSQLAggregatedCommandExecutor.java:41)
        at org.apache.shardingsphere.proxy.frontend.command.CommandExecutorTask.executeCommand(CommandExecutorTask.java:111)
        at org.apache.shardingsphere.proxy.frontend.command.CommandExecutorTask.run(CommandExecutorTask.java:78)
        at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)
        at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
        at java.base/java.lang.Thread.run(Thread.java:833)


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/705466.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Spring Boot 中的 @SendTo 注解

Spring Boot 中的 SendTo 注解 在 Spring Boot 中&#xff0c;SendTo 注解是一个非常有用的注解&#xff0c;它可以用于实现 WebSocket 的消息转发功能。本文将介绍 SendTo 注解的原理、使用方法和示例代码。 什么是 SendTo 注解 SendTo 注解是 Spring Boot 中用于将消息发送…

个人和企业如何有效保护IP地址?

随着互联网的快速发展&#xff0c;个人和企业对于保护IP地址的重要性越来越清晰。为了帮助读者更好地了解如何有效保护IP地址&#xff0c;以下将介绍几种方法&#xff0c;并提供一些相关的数据和专家意见。 使用防火墙是保护IP地址的一个重要手段。防火墙可以监控和过滤网络流量…

react native 使用Native Module、Intent、广播接收器 实现两个app之间的相互通信

一、react native版本环境: “react”: “18.1.0”, “react-native”: “0.70.6”, “node”: "14.18.2 二、发送端步骤: 在A app中注册一个Native Module模块,使用Intent 连接B app,sendBroadcast 发送广播传递数据。 (1)首先在 /android/app/src/main/java/com/j…

ASP.NET Core MVC从入门到精通[PDF版]

随着技术的发展&#xff0c;ASP.NET Core MVC也推出了好长时间&#xff0c;经过不断的版本更新迭代&#xff0c;已经越来越完善&#xff0c;本系列文章主要讲解ASP.NET Core MVC开发B/S系统过程中所涉及到的相关内容&#xff0c;适用于初学者&#xff0c;在校毕业生&#xff0c…

three.js点材质(PointsMaterial)常用属性设置

一、前景回顾 上一章节简单介绍了下怎么使用点材质和点对象创建物体点对象和点材质介绍 点材质和点对象基本运用示例代码&#xff1a; import * as THREE from "three"; // 导入轨道控制器 import { OrbitControls } from "three/examples/jsm/controls/Orbit…

A核与M核异构通信过程解析

现在越来越多的产品具有M core和A core的异构架构&#xff0c;既能达到M核的实时要求&#xff0c;又能满足A核的生态和算力。比如NXP的i.MX8系列、瑞萨的RZ/G2L系列以及TI的AM62x系列等等。虽然这些处理器的品牌及性能有所不同&#xff0c;但多核通信原理基本一致&#xff0c;都…

Linux操作系统配置代理服务器

PS:本文只是针对Linux操作系统对于代理服务器的配置操作&#xff0c;不涉及广告 1.代理的概念 代理服务器英文全称是Proxy Server&#xff0c;其功能就是代理网络用户去取得网络信息。形象的说&#xff1a;它是网络信息的中转站。在一般情况下&#xff0c;我们使用网络浏览器直…

华为智能高校出口安全解决方案(1)

华为智能高校出口安全解决方案&#xff08;1&#xff09; 视频链接方案背景需求分析高校园区网概述高校园区网全景高校出口场景介绍高校出口整体需求分析业务安全需求攻击防御需求运维审计需求 方案规划华为智能高校出口安全解决方案架构华为智能高校出口安全解决方案功能划分业…

(二)Qt QGraphicsScene模块实现圆点绘制在所有窗体的最前方,实现圆点的“彩色拖尾”效果以及“选中方框”效果

系列文章目录 通过Qt实现手势识别控制软件操作相关系列技术方案 &#xff08;一&#xff09;Qt 将某控件、图案绘制在最前面的方法&#xff0c;通过QGraphicsScene模块实现 &#xff08;二&#xff09;Qt QGraphicsScene模块实现圆点绘制在所有窗体的最前方&#xff0c;实现圆…

强化学习从基础到进阶-案例与实践[5.1]:Policy Gradient-Cart pole游戏展示

强化学习从基础到进阶-案例与实践[5.1]&#xff1a;Policy Gradient-Cart pole游戏展示 强化学习&#xff08;Reinforcement learning&#xff0c;简称RL&#xff09;是机器学习中的一个领域&#xff0c;区别与监督学习和无监督学习&#xff0c;强调如何基于环境而行动&#x…

关于u(x,t)=f(x)*g(t)形式证明的思考

突然想起来&#xff0c;二维高斯函数是可以拆分成两个一维高斯函数相乘的&#xff1a; 原来在学概率论的时候&#xff0c;证明过&#xff0c;这只能说高斯函数可以&#xff0c;这是一个思路。 一维波动函数应该也是这个套路。 那么还有没有其他函数可以如此&#xff0c;有如此…

javascript和css实现瀑布流排列

Grid 布局 实现瀑布流 html <div class"gridDiv"><divv-for"(item,index) in 20":style"{grid-row: auto / span ${heightArray[index]}}"><div class"gridItemConten"><div class"gridText">{{ite…

VS2022编译运行VS2015的项目

最近新装了VisualStudio2022&#xff0c;有一些VS2015老的项目需要运行&#xff0c;但不想再安装VS2015&#xff0c;就想能否直接在VS2022编译运行&#xff0c;研究一下发现可行&#xff0c;记录一下。 1. 直接升级VS2015项目到2022使用windows sdk 10.0 发现老代码里的一些语…

#10044 「一本通 2.2 例 2」Power Strings(KMP)(内附封面)

题目描述 原题来自&#xff1a;POJ 2406 给定若干个长度 \le 10^6 的字符串&#xff0c;询问每个字符串最多是由多少个相同的子字符串重复连接而成的。如&#xff1a;ababab 则最多有 3 个 ab 连接而成。 输入格式 输入若干行&#xff0c;每行有一个字符串。特别的&#xf…

第一章:R-CNN网络详解(丰富特征层次用于准确的目标检测和语义分割技术报告(v5))

(目标检测篇&#xff09;系列文章目录 第一章:R-CNN网络详解 第二章:Fast R-CNN网络详解 第三章:Faster R-CNN网络详解 第四章:YOLO v1网络详解 第五章:YOLO v2网络详解 第六章:YOLO v3网络详解 文章目录 系列文章目录技术干货集锦前言一、摘要二、正文分析 1.引入库2.读入…

迅为RK3568/RK3588开发板视频教程 | RKNPU2 从入门到实践一套搞定!

迅为电子嵌入式视频教程更新了&#xff01;——「AI深度学习推理加速器--RKNPU2 从入门到实践」&#xff08;基于RK3588和RK3568&#xff09; 课程内容分为三个阶段&#xff1a;认识RKNPU、RKNPU开发学习以及项目实战。 首先&#xff0c;我们将从认识RKNPU阶段开始&#xff0…

Redis实战——短信登录(一)

项目搭建 前期准备 导入SQL CREATE TABLE tb_user (id bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 主键,phone varchar(11) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT 手机号码,password varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4…

【Redis】Redis主从复制哨兵模式集群

文章目录 一、Redis 持久化1. 主从复制2. 哨兵模式3. 集群 二、 Redis 主从复制1. 概述2. 主从复制的作用3. 主从复制流程4. 搭建 Redis 主从复制4.1 环境准备4.2 安装 Redis4.3 修改 Master 节点配置文件4.4 修改Slave节点配置文件&#xff08;Slave1和Slave2配置相同&#xf…

关于Docker中 docker build 时no such file or directory报错

ERROR: failed to solve: failed to read dockerfile: open /var/lib/docker/tmp/buildkit-mount545066663/Dockerfile: no such file or directory 主要原因是命令行没有在文件夹下执行docker build&#xff0c;cd到指定文件夹下执行即可

windows-x86使用qemu打开x86和arm虚拟机

1、下载qemu软件 下载固件&#xff08;UEFI固件镜像文件&#xff0c;BIOS的替代方案&#xff09;&#xff09; 2、配置qemu环境变量 使用cmd执行qemu命令&#xff0c;配置好环境变量比较方便 3、准备镜像 准备好一个x86的镜像或者arm的镜像&#xff0c;格式可以为qcow2 4、打…