search
HomeDatabaseMysql TutorialData Guard环境做到Client的自动切换

使用Data guard作为HA方案,要解决的一个问题在于:后台数据库发生了主备切换,client连接如何做到自动切到新的primary数据库上?

使用Data guard作为HA方案,要解决的一个问题在于:后台数据库发生了主备切换,client连接如何做到自动切到新的primary数据库上?
 
如果做通用的方案,需要客户端自己提供自动重连的能力,这点大多数java的occi的连接池都有实现。
 
但这些已有实现大多是对同一连接配置发起重连,所以需要考虑为application提供透明的连接方式,而不让应用看到具体data guard的多个ip和service name,这就需要做些额外的配置工作。
 
    一种方式通过vip,真实转发的ip只挂靠在有效数据库的ip上。这种方式切换发生后,application在断连的旧connection上发起dml会获得ORA-3113 "end of file on communication channel"的错误,此时application可以尝试重连机制和新的primary建立连接。
 
在f5上可以通过设置心跳sql和期望的返回结果内容,以类似ping方式获取远端数据库是否可用,来决定ip是否应该转发到该物理ip上。
 
    另一种方式是通过设置tns和数据库的service name来访问,通过合理设置,甚至可以做到在发生切换时的select操作仅仅被阻塞一会,而不会感觉到数据库已经完成了主备切换。
 
设置步骤如下:
 
 1.客户端的tnsnames.ora中tns配置成
 
MYAPP =
  (DESCRIPTION =
  (ADDRESS_LIST =
  (ADDRESS = (PROTOCOL = TCP)(HOST = HostA)(PORT = 1521))
  (ADDRESS = (PROTOCOL = TCP)(HOST = HostB)(PORT = 1521))
  )
  (CONNECT_DATA =
  (SERVICE_NAME = myapp)
  )
  )
 
 
 
2.在primary数据库运行
 
 begin
  dbms_service.create_service("myapp","myapp");
 end;
 /
 begin
  DBMS_SERVICE.START_SERVICE("myapp");
 end;
 /
 
 3.在primary数据库创建触发器:
 
create trigger myapptrigg after startup on database
 declare
  v_role varchar(30);
 begin
  select database_role into v_role from v$database;
  if v_role = "PRIMARY" then
  DBMS_SERVICE.START_SERVICE("myapp");
  else
  DBMS_SERVICE.STOP_SERVICE("myapp");
  end if;
 end;
 /
 
解释下:这个方案的思路就是将两边的数据库的service name都设置成"myapp",当发生切换时,由触发器在数据库startup的时候把primary的实例以"myapp"的名字显示,而把standby的"myapp"服务名给停掉,这样任何时刻只有主节点显示名字为"myapp"的服务。
 
注意这里的plsql都是运行在primary,无需在standby上做任何设置,因为data guard会自动将变化同步到standby数据库。
 
通过在primary数据库运行下面程序,可以让客户端在做select的时候甚至意识不到数据库的切换:
 
begin
  dbms_service.modify_service
  ("myapp",
  FAILOVER_METHOD => "BASIC",
  FAILOVER_TYPE => "SELECT",
  FAILOVER_RETRIES => 200,
  FAILOVER_DELAY => 1);
 end;
 /
 
注意如果在切换时有comit的提交事务发生,还是会出现失误提交失败,要求回滚的情况。
 
 
 
下面tns是另一种配置方式(类似rac的failover配置思想),,使用这种方式,不需要在Oracle server中运行任何plsql脚本,在DESCRIPTION_LIST中的两个数据库甚至根本不需要处于data guard中,可以是任意两个数据库。driver会按顺序遍历list中的数据库,一直到能连接上为止。
 
MYAPP =
 (DESCRIPTION_LIST=
  (LOAD_BALANCE=off)
  (FAILOVER=on)
  (DESCRIPTION =(CONNECT_TIMEOUT=5)(TRANSPORT_CONNECT_TIMEOUT=3)(RETRY_COUNT=10)
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVICE_NAME = myapp1)
    )
  )
  (DESCRIPTION =(CONNECT_TIMEOUT=5)(TRANSPORT_CONNECT_TIMEOUT=3)(RETRY_COUNT=10)
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = otherIP)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVICE_NAME = myapp2)
    )
  )
 )
 
 
 
这种方式需要注意的地方:
 
1.jdbc必须走oci的方式,如果为jdbc:thin+tns方式,则会出现
 
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 545
  at oracle.net.nl.NVTokens.parseTokens(Unknown Source)
  at oracle.net.nl.NVFactory.createNVPair(Unknown Source)
 
其原因在于jdbc的driver本身无法识别这种格式的tns内容。
 
此时即使以jdbc:thin+tns的方式访问其他正常的tns也会一样抛出这个错误,因为这导致了jdbc根本无法正确解析整个tnsnames.ora文件。
 
而jdbc:oci实际上负责解析tnsnames.ora和处理通信的是依赖oci.lib,因此就不存在这个问题。
 
2.这种配置适用于任何依赖oci通信的客户端,包括oci,occi,一些基于它们的wrap库,以及pl/sql developer此类的工具软件。
 
3.注意如果连接的数据库组属于manually switch的模式,而不是fail down导致的切换,比如tns中的a数据库是mount状态,b是primary,而tns的列表顺序是先a后b,则会出现尽管客户端连a时,抛出ORA-0133错误,但是不会按顺序去尝试连接b。
 
