前端技术
HTML
CSS
Javascript
前端框架和UI库
VUE
ReactJS
AngularJS
JQuery
NodeJS
JSON
Element-UI
Bootstrap
Material UI
服务端和客户端
Java
Python
PHP
Golang
Scala
Kotlin
Groovy
Ruby
Lua
.net
c#
c++
后端WEB和工程框架
SpringBoot
SpringCloud
Struts2
MyBatis
Hibernate
Tornado
Beego
Go-Spring
Go Gin
Go Iris
Dubbo
HessianRPC
Maven
Gradle
数据库
MySQL
Oracle
Mongo
中间件与web容器
Redis
MemCache
Etcd
Cassandra
Kafka
RabbitMQ
RocketMQ
ActiveMQ
Nacos
Consul
Tomcat
Nginx
Netty
大数据技术
Hive
Impala
ClickHouse
DorisDB
Greenplum
PostgreSQL
HBase
Kylin
Hadoop
Apache Pig
ZooKeeper
SeaTunnel
Sqoop
Datax
Flink
Spark
Mahout
数据搜索与日志
ElasticSearch
Apache Lucene
Apache Solr
Kibana
Logstash
数据可视化与OLAP
Apache Atlas
Superset
Saiku
Tesseract
系统与容器
Linux
Shell
Docker
Kubernetes
[基于命令行查询MySQL安装位置 ]的搜索结果
这里是文章列表。热门标签的颜色随机变换,标签颜色没有特殊含义。
点击某个标签可搜索标签相关的文章。
点击某个标签可搜索标签相关的文章。
MySQL
MySQL , MySQL是一种开源的关系型数据库管理系统,广泛应用于各种规模的项目中,从小型个人网站到大型企业级应用。在本文中,用户通过命令行方式对MySQL进行初始化、启动服务以及登录管理等操作。 命令行界面(CMD或PowerShell) , 命令行界面是一种基于文本的用户界面,用户通过输入特定命令来与操作系统交互并执行各种任务,如导航目录结构、运行程序和服务等。在本文语境下,用户通过Windows命令行窗口执行MySQL相关的命令以管理和配置MySQL服务器。 MySQL服务 , MySQL服务是指在操作系统层面运行的MySQL数据库实例,它可以持续监听并响应客户端请求,处理包括连接管理、查询执行在内的数据库操作。在文章中提到,用户通过命令行工具初始化MySQL服务,并使用特定参数以管理员权限启动该服务,确保MySQL数据库能够正常运行和提供数据服务。 bin文件夹 , 在软件安装目录中,bin(binary的缩写)文件夹通常包含了一组用于执行程序、脚本和其他必要的二进制文件。对于MySQL来说,其bin目录下存放了诸如mysqld(MySQL服务器)、mysql(命令行客户端)等关键可执行文件,用户通过调用这些文件来进行MySQL数据库的安装、配置、启动、停止和管理等各种操作。
2023-11-16 22:43:19
84
键盘勇士
MySQL
在了解如何通过命令行查找MySQL实例的安装位置后,我们还可以进一步探讨MySQL数据库的管理与优化。近日,MySQL 8.0版本推出了一系列新特性,如窗口函数的增强、JSON功能的升级以及性能改进等,这为数据库管理员提供了更高效便捷的操作手段。例如,基于新的窗口函数,可以更轻松地进行复杂的数据分析和统计计算;而JSON字段类型的增强则顺应了现代应用中大量非结构化数据处理的需求。 同时,对于MySQL实例的运维管理,安全性和稳定性至关重要。定期检查并更新MySQL服务器的配置文件、确保数据目录的安全权限设置,并合理利用缓存机制以提升查询效率,是每一位数据库管理人员应熟练掌握的基本功。此外,针对线上大规模并发访问场景,深入理解并运用MySQL的InnoDB存储引擎的事务处理机制、锁机制及索引策略,有助于提升系统整体性能和用户体验。 另外,在云服务日益普及的今天,各大云服务商(如AWS RDS、阿里云RDS等)提供了托管型MySQL服务,用户无需关心底层MySQL实例的具体安装位置,即可享受到便捷的数据库创建、备份恢复及监控告警等功能。但这也要求DBA们熟悉云环境下的MySQL管理工具和服务接口,以便更好地适应云计算时代的新挑战。 总之,无论是对MySQL实例进行精细的本地部署维护,还是依托于云平台实现高效便捷的数据库管理,都需要不断跟进MySQL技术的发展动态,深入理解其核心原理,并结合实际业务场景灵活运用各种优化策略,从而确保数据库系统的稳定、安全、高效运行。
2023-04-12 10:49:01
62
键盘勇士
转载文章
...除相应内容。 2. MySQL 2.1. 快速参考 维护者:Docker 社区和 MySQL 团队 从哪里获得帮助:Docker 社区论坛、Docker 社区 Slack 或 Stack Overflow 2.2. 支持的标签和各自的 Dockerfile 链接 8.0.28, 8.0, 8, latest 5.7.37, 5.7, 5 2.3. 快速参考(续) 在哪里提交问题:https://github.com/docker-library/mysql/issues 支持的架构:(更多信息)amd64 发布的镜像工件详情:repo-info repo 的 repos/mysql/ 目录(历史)(镜像元数据、传输大小等) 镜像更新:official-images repo 的 library/mysql 标签 官方图像 repo 的库/mysql 文件(历史) 此描述的来源:docs repo 的 mysql/ 目录(历史) 2.4. 如何使用镜像 2.4.1. 启动一个mysql服务器实例 启动 MySQL 实例很简单: $ docker run --name some-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:tag 其中 some-mysql 是您要分配给容器的名称, my-secret-pw 是要为 MySQL root 用户设置的密码,而 tag 是指定您想要的 MySQL 版本的标签。 有关相关标签,请参见上面的列表。 以下是示例(通常要设置时区),注意-v 这里是挂载磁盘,请提前创建目录/var/mysql/data,/var/lib/mysql是容器里的原持久化目录: docker run --name mysql202201 -e MYSQL_ROOT_PASSWORD=123456 -e TZ=Asia/Shanghai -v /var/mysql/data:/var/lib/mysql -d mysql:5.7 2.4.2. 从 MySQL 命令行客户端连接到 MySQL 以下命令启动另一个 mysql 容器实例并针对您的原始 mysql 容器运行 mysql 命令行客户端,允许您针对您的数据库实例执行 SQL 语句: $ docker run -it --network some-network --rm mysql mysql -hsome-mysql -uexample-user -p 其中 some-mysql 是原始 mysql 容器的名称(连接到 some-network Docker 网络)。 此镜像也可以用作非 Docker 或远程实例的客户端: $ docker run -it --rm mysql mysql -hsome.mysql.host -usome-mysql-user -p 有关 MySQL 命令行客户端的更多信息,请参阅 MySQL 文档。 2.4.3. 容器外访问和查看 MySQL 日志 docker exec 命令允许您在 Docker 容器内运行命令。 以下命令行将为您提供 mysql 容器内的 bash shell: $ docker exec -it some-mysql bash 第一次启动一个MySQL容器后,需要对账户进行授权,否则无法远程访问,请先使用上面的命令进入容器内,然后使用以下命令连接到mysql服务: mysql -uroot -p 输入密码回车,进入mysql命令界面mysql> 接着授权root远程访问权限: mysql> GRANT ALL PRIVILEGES ON . TO 'root'@'%' IDENTIFIED BY '123456'; 然后就可以远程用MySQL客户端连接到MySQL容器了。 日志可通过 Docker 的容器日志获得: $ docker logs some-mysql 2.4.4. 使用自定义 MySQL 配置文件 MySQL 的默认配置可以在 /etc/mysql/my.cnf 中找到,其中可能包含额外的目录,例如 /etc/mysql/conf.d 或 /etc/mysql/mysql.conf.d。 请检查 mysql 映像本身中的相关文件和目录以获取更多详细信息。 如果 /my/custom/config-file.cnf 是你的自定义配置文件的路径和名称,你可以这样启动你的 mysql 容器(注意这个命令只使用了自定义配置文件的目录路径): $ docker run --name some-mysql -v /my/custom:/etc/mysql/conf.d -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:tag 这将启动一个新容器 some-mysql,其中 MySQL 实例使用来自 /etc/mysql/my.cnf 和 /etc/mysql/conf.d/config-file.cnf 的组合启动设置,后者的设置优先 . 没有 cnf 文件的配置 许多配置选项可以作为标志传递给 mysqld。 这将使您可以灵活地自定义容器,而无需 cnf 文件。 例如,如果要将所有表的默认编码和排序规则更改为使用 UTF-8 (utf8mb4),只需运行以下命令: $ docker run --name some-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:tag --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci 如果您想查看可用选项的完整列表,只需运行: $ docker run -it --rm mysql:tag --verbose --help 2.4.5. 环境变量 启动 mysql 镜像时,可以通过在 docker run 命令行中传递一个或多个环境变量来调整 MySQL 实例的配置。 请注意,如果您使用已包含数据库的数据目录启动容器,则以下任何变量都不会产生任何影响:任何预先存在的数据库在容器启动时将始终保持不变。 另请参阅 https://dev.mysql.com/doc/refman/5.7/en/environment-variables.html 以获取 MySQL 的环境变量的文档(尤其是 MYSQL_HOST 等变量,已知与此镜像一起使用时会导致问题)。 MYSQL_ROOT_PASSWORD 此变量是必需的,并指定将为 MySQL root 超级用户帐户设置的密码。 在上面的示例中,它被设置为 my-secret-pw。 MYSQL_DATABASE 此变量是可选的,允许您指定要在映像启动时创建的数据库的名称。 如果提供了用户/密码(见下文),则该用户将被授予对此数据库的超级用户访问权限(对应于 GRANT ALL)。 MYSQL_USER、MYSQL_PASSWORD 这些变量是可选的,用于创建新用户和设置该用户的密码。 该用户将被授予对 MYSQL_DATABASE 变量指定的数据库的超级用户权限(见上文)。 要创建用户,这两个变量都是必需的。 请注意,不需要使用此机制来创建超级用户超级用户,默认情况下会使用 MYSQL_ROOT_PASSWORD 变量指定的密码创建该用户。 MYSQL_ALLOW_EMPTY_PASSWORD 这是一个可选变量。 设置为非空值,例如 yes,以允许使用 root 用户的空白密码启动容器。 注意:除非您真的知道自己在做什么,否则不建议将此变量设置为 yes,因为这将使您的 MySQL 实例完全不受保护,从而允许任何人获得完全的超级用户访问权限。 MYSQL_RANDOM_ROOT_PASSWORD 这是一个可选变量。 设置为非空值,如 yes,为 root 用户生成随机初始密码(使用 pwgen)。 生成的根密码将打印到标准输出(生成的根密码:…)。 MYSQL_ONETIME_PASSWORD 一旦初始化完成,将 root(不是 MYSQL_USER 中指定的用户!)用户设置为过期,强制在第一次登录时更改密码。 任何非空值都将激活此设置。 注意:此功能仅在 MySQL 5.6+ 上受支持。 在 MySQL 5.5 上使用此选项将在初始化期间引发适当的错误。 MYSQL_INITDB_SKIP_TZINFO 默认情况下,入口点脚本会自动加载 CONVERT_TZ() 函数所需的时区数据。 如果不需要,任何非空值都会禁用时区加载。 2.4.6. Docker Secrets 作为通过环境变量传递敏感信息的替代方法,_FILE 可以附加到先前列出的环境变量中,从而导致初始化脚本从容器中存在的文件中加载这些变量的值。 特别是,这可用于从存储在 /run/secrets/<secret_name> 文件中的 Docker 机密中加载密码。 例如: $ docker run --name some-mysql -e MYSQL_ROOT_PASSWORD_FILE=/run/secrets/mysql-root -d mysql:tag 目前,这仅支持 MYSQL_ROOT_PASSWORD、MYSQL_ROOT_HOST、MYSQL_DATABASE、MYSQL_USER和 MYSQL_PASSWORD。 2.4.7. 初始化一个新实例 首次启动容器时,将使用提供的配置变量创建并初始化具有指定名称的新数据库。 此外,它将执行 /docker-entrypoint-initdb.d 中的扩展名为 .sh、.sql 和 .sql.gz 的文件。 文件将按字母顺序执行。 您可以通过将 SQL 转储安装到该目录并提供带有贡献数据的自定义镜像来轻松填充您的 mysql 服务。 SQL 文件将默认导入到 MYSQL_DATABASE 变量指定的数据库中。 2.5. 注意事项 2.5.1. 在哪里存储数据 重要提示:有几种方法可以存储在 Docker 容器中运行的应用程序使用的数据。 我们鼓励 mysql 映像的用户熟悉可用的选项,包括: 让 Docker 通过使用自己的内部卷管理将数据库文件写入主机系统上的磁盘来管理数据库数据的存储。 这是默认设置,对用户来说简单且相当透明。 缺点是对于直接在主机系统(即外部容器)上运行的工具和应用程序,可能很难找到这些文件。 在主机系统(容器外部)上创建一个数据目录,并将其挂载到容器内部可见的目录。 这会将数据库文件放置在主机系统上的已知位置,并使主机系统上的工具和应用程序可以轻松访问这些文件。 缺点是用户需要确保目录存在,例如主机系统上的目录权限和其他安全机制设置正确。 Docker 文档是了解不同存储选项和变体的一个很好的起点,并且有多个博客和论坛帖子在该领域讨论和提供建议。 我们将在这里简单地展示上面后一个选项的基本过程: 在主机系统上的合适卷上创建数据目录,例如 /my/own/datadir。 像这样启动你的 mysql 容器: $ docker run --name some-mysql -v /my/own/datadir:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:tag 命令的 -v /my/own/datadir:/var/lib/mysql 部分将底层主机系统中的 /my/own/datadir 目录挂载为容器内的 /var/lib/mysql ,默认情况下 MySQL 将 写入其数据文件。 2.5.2. 在 MySQL 初始化完成之前没有连接 如果容器启动时没有初始化数据库,则会创建一个默认数据库。 虽然这是预期的行为,但这意味着在初始化完成之前它不会接受传入的连接。 在使用同时启动多个容器的自动化工具(例如 docker-compose)时,这可能会导致问题。 如果您尝试连接到 MySQL 的应用程序没有处理 MySQL 停机时间或等待 MySQL 正常启动,那么在服务启动之前放置一个连接重试循环可能是必要的。 有关官方图像中此类实现的示例,请参阅 WordPress 或 Bonita。 2.5.3. 针对现有数据库的使用 如果您使用已经包含数据库的数据目录(特别是 mysql 子目录)启动 mysql 容器实例,则应该从运行命令行中省略 $MYSQL_ROOT_PASSWORD 变量; 在任何情况下都将被忽略,并且不会以任何方式更改预先存在的数据库。 2.5.4. 以任意用户身份运行 如果你知道你的目录的权限已经被适当地设置了(例如对一个现有的数据库运行,如上所述)或者你需要使用特定的 UID/GID 运行 mysqld,那么可以使用 --user 调用这个镜像设置为任何值(root/0 除外)以实现所需的访问/配置: $ mkdir data$ ls -lnd datadrwxr-xr-x 2 1000 1000 4096 Aug 27 15:54 data$ docker run -v "$PWD/data":/var/lib/mysql --user 1000:1000 --name some-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:tag 2.5.5. 创建数据库转储 大多数普通工具都可以工作,尽管在某些情况下它们的使用可能有点复杂,以确保它们可以访问 mysqld 服务器。 确保这一点的一种简单方法是使用 docker exec 并从同一容器运行该工具,类似于以下内容: $ docker exec some-mysql sh -c 'exec mysqldump --all-databases -uroot -p"$MYSQL_ROOT_PASSWORD"' > /some/path/on/your/host/all-databases.sql 2.5.6. 从转储文件恢复数据 用于恢复数据。 您可以使用带有 -i 标志的 docker exec 命令,类似于以下内容: $ docker exec -i some-mysql sh -c 'exec mysql -uroot -p"$MYSQL_ROOT_PASSWORD"' < /some/path/on/your/host/all-databases.sql 备注 docker安装完MySQL,后面就是MySQL容器在跑,基本上就是当MySQL服务去操作,以前MySQL怎么做现在还是一样怎么做,只是个别操作因为docker包了一层,麻烦一点。 有需要的话,我们也可以基于MySQL官方镜像去定制我们自己的镜像,就比如主从镜像之类的。 本篇文章为转载内容。原文链接:https://blog.csdn.net/muluo7fen/article/details/122731852。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-05-29 17:31:06
101
转载
转载文章
...其他默认调优值 MySQL Server Instance Configuration File MySQL服务器实例配置文件 ---------------------------------------------------------------------- Generated by the MySQL Server Instance Configuration Wizard 由MySQL服务器实例配置向导生成 Installation Instructions 安装说明 ---------------------------------------------------------------------- On Linux you can copy this file to /etc/my.cnf to set global options, mysql-data-dir/my.cnf to set server-specific options (@localstatedir@ for this installation) or to ~/.my.cnf to set user-specific options. 在Linux上,您可以将该文件复制到/etc/my.cnf来设置全局选项,mysql-data-dir/my.cnf来设置特定于服务器的选项(此安装的@localstatedir@),或者~/.my.cnf来设置特定于用户的选项。 On Windows you should keep this file in the installation directory of your server (e.g. C:\Program Files\MySQL\MySQL Server X.Y). To make sure the server reads the config file use the startup option "--defaults-file". 在Windows上你应该保持这个文件在服务器的安装目录(例如C:\Program Files\MySQL\MySQL服务器X.Y)。要确保服务器读取配置文件,请使用启动选项“——default -file”。 To run the server from the command line, execute this in a command line shell, e.g. mysqld --defaults-file="C:\Program Files\MySQL\MySQL Server X.Y\my.ini" 要从命令行运行服务器,请在命令行shell中执行,例如mysqld——default -file="C:\Program Files\MySQL\MySQL server X.Y\my.ini" To install the server as a Windows service manually, execute this in a command line shell, e.g. mysqld --install MySQLXY --defaults-file="C:\Program Files\MySQL\MySQL Server X.Y\my.ini" 要手动将服务器安装为Windows服务,请在命令行shell中执行此操作,例如mysqld——install MySQLXY——default -file="C:\Program Files\MySQL\MySQL server X.Y\my.ini" And then execute this in a command line shell to start the server, e.g. net start MySQLXY 然后在命令行shell中执行这个命令来启动服务器,例如net start MySQLXY Guidelines for editing this file编辑此文件的指南 ---------------------------------------------------------------------- In this file, you can use all long options that the program supports. If you want to know the options a program supports, start the program with the "--help" option. 在这个文件中,您可以使用程序支持的所有长选项。如果您想知道程序支持的选项,请使用“——help”选项启动程序。 More detailed information about the individual options can also be found in the manual. For advice on how to change settings please see https://dev.mysql.com/doc/refman/8.0/en/server-configuration-defaults.html 有关各个选项的更详细信息也可以在手册中找到。有关如何更改设置的建议,请参见https://dev.mysql.com/doc/refman/8.0/en/server-configuration-defaults.html CLIENT SECTION 客户端部分 ---------------------------------------------------------------------- The following options will be read by MySQL client applications. Note that only client applications shipped by MySQL are guaranteed to read this section. If you want your own MySQL client program to honor these values, you need to specify it as an option during the MySQL client library initialization. MySQL客户机应用程序将读取以下选项。注意,只有MySQL提供的客户端应用程序才能阅读本节。如果您希望自己的MySQL客户机程序遵守这些值,您需要在初始化MySQL客户机库时将其指定为一个选项。 [client] pipe= socket=MYSQL port=3306 [mysql] no-beep default-character-set= SERVER SECTION 服务器部分 ---------------------------------------------------------------------- The following options will be read by the MySQL Server. Make sure that you have installed the server correctly (see above) so it reads this file. MySQL服务器将读取以下选项。确保您已经正确安装了服务器(参见上面),以便它读取这个文件。 server_type=3 [mysqld] The next three options are mutually exclusive to SERVER_PORT below. 下面的三个选项对SERVER_PORT是互斥的。skip-networking enable-named-pipe 共享内存 skip-networking enable-named-pipe shared-memory shared-memory-base-name=MYSQL The Pipe the MySQL Server will use socket=MYSQL The TCP/IP Port the MySQL Server will listen on port=3306 Path to installation directory. All paths are usually resolved relative to this. basedir="C:/Program Files/MySQL/MySQL Server 8.0/" Path to the database root datadir=C:/ProgramData/MySQL/MySQL Server 8.0/Data The default character set that will be used when a new schema or table is created and no character set is defined 创建新模式或表时使用的默认字符集,并且没有定义字符集 character-set-server= The default authentication plugin to be used when connecting to the server 连接到服务器时使用的默认身份验证插件 default_authentication_plugin=caching_sha2_password The default storage engine that will be used when create new tables when 当创建新表时将使用的默认存储引擎 default-storage-engine=INNODB Set the SQL mode to strict 将SQL模式设置为strict sql-mode="STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION" General and Slow logging. 一般和缓慢的日志。 log-output=NONE general-log=0 general_log_file="DESKTOP-NF9QETB.log" slow-query-log=0 slow_query_log_file="DESKTOP-NF9QETB-slow.log" long_query_time=10 Binary Logging. 二进制日志。 log-bin Error Logging. 错误日志记录。 log-error="DESKTOP-NF9QETB.err" Server Id. server-id=1 Indicates how table and database names are stored on disk and used in MySQL. 指示表名和数据库名如何存储在磁盘上并在MySQL中使用。 Value = 0: Table and database names are stored on disk using the lettercase specified in the CREATE TABLE or CREATE DATABASE statement. Name comparisons are case sensitive. You should not set this variable to 0 if you are running MySQL on a system that has case-insensitive file names (such as Windows or macOS). Value = 0:表名和数据库名使用CREATE Table或CREATE database语句中指定的lettercase存储在磁盘上。名称比较区分大小写。如果您在一个具有不区分大小写文件名(如Windows或macOS)的系统上运行MySQL,则不应将该变量设置为0。 Value = 1: Table names are stored in lowercase on disk and name comparisons are not case-sensitive. MySQL converts all table names to lowercase on storage and lookup. This behavior also applies to database names and table aliases. 表名以小写存储在磁盘上,并且名称比较不区分大小写。MySQL在存储和查找时将所有表名转换为小写。此行为也适用于数据库名称和表别名。 Value = 3, Table and database names are stored on disk using the lettercase specified in the CREATE TABLE or CREATE DATABASE statement, but MySQL converts them to lowercase on lookup. Name comparisons are not case sensitive. This works only on file systems that are not case-sensitive! InnoDB table names and view names are stored in lowercase, as for Value = 1.表名和数据库名使用CREATE Table或CREATE database语句中指定的lettercase存储在磁盘上,但是MySQL在查找时将它们转换为小写。名称比较不区分大小写。这只适用于不区分大小写的文件系统!InnoDB表名和视图名以小写存储,Value = 1。 NOTE: lower_case_table_names can only be configured when initializing the server. Changing the lower_case_table_names setting after the server is initialized is prohibited. lower_case_table_names=1 Secure File Priv. 权限安全文件 secure-file-priv="C:/ProgramData/MySQL/MySQL Server 8.0/Uploads" The maximum amount of concurrent sessions the MySQL server will allow. One of these connections will be reserved for a user with SUPER privileges to allow the administrator to login even if the connection limit has been reached. MySQL服务器允许的最大并发会话量。这些连接中的一个将保留给具有超级特权的用户,以便允许管理员登录,即使已经达到连接限制。 max_connections=151 The number of open tables for all threads. Increasing this value increases the number of file descriptors that mysqld requires. Therefore you have to make sure to set the amount of open files allowed to at least 4096 in the variable "open-files-limit" in 为所有线程打开的表的数量。增加这个值会增加mysqld需要的文件描述符的数量。因此,您必须确保在[mysqld_safe]节中的变量“open-files-limit”中将允许打开的文件数量至少设置为4096 section [mysqld_safe] table_open_cache=2000 Maximum size for internal (in-memory) temporary tables. If a table grows larger than this value, it is automatically converted to disk based table This limitation is for a single table. There can be many of them. 内部(内存)临时表的最大大小。如果一个表比这个值大,那么它将自动转换为基于磁盘的表。可以有很多。 tmp_table_size=94M How many threads we should keep in a cache for reuse. When a client disconnects, the client's threads are put in the cache if there aren't more than thread_cache_size threads from before. This greatly reduces the amount of thread creations needed if you have a lot of new connections. (Normally this doesn't give a notable performance improvement if you have a good thread implementation.) 我们应该在缓存中保留多少线程以供重用。当客户机断开连接时,如果之前的线程数不超过thread_cache_size,则将客户机的线程放入缓存。如果您有很多新连接,这将大大减少所需的线程创建量(通常,如果您有一个良好的线程实现,这不会带来显著的性能改进)。 thread_cache_size=10 MyISAM Specific options The maximum size of the temporary file MySQL is allowed to use while recreating the index (during REPAIR, ALTER TABLE or LOAD DATA INFILE. If the file-size would be bigger than this, the index will be created through the key cache (which is slower). MySQL允许在重新创建索引时(在修复、修改表或加载数据时)使用临时文件的最大大小。如果文件大小大于这个值,那么索引将通过键缓存创建(这比较慢)。 myisam_max_sort_file_size=100G If the temporary file used for fast index creation would be bigger than using the key cache by the amount specified here, then prefer the key cache method. This is mainly used to force long character keys in large tables to use the slower key cache method to create the index. myisam_sort_buffer_size=179M Size of the Key Buffer, used to cache index blocks for MyISAM tables. Do not set it larger than 30% of your available memory, as some memory is also required by the OS to cache rows. Even if you're not using MyISAM tables, you should still set it to 8-64M as it will also be used for internal temporary disk tables. 如果用于快速创建索引的临时文件比这里指定的使用键缓存的文件大,则首选键缓存方法。这主要用于强制大型表中的长字符键使用较慢的键缓存方法来创建索引。 key_buffer_size=8M Size of the buffer used for doing full table scans of MyISAM tables. Allocated per thread, if a full scan is needed. 用于对MyISAM表执行全表扫描的缓冲区的大小。如果需要完整的扫描,则为每个线程分配。 read_buffer_size=256K read_rnd_buffer_size=512K INNODB Specific options INNODB特定选项 innodb_data_home_dir= Use this option if you have a MySQL server with InnoDB support enabled but you do not plan to use it. This will save memory and disk space and speed up some things. 如果您启用了一个支持InnoDB的MySQL服务器,但是您不打算使用它,那么可以使用这个选项。这将节省内存和磁盘空间,并加快一些事情。skip-innodb skip-innodb If set to 1, InnoDB will flush (fsync) the transaction logs to the disk at each commit, which offers full ACID behavior. If you are willing to compromise this safety, and you are running small transactions, you may set this to 0 or 2 to reduce disk I/O to the logs. Value 0 means that the log is only written to the log file and the log file flushed to disk approximately once per second. Value 2 means the log is written to the log file at each commit, but the log file is only flushed to disk approximately once per second. 如果设置为1,InnoDB将在每次提交时将事务日志刷新(fsync)到磁盘,这将提供完整的ACID行为。如果您愿意牺牲这种安全性,并且正在运行小型事务,您可以将其设置为0或2,以将磁盘I/O减少到日志。值0表示日志仅写入日志文件,日志文件大约每秒刷新一次磁盘。值2表示日志在每次提交时写入日志文件,但是日志文件大约每秒只刷新一次磁盘。 innodb_flush_log_at_trx_commit=1 The size of the buffer InnoDB uses for buffering log data. As soon as it is full, InnoDB will have to flush it to disk. As it is flushed once per second anyway, it does not make sense to have it very large (even with long transactions).InnoDB用于缓冲日志数据的缓冲区大小。一旦它满了,InnoDB就必须将它刷新到磁盘。由于它无论如何每秒刷新一次,所以将它设置为非常大的值是没有意义的(即使是长事务)。 innodb_log_buffer_size=5M InnoDB, unlike MyISAM, uses a buffer pool to cache both indexes and row data. The bigger you set this the less disk I/O is needed to access data in tables. On a dedicated database server you may set this parameter up to 80% of the machine physical memory size. Do not set it too large, though, because competition of the physical memory may cause paging in the operating system. Note that on 32bit systems you might be limited to 2-3.5G of user level memory per process, so do not set it too high. 与MyISAM不同,InnoDB使用缓冲池来缓存索引和行数据。设置的值越大,访问表中的数据所需的磁盘I/O就越少。在专用数据库服务器上,可以将该参数设置为机器物理内存大小的80%。但是,不要将它设置得太大,因为物理内存的竞争可能会导致操作系统中的分页。注意,在32位系统上,每个进程的用户级内存可能被限制在2-3.5G,所以不要设置得太高。 innodb_buffer_pool_size=20M Size of each log file in a log group. You should set the combined size of log files to about 25%-100% of your buffer pool size to avoid unneeded buffer pool flush activity on log file overwrite. However, note that a larger logfile size will increase the time needed for the recovery process. 日志组中每个日志文件的大小。您应该将日志文件的合并大小设置为缓冲池大小的25%-100%,以避免在覆盖日志文件时出现不必要的缓冲池刷新活动。但是,请注意,较大的日志文件大小将增加恢复过程所需的时间。 innodb_log_file_size=48M Number of threads allowed inside the InnoDB kernel. The optimal value depends highly on the application, hardware as well as the OS scheduler properties. A too high value may lead to thread thrashing. InnoDB内核中允许的线程数。最优值在很大程度上取决于应用程序、硬件以及OS调度程序属性。过高的值可能导致线程抖动。 innodb_thread_concurrency=9 The increment size (in MB) for extending the size of an auto-extend InnoDB system tablespace file when it becomes full. 增量大小(以MB为单位),用于在表空间满时扩展自动扩展的InnoDB系统表空间文件的大小。 innodb_autoextend_increment=128 The number of regions that the InnoDB buffer pool is divided into. For systems with buffer pools in the multi-gigabyte range, dividing the buffer pool into separate instances can improve concurrency, by reducing contention as different threads read and write to cached pages. InnoDB缓冲池划分的区域数。对于具有多gb缓冲池的系统,将缓冲池划分为单独的实例可以提高并发性,因为不同的线程对缓存页面的读写会减少争用。 innodb_buffer_pool_instances=8 Determines the number of threads that can enter InnoDB concurrently. 确定可以同时进入InnoDB的线程数 innodb_concurrency_tickets=5000 Specifies how long in milliseconds (ms) a block inserted into the old sublist must stay there after its first access before it can be moved to the new sublist. 指定插入到旧子列表中的块必须在第一次访问之后停留多长时间(毫秒),然后才能移动到新子列表。 innodb_old_blocks_time=1000 It specifies the maximum number of .ibd files that MySQL can keep open at one time. The minimum value is 10. 它指定MySQL一次可以打开的.ibd文件的最大数量。最小值是10。 innodb_open_files=300 When this variable is enabled, InnoDB updates statistics during metadata statements. 当启用此变量时,InnoDB会在元数据语句期间更新统计信息。 innodb_stats_on_metadata=0 When innodb_file_per_table is enabled (the default in 5.6.6 and higher), InnoDB stores the data and indexes for each newly created table in a separate .ibd file, rather than in the system tablespace. 当启用innodb_file_per_table(5.6.6或更高版本的默认值)时,InnoDB将每个新创建的表的数据和索引存储在单独的.ibd文件中,而不是系统表空间中。 innodb_file_per_table=1 Use the following list of values: 0 for crc32, 1 for strict_crc32, 2 for innodb, 3 for strict_innodb, 4 for none, 5 for strict_none. 使用以下值列表:0表示crc32, 1表示strict_crc32, 2表示innodb, 3表示strict_innodb, 4表示none, 5表示strict_none。 innodb_checksum_algorithm=0 The number of outstanding connection requests MySQL can have. This option is useful when the main MySQL thread gets many connection requests in a very short time. It then takes some time (although very little) for the main thread to check the connection and start a new thread. The back_log value indicates how many requests can be stacked during this short time before MySQL momentarily stops answering new requests. You need to increase this only if you expect a large number of connections in a short period of time. MySQL可以有多少未完成连接请求。当MySQL主线程在很短的时间内收到许多连接请求时,这个选项非常有用。然后,主线程需要一些时间(尽管很少)来检查连接并启动一个新线程。back_log值表示在MySQL暂时停止响应新请求之前的短时间内可以堆多少个请求。只有当您预期在短时间内会有大量连接时,才需要增加这个值。 back_log=80 If this is set to a nonzero value, all tables are closed every flush_time seconds to free up resources and synchronize unflushed data to disk. This option is best used only on systems with minimal resources. 如果将该值设置为非零值,则每隔flush_time秒关闭所有表,以释放资源并将未刷新的数据同步到磁盘。这个选项最好只在资源最少的系统上使用。 flush_time=0 The minimum size of the buffer that is used for plain index scans, range index scans, and joins that do not use 用于普通索引扫描、范围索引扫描和不使用索引执行全表扫描的连接的缓冲区的最小大小。 indexes and thus perform full table scans. join_buffer_size=200M The maximum size of one packet or any generated or intermediate string, or any parameter sent by the mysql_stmt_send_long_data() C API function. 由mysql_stmt_send_long_data() C API函数发送的一个包或任何生成的或中间字符串或任何参数的最大大小 max_allowed_packet=500M If more than this many successive connection requests from a host are interrupted without a successful connection, the server blocks that host from performing further connections. 如果在没有成功连接的情况下中断了来自主机的多个连续连接请求,则服务器将阻止主机执行进一步的连接。 max_connect_errors=100 Changes the number of file descriptors available to mysqld. You should try increasing the value of this option if mysqld gives you the error "Too many open files". 更改mysqld可用的文件描述符的数量。如果mysqld给您的错误是“打开的文件太多”,您应该尝试增加这个选项的值。 open_files_limit=4161 If you see many sort_merge_passes per second in SHOW GLOBAL STATUS output, you can consider increasing the sort_buffer_size value to speed up ORDER BY or GROUP BY operations that cannot be improved with query optimization or improved indexing. 如果在SHOW GLOBAL STATUS输出中每秒看到许多sort_merge_passes,可以考虑增加sort_buffer_size值,以加快ORDER BY或GROUP BY操作的速度,这些操作无法通过查询优化或改进索引来改进。 sort_buffer_size=1M The number of table definitions (from .frm files) that can be stored in the definition cache. If you use a large number of tables, you can create a large table definition cache to speed up opening of tables. The table definition cache takes less space and does not use file descriptors, unlike the normal table cache. The minimum and default values are both 400. 可以存储在定义缓存中的表定义的数量(来自.frm文件)。如果使用大量表,可以创建一个大型表定义缓存来加速表的打开。与普通的表缓存不同,表定义缓存占用更少的空间,并且不使用文件描述符。最小值和默认值都是400。 table_definition_cache=1400 Specify the maximum size of a row-based binary log event, in bytes. Rows are grouped into events smaller than this size if possible. The value should be a multiple of 256. 指定基于行的二进制日志事件的最大大小,单位为字节。如果可能,将行分组为小于此大小的事件。这个值应该是256的倍数。 binlog_row_event_max_size=8K If the value of this variable is greater than 0, a replication slave synchronizes its master.info file to disk. (using fdatasync()) after every sync_master_info events. 如果该变量的值大于0,则复制奴隶将其主.info文件同步到磁盘。(在每个sync_master_info事件之后使用fdatasync())。 sync_master_info=10000 If the value of this variable is greater than 0, the MySQL server synchronizes its relay log to disk. (using fdatasync()) after every sync_relay_log writes to the relay log. 如果这个变量的值大于0,MySQL服务器将其中继日志同步到磁盘。(在每个sync_relay_log写入到中继日志之后使用fdatasync())。 sync_relay_log=10000 If the value of this variable is greater than 0, a replication slave synchronizes its relay-log.info file to disk. (using fdatasync()) after every sync_relay_log_info transactions. 如果该变量的值大于0,则复制奴隶将其中继日志.info文件同步到磁盘。(在每个sync_relay_log_info事务之后使用fdatasync())。 sync_relay_log_info=10000 Load mysql plugins at start."plugin_x ; plugin_y". 开始时加载mysql插件。“plugin_x;plugin_y” plugin_load The TCP/IP Port the MySQL Server X Protocol will listen on. MySQL服务器X协议将监听TCP/IP端口。 loose_mysqlx_port=33060 本篇文章为转载内容。原文链接:https://blog.csdn.net/mywpython/article/details/89499852。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-10-08 09:56:02
129
转载
MySQL
MySQL , MySQL是一种开源的关系型数据库管理系统,广泛应用于Web应用开发中,尤其在LAMP(Linux、Apache、MySQL、PHP/Perl/Python)架构中扮演核心角色。用户可以使用SQL语言对MySQL进行数据查询、更新、管理和控制。在本文中,MySQL是被检测和安装的目标程序,用于满足用户在工作中处理和存储数据的需求。 sudo apt-get , 这是基于Debian和Ubuntu等Linux操作系统的包管理器命令,用于自动从软件仓库获取、安装、升级或卸载软件包及其依赖项。在本文语境下,当需要在Ubuntu系统上安装MySQL时,用户会运行\ sudo apt-get update\ 来更新软件源列表信息,接着执行\ sudo apt-get install mysql-server\ 命令以下载并安装MySQL服务器。 Windows命令提示符/终端 , Windows命令提示符(对于Windows操作系统)和终端(对于macOS和Linux操作系统)是操作系统提供的命令行界面工具,允许用户通过输入文本指令与系统交互,执行各种任务,包括文件管理、系统配置以及软件安装与管理等。在本文中,用户需在命令提示符或终端中输入特定命令来检测MySQL是否已安装,以及在必要时安装MySQL。
2023-02-06 16:45:27
103
程序媛
MySQL
...理的系统。在本文中,MySQL即是最受欢迎的一种关系型数据库管理系统,它将数据存储在一系列相互关联的表中,利用SQL(结构化查询语言)进行数据的检索、更新与管理。 MySQL Community Server , MySQL Community Server是MySQL官方提供的开源版本,适用于个人开发者、小型团队以及企业内部非生产环境使用。这个版本免费提供给用户下载和安装,具有丰富的功能特性,能够满足大部分应用场景的需求。在文章中,用户被指导访问MySQL官方网站下载MySQL Community Server来完成MySQL的安装过程。 终端/命令行窗口 , 终端或命令行窗口是一种基于文本的用户界面,允许用户通过输入特定的命令与操作系统交互。在macOS/Linux系统中通常称为“终端”,而在Windows系统中则称为“命令提示符”或“PowerShell”。在这篇文章里,用户需要通过打开终端或命令行窗口来执行相应的命令,如which mysql和mysql -V,以此查看MySQL是否已安装及确认其版本信息。
2023-09-19 12:58:09
133
算法侠
MySQL
何为MySQL服务 MySQL是一种普遍的关联型DBMS,它使用SQL语言来检索、添加、修改和移除数据。MySQL服务是指在本地计算机上运行的一个MySQL例子,允许用户在命令行和其他客户端应用程序中访问和管控数据。 装配MySQL服务 在开启MySQL服务之前,您需要先装配MySQL安装包。您可以从MySQL官方网站获取适合您系统软件版次的安装包,并按照指示运行装配向导。装配完成后,您将获得一个MySQL服务器并可以开始开启服务。 开启MySQL服务 使用Windows的用户可以通过打开命令提示符(cmd)程序来开启MySQL服务。在开始菜单的搜索栏中输入“cmd”,然后选择打开程序。在命令提示符窗口中,输入以下命令: net start mysql 按下回车键后,MySQL服务将开始运行,您现在可以通过其他客户端应用程序(如MySQL Workbench)访问数据库。 关闭MySQL服务 有时候您需要关闭MySQL服务。在命令提示符窗口,输入以下命令: net stop mysql 按下回车键后,MySQL服务将停止运行。在您需要再次使用MySQL服务时,需要再次以相同方式开启服务。 总结 通过在命令提示符窗口输入简单的命令,您可以轻松开启和停止MySQL服务。如果您有其他需要处理的数据库任务,可以使用客户端数据库管控软件(如MySQL Workbench)来运行更高级的操作。MySQL服务是非常有用的工具,在适当的配置和使用下,可以帮助您轻松管控和处理大量的数据。
2023-04-15 17:10:20
127
键盘勇士
MySQL
...(RDBMS)是一种基于关系模型的数据库管理系统,它通过表格、行和列的形式组织数据,并利用SQL(Structured Query Language)语言进行数据查询、更新等操作。在MySQL中,数据以表的形式存储,各个表之间可以建立关联,形成复杂的数据关系网络,以此实现高效、可靠的数据管理。 SQL语言 , SQL(Structured Query Language)是一种用于管理关系数据库的标准计算机编程语言,包括数据查询、数据插入、更新和删除以及数据库结构管理等功能。在MySQL环境中,用户可以使用SQL语句创建、修改或删除数据库及其中的表结构,同时也可以对数据进行复杂的检索、排序、统计与聚合操作。 mysqldump命令 , mysqldump是MySQL提供的一种用于备份数据库的重要工具,它可以将MySQL数据库中的所有数据和表结构生成为一个可移植的SQL脚本文件。通过执行mysqldump命令,用户能够完整地备份整个数据库或者部分特定的数据库表,便于在数据丢失或需要恢复时快速还原到某个时间点的状态,确保数据的安全性和完整性。例如,在MySQL中,用户可以通过命令行运行mysqldump命令,指定要备份的数据库名和其他相关参数来完成备份任务。
2023-02-05 14:43:17
74
程序媛
Apache Solr
...he Solr是一款基于Lucene的开源全文搜索引擎,广泛应用于各种场景下的数据检索。不过呢,随着Solr这家伙越来越受欢迎,用得越来越广泛,管理和维护它的工作也变得愈发繁琐复杂了。特别是对于大型系统而言,实时监控和性能日志记录显得尤为重要。这篇文章要手把手教你如何把Solr的实时监控和性能日志功能调校好,让你的系统稳如泰山,靠得住,一点儿都不含糊! 二、实时监控 实时监控可以帮助我们及时发现并解决系统中的问题,保证系统的正常运行。以下是配置Solr实时监控的步骤: 1. 添加JMX支持 Solr自带了JMX的支持,只需要在启动命令行中添加参数-Dcom.sun.management.jmxremote即可启用JMX监控。例如: bash java -Dcom.sun.management.jmxremote -jar start.jar 2. 安装JConsole JConsole是Java提供的一款图形化监控工具,可以通过它来查看Solr的各项指标和状态。 3. 启动JConsole 启动JConsole后,连接到localhost:9999/jconsole即可看到Solr的各种指标和状态。 三、性能日志记录 性能日志记录可以帮助我们了解Solr的工作情况和性能瓶颈,从而进行优化。以下是配置Solr性能日志记录的步骤: 1. 设置日志级别 在Solr的配置文件中设置日志级别,例如: xml ... 这里我们将日志级别设置为info,表示只记录重要信息和错误信息。 2. 设置日志格式 在Solr的配置文件中设置日志格式,例如: xml logs/solr.log %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n 这里我们将日志格式设置为"%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n",表示每行日志包含日期、时间、线程ID、日志级别、类名和方法名以及日志内容。 四、结论 配置Solr的实时监控和性能日志记录不仅可以帮助我们及时发现和解决系统中的问题,还可以让我们更好地理解和优化Solr的工作方式和性能。大家伙儿在实际操作时,可得把这些技巧玩转起来,让Solr跑得更溜、更稳当,实实在在提升运行效率和稳定性哈!
2023-03-17 20:56:07
473
半夏微凉-t
MySQL
...言 在编程的世界里,MySQL就像一座坚固的城堡,为数据提供了安全的存储和管理。如果你正计划踏上这个数据库管理的旅程,第一步就是确认它是否已经成功地安家在你的计算机上。本文将带你通过一系列步骤,一步步探索如何确认MySQL是否已经在你的系统中占据了一席之地。 二、步骤一 启动命令行探险 1.1 打开命令行的宝箱 首先,我们打开那个神秘的黑色窗口——命令提示符(Windows)或终端(Mac/Linux)。这将是我们与MySQL进行对话的第一个界面。 2.2 寻找MySQL的踪影 键入cmd或Terminal,然后按回车。接着,让我们尝试进入MySQL的根目录,例如,如果你的MySQL安装在C盘的Program Files文件夹下,你可以输入: bash cd C:\Program Files\MySQL\MySQL Server 5.7 (或你的实际版本) 确保替换5.7为你实际的MySQL服务器版本号。 三、步骤二 试驾MySQL马车 1.3 登录MySQL的王国 一旦到达目的地,我们需要驾驭mysql命令来连接到我们的数据库。输入以下命令: bash mysql -u root -p 然后按回车。系统会提示你输入root用户的密码。输入后,你会看到类似这样的欢迎信息: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 100 Server version: 5.7.33 MySQL Community Server (GPL) 如果看到类似的输出,那就意味着MySQL正在运行,并且你已经成功登录。 四、步骤三 深入检查安装状态 1.4 确认安装细节 为了进一步验证,我们可以执行status命令,这将显示服务器的状态和版本信息: SHOW VARIABLES LIKE 'version'; 这段代码会返回你的MySQL服务器的具体版本号,确认安装是否正确。 五、步骤四 启动服务的另一种方式 1.5 刷新记忆:服务视角 有时候,我们可能想要通过操作系统的服务管理器来检查MySQL是否作为服务正在运行。在Windows上,可以输入: powershell sc query mysql 在Linux或macOS中,使用systemctl status mysql或service mysql status。 六、代码片段 连接与断开 1.6 实战演练:连接失败的警示 为了展示连接不成功的场景,假设连接失败,你可能会看到类似这样的错误: php $conn = mysqli_connect('localhost', 'root', 'password'); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } 如果代码中mysqli_connect_error()返回非空字符串,那就意味着连接有问题。 七、结论 建立信任关系 通过以上步骤,你应该能够确定MySQL是否已经成功安装并运行。记住了啊,每当你要开始新的项目或者打算调整系统设置的时候,一定要记得这个重点,因为一个健健康康的数据库,那可是任何应用程序运行的命脉所在啊,就像人的心脏一样重要。要是你碰到啥问题,千万记得翻翻MySQL的官方宝典,或者去社区里找大伙儿帮忙。那儿可有一大群身经百战的老骑士们,他们绝对能给你提供靠谱的指导! 在你的编程旅程中,MySQL的安装和管理只是开始,随着你对其掌握的加深,你将能驾驭更多的高级特性,让数据安全而高效地流淌。祝你在数据库管理的征途上马到成功!
2024-03-08 11:25:52
117
昨夜星辰昨夜风-t
MySQL
序号 1:MySQL简介 作为全球最受欢迎的关系型数据库管理系统之一,MySQL以其高效、稳定和易用的特点,赢得了广泛的用户群体。它支持多种编程语言,如Java、PHP、Python等,使得开发人员可以轻松地与之集成。 序号 2:什么是完整的MySQL安装? 完成完整的MySQL安装意味着MySQL的所有组件都已成功安装,并且可以在系统上正常工作。包括但不限于: 1)MySQL服务器软件; 2)MySQL客户端工具(如MySQL Workbench); 3)MySQL相关的命令行工具(如MySQL Server Manager); 4)MySQL数据文件。 序号 3:如何测试MySQL是否安装完整? 为了确保MySQL已经安装完成,我们需要对其进行一些基本的测试。以下是几个简单的步骤: 步骤1:打开命令提示符或者终端窗口 首先,你需要打开命令提示符或者终端窗口。在用Windows系统的时候,你只要同时按住那个画着窗户的“Win”键和字母“R”键,就仿佛启动了一个小机关。接着,在弹出的小窗口里输入神秘的三个字母"cmd",再敲下回车键,就像施了个魔法一样,就能打开命令提示符这个神奇的小黑框了!在用Linux或者Mac电脑的时候,你只需要轻松几步就能打开终端。首先,在屏幕上的搜索框里键入"Terminal",然后敲下回车键,瞧!你的终端窗口就瞬间蹦出来了。 步骤2:检查MySQL服务是否正在运行 在命令提示符或者终端窗口中,输入以下命令来检查MySQL服务是否正在运行: sql netstat -ano | findstr MySQL 如果MySQL服务正在运行,上述命令将会返回相应的端口号和服务名。如果未找到相关信息,则表示MySQL服务并未运行。 步骤3:连接到MySQL服务器 接下来,我们尝试连接到MySQL服务器。在命令提示符或者终端窗口中,输入以下命令: css mysql -u root -p 这段命令的意思是使用root账户登录到MySQL服务器。如果成功连接,你将会看到一个提示符,提示你输入密码。输入正确的密码后,你就可以开始在MySQL服务器上进行操作了。 步骤4:创建一个新的数据库 在MySQL服务器上,你可以通过以下命令来创建一个新的数据库: sql CREATE DATABASE example; 这段命令将会创建一个名为example的新数据库。 步骤5:创建一个新的表 在新创建的数据库中,你可以通过以下命令来创建一个新的表: sql USE example; CREATE TABLE users ( id INT NOT NULL AUTO_INCREMENT, name VARCHAR(255), email VARCHAR(255), PRIMARY KEY (id) ); 这段命令将会在example数据库中创建一个名为users的新表,包含id、name和email三个字段。 步骤6:查询数据库 在MySQL服务器上,你可以通过以下命令来查询新创建的数据库和表: sql SHOW DATABASES; SHOW TABLES FROM example; SELECT FROM example.users; 以上就是测试MySQL是否安装完整的几个基本步骤。经过这些步骤,你就能确保MySQL的服务器软件、客户端小工具、命令行神器还有数据文件都妥妥地安装好了,并且随时可以正常启动,愉快地使用起来啦!同时呢,你还可以亲自去瞅瞅MySQL的运行状况啊,还有它的性能表现啥的,这样一来,就能更棒地打理和调优你的MySQL数据库了,让它的表现更上一层楼! 总结起来,要想保证MySQL能够正常运行,就需要对其进行全面的测试。这包括瞅瞅MySQL服务的小火车跑得顺不顺畅,确保它能稳妥连接。咱们还要亲自上手,捣鼓捣鼓创建数据库和表的操作,再溜达一圈,试试查询功能灵不灵光,这些可都是必不可少的环节~只要按照上述步骤进行操作,就能够确保MySQL安装的完整性。
2023-06-26 18:05:53
32
风轻云淡_t
DorisDB
...实现快速的数据分析与查询。在本文的语境中,用户在使用过程中可能会遇到DorisDB版本与所使用的数据库软件版本不兼容的问题。 ODBC驱动程序 , ODBC全称为Open Database Connectivity(开放数据库连接),是一种由微软公司制定的应用程序编程接口(API)。ODBC驱动程序是基于此标准开发的一种中间件,允许应用程序访问不同类型的数据库,而不必考虑其底层数据库管理系统(DBMS)的具体实现和版本差异。在解决数据库版本不匹配问题时,通过ODBC驱动程序可以在各种不同的数据库之间进行数据迁移和交互,充当一个灵活的桥梁角色。 MPP(大规模并行处理) , MPP是一种数据库架构设计方式,它允许多个处理器同时并行处理大量数据,每个处理器都拥有独立的内存和磁盘存储空间,共同协作完成复杂的查询任务。这种架构特别适合于大数据量的在线分析处理(OLAP)场景,能够显著提升数据处理速度和效率,如文中提及的DorisDB即采用了MPP架构设计。 数据库版本不匹配 , 在数据库管理和维护过程中,当某一数据库软件(如MySQL、Oracle等)更新至新版本后,如果与其对接的其他数据库系统(如DorisDB)未及时同步更新,则可能出现两者之间因接口、协议或功能上的差异而导致无法正常通信、交换数据的现象,这就是所谓的“数据库版本不匹配”。
2023-03-28 13:12:45
429
笑傲江湖-t
Linux
...odb/ (根据实际安装配置可能有所不同) sudo cp -R /var/lib/mongodb/ /path/to/backup/ 通过Linux命令行直接复制MongoDB的数据文件目录到备份位置,这是一种最基础的物理备份方式。不过要注意,在咱们进行备份的时候,务必要保证数据库没在进行任何写入操作。要不然的话,可能会让备份出来的文件出现不一致的情况,那就麻烦啦。 2.2 mongodump工具备份 (代码示例) bash mongodump --host localhost --port 27017 --db your_database_name --out /path/to/backup/ mongodump是MongoDB官方提供的用于逻辑备份的工具,它会将数据库的内容导出为JSON格式的bson文件,这样可以方便地在其他MongoDB实例上导入恢复。在上述命令中,我们指定了目标数据库地址、端口以及备份输出目录。 2.3 使用MongoDB Atlas自动备份服务(可选) 对于使用MongoDB云服务Atlas的用户,其内置了自动备份功能,只需在控制台设置好备份策略,系统就会按照设定的时间周期自动完成数据库的备份,无需手动干预。 3. 实战 结合cron定时任务实现自动化备份 (思考过程)为了保证备份的及时性与连续性,我们可以借助Linux的cron定时任务服务,每天、每周或每月定期执行备份任务。 (代码示例) bash 编辑crontab任务列表 crontab -e 添加以下定时任务,每天凌晨1点执行mongodump备份 0 1 mongodump --host localhost --port 27017 --db your_database_name --out /path/to/backup/$(date +\%Y-\%m-\%d) 保存并退出编辑器 以上示例中,我们设置了每日凌晨1点执行mongodump备份,并将备份文件保存在按日期命名的子目录下,便于后期管理和恢复。 4. 结语 备份策略的优化与完善 尽管我们已经掌握了MongoDB在Linux下的备份方法,但这只是万里长征的第一步。在实际操作时,咱们还要琢磨一下怎么把备份文件给压缩、加密了,再送到远程的地方存好,甚至要考虑只备份有变动的部分(增量备份)。而且,最好能整出一套全面的灾备方案,以备不时之需。总的来说,咱们对待数据库备份这事儿,就得像呵护自家压箱底的宝贝一样倍加小心。你想啊,数据这玩意儿的价值,那可是无价之宝,而备份呢,就是我们保护这个宝贝不丢的关键法宝,可得看重喽! (探讨性话术)亲爱的读者,你是否已开始构思自己项目的MongoDB备份方案?不妨分享你的见解和实践经验,让我们共同探讨如何更好地保护那些宝贵的数据资源。
2023-06-14 17:58:12
452
寂静森林_
SpringBoot
...活的数据模型、强大的查询能力和易于使用的API,成为了许多企业的首选。在众多的NoSQL数据库里头,SpringBoot和MongoDB的联手合作可是相当普遍,而且技术上也相当成熟,可以说是其中一对黄金搭档啦!这篇文稿,咱们要手把手地教你如何在SpringBoot这个大家伙里头接入MongoDB数据库,并且还会举些实实在在的例子,演示一些你可能会经常用到的操作步骤,保证接地气儿,不玩虚的。 2. 环境搭建 在开始集成之前,我们需要先准备好相应的开发环境。首先,兄弟姐妹们,咱得先下载并安装Java运行环境。版本上没硬性要求,不过我强烈建议你们选择最新潮的那个——Java 8或者更新更高的版本,这样用起来更溜~然后,我们需要下载并安装SpringBoot和Maven这两个工具。SpringBoot可以为我们提供一个快速构建Web应用的基础框架,而Maven则可以帮助我们管理项目的依赖关系。 3. 创建SpringBoot项目 接下来,我们可以开始创建我们的SpringBoot项目。首先,打开命令行工具,并进入你要存放项目的位置。然后,输入以下命令来创建一个新的SpringBoot项目: bash mvn archetype:generate -DgroupId=com.example -DartifactId=springboot-mongoapp -DarchetypeArtifactId= spring-boot-starter-parent -DinteractiveMode=false 这行命令的意思是使用Maven的archetype功能来生成一个新的SpringBoot项目,该项目的组ID为com.example, artifactID为springboot-mongoapp,父依赖为spring-boot-starter-parent。这个命令会自动为你创建好所有的项目文件和目录结构,包括pom.xml和src/main/java/com/example/springbootmongoapp等文件。 4. 配置SpringBoot和MongoDB 在创建好项目之后,我们需要进行一些配置工作。首先,我们需要在pom.xml文件中添加SpringDataMongoDB的依赖: xml org.springframework.boot spring-boot-starter-data-mongodb 这行代码的意思是我们需要使用SpringDataMongoDB来处理MongoDB的相关操作。然后,我们需要在application.properties文件中添加MongoDB的连接信息: properties spring.data.mongodb.uri=mongodb://localhost:27017/mydb 这行代码的意思是我们的MongoDB服务器位于本地主机的27017端口上,且数据库名为mydb。 5. 使用MongoTemplate操作MongoDB 在配置完成后,我们就可以开始使用MongoTemplate来操作MongoDB了。MongoTemplate是SpringDataMongoDB提供的一个类,它可以帮助我们执行各种数据库操作。下面是一些基本的操作示例: java @Autowired private MongoTemplate mongoTemplate; public void insert(String collectionName, String id, Object entity) { mongoTemplate.insert(entity, collectionName); } public List find(String collectionName, Query query) { return mongoTemplate.find(query, Object.class, collectionName); } 6. 使用Repository操作MongoDB 除了MongoTemplate之外,SpringDataMongoDB还提供了Repository接口,它可以帮助我们更加方便地进行数据库操作。我们完全可以把这个接口“继承”下来,然后自己动手编写几个核心的方法,就像是插入数据、查找信息、更新记录、删除项目这些基本操作,让它们各司其职,活跃在我们的程序里。下面是一个简单的示例: java @Repository public interface UserRepository extends MongoRepository { User findByUsername(String username); void deleteByUsername(String username); default void save(User user) { if (user.getId() == null) { user.setId(UUID.randomUUID().toString()); } super.save(user); } @Query(value = "{'username':?0}") List findByUsername(String username); } 7. 总结 总的来说,SpringBoot与MongoDB的集成是非常简单和便捷的。只需要几步简单的配置,我们就可以使用SpringBoot的强大功能来操作MongoDB。而且你知道吗,SpringDataMongoDB这家伙还藏着不少好东西嘞,像数据映射、查询、聚合这些高级功能,全都是它的拿手好戏。这样一来,我们开发应用程序就能又快又高效,简直像是插上了小翅膀一样飞速前进!所以,如果你正在琢磨着用NoSQL数据库来搭建你的数据存储方案,那我真心实意地拍胸脯推荐你试试SpringBoot配上MongoDB这个黄金组合,准保不会让你失望!
2023-04-09 13:34:32
76
岁月如歌-t
MySQL
怎么查看MySQL数据库IP?手把手教你找到数据库的“家” 嗨,朋友们!今天咱们来聊聊一个超级实用的小问题——怎么查看MySQL数据库的IP地址。这事儿看起来简单,但其实背后藏着不少门道。嘿,作为一个在数据库这条路上摸爬滚打多年的老鸟,我觉得是时候跟大家唠唠这个事儿了! 首先,咱们得搞清楚为什么需要知道MySQL数据库的IP地址。其实,这个问题的答案可能因人而异。嘿,有的人捣鼓服务器连接,有的人在查网络为啥出问题,还有一堆人就单纯想搞清楚自己鼓捣出来的数据库到底“住”在哪儿,就跟想知道自家小宠物被关在哪间房一样好奇!不管你到底是为了啥,能整清楚数据库的那个IP地址,这本事可真挺关键的!那么接下来,咱们就一步步来解决这个问题! --- 1. 本地MySQL数据库的IP地址 情况一:数据库运行在你的电脑上 如果你的MySQL数据库是安装在你自己的机器上,并且你只打算让它服务于本地的应用程序,那么它的IP地址通常就是localhost或者127.0.0.1。这是最常见的情况之一,也是初学者最容易遇到的场景。 如何确认? 打开命令行工具(Windows用户可以用CMD,Mac/Linux用户可以用Terminal),然后输入以下命令: sql SELECT @@hostname; 这条SQL语句会返回当前MySQL服务器所在的主机名。如果你想进一步验证是不是本地环境,可以再试试: sql SELECT @@datadir; 这段代码会显示MySQL的数据目录路径。要是文件路径里提到你的用户名,或者用的是系统盘符(像 C:\ProgramData\MySQL\MySQL Server 8.0\Data 这种),那十有八九数据库就在你自己的电脑上啦! --- 情况二:数据库运行在远程服务器上 如果你的MySQL数据库部署在一台远程服务器上,那么它的IP地址就不会是localhost了。你需要通过一些工具或者命令来获取具体的IP地址。 方法一:直接登录服务器查看 假设你有一台Linux服务器,可以通过SSH工具(比如PuTTY或终端)登录到服务器后,执行以下命令: bash ifconfig | grep "inet " 这段命令会列出服务器的所有网络接口及其对应的IP地址。如果你看到类似inet 192.168.1.100这样的输出,恭喜你,这就是MySQL数据库所在服务器的IP地址啦! 方法二:通过MySQL命令查看 如果你已经成功连接到了远程MySQL服务器,也可以在MySQL客户端中执行以下命令: sql SELECT @@hostname; 这条命令同样会返回数据库所在的主机名。不过,这里得到的通常是服务器的域名(比如myserver.example.com)。为了找到真实的IP地址,你可以使用ping命令进行测试: bash ping myserver.example.com 通过这种方式,你可以轻松地将域名解析为实际的IP地址。 --- 2. MySQL配置文件中的IP地址 有时候,数据库的IP地址并不是动态分配的,而是明确写在了配置文件里。这种情况下,我们只需要找到配置文件的位置并读取它即可。 配置文件在哪里? 不同的操作系统和安装方式可能会导致配置文件的位置有所不同。以下是常见的几个位置: - Linux/Unix系统:通常是/etc/mysql/my.cnf或者/etc/my.cnf。 - Windows系统:可能是C:\ProgramData\MySQL\MySQL Server 8.0\my.ini。 - macOS:可以尝试查找/usr/local/mysql/my.cnf。 打开配置文件后,搜索关键词bind-address。这个参数定义了MySQL服务监听的IP地址。例如: ini bind-address = 192.168.1.100 这里的192.168.1.100就是MySQL数据库的IP地址。如果该值为空,则表示MySQL监听所有可用的IP地址。 --- 3. 使用第三方工具检测数据库IP 如果你没有权限直接访问服务器或者配置文件,还可以借助一些第三方工具来探测数据库的IP地址。 工具推荐: 1. Nmap 一款强大的网络扫描工具,可以帮助你发现目标服务器上的开放端口和服务。 bash nmap -p 3306 yourdomain.com 如果MySQL服务正在运行并且监听了外部请求,那么这段命令会显示出相应的IP地址。 2. telnet 一种简单的远程连接工具,用于检查特定端口是否可达。 bash telnet yourdomain.com 3306 如果连接成功,说明MySQL服务正在指定的IP地址上运行。 --- 4. 小结与反思 经过一番折腾,我们终于找到了MySQL数据库的IP地址。虽然过程有些曲折,但我相信这些方法对大家来说都非常实用。在这个过程中,我也学到了很多新东西,比如如何解读配置文件、如何利用命令行工具解决问题等等。 最后想提醒大家一句:无论你是新手还是老鸟,在操作数据库时都要小心谨慎,尤其是在涉及网络配置的时候。毕竟,稍不留神就可能导致数据泄露或者其他严重后果。所以,动手之前一定要三思而后行哦! 好了,今天的分享就到这里啦!如果你还有什么疑问或者更好的解决方案,欢迎随时留言交流。咱们下期再见!
2025-03-24 15:46:41
78
笑傲江湖
转载文章
...句类型,比如:关联子查询 支持绝大部分PostgreSQL的SQL语句 分布式多版本并发控制(MVCC:Multi-version Concurrency Control) 支持JSON和XML格式 Postgres-XL缺少的功能 内建的高可用机制 使用外部机制实现高可能,如:Corosync/Pacemaker 有未来功能提升的空间 增加节点/重新分片数据(re-shard)的简便性 数据重分布(redistribution)期间会锁表 可采用预分片(pre-shard)方式解决,在同台物理服务器上建立多个数据节点,每个节点存储一个数据分片。数据重分布时,将一些数据节点迁出即可 某些外键、唯一性约束功能 Postgres-XL架构 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-M9lFuEIP-1640133702200)(./assets/postgre-xl.jpg)] 基于开源项目Postgres-XC XL增加了MPP,允许数据节点间直接通讯,交换复杂跨节点关联查询相关数据信息,减少协调器负载。 多个协调器(Coordinator) 应用程序的数据库连入点 分析查询语句,生成执行计划 多个数据节点(DataNode) 实际的数据存储 数据自动打散分布到集群中各数据节点 本地执行查询 一个查询在所有相关节点上并行查询 全局事务管理器(GTM:Global Transaction Manager) 提供事务间一致性视图 部署GTM Proxy实例,以提高性能 Postgre-XL主要组件 GTM (Global Transaction Manager) - 全局事务管理器 GTM是Postgres-XL的一个关键组件,用于提供一致的事务管理和元组可见性控制。 GTM Standby GTM的备节点,在pgxc,pgxl中,GTM控制所有的全局事务分配,如果出现问题,就会导致整个集群不可用,为了增加可用性,增加该备用节点。当GTM出现问题时,GTM Standby可以升级为GTM,保证集群正常工作。 GTM-Proxy GTM需要与所有的Coordinators通信,为了降低压力,可以在每个Coordinator机器上部署一个GTM-Proxy。 Coordinator --协调器 协调器是应用程序到数据库的接口。它的作用类似于传统的PostgreSQL后台进程,但是协调器不存储任何实际数据。实际数据由数据节点存储。协调器接收SQL语句,根据需要获取全局事务Id和全局快照,确定涉及哪些数据节点,并要求它们执行(部分)语句。当向数据节点发出语句时,它与GXID和全局快照相关联,以便多版本并发控制(MVCC)属性扩展到集群范围。 Datanode --数据节点 用于实际存储数据。表可以分布在各个数据节点之间,也可以复制到所有数据节点。数据节点没有整个数据库的全局视图,它只负责本地存储的数据。接下来,协调器将检查传入语句,并制定子计划。然后,根据需要将这些数据连同GXID和全局快照一起传输到涉及的每个数据节点。数据节点可以在不同的会话中接收来自各个协调器的请求。但是,由于每个事务都是惟一标识的,并且与一致的(全局)快照相关联,所以每个数据节点都可以在其事务和快照上下文中正确执行。 Postgres-XL继承了PostgreSQL Postgres-XL是PostgreSQL的扩展并继承了其很多特性: 复杂查询 外键 触发器 视图 事务 MVCC(多版本控制) 此外,类似于PostgreSQL,用户可以通过多种方式扩展Postgres-XL,例如添加新的 数据类型 函数 操作 聚合函数 索引类型 过程语言 安装 环境说明 由于资源有限,gtm一台、另外两台身兼数职。 主机名 IP 角色 端口 nodename 数据目录 gtm 192.168.20.132 GTM 6666 gtm /nodes/gtm 协调器 5432 coord1 /nodes/coordinator xl1 192.168.20.133 数据节点 5433 node1 /nodes/pgdata gtm代理 6666 gtmpoxy01 /nodes/gtm_pxy1 协调器 5432 coord2 /nodes/coordinator xl2 192.168.20.134 数据节点 5433 node2 /nodes/pgdata gtm代理 6666 gtmpoxy02 /nodes/gtm_pxy2 要求 GNU make版本 3.8及以上版本 [root@pg ~] make --versionGNU Make 3.82Built for x86_64-redhat-linux-gnuCopyright (C) 2010 Free Software Foundation, Inc.License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>This is free software: you are free to change and redistribute it.There is NO WARRANTY, to the extent permitted by law. 需安装GCC包 需安装tar包 用于解压缩文件 默认需要GNU Readline library 其作用是可以让psql命令行记住执行过的命令,并且可以通过键盘上下键切换命令。但是可以通过--without-readline禁用这个特性,或者可以指定--withlibedit-preferred选项来使用libedit 默认使用zlib压缩库 可通过--without-zlib选项来禁用 配置hosts 所有主机上都配置 [root@xl2 11] cat /etc/hosts127.0.0.1 localhost192.168.20.132 gtm192.168.20.133 xl1192.168.20.134 xl2 关闭防火墙、Selinux 所有主机都执行 关闭防火墙: [root@gtm ~] systemctl stop firewalld.service[root@gtm ~] systemctl disable firewalld.service selinux设置: [root@gtm ~]vim /etc/selinux/config 设置SELINUX=disabled,保存退出。 This file controls the state of SELinux on the system. SELINUX= can take one of these three values: enforcing - SELinux security policy is enforced. permissive - SELinux prints warnings instead of enforcing. disabled - No SELinux policy is loaded.SELINUX=disabled SELINUXTYPE= can take one of three two values: targeted - Targeted processes are protected, minimum - Modification of targeted policy. Only selected processes are protected. mls - Multi Level Security protection. 安装依赖包 所有主机上都执行 yum install -y flex bison readline-devel zlib-devel openjade docbook-style-dsssl gcc 创建用户 所有主机上都执行 [root@gtm ~] useradd postgres[root@gtm ~] passwd postgres[root@gtm ~] su - postgres[root@gtm ~] mkdir ~/.ssh[root@gtm ~] chmod 700 ~/.ssh 配置SSH免密登录 仅仅在gtm节点配置如下操作: [root@gtm ~] su - postgres[postgres@gtm ~] ssh-keygen -t rsa[postgres@gtm ~] cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys[postgres@gtm ~] chmod 600 ~/.ssh/authorized_keys 将刚生成的认证文件拷贝到xl1到xl2中,使得gtm节点可以免密码登录xl1~xl2的任意一个节点: [postgres@gtm ~] scp ~/.ssh/authorized_keys postgres@xl1:~/.ssh/[postgres@gtm ~] scp ~/.ssh/authorized_keys postgres@xl2:~/.ssh/ 对所有提示都不要输入,直接enter下一步。直到最后,因为第一次要求输入目标机器的用户密码,输入即可。 下载源码 下载地址:https://www.postgres-xl.org/download/ [root@slave ~] ll postgres-xl-10r1.1.tar.gz-rw-r--r-- 1 root root 28121666 May 30 05:21 postgres-xl-10r1.1.tar.gz 编译、安装Postgres-XL 所有节点都安装,编译需要一点时间,最好同时进行编译。 [root@slave ~] tar xvf postgres-xl-10r1.1.tar.gz[root@slave ~] ./configure --prefix=/home/postgres/pgxl/[root@slave ~] make[root@slave ~] make install[root@slave ~] cd contrib/ --安装必要的工具,在gtm节点上安装即可[root@slave ~] make[root@slave ~] make install 配置环境变量 所有节点都要配置 进入postgres用户,修改其环境变量,开始编辑 [root@gtm ~]su - postgres[postgres@gtm ~]vi .bashrc --不是.bash_profile 在打开的文件末尾,新增如下变量配置: export PGHOME=/home/postgres/pgxlexport LD_LIBRARY_PATH=$PGHOME/lib:$LD_LIBRARY_PATHexport PATH=$PGHOME/bin:$PATH 按住esc,然后输入:wq!保存退出。输入以下命令对更改重启生效。 [postgres@gtm ~] source .bashrc --不是.bash_profile 输入以下语句,如果输出变量结果,代表生效 [postgres@gtm ~] echo $PGHOME 应该输出/home/postgres/pgxl代表生效 配置集群 生成pgxc_ctl.conf配置文件 [postgres@gtm ~] pgxc_ctl prepare/bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxl/pgxc_ctl/pgxc_ctl_bash.ERROR: File "/home/postgres/pgxl/pgxc_ctl/pgxc_ctl.conf" not found or not a regular file. No such file or directoryInstalling pgxc_ctl_bash script as /home/postgres/pgxl/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxl/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxl/pgxc_ctl --configuration /home/postgres/pgxl/pgxc_ctl/pgxc_ctl.confFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxl/pgxc_ctl 配置pgxc_ctl.conf 新建/home/postgres/pgxc_ctl/pgxc_ctl.conf文件,编辑如下: 对着模板文件一个一个修改,否则会造成初始化过程出现各种神奇问题。 pgxcInstallDir=$PGHOMEpgxlDATA=$PGHOME/data pgxcOwner=postgres---- GTM Master -----------------------------------------gtmName=gtmgtmMasterServer=gtmgtmMasterPort=6666gtmMasterDir=$pgxlDATA/nodes/gtmgtmSlave=y Specify y if you configure GTM Slave. Otherwise, GTM slave will not be configured and all the following variables will be reset.gtmSlaveName=gtmSlavegtmSlaveServer=gtm value none means GTM slave is not available. Give none if you don't configure GTM Slave.gtmSlavePort=20001 Not used if you don't configure GTM slave.gtmSlaveDir=$pgxlDATA/nodes/gtmSlave Not used if you don't configure GTM slave.---- GTM-Proxy Master -------gtmProxyDir=$pgxlDATA/nodes/gtm_proxygtmProxy=y gtmProxyNames=(gtm_pxy1 gtm_pxy2) gtmProxyServers=(xl1 xl2) gtmProxyPorts=(6666 6666) gtmProxyDirs=($gtmProxyDir $gtmProxyDir) ---- Coordinators ---------coordMasterDir=$pgxlDATA/nodes/coordcoordNames=(coord1 coord2) coordPorts=(5432 5432) poolerPorts=(6667 6667) coordPgHbaEntries=(0.0.0.0/0)coordMasterServers=(xl1 xl2) coordMasterDirs=($coordMasterDir $coordMasterDir)coordMaxWALsernder=0 没设置备份节点,设置为0coordMaxWALSenders=($coordMaxWALsernder $coordMaxWALsernder) 数量保持和coordMasterServers一致coordSlave=n---- Datanodes ----------datanodeMasterDir=$pgxlDATA/nodes/dn_masterprimaryDatanode=xl1 主数据节点datanodeNames=(node1 node2)datanodePorts=(5433 5433) datanodePoolerPorts=(6668 6668) datanodePgHbaEntries=(0.0.0.0/0)datanodeMasterServers=(xl1 xl2)datanodeMasterDirs=($datanodeMasterDir $datanodeMasterDir)datanodeMaxWalSender=4datanodeMaxWALSenders=($datanodeMaxWalSender $datanodeMaxWalSender) 集群初始化,启动,停止 初始化 pgxc_ctl -c /home/postgres/pgxc_ctl/pgxc_ctl.conf init all 输出结果: /bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Installing pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxc_ctl --configuration /home/postgres/pgxc_ctl/pgxc_ctl.conf/home/postgres/pgxc_ctl/pgxc_ctl.conf: line 189: $coordExtraConfig: ambiguous redirectFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxc_ctlStopping all the coordinator masters.Stopping coordinator master coord1.Stopping coordinator master coord2.pg_ctl: directory "/home/postgres/pgxc/nodes/coord/coord1" does not existpg_ctl: directory "/home/postgres/pgxc/nodes/coord/coord2" does not existDone.Stopping all the datanode masters.Stopping datanode master datanode1.Stopping datanode master datanode2.pg_ctl: PID file "/home/postgres/pgxc/nodes/datanode/datanode1/postmaster.pid" does not existIs server running?Done.Stop GTM masterwaiting for server to shut down.... doneserver stopped[postgres@gtm ~]$ echo $PGHOME/home/postgres/pgxl[postgres@gtm ~]$ ll /home/postgres/pgxl/pgxc/nodes/gtm/gtm.^C[postgres@gtm ~]$ pgxc_ctl -c /home/postgres/pgxc_ctl/pgxc_ctl.conf init all/bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Installing pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxc_ctl --configuration /home/postgres/pgxc_ctl/pgxc_ctl.conf/home/postgres/pgxc_ctl/pgxc_ctl.conf: line 189: $coordExtraConfig: ambiguous redirectFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxc_ctlInitialize GTM masterERROR: target directory (/home/postgres/pgxc/nodes/gtm) exists and not empty. Skip GTM initilializationDone.Start GTM masterserver startingInitialize all the coordinator masters.Initialize coordinator master coord1.ERROR: target coordinator master coord1 is running now. Skip initilialization.Initialize coordinator master coord2.The files belonging to this database system will be owned by user "postgres".This user must also own the server process.The database cluster will be initialized with locale "en_US.UTF-8".The default database encoding has accordingly been set to "UTF8".The default text search configuration will be set to "english".Data page checksums are disabled.fixing permissions on existing directory /home/postgres/pgxc/nodes/coord/coord2 ... okcreating subdirectories ... okselecting default max_connections ... 100selecting default shared_buffers ... 128MBselecting dynamic shared memory implementation ... posixcreating configuration files ... okrunning bootstrap script ... okperforming post-bootstrap initialization ... creating cluster information ... oksyncing data to disk ... okfreezing database template0 ... okfreezing database template1 ... okfreezing database postgres ... okWARNING: enabling "trust" authentication for local connectionsYou can change this by editing pg_hba.conf or using the option -A, or--auth-local and --auth-host, the next time you run initdb.Success.Done.Starting coordinator master.Starting coordinator master coord1ERROR: target coordinator master coord1 is already running now. Skip initialization.Starting coordinator master coord22019-05-30 21:09:25.562 EDT [2148] LOG: listening on IPv4 address "0.0.0.0", port 54322019-05-30 21:09:25.562 EDT [2148] LOG: listening on IPv6 address "::", port 54322019-05-30 21:09:25.563 EDT [2148] LOG: listening on Unix socket "/tmp/.s.PGSQL.5432"2019-05-30 21:09:25.601 EDT [2149] LOG: database system was shut down at 2019-05-30 21:09:22 EDT2019-05-30 21:09:25.605 EDT [2148] LOG: database system is ready to accept connections2019-05-30 21:09:25.612 EDT [2156] LOG: cluster monitor startedDone.Initialize all the datanode masters.Initialize the datanode master datanode1.Initialize the datanode master datanode2.The files belonging to this database system will be owned by user "postgres".This user must also own the server process.The database cluster will be initialized with locale "en_US.UTF-8".The default database encoding has accordingly been set to "UTF8".The default text search configuration will be set to "english".Data page checksums are disabled.fixing permissions on existing directory /home/postgres/pgxc/nodes/datanode/datanode1 ... okcreating subdirectories ... okselecting default max_connections ... 100selecting default shared_buffers ... 128MBselecting dynamic shared memory implementation ... posixcreating configuration files ... okrunning bootstrap script ... okperforming post-bootstrap initialization ... creating cluster information ... oksyncing data to disk ... okfreezing database template0 ... okfreezing database template1 ... okfreezing database postgres ... okWARNING: enabling "trust" authentication for local connectionsYou can change this by editing pg_hba.conf or using the option -A, or--auth-local and --auth-host, the next time you run initdb.Success.The files belonging to this database system will be owned by user "postgres".This user must also own the server process.The database cluster will be initialized with locale "en_US.UTF-8".The default database encoding has accordingly been set to "UTF8".The default text search configuration will be set to "english".Data page checksums are disabled.fixing permissions on existing directory /home/postgres/pgxc/nodes/datanode/datanode2 ... okcreating subdirectories ... okselecting default max_connections ... 100selecting default shared_buffers ... 128MBselecting dynamic shared memory implementation ... posixcreating configuration files ... okrunning bootstrap script ... okperforming post-bootstrap initialization ... creating cluster information ... oksyncing data to disk ... okfreezing database template0 ... okfreezing database template1 ... okfreezing database postgres ... okWARNING: enabling "trust" authentication for local connectionsYou can change this by editing pg_hba.conf or using the option -A, or--auth-local and --auth-host, the next time you run initdb.Success.Done.Starting all the datanode masters.Starting datanode master datanode1.WARNING: datanode master datanode1 is running now. Skipping.Starting datanode master datanode2.2019-05-30 21:09:33.352 EDT [2404] LOG: listening on IPv4 address "0.0.0.0", port 154322019-05-30 21:09:33.352 EDT [2404] LOG: listening on IPv6 address "::", port 154322019-05-30 21:09:33.355 EDT [2404] LOG: listening on Unix socket "/tmp/.s.PGSQL.15432"2019-05-30 21:09:33.392 EDT [2404] LOG: redirecting log output to logging collector process2019-05-30 21:09:33.392 EDT [2404] HINT: Future log output will appear in directory "pg_log".Done.psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"Done.psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"Done.[postgres@gtm ~]$ pgxc_ctl -c /home/postgres/pgxc_ctl/pgxc_ctl.conf stop all/bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Installing pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxc_ctl --configuration /home/postgres/pgxc_ctl/pgxc_ctl.conf/home/postgres/pgxc_ctl/pgxc_ctl.conf: line 189: $coordExtraConfig: ambiguous redirectFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxc_ctlStopping all the coordinator masters.Stopping coordinator master coord1.Stopping coordinator master coord2.pg_ctl: directory "/home/postgres/pgxc/nodes/coord/coord1" does not existDone.Stopping all the datanode masters.Stopping datanode master datanode1.Stopping datanode master datanode2.pg_ctl: PID file "/home/postgres/pgxc/nodes/datanode/datanode1/postmaster.pid" does not existIs server running?Done.Stop GTM masterwaiting for server to shut down.... doneserver stopped[postgres@gtm ~]$ pgxc_ctl/bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Installing pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxc_ctl --configuration /home/postgres/pgxc_ctl/pgxc_ctl.conf/home/postgres/pgxc_ctl/pgxc_ctl.conf: line 189: $coordExtraConfig: ambiguous redirectFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxc_ctlPGXC monitor allNot running: gtm masterRunning: coordinator master coord1Not running: coordinator master coord2Running: datanode master datanode1Not running: datanode master datanode2PGXC stop coordinator master coord1Stopping coordinator master coord1.pg_ctl: directory "/home/postgres/pgxc/nodes/coord/coord1" does not existDone.PGXC stop datanode master datanode1Stopping datanode master datanode1.pg_ctl: PID file "/home/postgres/pgxc/nodes/datanode/datanode1/postmaster.pid" does not existIs server running?Done.PGXC monitor allNot running: gtm masterRunning: coordinator master coord1Not running: coordinator master coord2Running: datanode master datanode1Not running: datanode master datanode2PGXC monitor allNot running: gtm masterNot running: coordinator master coord1Not running: coordinator master coord2Not running: datanode master datanode1Not running: datanode master datanode2PGXC exit[postgres@gtm ~]$ pgxc_ctl -c /home/postgres/pgxc_ctl/pgxc_ctl.conf init all/bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Installing pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxc_ctl --configuration /home/postgres/pgxc_ctl/pgxc_ctl.conf/home/postgres/pgxc_ctl/pgxc_ctl.conf: line 189: $coordExtraConfig: ambiguous redirectFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxc_ctlInitialize GTM masterERROR: target directory (/home/postgres/pgxc/nodes/gtm) exists and not empty. Skip GTM initilializationDone.Start GTM masterserver startingInitialize all the coordinator masters.Initialize coordinator master coord1.Initialize coordinator master coord2.The files belonging to this database system will be owned by user "postgres".This user must also own the server process.The database cluster will be initialized with locale "en_US.UTF-8".The default database encoding has accordingly been set to "UTF8".The default text search configuration will be set to "english".Data page checksums are disabled.fixing permissions on existing directory /home/postgres/pgxc/nodes/coord/coord1 ... okcreating subdirectories ... okselecting default max_connections ... 100selecting default shared_buffers ... 128MBselecting dynamic shared memory implementation ... posixcreating configuration files ... okrunning bootstrap script ... okperforming post-bootstrap initialization ... creating cluster information ... oksyncing data to disk ... okfreezing database template0 ... okfreezing database template1 ... okfreezing database postgres ... okWARNING: enabling "trust" authentication for local connectionsYou can change this by editing pg_hba.conf or using the option -A, or--auth-local and --auth-host, the next time you run initdb.Success.The files belonging to this database system will be owned by user "postgres".This user must also own the server process.The database cluster will be initialized with locale "en_US.UTF-8".The default database encoding has accordingly been set to "UTF8".The default text search configuration will be set to "english".Data page checksums are disabled.fixing permissions on existing directory /home/postgres/pgxc/nodes/coord/coord2 ... okcreating subdirectories ... okselecting default max_connections ... 100selecting default shared_buffers ... 128MBselecting dynamic shared memory implementation ... posixcreating configuration files ... okrunning bootstrap script ... okperforming post-bootstrap initialization ... creating cluster information ... oksyncing data to disk ... okfreezing database template0 ... okfreezing database template1 ... okfreezing database postgres ... okWARNING: enabling "trust" authentication for local connectionsYou can change this by editing pg_hba.conf or using the option -A, or--auth-local and --auth-host, the next time you run initdb.Success.Done.Starting coordinator master.Starting coordinator master coord1Starting coordinator master coord22019-05-30 21:13:03.998 EDT [25137] LOG: listening on IPv4 address "0.0.0.0", port 54322019-05-30 21:13:03.998 EDT [25137] LOG: listening on IPv6 address "::", port 54322019-05-30 21:13:04.000 EDT [25137] LOG: listening on Unix socket "/tmp/.s.PGSQL.5432"2019-05-30 21:13:04.038 EDT [25138] LOG: database system was shut down at 2019-05-30 21:13:00 EDT2019-05-30 21:13:04.042 EDT [25137] LOG: database system is ready to accept connections2019-05-30 21:13:04.049 EDT [25145] LOG: cluster monitor started2019-05-30 21:13:04.020 EDT [2730] LOG: listening on IPv4 address "0.0.0.0", port 54322019-05-30 21:13:04.020 EDT [2730] LOG: listening on IPv6 address "::", port 54322019-05-30 21:13:04.021 EDT [2730] LOG: listening on Unix socket "/tmp/.s.PGSQL.5432"2019-05-30 21:13:04.057 EDT [2731] LOG: database system was shut down at 2019-05-30 21:13:00 EDT2019-05-30 21:13:04.061 EDT [2730] LOG: database system is ready to accept connections2019-05-30 21:13:04.062 EDT [2738] LOG: cluster monitor startedDone.Initialize all the datanode masters.Initialize the datanode master datanode1.Initialize the datanode master datanode2.The files belonging to this database system will be owned by user "postgres".This user must also own the server process.The database cluster will be initialized with locale "en_US.UTF-8".The default database encoding has accordingly been set to "UTF8".The default text search configuration will be set to "english".Data page checksums are disabled.fixing permissions on existing directory /home/postgres/pgxc/nodes/datanode/datanode1 ... okcreating subdirectories ... okselecting default max_connections ... 100selecting default shared_buffers ... 128MBselecting dynamic shared memory implementation ... posixcreating configuration files ... okrunning bootstrap script ... okperforming post-bootstrap initialization ... creating cluster information ... oksyncing data to disk ... okfreezing database template0 ... okfreezing database template1 ... okfreezing database postgres ... okWARNING: enabling "trust" authentication for local connectionsYou can change this by editing pg_hba.conf or using the option -A, or--auth-local and --auth-host, the next time you run initdb.Success.The files belonging to this database system will be owned by user "postgres".This user must also own the server process.The database cluster will be initialized with locale "en_US.UTF-8".The default database encoding has accordingly been set to "UTF8".The default text search configuration will be set to "english".Data page checksums are disabled.fixing permissions on existing directory /home/postgres/pgxc/nodes/datanode/datanode2 ... okcreating subdirectories ... okselecting default max_connections ... 100selecting default shared_buffers ... 128MBselecting dynamic shared memory implementation ... posixcreating configuration files ... okrunning bootstrap script ... okperforming post-bootstrap initialization ... creating cluster information ... oksyncing data to disk ... okfreezing database template0 ... okfreezing database template1 ... okfreezing database postgres ... okWARNING: enabling "trust" authentication for local connectionsYou can change this by editing pg_hba.conf or using the option -A, or--auth-local and --auth-host, the next time you run initdb.Success.Done.Starting all the datanode masters.Starting datanode master datanode1.Starting datanode master datanode2.2019-05-30 21:13:12.077 EDT [25392] LOG: listening on IPv4 address "0.0.0.0", port 154322019-05-30 21:13:12.077 EDT [25392] LOG: listening on IPv6 address "::", port 154322019-05-30 21:13:12.079 EDT [25392] LOG: listening on Unix socket "/tmp/.s.PGSQL.15432"2019-05-30 21:13:12.114 EDT [25392] LOG: redirecting log output to logging collector process2019-05-30 21:13:12.114 EDT [25392] HINT: Future log output will appear in directory "pg_log".2019-05-30 21:13:12.079 EDT [2985] LOG: listening on IPv4 address "0.0.0.0", port 154322019-05-30 21:13:12.079 EDT [2985] LOG: listening on IPv6 address "::", port 154322019-05-30 21:13:12.081 EDT [2985] LOG: listening on Unix socket "/tmp/.s.PGSQL.15432"2019-05-30 21:13:12.117 EDT [2985] LOG: redirecting log output to logging collector process2019-05-30 21:13:12.117 EDT [2985] HINT: Future log output will appear in directory "pg_log".Done.psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"Done.psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"psql: FATAL: no pg_hba.conf entry for host "192.168.20.132", user "postgres", database "postgres"Done. 启动 pgxc_ctl -c /home/postgres/pgxc_ctl/pgxc_ctl.conf start all 关闭 pgxc_ctl -c /home/postgres/pgxc_ctl/pgxc_ctl.conf stop all 查看集群状态 [postgres@gtm ~]$ pgxc_ctl monitor all/bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Installing pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxc_ctl --configuration /home/postgres/pgxc_ctl/pgxc_ctl.conf/home/postgres/pgxc_ctl/pgxc_ctl.conf: line 189: $coordExtraConfig: ambiguous redirectFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxc_ctlRunning: gtm masterRunning: coordinator master coord1Running: coordinator master coord2Running: datanode master datanode1Running: datanode master datanode2 配置集群信息 分别在数据节点、协调器节点上分别执行以下命令: 注:本节点只执行修改操作即可(alert node),其他节点执行创建命令(create node)。因为本节点已经包含本节点的信息。 create node coord1 with (type=coordinator,host=xl1, port=5432);create node coord2 with (type=coordinator,host=xl2, port=5432);alter node coord1 with (type=coordinator,host=xl1, port=5432);alter node coord2 with (type=coordinator,host=xl2, port=5432);create node datanode1 with (type=datanode, host=xl1,port=15432,primary=true,PREFERRED);create node datanode2 with (type=datanode, host=xl2,port=15432);alter node datanode1 with (type=datanode, host=xl1,port=15432,primary=true,PREFERRED);alter node datanode2 with (type=datanode, host=xl2,port=15432);select pgxc_pool_reload(); 分别登陆数据节点、协调器节点验证 postgres= select from pgxc_node;node_name | node_type | node_port | node_host | nodeis_primary | nodeis_preferred | node_id-----------+-----------+-----------+-----------+----------------+------------------+-------------coord1 | C | 5432 | xl1 | f | f | 1885696643coord2 | C | 5432 | xl2 | f | f | -1197102633datanode2 | D | 15432 | xl2 | f | f | -905831925datanode1 | D | 15432 | xl1 | t | f | 888802358(4 rows) 测试 插入数据 在数据节点1,执行相关操作。 通过协调器端口登录PG [postgres@xl1 ~]$ psql -p 5432psql (PGXL 10r1.1, based on PG 10.6 (Postgres-XL 10r1.1))Type "help" for help.postgres= create database lei;CREATE DATABASEpostgres= \c lei;You are now connected to database "lei" as user "postgres".lei= create table test1(id int,name text);CREATE TABLElei= insert into test1(id,name) select generate_series(1,8),'测试';INSERT 0 8lei= select from test1;id | name----+------1 | 测试2 | 测试5 | 测试6 | 测试8 | 测试3 | 测试4 | 测试7 | 测试(8 rows) 注:默认创建的表为分布式表,也就是每个数据节点值存储表的部分数据。关于表类型具体说明,下面有说明。 通过15432端口登录数据节点,查看数据 有5条数据 [postgres@xl1 ~]$ psql -p 15432psql (PGXL 10r1.1, based on PG 10.6 (Postgres-XL 10r1.1))Type "help" for help.postgres= \c lei;You are now connected to database "lei" as user "postgres".lei= select from test1;id | name----+------1 | 测试2 | 测试5 | 测试6 | 测试8 | 测试(5 rows) 登录到节点2,查看数据 有3条数据 [postgres@xl2 ~]$ psql -p15432psql (PGXL 10r1.1, based on PG 10.6 (Postgres-XL 10r1.1))Type "help" for help.postgres= \c lei;You are now connected to database "lei" as user "postgres".lei= select from test1;id | name----+------3 | 测试4 | 测试7 | 测试(3 rows) 两个节点的数据加起来整个8条,没有问题。 至此Postgre-XL集群搭建完成。 创建数据库、表时可能会出现以下错误: ERROR: Failed to get pooled connections 是因为pg_hba.conf配置不对,所有节点加上host all all 192.168.20.0/0 trust并重启集群即可。 ERROR: No Datanode defined in cluster 首先确认是否创建了数据节点,也就是create node相关的命令。如果创建了则执行select pgxc_pool_reload();使其生效即可。 集群管理与应用 表类型说明 REPLICATION表:各个datanode节点中,表的数据完全相同,也就是说,插入数据时,会分别在每个datanode节点插入相同数据。读数据时,只需要读任意一个datanode节点上的数据。 建表语法: CREATE TABLE repltab (col1 int, col2 int) DISTRIBUTE BY REPLICATION; DISTRIBUTE :会将插入的数据,按照拆分规则,分配到不同的datanode节点中存储,也就是sharding技术。每个datanode节点只保存了部分数据,通过coordinate节点可以查询完整的数据视图。 CREATE TABLE disttab(col1 int, col2 int, col3 text) DISTRIBUTE BY HASH(col1); 模拟数据插入 任意登录一个coordinate节点进行建表操作 [postgres@gtm ~]$ psql -h xl1 -p 5432 -U postgrespostgres= INSERT INTO disttab SELECT generate_series(1,100), generate_series(101, 200), 'foo';INSERT 0 100postgres= INSERT INTO repltab SELECT generate_series(1,100), generate_series(101, 200);INSERT 0 100 查看数据分布结果: DISTRIBUTE表分布结果 postgres= SELECT xc_node_id, count() FROM disttab GROUP BY xc_node_id;xc_node_id | count ------------+-------1148549230 | 42-927910690 | 58(2 rows) REPLICATION表分布结果 postgres= SELECT count() FROM repltab;count -------100(1 row) 查看另一个datanode2中repltab表结果 [postgres@datanode2 pgxl9.5]$ psql -p 15432psql (PGXL 10r1.1, based on PG 10.6 (Postgres-XL 10r1.1))Type "help" for help.postgres= SELECT count() FROM repltab;count -------100(1 row) 结论:REPLICATION表中,datanode1,datanode2中表是全部数据,一模一样。而DISTRIBUTE表,数据散落近乎平均分配到了datanode1,datanode2节点中。 新增数据节点与数据重分布 在线新增节点、并重新分布数据。 新增datanode节点 在gtm集群管理节点上执行pgxc_ctl命令 [postgres@gtm ~]$ pgxc_ctl/bin/bashInstalling pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Installing pgxc_ctl_bash script as /home/postgres/pgxc_ctl/pgxc_ctl_bash.Reading configuration using /home/postgres/pgxc_ctl/pgxc_ctl_bash --home /home/postgres/pgxc_ctl --configuration /home/postgres/pgxc_ctl/pgxc_ctl.confFinished reading configuration. PGXC_CTL START Current directory: /home/postgres/pgxc_ctlPGXC 在服务器xl3上,新增一个master角色的datanode节点,名称是datanode3 端口号暂定5430,pool master暂定6669 ,指定好数据目录位置,从两个节点升级到3个节点,之后要写3个none none应该是datanodeSpecificExtraConfig或者datanodeSpecificExtraPgHba配置PGXC add datanode master datanode3 xl3 15432 6671 /home/postgres/pgxc/nodes/datanode/datanode3 none none none 等待新增完成后,查询集群节点状态: postgres= select from pgxc_node;node_name | node_type | node_port | node_host | nodeis_primary | nodeis_preferred | node_id-----------+-----------+-----------+-----------+----------------+------------------+-------------datanode1 | D | 15432 | xl1 | t | f | 888802358datanode2 | D | 15432 | xl2 | f | f | -905831925datanode3 | D | 15432 | xl3 | f | f | -705831925coord1 | C | 5432 | xl1 | f | f | 1885696643coord2 | C | 5432 | xl2 | f | f | -1197102633(4 rows) 节点新增完毕 数据重新分布 由于新增节点后无法自动完成数据重新分布,需要手动操作。 DISTRIBUTE表分布在了node1,node2节点上,如下: postgres= SELECT xc_node_id, count() FROM disttab GROUP BY xc_node_id;xc_node_id | count ------------+-------1148549230 | 42-927910690 | 58(2 rows) 新增一个节点后,将sharding表数据重新分配到三个节点上,将repl表复制到新节点 重分布sharding表postgres= ALTER TABLE disttab ADD NODE (datanode3);ALTER TABLE 复制数据到新节点postgres= ALTER TABLE repltab ADD NODE (datanode3);ALTER TABLE 查看新的数据分布: postgres= SELECT xc_node_id, count() FROM disttab GROUP BY xc_node_id;xc_node_id | count ------------+--------700122826 | 36-927910690 | 321148549230 | 32(3 rows) 登录datanode3(新增的时候,放在了xl3服务器上,端口15432)节点查看数据: [postgres@gtm ~]$ psql -h xl3 -p 15432 -U postgrespsql (PGXL 10r1.1, based on PG 10.6 (Postgres-XL 10r1.1))Type "help" for help.postgres= select count() from repltab;count -------100(1 row) 很明显,通过 ALTER TABLE tt ADD NODE (dn)命令,可以将DISTRIBUTE表数据重新分布到新节点,重分布过程中会中断所有事务。可以将REPLICATION表数据复制到新节点。 从datanode节点中回收数据 postgres= ALTER TABLE disttab DELETE NODE (datanode3);ALTER TABLEpostgres= ALTER TABLE repltab DELETE NODE (datanode3);ALTER TABLE 删除数据节点 Postgresql-XL并没有检查将被删除的datanode节点是否有replicated/distributed表的数据,为了数据安全,在删除之前需要检查下被删除节点上的数据,有数据的话,要回收掉分配到其他节点,然后才能安全删除。删除数据节点分为四步骤: 1.查询要删除节点dn3的oid postgres= SELECT oid, FROM pgxc_node;oid | node_name | node_type | node_port | node_host | nodeis_primary | nodeis_preferred | node_id -------+-----------+-----------+-----------+-----------+----------------+------------------+-------------11819 | coord1 | C | 5432 | datanode1 | f | f | 188569664316384 | coord2 | C | 5432 | datanode2 | f | f | -119710263316385 | node1 | D | 5433 | datanode1 | f | t | 114854923016386 | node2 | D | 5433 | datanode2 | f | f | -92791069016397 | dn3 | D | 5430 | datanode1 | f | f | -700122826(5 rows) 2.查询dn3对应的oid中是否有数据 testdb= SELECT FROM pgxc_class WHERE nodeoids::integer[] @> ARRAY[16397];pcrelid | pclocatortype | pcattnum | pchashalgorithm | pchashbuckets | nodeoids ---------+---------------+----------+-----------------+---------------+-------------------16388 | H | 1 | 1 | 4096 | 16397 16385 1638616394 | R | 0 | 0 | 0 | 16397 16385 16386(2 rows) 3.有数据的先回收数据 postgres= ALTER TABLE disttab DELETE NODE (dn3);ALTER TABLEpostgres= ALTER TABLE repltab DELETE NODE (dn3);ALTER TABLEpostgres= SELECT FROM pgxc_class WHERE nodeoids::integer[] @> ARRAY[16397];pcrelid | pclocatortype | pcattnum | pchashalgorithm | pchashbuckets | nodeoids ---------+---------------+----------+-----------------+---------------+----------(0 rows) 4.安全删除dn3 PGXC$ remove datanode master dn3 clean 故障节点FAILOVER 1.查看当前集群状态 [postgres@gtm ~]$ psql -h xl1 -p 5432psql (PGXL 10r1.1, based on PG 10.6 (Postgres-XL 10r1.1))Type "help" for help.postgres= SELECT oid, FROM pgxc_node;oid | node_name | node_type | node_port | node_host | nodeis_primary | nodeis_preferred | node_id-------+-----------+-----------+-----------+-----------+----------------+------------------+-------------11739 | coord1 | C | 5432 | xl1 | f | f | 188569664316384 | coord2 | C | 5432 | xl2 | f | f | -119710263316387 | datanode2 | D | 15432 | xl2 | f | f | -90583192516388 | datanode1 | D | 15432 | xl1 | t | t | 888802358(4 rows) 2.模拟datanode1节点故障 直接关闭即可 PGXC stop -m immediate datanode master datanode1Stopping datanode master datanode1.Done. 3.测试查询 只要查询涉及到datanode1上的数据,那么该查询就会报错 postgres= SELECT xc_node_id, count() FROM disttab GROUP BY xc_node_id;WARNING: failed to receive file descriptors for connectionsERROR: Failed to get pooled connectionsHINT: This may happen because one or more nodes are currently unreachable, either because of node or network failure.Its also possible that the target node may have hit the connection limit or the pooler is configured with low connections.Please check if all nodes are running fine and also review max_connections and max_pool_size configuration parameterspostgres= SELECT xc_node_id, FROM disttab WHERE col1 = 3;xc_node_id | col1 | col2 | col3------------+------+------+-------905831925 | 3 | 103 | foo(1 row) 测试发现,查询范围如果涉及到故障的node1节点,会报错,而查询的数据范围不在node1上的话,仍然可以查询。 4.手动切换 要想切换,必须要提前配置slave节点。 PGXC$ failover datanode node1 切换完成后,查询集群 postgres= SELECT oid, FROM pgxc_node;oid | node_name | node_type | node_port | node_host | nodeis_primary | nodeis_preferred | node_id -------+-----------+-----------+-----------+-----------+----------------+------------------+-------------11819 | coord1 | C | 5432 | datanode1 | f | f | 188569664316384 | coord2 | C | 5432 | datanode2 | f | f | -119710263316386 | node2 | D | 15432 | datanode2 | f | f | -92791069016385 | node1 | D | 15433 | datanode2 | f | t | 1148549230(4 rows) 发现datanode1节点的ip和端口都已经替换为配置的slave了。 本篇文章为转载内容。原文链接:https://blog.csdn.net/qianglei6077/article/details/94379331。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-01-30 11:09:03
94
转载
转载文章
...。 yum和源码编译安装的区别 1.路径区别-yum安装的软件是他自定义的,源码安装的软件./configure --preifx=软件安装的绝对路径 2.yum仓库的软件,版本可能比较低,而源码编译安装,版本可控 3.编译安装的软件,支持第三方功能扩展./configure 这里可以加上很多参数,定制功能 1.安装mariadb,配置官方的mariadb的yum源,手动创建 mariadb.repo仓库文件 添加MariaDB源 vi /etc/yum.repos.d/MariaDB.repo 粘贴官方的或者阿里云的镜像: [mariadb]name = MariaDBbaseurl = http://yum.mariadb.org/10.3/centos7-amd64gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDBgpgcheck=1[mariadb]name = MariaDBbaseurl = https://mirrors.aliyun.com/mariadb/yum/10.4/centos7-amd64/gpgkey=https://mirrors.aliyun.com/mariadb/yum/RPM-GPG-KEY-MariaDBgpgcheck=1 2.如果下载速度太慢,请删除 mariadb.repo,只是为了使用阿里云的yum源中的mariadb rm -rf /etc/yum.repos.d/Mariadb.repo然后清空yum 缓存yum clean all 3.通过yum安装mariadb软件,安装mariadb服务端和客户端 官方 yum install MariaDB-server MariaDB-client -y阿里云 yum install mariadb mariadb-server -y 4.安装完成后,启动mariadb服务端 systemctl start/stop/restart/status mariadbsystemctl enable mariadb 开机启动mariadb 5. mariadb初始化 这条命令可以初始化mysql,删除匿名用户,设置root密码等等....mysql_secure_installation1.输入当前密码,初次安装后是没有密码的,直接回车2.询问是否使用 'unix_socket' 进行身份验证: n3.为 root 设置密码:y4.输入 root 的新密码: root5.确认输入 root 的新密码: root6.是否移除匿名用户,这个随意,建议删除: y7.拒绝用户远程登录,这个建议开启:n8.删除 test 库,可以保留:n9.重新加载权限表:y 6. 设置mysql的中文编码支持,修改/etc/my.cnf 1.vi /etc/my.cnf在[mysqld]中添加参数,使得mariadb服务端支持中文[mysqld]character-set-server=utf8collation-server=utf8_general_ci2.重启mariadb服务,读取my.cnf新配置systemctl restart mariadb 3.登录数据库,查看字符编码mysql -uroot -p输入 \s 查看编码 7. mysql常用命 desc 查看表结构create database 数据库名create table 表名查看如何创建db的show create database 库名 查看如何创建table结构的show create table 表名; 修改mysql的密码set password = PASSWORD('redhat'); 创建mysql的普通用户,默认权限非常低create user zhang@'%' identified by '123456'; 查询mysql数据库中的用户信息use mysql;select host,user,password from user; 7. 给用户添加权限命令 对所有库和所有表授权所有权限grant all privileges on . to 账户@主机名 给zhang用户授予所有权限grant all privileges on . to zhang@'%'; 刷新授权表flush privileges; 8. 给用户添加权限命令 给zhangsan用户授予所有权限grant all privileges on . to zhangsan@'%'; 给与root权限授予远程登录的命令 'centos这是密码随意设置grant all privileges on . to root@'%' identified by '123456'; 此时可以在windows登录linux的数据库 连接服务器的mysqlmysql -uyining -p -h 服务器的地址 9. 数据备份与恢复 导出当前数据库的所有db,到一个文件中1.mysqldump -u root -p --all-databases > /data/AllMysql.dump2.登录mysql 导入数据mysql -u root -p> source /data/AllMysql.dump3.通过命令导入数据 在登录时候,导入数据文件,一样可以写入数据mysql -uroot -p < /data/AllMysql.dump 10. 修改Mariadb存储路径 10.1 首先确定MariaDB数据库能正常运行,确定正常后关闭服务 systemctl stop mariadb 10.2 建立要更改数据存放的目录,如:我这单独分了一个区/data存放MariaDB的数据 mkdir /data/mysql_data chown -R mysql:mysql /data/mysql_data 10.3 复制默认数据存放文件夹到/data/mysql_data cp -a /var/lib/mysql /data/mysql_data 10.4 修改/etc/my.cnf.d/server.cnf vim /etc/my.cnf.d/server.cnf 在[mysqld]标签下添加如下内容 datadir=/data/mysql_data/mysqlsocket=/var/lib/mysql/mysql.sockdefault-character-set=utf8character_set_server=utf8slow_query_log=onslow_query_log_file=/data/mysql_data/slow_query_log.loglong_query_time=2 10.5 配置MariaDB慢查询 touch /data/mysql_data/slow_query_log.logchown mysql:mysql /data/mysql_data/slow_query_log.log 10.6 重启数据库 systemctl start mariadb 10.7 注意: 1、配置文件my.cnf存在,但是修改的并不是my.cnf,而是/etc/my.cnf.d/server.cnf; 2、并没有更改mysql.sock的路径配置; 3、没有修改/etc/init.d/mysql中的内容; 4、没有修改mysql_safe中的内容; 5、增加了数据库的慢查询配置。 11. Mariadb主从复制 11.1 主从库初始化 这条命令可以初始化mysql,删除匿名用户,设置root密码等等....mysql_secure_installation1.输入当前密码,初次安装后是没有密码的,直接回车2.询问是否使用 'unix_socket' 进行身份验证: n3.为 root 设置密码:y4.输入 root 的新密码: root5.确认输入 root 的新密码: root6.是否移除匿名用户,这个随意,建议删除: y7.拒绝用户远程登录,这个建议开启:n8.删除 test 库,可以保留:n9.重新加载权限表:y 11.2 修改主库配置 [root@mster mysql] grep -Ev "^$|^" /etc/my.cnf.d/server.cnf[server][mysqld]character-set-server=utf8collation-server=utf8_general_ciserver_id = 13 一组主从组里的每个id必须是唯一值。推荐用ip位数log-bin= mysql-bin 二进制日志,后面指定存放位置。如果只是指定名字,默认存放在/var/lib/mysql下lower_case_table_names=1 不区分大小写binlog-format=ROW 二进制日志文件格式log-slave-updates=True slave更新是否记入日志sync-master-info=1 值为1确保信息不会丢失slave-parallel-threads=3 同时启动多少个复制线程,最多与要复制的数据库数量相等即可binlog-checksum=CRC32 效验码master-verify-checksum=1 启动主服务器效验slave-sql-verify-checksum=1 启动从服务器效验[galera][embedded][mariadb][mariadb-10.6][root@mster-k8s mysql] 11.2 修改从库配置 [mysqld]character-set-server=utf8collation-server=utf8_general_ciserver_id=14log-bin= mysql-bin log-bin是二进制文件relay_log = relay-bin 中继日志, 后面指定存放位置。如果只是指定名字,默认存放在/var/lib/mysql下lower_case_table_names=1 11.3 重启主库和从库服务 systemctl restart mariad 11.4 master节点配置 MariaDB [huawei]> grant replication slave, replication client on . to 'liu'@'%' identified by '123456';Query OK, 0 rows affected (0.001 sec)MariaDB [huawei]> show master status;+------------------+----------+--------------+------------------+| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |+------------------+----------+--------------+------------------+| mysql-bin.000001 | 4990 | | |+------------------+----------+--------------+------------------+1 row in set (0.000 sec)MariaDB [huawei]> select binlog_gtid_pos('mysql-bin.000001', 4990 );+-------------------------------------------+| binlog_gtid_pos('mysql-bin.000001', 4990) |+-------------------------------------------+| 0-13-80 |+-------------------------------------------+1 row in set (0.000 sec)MariaDB [huawei]> flush privileges; 11.5 slave节点配置 MariaDB [(none)]> set global gtid_slave_pos='0-13-80';Query OK, 0 rows affected (0.004 sec)MariaDB [(none)]> change master to master_host='101.34.141.216',master_user='liu',master_password='123456',master_use_gtid=slave_pos;Query OK, 0 rows affected (0.008 sec)MariaDB [(none)]> start slave;Query OK, 0 rows affected (0.005 sec)MariaDB [(none)]> 11.6 验证salve状态 MariaDB [(none)]> show slave status\G 1. row Slave_IO_State: Waiting for master to send eventMaster_Host: 101.34.141.216Master_User: liuMaster_Port: 3306Connect_Retry: 60Master_Log_File: mysql-bin.000001Read_Master_Log_Pos: 13260Relay_Log_File: relay-bin.000002Relay_Log_Pos: 10246Relay_Master_Log_File: mysql-bin.000001Slave_IO_Running: YesSlave_SQL_Running: YesReplicate_Do_DB: Replicate_Ignore_DB: Replicate_Do_Table: Replicate_Ignore_Table: Replicate_Wild_Do_Table: Replicate_Wild_Ignore_Table: Last_Errno: 0Last_Error: Skip_Counter: 0Exec_Master_Log_Pos: 13260Relay_Log_Space: 10549Until_Condition: NoneUntil_Log_File: Until_Log_Pos: 0Master_SSL_Allowed: NoMaster_SSL_CA_File: 本篇文章为转载内容。原文链接:https://blog.csdn.net/l363130002/article/details/126121255。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-07-12 10:11:01
310
转载
转载文章
...内容。 Linux Mysql 搭建 systemctl stop firewalld 停止防火墙服务systemctl disable firewalld 禁止防火墙服务开机自启动sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/sysconfig/selinux // 将 selinux文件中的SELINUX值修改为disabledwget -O /etc/yum.repos.d/openEulerOS.repo https://repo.huaweicloud.com/repository/conf/openeuler_aarch64.repo 增加openEulerOS.repo yum clean all 清除之前的所有仓库缓存yum makecache 生成软件包信息缓存,以提高搜索安装软件的速度dnf install mysqlmkdir /var/lib/mysql // 在 /var/lib 目录下创建一个mysql 目录cd /var/lib/mysql/ // 切换到这个目录mkdir data tmp run log // 在 mysql目录下 创建 data, tmp,run,log 四个子目录touch /var/lib/mysql/log/mysql.log // 在log 目录下 创建mysql.log空文件chown -R mysql:mysql /var/lib/mysql/ // 将 mysql目录下的所有文件 所有者及群组都设为 mysqlrm -f /etc/my.cnf// 将一些信息导入到 my.cnf 中echo -e "[mysqld_safe]\nlog-error=/var/lib/mysql/log/mysql.log\npid-file=/var/lib/mysql/run/mysqld.pid\n\n[mysqldump]\nquick\n\n[mysql]\nno-auto-rehash\n\n[client]\nport=3306\nmax_allowed_packet=64M\ndefault-character-set=utf8\n\n[mysqld]\nuser=root\nport=3306\nbasedir=/usr/local/mysql\nsocket=/var/lib/mysql/run/mysql.sock\ntmpdir=/var/lib/mysql/tmp\ndatadir=/var/lib/mysql/data\ndefault_authentication_plugin=mysql_native_password\nskip-grant-tables\nkey_buffer_size=16M" > /etc/my.cnfcat /etc/my.cnf // 查看文件内容chown mysql:mysql /etc/my.cnf // 将该文件的所有者及群组 都设为 mysqlll /etc/my.cnfchmod 777 /usr/local/mysql/support-files/mysql.server //对mysql.server的所有者,群组,其他用户设置读,写,执行,权限cp /usr/local/mysql/support-files/mysql.server /etc/init.d/mysqlchkconfig mysql on // 开机自动启动chown -R mysql:mysql /etc/init.d/mysqlvi /etc/profile // 把 export PATH=$PATH:/usr/local/mysql/bin 放到文件尾端,设置环境变量source /etc/profile // 重新执行刚修改的文件,使之立即生效env // 显示系统的环境变量mysqld --defaults-file=/etc/my.cnf --initializechown -R mysql:mysql /var/lib/mysql/datall /var/lib/mysql/dataservice mysql startservice mysql status // 查看服务状态ps -ef | grep mysqlnetstat -anptnetstat -anpt | grep mysqlnetstat -anpt | grep 3306 显示有关mysql的进程mysql -u root -p -S /var/lib/mysql/run/mysql.sock // 输入密码进入到了mysqlalter user 'root'@'localhost' identified by "123456";flush privileges;create user 'user'@'%' identified by '123456';grant all privileges on . to 'user'@'%' with grant option;flush privileges;select user,host from mysql.user; service mysql stop 停止服务\q回到命令行vi /etc/ld.so.confldconfig 搜索出可共享的动态链接库(格式如lib.so),进而创建出动态装入程序(ld.so)所需的连接和缓存文件。缓存文件默认为/etc/ld.so.cacheln -s /var/ldconfiglib/mysql/run/mysql.sock /tmp/mysql.sock 建立软连接 service 和 chkconfig 都可以用 systemctl 来代替 遇到 Can’t connect to local MySQL server through socket ‘/tmp/mysql.sock’ (2) service mysql stop // 先停用ln -s /var/lib/mysql/mysql.sock /tmp/mysql.sock // 建立软连接vi /etc/my.cnf // 修改里面的 socket 路径service mysql start // 重启 Linux chmod 命令 Linux文件的所有者、群组和其他人 本篇文章为转载内容。原文链接:https://blog.csdn.net/qq_53318060/article/details/121664128。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-05-24 19:00:46
118
转载
转载文章
...用 课程计划媒资信息查询接口,获取该课程计划的视频播放的 m3u8 url地址,并返回给前端,前端使用该 url 进行视频的在线播放。 在线学习完整的测试流程:媒资信息的上传、选择、发布到前端门户、搜索门户测试,在线学习的播放视频。 目录 内容会比较多,小伙伴门可以根据目录进行按需查阅。 文章目录 😎 知识点概览 目录 一、学习页面:查询课程计划 0x01 需求分析 0x02 Api接口 0x03 服务端开发 Controller Service 测试 0x04 前端开发 配置NGINX虚拟主机 前端 API 方法 前端 API 方法调用 测试 二、学习页面:获取视频播放地址 0x01 需求分析 0x02 课程发布:储存媒资信息 需求分析 数据模型 Dao Service 测试 0x03 Logstash:扫描课程计划媒资 创建索引 创建模板文件 配置 mysql.conf 启动 logstash.bat Logstash多实例运行 0x04 搜素服务:查询课程媒资接口 需求分析 Api接口定义 Service Controller 测试 三、在线学习:接口开发 0x01 需求分析 0x02 搭建开发环境 0x03 Api接口 0x04 服务端开发 需求分析 搜索服务注册Eureka 搜索服务客户端 自定义错误代码 Service Controller 测试 0x05 前端开发 需求分析 api方法 配置代理 视频播放页面 简单的测试 完整的测试 1、上传文件 一些问题 ~~方案1:删除本地分块文件重新尝试上传~~ 方案2:检查前端提交的MD5值是否正确 2、为课程计划选择媒资信息 3、前端门户测试 四、待完善的一些功能 😁 认识作者 一、学习页面:查询课程计划 0x01 需求分析 到目前为止,我们已可以编辑课程计划信息并上传课程视频,下一步我们要实现在线学习页面动态读取章节对应的视频并进行播放。在线学习页面所需要的信息有两类: 课程计划信息 课程学习信息(视频地址、学习进度等) 如下图: 在线学习集成媒资管理的需求如下: 1、在线学习页面显示课程计划 2、点击课程计划播放该课程计划对应的视频 本章节实现学习页面动态显示课程计划,进入不同课程的学习页面右侧动态显示当前课程的课程计划。 0x02 Api接口 课程计划信息从哪里获取? 在课程发布完成后会自动发布到一个 course_pub 的表中,logstash 会自动将课程发布后的信息自动采集到 ES 索引库中,这些信息也包含课程计划信息。 所以考虑性能要求,课程发布后对课程的查询统一从 ES 索引库中查询。 前端通过请求 搜索服务 获取课程信息,需要单独在 搜索服务 中定义课程信息查询接口。 本接口接收课程id,查询课程所有信息返回给前端。 我们在搜素服务 API 下添加以下方法 @ApiOperation("根据id搜索课程发布信息")public Map<String,CoursePub> getdetail(String id); 返回的课程信息为 json 结构:key 为课程id,value 为课程内容。 0x03 服务端开发 在搜索服务中开发查询课程信息接口。 Controller 在搜素服务下添加以下方法 / 根据id搜索课程发布信息 @param id 课程id @return JSON数据/@Override@GetMapping("/getdetail/{id}")public Map<String, CoursePub> getdetail(@PathVariable("id")String id) {return esCourseService.getdetail(id);} Service / 根据id搜索课程发布信息 @param id 课程id @return JSON数据/public Map<String, CoursePub> getdetail(String id) {//设置索引SearchRequest searchRequest = new SearchRequest(es_index);//设置类型searchRequest.types(es_type);//创建搜索源对象SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();//设置查询条件,根据id进行查询searchSourceBuilder.query(QueryBuilders.termQuery("id",id));//这里不使用source的原字段过滤,查询所有字段// searchSourceBuilder.fetchSource(new String[]{"name", "grade", "charge","pic"}, newString[]{});//设置搜索源对象searchRequest.source(searchSourceBuilder);//执行搜索SearchResponse searchResponse = null;try {searchResponse = restHighLevelClient.search(searchRequest);} catch (IOException e) {e.printStackTrace();}//获取搜索结果SearchHits hits = searchResponse.getHits();SearchHit[] searchHits = hits.getHits(); //获取最优结果Map<String,CoursePub> map = new HashMap<>();for (SearchHit hit: searchHits) {//从搜索结果中取值并添加到coursePub对象Map<String, Object> sourceAsMap = hit.getSourceAsMap();String courseId = (String) sourceAsMap.get("id");String name = (String) sourceAsMap.get("name");String grade = (String) sourceAsMap.get("grade");String charge = (String) sourceAsMap.get("charge");String pic = (String) sourceAsMap.get("pic");String description = (String) sourceAsMap.get("description");String teachplan = (String) sourceAsMap.get("teachplan");CoursePub coursePub = new CoursePub();coursePub.setId(courseId);coursePub.setName(name);coursePub.setPic(pic);coursePub.setGrade(grade);coursePub.setTeachplan(teachplan);coursePub.setDescription(description);//设置map对象map.put(courseId,coursePub);}return map;} 测试 使用 swagger-ui 或 postman 测试查询课程信息接口。 0x04 前端开发 配置NGINX虚拟主机 学习中心的二级域名为 ucenter.xuecheng.com ,我们在 nginx 中配置 ucenter 虚拟主机。 学成网用户中心server {listen 80;server_name ucenter.xuecheng.com;个人中心location / {proxy_pass http://ucenter_server_pool;} } 前端ucenterupstream ucenter_server_pool{server 127.0.0.1:7081 weight=10;server 127.0.0.1:13000 weight=10;} 在学习中心要调用搜索的 API,使用 Nginx 解决代理,如下图: 在 ucenter 虚拟主机下配置搜索 Api 代理路径 后台搜索(公开api)upstream search_server_pool{server 127.0.0.1:40100 weight=10;} 学成网用户中心server {listen 80;server_name ucenter.xuecheng.com;个人中心location / {proxy_pass http://ucenter_server_pool;}后端搜索服务location /openapi/search/ {proxy_pass http://search_server_pool/search/;} } 前端 API 方法 在学习中心 xc-ui-pc-leanring 对课程信息的查询属于基础常用功能,所以我们将课程查询的 api 方法定义在base 模块下,如下图: 在system.js 中定义课程查询方法: import http from './public'export const course_view = id => {return http.requestGet('/openapi/search/course/getdetail/'+id);} 前端 API 方法调用 在 learning_video.vue 页面中调用课程信息查询接口得到课程计划,将课程计划json 串转成对象。 xc-ui-pc-leanring/src/module/course/page/learning_video.vue 1、定义视图 课程计划 <!--课程计划部分代码--><div class="navCont"><div class="course-weeklist"><div class="nav nav-stacked" v-for="(teachplan_first, index) in teachplanList"><div class="tit nav-justified text-center"><i class="pull-left glyphicon glyphicon-th-list"></i>{ {teachplan_first.pname} }<i class="pull-right"></i></div><li v-if="teachplan_first.children!=null" v-for="(teachplan_second, index) in teachplan_first.children"><i class="glyphicon glyphicon-check"></i><a :href="url" @click="study(teachplan_second.id)">{ {teachplan_second.pname} }</a></li><!-- <div class="tit nav-justified text-center"><i class="pull-left glyphicon glyphicon-th-list"></i>第一章<i class="pull-right"></i></div><li ><i class="glyphicon glyphicon-check"></i><a :href="url" >第一节</a></li>--><!--<li><i class="glyphicon glyphicon-unchecked"></i>为什么分为A、B、C部分</li>--></div></div></div> 课程名称 <div class="top text-center">{ {coursename} }</div> 定义数据对象 data() {return {url:'',//当前urlcourseId:'',//课程idchapter:'',//章节Idcoursename:'',//课程名称coursepic:'',//课程图片teachplanList:[],//课程计划playerOptions: {//播放参数autoplay: false,controls: true,sources: [{type: "application/x-mpegURL",src: ''}]},} } 在 created 钩子方法中获取课程信息 created(){//当前请求的urlthis.url = window.location//课程idthis.courseId = this.$route.params.courseId//章节idthis.chapter = this.$route.params.chapter//查询课程信息systemApi.course_view(this.courseId).then((view_course)=>{if(!view_course || !view_course[this.courseId]){this.$message.error("获取课程信息失败,请重新进入此页面!")return ;} let courseInfo = view_course[this.courseId]console.log(courseInfo)this.coursename = courseInfo.nameif(courseInfo.teachplan){let teachplan = JSON.parse(courseInfo.teachplan);this.teachplanList = teachplan.children;} })}, 测试 在浏览器请求:http://ucenter.xuecheng.com//learning/4028e581617f945f01617f9dabc40000/0 4028e581617f945f01617f9dabc40000:第一个参数为课程 id,测试时从 ES索引库找一个课程 id 0:第二个参数为课程计划 id,此参数用于点击课程计划播放视频。 如果出现跨域问题,但是确定已经配置了跨域,请尝试结束所以 nginx.exe 的进程 和 清空浏览器缓存。 如果还没有解决?重启电脑试试。 二、学习页面:获取视频播放地址 0x01 需求分析 用户进入在线学习页面,点击课程计划将播放该课程计划对应的教学视频。 业务流程如下: 业务流程说明: 1、用户进入在线学习页面,页面请求搜索服务获取课程信息(包括课程计划信息)并且在页面展示。 2、在线学习请求学习服务获取视频播放地址。 3、学习服务校验当前用户是否有权限学习,如果没有权限学习则提示用户。 4、学习服务校验通过,请求搜索服务获取课程媒资信息。 5、搜索服务请求ElasticSearch获取课程媒资信息。 为什么要请求 ElasticSearch 查询课程媒资信息? 出于性能的考虑,公开查询课程信息从搜索服务查询,分摊 mysql 数据库的访问压力。 什么时候将课程媒资信息存储到 ElasticSearch 中? 课程媒资信息是在课程发布的时候存入 ElasticSearch,因为课程发布后课程信息将基本不再修改。 0x02 课程发布:储存媒资信息 需求分析 课程媒资信息是在课程发布的时候存入 ElasticSearch 索引库,因为课程发布后课程信息将基本不再修改,具体的业务流程如下。 1、课程发布,向课程媒资信息表写入数据。 1)根据课程 id 删除 teachplanMediaPub 中的数据 2)根据课程 id 查询 teachplanMedia 数据 3)将查询到的 teachplanMedia 数据插入到 teachplanMediaPub 中 2、Logstash 定时扫描课程媒资信息表,并将课程媒资信息写入索引库。 数据模型 在 xc_course 数据库创建课程计划媒资发布表: CREATE TABLE teachplan_media_pub (teachplan_id varchar(32) NOT NULL COMMENT '课程计划id',media_id varchar(32) NOT NULL COMMENT '媒资文件id',media_fileoriginalname varchar(128) NOT NULL COMMENT '媒资文件的原始名称',media_url varchar(256) NOT NULL COMMENT '媒资文件访问地址',courseid varchar(32) NOT NULL COMMENT '课程Id',timestamp timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT'logstash使用',PRIMARY KEY (teachplan_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8 数据模型类如下: package com.xuecheng.framework.domain.course;import lombok.Data;import lombok.ToString;import org.hibernate.annotations.GenericGenerator;import javax.persistence.;import java.io.Serializable;import java.util.Date;@Data@ToString@Entity@Table(name="teachplan_media_pub")@GenericGenerator(name = "jpa-assigned", strategy = "assigned")public class TeachplanMediaPub implements Serializable {private static final long serialVersionUID = -916357110051689485L;@Id@GeneratedValue(generator = "jpa-assigned")@Column(name="teachplan_id")private String teachplanId;@Column(name="media_id")private String mediaId;@Column(name="media_fileoriginalname")private String mediaFileOriginalName;@Column(name="media_url")private String mediaUrl;@Column(name="courseid")private String courseId;@Column(name="timestamp")private Date timestamp;//时间戳} Dao 创建 TeachplanMediaPub 表的 Dao,向 TeachplanMediaPub 存储信息采用先删除该课程的媒资信息,再添加该课程的媒资信息,所以这里定义根据课程 id 删除课程计划媒资方法: public interface TeachplanMediaPubRepository extends JpaRepository<TeachplanMediaPub, String> {//根据课程id删除课程计划媒资信息long deleteByCourseId(String courseId);} 从TeachplanMedia查询课程计划媒资信息 //从TeachplanMedia查询课程计划媒资信息public interface TeachplanMediaRepository extends JpaRepository<TeachplanMedia, String> {List<TeachplanMedia> findByCourseId(String courseId);} Service 编写保存课程计划媒资信息方法,并在课程发布时调用此方法。 1、保存课程计划媒资信息方法 本方法采用先删除该课程的媒资信息,再添加该课程的媒资信息,在 CourseService 下定义该方法 //保存课程计划媒资信息private void saveTeachplanMediaPub(String courseId){//查询课程媒资信息List<TeachplanMedia> byCourseId = teachplanMediaRepository.findByCourseId(courseId);if(byCourseId == null) return; //没有查询到媒资数据则直接结束该方法//将课程计划媒资信息储存到待索引表//删除原有的索引信息teachplanMediaPubRepository.deleteByCourseId(courseId);//一个课程可能会有多个媒资信息,遍历并使用list进行储存List<TeachplanMediaPub> teachplanMediaPubList = new ArrayList<>();for (TeachplanMedia teachplanMedia: byCourseId) {TeachplanMediaPub teachplanMediaPub = new TeachplanMediaPub();BeanUtils.copyProperties(teachplanMedia, teachplanMediaPub);teachplanMediaPubList.add(teachplanMediaPub);}//保存所有信息teachplanMediaPubRepository.saveAll(teachplanMediaPubList);} 2、课程发布时调用此方法 修改课程发布的 coursePublish 方法: ....//保存课程计划媒资信息到待索引表saveTeachplanMediaPub(courseId);//页面urlString pageUrl = cmsPostPageResult.getPageUrl();return new CoursePublishResult(CommonCode.SUCCESS,pageUrl);..... 测试 测试课程发布后是否成功将课程媒资信息存储到 teachplan_media_pub 中,测试流程如下: 1、指定一个课程 2、为课程计划添加课程媒资 3、执行课程发布 4、观察课程计划媒资信息是否存储至 teachplan_media_pub 中 注意:由于此测试仅用于测试发布课程计划媒资信息的功能,可暂时将 cms页面发布的功能暂时屏蔽,提高测试效率。 测试结果如下 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Vrzs5589-1595567273126)(https://qnoss.codeyee.com/20200704_15/image7)] 0x03 Logstash:扫描课程计划媒资 Logstash 定时扫描课程媒资信息表,并将课程媒资信息写入索引库。 创建索引 1、创建 xc_course_media 索引 2、并向此索引创建如下映射 POST: http://localhost:9200/xc_course_media/doc/_mapping {"properties" : {"courseid" : {"type" : "keyword"},"teachplan_id" : {"type" : "keyword"},"media_id" : {"type" : "keyword"},"media_url" : {"index" : false,"type" : "text"},"media_fileoriginalname" : {"index" : false,"type" : "text"} }} 索引创建成功 创建模板文件 在 logstach 的 config 目录文件 xc_course_media_template.json 文件路径为 %ES_ROOT_DIR%/logstash6.8.8/config/xc_course_media_template.json %ES_ROOT_DIR% 为 ElasticSearch 和 logstash 的安装目录 内容如下: {"mappings" : {"doc" : {"properties" : {"courseid" : {"type" : "keyword"},"teachplan_id" : {"type" : "keyword"},"media_id" : {"type" : "keyword"},"media_url" : {"index" : false,"type" : "text"},"media_fileoriginalname" : {"index" : false,"type" : "text"} }},"template" : "xc_course_media"} } 配置 mysql.conf 在logstash的 config 目录下配置 mysql_course_media.conf 文件供 logstash 使用,logstash 会根据 mysql_course_media.conf 文件的配置的地址从 MySQL 中读取数据向 ES 中写入索引。 参考https://www.elastic.co/guide/en/logstash/current/plugins-inputs-jdbc.html 配置输入数据源和输出数据源。 input {stdin {} jdbc {jdbc_connection_string => "jdbc:mysql://localhost:3306/xc_course?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC" 数据库信息jdbc_user => "root"jdbc_password => "123123" MYSQL 驱动地址,修改为maven仓库对应的位置jdbc_driver_library => "D:/soft/apache-maven-3.5.4/repository/mysql/mysql-connector-java/5.1.40/mysql-connector-java-5.1.40.jar" the name of the driver class for mysqljdbc_driver_class => "com.mysql.jdbc.Driver"jdbc_paging_enabled => "true"jdbc_page_size => "50000"要执行的sql文件statement_filepath => "/conf/course.sql"statement => "select from teachplan_media_pub where timestamp > date_add(:sql_last_value,INTERVAL 8 HOUR)"定时配置schedule => " "record_last_run => truelast_run_metadata_path => "D:/soft/elasticsearch/logstash-6.8.8/config/xc_course_media_metadata"} } output {elasticsearch {ES的ip地址和端口hosts => "localhost:9200"hosts => ["localhost:9200","localhost:9202","localhost:9203"]ES索引库名称index => "xc_course_media"document_id => "%{teachplan_id}"document_type => "doc"template => "D:/soft/elasticsearch/logstash-6.8.8/config/xc_course_media_template.json"template_name =>"xc_course_media"template_overwrite =>"true"} stdout {日志输出codec => json_lines} } 启动 logstash.bat 启动 logstash.bat 采集 teachplan_media_pub 中的数据,向 ES 写入索引。 logstash.bat -f ../config/mysql_course_media.conf 课程发布成功后,Logstash 会自动参加 teachplan_media_pub 表中新增的数据,效果如下 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ILPBxfXi-1595567273134)(https://qnoss.codeyee.com/20200704_15/image10)] Logstash多实例运行 由于之前我们还启动了一个 Logstash 对课程的发布信息进行采集,所以如果想两个 logstash 实例同时运行,因为每个实例都有一个.lock文件,所以不能使用同一个目录来存放数据,所以我们需要使用 --path.data= 为每个实例指定单独的数据目录,具体的代码如下: 该配置是在windows下进行的 课程发布实例 logstash_start_course_pub.bat @title logstash in course_publogstash.bat -f ..\config\mysql.conf --path.data=../data/course_pub 课程计划媒体发布实例 logstash_start_teachplan_media.bat @title logstash i n teachplan_media_publogstash.bat -f ../config/mysql_course_media.conf --path.data=../data/teachplan_media/ 同时运行效果如下 0x04 搜素服务:查询课程媒资接口 需求分析 搜索服务 提供查询课程媒资接口,此接口供学习服务调用。 Api接口定义 @ApiOperation("根据课程计划查询媒资信息")public TeachplanMediaPub getmedia(String teachplanId); Service 1、配置课程计划媒资索引库等信息 在 application.yml 中配置 xuecheng:elasticsearch:hostlist: ${eshostlist:127.0.0.1:9200} 多个结点中间用逗号分隔course:index: xc_coursetype: docsource_field: id,name,grade,mt,st,charge,valid,pic,qq,price,price_old,status,studymodel,teachmode,expires,pub_time,start_time,end_timemedia:index: xc_course_mediatype: docsource_field: courseid,media_id,media_url,teachplan_id,media_fileoriginalname 2、service 方法开发 在 课程搜索服务 中定义课程媒资查询接口,为了适应后续需求,service 参数定义为数组,可一次查询多个课程计划的媒资信息。 / 根据一个或者多个课程计划id查询媒资信息 @param teachplanIds 课程id @return QueryResponseResult/public QueryResponseResult<TeachplanMediaPub> getmedia(String [] teachplanIds){//设置索引SearchRequest searchRequest = new SearchRequest(media_index);//设置类型searchRequest.types(media_type);//创建搜索源对象SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();//源字段过滤String[] media_index_arr = media_field.split(",");searchSourceBuilder.fetchSource(media_index_arr, new String[]{});//查询条件,根据课程计划id查询(可以传入多个课程计划id)searchSourceBuilder.query(QueryBuilders.termsQuery("teachplan_id", teachplanIds));searchRequest.source(searchSourceBuilder);SearchResponse searchResponse = null;try {searchResponse = restHighLevelClient.search(searchRequest);} catch (IOException e) {e.printStackTrace();}//获取结果SearchHits hits = searchResponse.getHits();long totalHits = hits.getTotalHits();SearchHit[] searchHits = hits.getHits();//数据列表List<TeachplanMediaPub> teachplanMediaPubList = new ArrayList<>();for(SearchHit hit:searchHits){TeachplanMediaPub teachplanMediaPub =new TeachplanMediaPub();Map<String, Object> sourceAsMap = hit.getSourceAsMap();//取出课程计划媒资信息String courseid = (String) sourceAsMap.get("courseid");String media_id = (String) sourceAsMap.get("media_id");String media_url = (String) sourceAsMap.get("media_url");String teachplan_id = (String) sourceAsMap.get("teachplan_id");String media_fileoriginalname = (String) sourceAsMap.get("media_fileoriginalname");teachplanMediaPub.setCourseId(courseid);teachplanMediaPub.setMediaUrl(media_url);teachplanMediaPub.setMediaFileOriginalName(media_fileoriginalname);teachplanMediaPub.setMediaId(media_id);teachplanMediaPub.setTeachplanId(teachplan_id);//将对象加入到列表中teachplanMediaPubList.add(teachplanMediaPub);}//构建返回课程媒资信息对象QueryResult<TeachplanMediaPub> queryResult = new QueryResult<>();queryResult.setList(teachplanMediaPubList);queryResult.setTotal(totalHits);return new QueryResponseResult<TeachplanMediaPub>(CommonCode.SUCCESS,queryResult);} Controller / 根据课程计划id搜索发布后的媒资信息 @param teachplanId @return/@GetMapping(value="/getmedia/{teachplanId}")@Overridepublic TeachplanMediaPub getmedia(@PathVariable("teachplanId") String teachplanId) {//为了service的拓展性,所以我们service接收的是数组作为参数,以便后续开发查询多个ID的接口String[] teachplanIds = new String[]{teachplanId};//通过service查询ES获取课程媒资信息QueryResponseResult<TeachplanMediaPub> mediaPubQueryResponseResult = esCourseService.getmedia(teachplanIds);QueryResult<TeachplanMediaPub> queryResult = mediaPubQueryResponseResult.getQueryResult();if(queryResult!=null&& queryResult.getList()!=null&& queryResult.getList().size()>0){//返回课程计划对应课程媒资return queryResult.getList().get(0);} return new TeachplanMediaPub();} 测试 使用 swagger-ui 和 postman 测试课程媒资查询接口。 三、在线学习:接口开发 0x01 需求分析 根据下边的业务流程,本章节完成前端学习页面请求学习服务获取课程视频地址,并自动播放视频。 0x02 搭建开发环境 1、创建数据库 创建 xc_learning 数据库,学习数据库将记录学生的选课信息、学习信息。 导入:资料/xc_learning.sql 2、创建学习服务工程 参考课程管理服务工程结构,创建学习服务工程: 导入:资料/xc-service-learning.zip 项目工程结构如下 0x03 Api接口 此 api 接口是课程学习页面请求学习服务获取课程学习地址。 定义返回值类型: package com.xuecheng.framework.domain.learning.response;import com.xuecheng.framework.model.response.ResponseResult;import com.xuecheng.framework.model.response.ResultCode;import lombok.Data;import lombok.NoArgsConstructor;import lombok.ToString;@Data@ToString@NoArgsConstructorpublic class GetMediaResult extends ResponseResult {public GetMediaResult(ResultCode resultCode, String fileUrl) {super(resultCode);this.fileUrl = fileUrl;}//媒资文件播放地址private String fileUrl;} 定义接口,学习服务根据传入课程 ID、章节 Id(课程计划 ID)来取学习地址。 @Api(value = "录播课程学习管理",description = "录播课程学习管理")public interface CourseLearningControllerApi {@ApiOperation("获取课程学习地址")public GetMediaResult getMediaPlayUrl(String courseId,String teachplanId);} 0x04 服务端开发 需求分析 学习服务根据传入课程ID、章节Id(课程计划ID)请求搜索服务获取学习地址。 搜索服务注册Eureka 学习服务要调用搜索服务查询课程媒资信息,所以需要将搜索服务注册到 eureka 中。 1、查看服务名称是否为 xc-service-search 注意修改application.xml中的服务名称:spring:application:name: xc‐service‐search 2、配置搜索服务的配置文件 application.yml,加入 Eureka 配置 如下: eureka:client:registerWithEureka: true 服务注册开关fetchRegistry: true 服务发现开关serviceUrl: Eureka客户端与Eureka服务端进行交互的地址,多个中间用逗号分隔defaultZone: ${EUREKA_SERVER:http://localhost:50101/eureka/,http://localhost:50102/eureka/}instance:prefer-ip-address: true 将自己的ip地址注册到Eureka服务中ip-address: ${IP_ADDRESS:127.0.0.1}instance-id: ${spring.application.name}:${server.port} 指定实例idribbon:MaxAutoRetries: 2 最大重试次数,当Eureka中可以找到服务,但是服务连不上时将会重试,如果eureka中找不到服务则直接走断路器MaxAutoRetriesNextServer: 3 切换实例的重试次数OkToRetryOnAllOperations: false 对所有操作请求都进行重试,如果是get则可以,如果是post,put等操作没有实现幂等的情况下是很危险的,所以设置为falseConnectTimeout: 5000 请求连接的超时时间ReadTimeout: 6000 请求处理的超时时间 3、添加 eureka 依赖 <dependency><groupId>org.springframework.cloud</groupId><artifactId>spring‐cloud‐starter‐netflix‐eureka‐client</artifactId></dependency> 4、修改启动类,在class上添加如下注解: @EnableDiscoveryClient 搜索服务客户端 在 学习服务 创建搜索服务的客户端接口,此接口会生成代理对象,调用搜索服务: package com.xuecheng.learning.client;import com.xuecheng.framework.domain.course.TeachplanMediaPub;import org.springframework.cloud.openfeign.FeignClient;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;@FeignClient(value = "xc‐service‐search")public interface CourseSearchClient {@GetMapping(value="/getmedia/{teachplanId}")public TeachplanMediaPub getmedia(@PathVariable("teachplanId") String teachplanId);} 自定义错误代码 我们在 com.xuecheng.framework.domain.learning.response 包下自定义一个错误消息模型 package com.xuecheng.framework.domain.learning.response;import com.xuecheng.framework.model.response.ResultCode;import lombok.ToString;@ToStringpublic enum LearningCode implements ResultCode {LEARNING_GET_MEDIA_ERROR(false,23001,"学习中心获取媒资信息错误!");//操作代码boolean success;//操作代码int code;//提示信息String message;private LearningCode(boolean success, int code, String message){this.success = success;this.code = code;this.message = message;}@Overridepublic boolean success() {return success;}@Overridepublic int code() {return code;}@Overridepublic String message() {return message;} } 该消息模型基于 ResultCode 来实现,代码如下 package com.xuecheng.framework.model.response;/ Created by mrt on 2018/3/5. 10000-- 通用错误代码 22000-- 媒资错误代码 23000-- 用户中心错误代码 24000-- cms错误代码 25000-- 文件系统/public interface ResultCode {//操作是否成功,true为成功,false操作失败boolean success();//操作代码int code();//提示信息String message(); 从 ResultCode 中我们可以看出,我们约定了用户中心的错误代码使用 23000,所以我们定义的一些错误信息的代码就从 23000 开始计数。 Service 在学习服务中定义 service 方法,此方法远程请求课程管理服务、媒资管理服务获取课程学习地址。 package com.xuecheng.learning.service.impl;import com.netflix.discovery.converters.Auto;import com.xuecheng.framework.domain.course.TeachplanMediaPub;import com.xuecheng.framework.domain.learning.response.GetMediaResult;import com.xuecheng.framework.exception.ExceptionCast;import com.xuecheng.framework.model.response.CommonCode;import com.xuecheng.learning.client.CourseSearchClient;import com.xuecheng.learning.service.LearningService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;@Servicepublic class LearningServiceImpl implements LearningService {@AutowiredCourseSearchClient courseSearchClient;/ 远程调用搜索服务获取已发布媒体信息中的url @param courseId 课程id @param teachplanId 媒体信息id @return/@Overridepublic GetMediaResult getMediaPlayUrl(String courseId, String teachplanId) {//校验学生权限,是否已付费等//远程调用搜索服务进行查询媒体信息TeachplanMediaPub mediaPub = courseSearchClient.getmedia(teachplanId);if(mediaPub == null) ExceptionCast.cast(CommonCode.FAIL);return new GetMediaResult(CommonCode.SUCCESS, mediaPub.getMediaUrl());} } Controller 调用 service 根据课程计划 id 查询视频播放地址: @RestController@RequestMapping("/learning/course")public class CourseLearningController implements CourseLearningControllerApi {@AutowiredLearningService learningService;@Override@GetMapping("/getmedia/{courseId}/{teachplanId}")public GetMediaResult getMediaPlayUrl(@PathVariable String courseId, @PathVariable String teachplanId) {//获取课程学习地址return learningService.getMedia(courseId, teachplanId);} } 测试 使用 swagger-ui 或postman 测试学习服务查询课程视频地址接口。 0x05 前端开发 需求分析 需要在学习中心前端页面需要完成如下功能: 1、进入课程学习页面需要带上 课程 Id参数及课程计划Id的参数,其中 课程 Id 参数必带,课程计划 Id 可以为空。 2、进入页面根据 课程 Id 取出该课程的课程计划显示在右侧。 3、进入页面后判断如果请求参数中有课程计划 Id 则播放该章节的视频。 4、进入页面后判断如果 课程计划id 为0则需要取出本课程第一个 课程计划的Id,并播放第一个课程计划的视频。 进入到模块 xc-ui-pc-leanring/src/module/course api方法 let sysConfig = require('@/../config/sysConfig')let apiUrl = sysConfig.xcApiUrlPre;/获取播放地址/export const get_media = (courseId,chapter) => {return http.requestGet(apiUrl+'/api/learning/course/getmedia/'+courseId+'/'+chapter);} 配置代理 在 Nginx 中的 ucenter.xuecheng.com 虚拟主机中配置 /api/learning/ 的路径转发,此url 请转发到学习服务。 学习服务upstream learning_server_pool{server 127.0.0.1:40600 weight=10;}学成网用户中心server {listen 80;server_name ucenter.xuecheng.com;个人中心location / {proxy_pass http://ucenter_server_pool;}后端搜索服务location /openapi/search/ {proxy_pass http://search_server_pool/search/; }学习服务location ^~ /api/learning/ {proxy_pass http://learning_server_pool/learning/;} } 视频播放页面 1、如果传入的课程计划id为0则取出第一个课程计划id 在 created 钩子方法中完成 created(){//当前请求的urlthis.url = window.location//课程idthis.courseId = this.$route.params.courseId//章节idthis.chapter = this.$route.params.chapter//查询课程信息systemApi.course_view(this.courseId).then((view_course)=>{if(!view_course || !view_course[this.courseId]){this.$message.error("获取课程信息失败,请重新进入此页面!")return ;}let courseInfo = view_course[this.courseId]console.log(courseInfo)this.coursename = courseInfo.nameif(courseInfo.teachplan){console.log("准备开始播放视频")let teachplan = JSON.parse(courseInfo.teachplan);this.teachplanList = teachplan.children;//开始学习if(this.chapter == "0" || !this.chapter){//取出第一个教学计划this.chapter = this.getFirstTeachplan();console.log("第一个教学计划id为 ",this.chapter);this.study(this.chapter);}else{this.study(this.chapter);} }})}, 取出第一个章节 id,用户未输入课程计划 id 或者输入为 0 时,播放第一个。 //取出第一个章节getFirstTeachplan(){for(var i=0;i<this.teachplanList.length;i++){let firstTeachplan = this.teachplanList[i];//如果当前children存在,则取出第一个返回if(firstTeachplan.children && firstTeachplan.children.length>0){let secondTeachplan = firstTeachplan.children[0];return secondTeachplan.id;} }return ;}, 开始学习: //开始学习study(chapter){// 获取播放地址courseApi.get_media(this.courseId,chapter).then((res)=>{if(res.success){let fileUrl = sysConfig.videoUrl + res.fileUrl//播放视频this.playvideo(fileUrl)}else if(res.message){this.$message.error(res.message)}else{this.$message.error("播放视频失败,请刷新页面重试")} }).catch(res=>{this.$message.error("播放视频失败,请刷新页面重试")});}, 2、点击右侧课程章节切换播放 在原有代码基础上添加 click 事件,点击调用开始学习方法(study)。 <li v‐if="teachplan_first.children!=null" v‐for="(teachplan_second, index) inteachplan_first.children"><i class="glyphicon glyphicon‐check"></i><a :href="url" @click="study(teachplan_second.id)">{ {teachplan_second.pname} }</a></li> 3、地址栏路由url变更 这里需要注意一个问题,在用户点击课程章节切换播放时,地址栏的 url 也应该同步改变为当前所选择的课程计划 id 4、在线学习按钮 将 learnstatus 默认更改为 1,这样就能显示出马上学习的按钮,方便我们后续的集成测试。 文件路径为 xc-ui-pc-static-portal/include/course_detail_dynamic.html 部分代码块如下 <script>var body= new Vue({ //创建一个Vue的实例el: "body", //挂载点是id="app"的地方data: {editLoading: false,title:'测试',courseId:'',charge:'',//203001免费,203002收费learnstatus: 1 ,//课程状态,1:马上学习,2:立即报名、3:立即购买course:{},companyId:'template',company_stat:[],course_stat:{"s601001":"","s601002":"","s601003":""} }, 简单的测试 访问在线学习页面:http://ucenter.xuecheng.com//learning/课程id/课程计划id 通过 url 传入两个参数:课程id 和 课程计划id 如果没有课程计划则传入0 测试项目如下: 1、传入正确的课程id、课程计划id,自动播放本章节的视频 2、传入正确的课程id、课程计划id传入0,自动播放第一个视频 3、传入错误的课程id 或 课程计划id,提示错误信息。 4、通过右侧章节目录切换章节及播放视频。 访问: http://ucenter.xuecheng.com//learning/4028e58161bcf7f40161bcf8b77c0000/4028e58161bd18ea0161bd1f73190008 传入正确的课程id、课程计划id,自动播放本章节的视频 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Ef0xxym7-1595567273153)(https://qnoss.codeyee.com/20200704_15/image17)] 传入正确的课程id、课程计划id传入0,自动播放第一个视频 访问 http://ucenter.xuecheng.com//learning/4028e58161bcf7f40161bcf8b77c0000/0 识别出第一个课程计划的 id 需要注意的是这里的 chapter 参数是我自己在 study 函数里加上去的,可以忽略。 传入错误的课程id或课程计划id,提示错误信息。 通过右侧章节目录切换章节及播放视频。 点击章节即可播放,但是点击制定章节后 url 没有发生改变,这个问题暂时还没有解决,关注笔记后面的内容。 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TOGdxwb4-1595567273158)(https://qnoss.codeyee.com/20200704_15/image20)] 完整的测试 准备工作 启动 RabbitMQ,启动 Logstash、ElasticSearch 建议把所有后端服务都开起来 启动 前端静态门户、启动 nginx 、启动课程管理前端 我们整理一下测试的流程 上传两个媒资视频文件,用于测试 进入到课程管理,为课程计划选择媒资信息 发布课程,等待 logstash 将数据采集到 ElasticSearch 的索引库中 进入学成网主页,点击课程,进入到搜索门户页面 搜索课程,进入到课程详情页面 点击开始学习,进入到课程学习页面,选择课程计划中的一个章节进行学习。 1、上传文件 首先我们使用之前开发的媒资管理模块,上传两个视频文件用于测试。 第一个文件上传成功 一些问题 在上传第二个文件时,发生了错误,我们来检查一下问题出在了哪里 在媒体服务的控制台中可以看到,在 mergeChunks 方法在校验文件 md5 时候抛出了异常 我们在 MD5 校验这里打个断点,重新上传文件,分析一下问题所在。 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OpEMZGI8-1595567273166)(https://qnoss.codeyee.com/20200704_15/image23)] 单步调试后发现,合并文件后的MD5值与用户上传的源文件值不相等 方案1:删除本地分块文件重新尝试上传 考虑到可能是在用户上传完 视频的分块文件时发生了一些问题,导致合并文件后与源文件的大小不等,导致MD5也不相同,这里我们把这个视频上传到本地的文件全部删除,在媒资上传页面重新上传文件。 对比所有分块文件的字节大小和本地源文件的大小,完全是相等的 删除所有文件后重新上传,md5值还是不等,考虑从调试一下文件合并的代码。 方案2:检查前端提交的MD5值是否正确 在查阅是否有其他的MD5值获取方案时,发现了一个使用 windows 本地命令获取文件MD5值的方法 certutil -hashfile .\19-在线学习接口-集成测试.avi md5 惊奇的发现,TM的原来是前端那边转换的MD5值不正确,后端这边是没有问题的。 从前面的图可以看出,本地和后端转换的都是以一个 f6f0 开头的MD5值 那么问题就出现在前端了,还需要花一些时间去分析一下,这里暂时就先告一段落,因为上传了几个文件测试中只有这一个文件出现了问题。 2、为课程计划选择媒资信息 进入到一个课程的管理页面 http://localhost:12000//course/manage/baseinfo/4028e58161bcf7f40161bcf8b77c0000 将刚才我们上传的媒资文件的信息和课程计划绑定 选择效果如下 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-epKaqzCD-1595567273178)(https://qnoss.codeyee.com/20200704_15/image29)] 2、发布课程,等待 logstash 从 course_pub 以及 teachplan_media_pub 表中采集数据到 ElasticSearch 当中 发布成功后,我们可以从 teachplan_media_pub 表中看到刚才我们发布的媒资信息 再观察 Logstash 的控制台,发现两个 Logstash 的实例都对更新的课程发布信息进行了采集 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hTUve2ik-1595567273183)(https://qnoss.codeyee.com/20200704_15/image32)] 3、前端门户测试 打开我们的门户主站 http://www.xuecheng.com/ [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4wZe9R84-1595567273185)(https://qnoss.codeyee.com/20200704_15/image33)] 点击导航栏的课程,进入到我们的搜索门户页面 如果无法进入到搜索门户,请检查你的 xc-ui-pc-portal 前端工程是否已经启动 进入到搜索门户后,可以看到一些初始化时搜索的课程数据,默认是搜索第一页的数据,每页2个课程。 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BJ1AKoJb-1595567273187)(https://qnoss.codeyee.com/20200704_15/image34)] 我们可以测试搜索一下前面我们选择媒资信息时所用的课程 点击课程,进入到课程详情页面,然后再点击开始学习。 点击马上学习后,会进入到该课程的在线学习页面,默认自动播放我们第一个课程计划中的视频。 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tcuLWnf2-1595567273193)(https://qnoss.codeyee.com/20200704_15/image37)] 我们可以在右侧的目录中选择第二个课程计划,会自动播放所选的课程计划所对应的媒资视频播放地址,该 播放地址正是我们刚才通过 Logstash 自动采集到 ElasticSearch 的索引信息,效果图如下 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Cvi9Dr0Y-1595567273195)(https://qnoss.codeyee.com/20200704_15/image38)] 四、待完善的一些功能 课程发布前,校验课程计划里面是否包含二级课程计划 课程发布前,校验课程计划信息里面是否全部包含媒资信息 删除媒资信息,并且同步删除ES中的索引 在获取该课程的播放地址时校验用户的合法、 在线学习页面,点击右侧目录中的课程计划同时改变url中的课程计划地址 视频文件 19-在线学习接口-集成测试.avi 前端上传时提交的MD5值不正确 😁 认识作者 作者:👦 LCyee ,全干型代码🐕 自建博客:https://www.codeyee.com 记录学习以及项目开发过程中的笔记与心得,记录认知迭代的过程,分享想法与观点。 CSDN 博客:https://blog.csdn.net/codeyee 记录和分享一些开发过程中遇到的问题以及解决的思路。 欢迎加入微服务练习生的队伍,一起交流项目学习过程中的一些问题、分享学习心得等,不定期组织一起刷题、刷项目,共同见证成长。 本篇文章为转载内容。原文链接:https://blog.csdn.net/codeyee/article/details/107558901。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-12-16 12:41:01
73
转载
MySQL
MySQL , MySQL是一个开源的关系型数据库管理系统,由Oracle公司开发并维护。在本文的语境中,MySQL是开发者在本地计算机上可能需要安装的核心软件,用于存储、管理和处理结构化数据,支持多种SQL语句进行数据操作,并可通过客户端与服务器架构与其他应用程序交互。 MySQL客户端 , MySQL客户端是指用来连接到MySQL服务器并执行查询、管理数据库等任务的软件工具。在文章中提到的“mysql --version”命令就是在检查用户电脑上是否安装了可以与MySQL服务器通信的客户端程序,以便进行数据库的相关操作和管理。 MySQL服务器 , MySQL服务器是MySQL数据库系统中的核心部分,负责接收来自客户端的请求,执行SQL语句,返回结果,并对存储在其中的数据进行管理和维护。在文章情境下,“mysql -u root -p -h localhost”命令是用来尝试连接到本地MySQL服务器,如果该命令无法执行,意味着用户的电脑尚未安装或启动MySQL服务器服务,不具备处理数据库请求的能力。 Python扩展包 , Python扩展包是为Python编程语言设计的附加模块,提供额外的功能以丰富Python应用生态。在本文中,\ pymysql\ 就是一种MySQL的Python扩展包,它允许Python开发者通过编写Python代码来连接MySQL数据库,执行SQL查询、插入、更新及删除数据等操作。通过运行\ import pymysql;print(pymysql.__version__)\ 指令,可以检测Python环境中是否已成功安装并导入了这个特定的MySQL连接库。
2023-04-24 15:12:40
49
电脑达人
MySQL
MySQL , MySQL是一个广泛应用于互联网和企业环境的开源关系型数据库管理系统,由Oracle公司开发并维护。它支持SQL语言,并以其稳定、高效、可扩展性强等特点被全球众多网站和应用程序用于存储和管理结构化数据。 配置文件(my.cnf或my.ini) , 在MySQL安装目录下,存在一个名为my.cnf(Unix/Linux系统中常见)或my.ini(Windows系统中常见)的配置文件,用于存储MySQL服务器的全局配置参数。用户可以在此文件中设置如数据库连接密码、端口号、数据存放路径等各种启动选项,当MySQL服务启动时,会读取这些配置信息以初始化和运行数据库服务。 命令行工具 , 命令行工具是一种通过文本界面与计算机系统交互的应用程序,用户通过输入特定指令来执行操作。在MySQL环境下,命令行工具即MySQL客户端,允许用户直接通过键盘输入SQL语句来查询、修改数据库中的数据,以及进行诸如查看和重置密码等管理操作,无需图形用户界面。例如,在文章中提到的“mysql -u root -p”命令就是利用MySQL命令行工具登录MySQL服务器的方式。
2024-02-18 15:42:33
121
码农
转载文章
...和下单的总金额,存入MySQL数据库shtd_store的nationeverymonth表(表结构如下)中,然后在Linux的MySQL命令行中根据订单总数、消费总额、国家表主键三列均逆序排序的方式,查询出前5条,将SQL语句与执行结果截图粘贴至对应报告中; spark.sql("select nationkey,regexp_replace(nationname,'\'','') as nationname,regionkey,regexp_replace(regionname,'\'','') as regionname,sum(totalnum) as totalorder,sum(totalprice) as totalconsumption,year,month from nationeverymonth group by nationkey,regionkey,month,nationname,year,regionname;") 我为了方便查询和之后的操作,将上面的查询结果导入到新表nationeverymonths 查表 接下来将hive中的数据导入mysql中 package com.atguigu.spark.sqlimport org.apache.spark.SparkConfimport org.apache.spark.sql.SparkSessionimport java.util.Propertiesobject DataHiveToMySQL {def main(args: Array[String]): Unit = {val sparkConf = new SparkConf().setMaster("local[]").setAppName("sparkSQL")val spark = SparkSession.builder().enableHiveSupport().config(sparkConf).getOrCreate()val result=spark.sql("select from ods.nationeverymonths")val props=new Properties()props.setProperty("user","root")props.setProperty("password","123456")props.setProperty("driver","com.mysql.jdbc.Driver")result.write.mode("overwrite").jdbc("jdbc:mysql://192.168.230.132:3306/user?serverTimezone=UTC&characterEncoding=UTF-8&useSSL=false", "nationeverymonth", props)println("导入成功")spark.stop()} } 运行可见导入成功 进入MySQL中查看结果 可见数据成功导入 接下来按照要求查询: 2.请根据dwd层表计算出某年每个国家的平均消费额和所有国家平均消费额相比较结果(“高/低/相同”),存入MySQL数据库shtd_store的nationavgcmp表(表结构如下)中,然后在Linux的MySQL命令行中根据订单总数、消费总额、国家表主键三列均逆序排序的方式,查询出前5条,将SQL语句与执行结果截图粘贴至对应报告中; 在解这道题的时候遇见一个问题,在求所有国家平均消费额的时候一直报错,由于没有数据这道题的题意还是有点没看明白,于是我就用了最简单的办法先新增一列,再单独将所有国家平均消费额求出来然后再插入,如果各位大佬有解决这个问题的办法希望能指导一下 先将每个国家的平均消费额求出来 spark.sql("select nationkey,nationname,avg(totalconsumption) as nationavgconsumption from nationeverymonths group by nationkey,nationname") 再新增一列所有国家平均消费额 spark.sql("alter table nationeverymonths add columns(avg_allstring)") 再将查询到的所有国家平均消费额导入进去 spark.sql("insert overwrite table nationeverymonths1 select nationkey,nationname,avg_totalconsumpt,1500 from nationeverymonths1") 再次查表 按照题意添加比较结果字段 spark.sql("select ,case when avg_totalconsumpt>avg_all then '高' when avg_totalconsumpt<avg_all then '低' when avg_totalconsumpt=avg_all then '相同' else 'null' end as comparison from nationeverymonths1").show 最后的排序语句和题一一样 本篇文章为转载内容。原文链接:https://blog.csdn.net/guo_0423/article/details/126352162。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-09-01 10:55:33
319
转载
站内搜索
用于搜索本网站内部文章,支持栏目切换。
知识学习
实践的时候请根据实际情况谨慎操作。
随机学习一条linux命令:
Ctrl+R
- 启动反向搜索历史命令功能。
推荐内容
推荐本栏目内的其它文章,看看还有哪些文章让你感兴趣。
2023-04-28
2023-08-09
2023-06-18
2023-04-14
2023-02-18
2023-04-17
2024-01-11
2023-10-03
2023-09-09
2023-06-13
2023-08-07
2023-03-11
历史内容
快速导航到对应月份的历史文章列表。
随便看看
拉到页底了吧,随便看看还有哪些文章你可能感兴趣。
时光飞逝
"流光容易把人抛,红了樱桃,绿了芭蕉。"