原因是在处理这个链接时,oci客户端会尝试通过listener和service建立连接。
 
如果listener是关闭的,或者客户端能连上listener但是找不到对应service,则都会尝试连接处于第二个的b,但是如果通过listener找到了对端的service,只是无法建立连接(如数据库处于mount状态),则此时不会尝试连接b,而直接会以抛出
 
ORA-0133:ORACLE initialization or shutdown in progress
 
终止连接尝试。
 
所以在使用这种tns的时候要确保通过tns列表能访问到的所有数据库都不会一直处于mount状态,否则连接它会打断对后面正常open数据库的连接尝试。
 
这也是为何手动切换的dataguard数据库,客户端不能依赖这种tns配置方法做自动切换,因为手动切换的dataguard数据库状态肯定是一个open一个mount,如果mount处于tns的列表靠前的位置,在连接它失败后会抛出ORA-0133异常阻止客户端尝试连接正常open的那个数据库。

推荐阅读:

RMAN 配置归档日志删除策略

Oracle基础教程之通过RMAN复制数据库

RMAN备份策略制定参考内容

RMAN备份学习笔记

Oracle数据库备份加密 RMAN加密

linux

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do you handle database upgrades in MySQL?How do you handle database upgrades in MySQL?Apr 30, 2025 am 12:28 AM

The steps for upgrading MySQL database include: 1. Backup the database, 2. Stop the current MySQL service, 3. Install the new version of MySQL, 4. Start the new version of MySQL service, 5. Recover the database. Compatibility issues are required during the upgrade process, and advanced tools such as PerconaToolkit can be used for testing and optimization.

What are the different backup strategies you can use for MySQL?What are the different backup strategies you can use for MySQL?Apr 30, 2025 am 12:28 AM

MySQL backup policies include logical backup, physical backup, incremental backup, replication-based backup, and cloud backup. 1. Logical backup uses mysqldump to export database structure and data, which is suitable for small databases and version migrations. 2. Physical backups are fast and comprehensive by copying data files, but require database consistency. 3. Incremental backup uses binary logging to record changes, which is suitable for large databases. 4. Replication-based backup reduces the impact on the production system by backing up from the server. 5. Cloud backups such as AmazonRDS provide automation solutions, but costs and control need to be considered. When selecting a policy, database size, downtime tolerance, recovery time, and recovery point goals should be considered.

What is MySQL clustering?What is MySQL clustering?Apr 30, 2025 am 12:28 AM

MySQLclusteringenhancesdatabaserobustnessandscalabilitybydistributingdataacrossmultiplenodes.ItusestheNDBenginefordatareplicationandfaulttolerance,ensuringhighavailability.Setupinvolvesconfiguringmanagement,data,andSQLnodes,withcarefulmonitoringandpe

How do you optimize database schema design for performance in MySQL?How do you optimize database schema design for performance in MySQL?Apr 30, 2025 am 12:27 AM

Optimizing database schema design in MySQL can improve performance through the following steps: 1. Index optimization: Create indexes on common query columns, balancing the overhead of query and inserting updates. 2. Table structure optimization: Reduce data redundancy through normalization or anti-normalization and improve access efficiency. 3. Data type selection: Use appropriate data types, such as INT instead of VARCHAR, to reduce storage space. 4. Partitioning and sub-table: For large data volumes, use partitioning and sub-table to disperse data to improve query and maintenance efficiency.

How can you optimize MySQL performance?How can you optimize MySQL performance?Apr 30, 2025 am 12:26 AM

TooptimizeMySQLperformance,followthesesteps:1)Implementproperindexingtospeedupqueries,2)UseEXPLAINtoanalyzeandoptimizequeryperformance,3)Adjustserverconfigurationsettingslikeinnodb_buffer_pool_sizeandmax_connections,4)Usepartitioningforlargetablestoi

How to use MySQL functions for data processing and calculationHow to use MySQL functions for data processing and calculationApr 29, 2025 pm 04:21 PM

MySQL functions can be used for data processing and calculation. 1. Basic usage includes string processing, date calculation and mathematical operations. 2. Advanced usage involves combining multiple functions to implement complex operations. 3. Performance optimization requires avoiding the use of functions in the WHERE clause and using GROUPBY and temporary tables.

An efficient way to batch insert data in MySQLAn efficient way to batch insert data in MySQLApr 29, 2025 pm 04:18 PM

Efficient methods for batch inserting data in MySQL include: 1. Using INSERTINTO...VALUES syntax, 2. Using LOADDATAINFILE command, 3. Using transaction processing, 4. Adjust batch size, 5. Disable indexing, 6. Using INSERTIGNORE or INSERT...ONDUPLICATEKEYUPDATE, these methods can significantly improve database operation efficiency.

Steps to add and delete fields to MySQL tablesSteps to add and delete fields to MySQL tablesApr 29, 2025 pm 04:15 PM

In MySQL, add fields using ALTERTABLEtable_nameADDCOLUMNnew_columnVARCHAR(255)AFTERexisting_column, delete fields using ALTERTABLEtable_nameDROPCOLUMNcolumn_to_drop. When adding fields, you need to specify a location to optimize query performance and data structure; before deleting fields, you need to confirm that the operation is irreversible; modifying table structure using online DDL, backup data, test environment, and low-load time periods is performance optimization and best practice.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools