数据库
首页 > 数据库> > Oracle-部署Physical Standby

Oracle-部署Physical Standby

作者:互联网

环境要求

硬件和操作系统要求

平台ID

col PLATFORM_NAME for a48
select * from v$TRANSPORTABLE_PLATFORM order by platform_id;

image-20210814140436961

支持异构环境的情形

物理备库
逻辑备库

Oracle 软件要求

Standby数据库目录结构注意事项

各种备用数据库的目录结构很重要,因为它决定了备用数据文件、归档重做日志文件和备用重做日志文件的路径名。

建议主备数据库上的数据文件、日志文件和控制文件使用相同的名称和路径名,并使用最佳灵活架构[Optimal Flexible Architecture (OFA)]命名。否则,在不同目录结构的主备系统中,必须使用设置文件名转换参数。

文件名转换参数

前期准备工作

Primary 数据库部署

可以是在运行中的Oracle Database数据库,也可以新部署一套完整Oracle Database数据库并正常启动起来。

创建数据库

12C
dbca -ignorePreReqs -ignorePrereqFailure -silent -createDatabase                    \
-gdbName albin                                                                      \
-sid albin                                                                          \
-templateName General_Purpose.dbc                                                   \
-characterSet AL32UTF8                                                              \
-createAsContainerDatabase true                                                     \
-numberOfPDBs 1                                                                     \
-pdbName tmpdb                                                                      \
-pdbAdminPassword oraP#ssw0rd                                                       \
-pdbOptions JSERVER:true,XML:true,CATJAVA:true,CONTEXT:true,ORDIM:true              \
-useLocalUndoForPDBs true                                                           \
-createListener albin:1680                                                          \
-databaseConfigType RAC                                                             \
-databaseType MULTIPURPOSE                                                          \
-datafileDestination +DATA                                                          \
-datafileJarLocation /oracle/app/oracle/product/12.2/db_1/assistants/dbca/templates \
-emConfiguration NONE                                                               \
-enableArchive false                                                                \
-memoryMgmtType AUTO_SGA                                                            \
-memoryPercentage 20                                                                \
-nationalCharacterSet AL16UTF16                                                     \
-nodelist vm-zqol12c01-rac01,vm-zqol12c01-rac02                                     \
-redoLogFileSize 100                                                                \
-storageType ASM                                                                    \
-sysPassword oraP#ssw0rd                                                            \
-systemPassword oraP#ssw0rd                                                         \
-useOMF true                                                                        \
-recoveryAreaDestination NONE

删除数据库

dbca -silent -deleteDatabase -sourceDB albin 

收集当前初始化参数配置

set linesize 168 pagesize 99
col value for a60
col name for a32
SELECT NAME, VALUE
  FROM v$parameter
 WHERE NAME IN ('db_name'
               ,'db_unique_name'
               ,'log_archive_config'
               ,'log_archive_dest_1'
               ,'log_archive_dest_2'
               ,'log_archive_dest_state_1'
               ,'log_archive_dest_state_2'
               ,'remote_login_passwordfile'
               ,'log_archive_format'
               ,'log_archive_max_processes'
               ,'fal_server'
                ,'fal_client'
               ,'db_file_name_convert'
               ,'log_file_name_convert'
               ,'standby_file_management'
                ,'compatiable'
               );


收集当前联机在线日志组信息

-- 查看online redo log 大小
set lines 200 pages 999
col member for a64
col INSTANCE_NAME for a15
col archived for a12
WITH redolog AS
 (SELECT inst_id
        ,group#
        ,thread#
        ,sequence#
        ,bytes
        ,blocksize
        ,archived
        ,status
        ,used
    FROM gv$standby_log
  UNION ALL
  SELECT inst_id
        ,group#
        ,thread#
        ,sequence#
        ,bytes
        ,blocksize
        ,archived
        ,status
        ,0 used
    FROM gv$log)
SELECT i.instance_name
      ,i.thread#
      ,f.group#
      ,sequence#
      ,f.member
      ,f.type
      ,l.status
      ,round(l.bytes / 1048576) init_size_mb
      ,round(l.used / 1048576) used_size_mb
      ,l.archived
  FROM gv$logfile f, redolog l, gv$instance i
 WHERE f.group# = l.group#
      -- AND l.thread# = i.thread#
   AND i.inst_id = f.inst_id
   AND f.inst_id = l.inst_id
 ORDER BY i.instance_name, f.group#, f.member
;

检查数据库配置值

set lines 300 pages 999
col unique_name for a18
col supp_log_min for a12
col standby_scn for 9999999999999999
col force_logging for a15
select db.name,
       db.db_unique_name unique_name,
       db.database_role,
       db.log_mode,
       db.supplemental_log_data_min supp_log_min,
       db.flashback_on,
       db.created,
       db.protection_mode,
       db.switchover_status,
    -- db.dataguard_broker,
    -- db.guard_status,
       db.force_logging,
       db.standby_became_primary_scn standby_scn
       ,db.PLATFORM_ID
  from v$database db;

Standby 数据库部署

仅需要安装Oracle Database软件和创建相关的目录即可。建议备库与主库的目录结构一致,便于日常维护。

配置Data Guard

Primary 数据库配置

配置监听和tnsname

  • 建议primary和standby数据库配置一致
  • 建议配置单独网络传输日志
静态监听配置
vi $(orabasehome)/network/admin/listener.ora
LSNR_DG = 
  (DESCRIPTION_LIST = (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = progs)
(PORT = 1535)(IP = FIRST))))
SID_LIST_LSNR_DG =
  (SID_LIST =
    (SID_DESC =
      (GLOBAL_DBNAME = albindg)
      (ORACLE_HOME = /oracle/app/12.2.0/grid)
      (SID_NAME = standby)
    )
    (SID_DESC =
      (GLOBAL_DBNAME = albindg_DGMGRL)
      (ORACLE_HOME = /oracle/app/12.2.0/grid)
      (SID_NAME = standby)
    )    
  )
tnsnames.ora配置
vi $(orabasehome)/network/admin/tnsnames.ora
tns_primary =
(DESCRIPTION =
    (ADDRESS_LIST =
        (ADDRESS = (PROTOCOL = TCP)(HOST = progs)(PORT = 1533))
    )
    (CONNECT_DATA =
        (SERVER = DEDICATED)
        (SERVICE_NAME = primary)
        (UR = A)
    )
)

tns_standby =
(DESCRIPTION =
    (ADDRESS_LIST =
        (ADDRESS = (PROTOCOL = TCP)(HOST = progs)(PORT = 1535))
    )
    (CONNECT_DATA =
        (SERVER = DEDICATED)
        (SERVICE_NAME = standby)
        (UR = A)
    )
)

归档模式配置

检查配置
-- 检查数据库是否运行在归档模式并开启
archive log list;
select name, db_unique_name, log_mode from v$database;
备份参数文件
# 创建pfile
DTIME=$(date +%Y%m%d%h)
sqlplus -S "/ as sysdba" <<EOF
create pfile='/tmp/pfile_${DTIME}.ora' from spfile;
quit;
EOF
初始化参数配置
RAC环境
-- 1. 设置归档日志文件名称格式
alter system set log_archive_format ='primary1_%t_%s_%r.arc' scope=spfile sid='primary1';
alter system set log_archive_format ='primary2_%t_%s_%r.arc' scope=spfile sid='primary2';
-- 2. 本地归档路径
alter system set log_archive_dest_1 ='LOCATION=+ARCH' scope=both sid='*';
alter system set standby_archive_dest = 'LOCATION=+ARCH' scope=both sid='*';
-- 3. 远程归档路径

NON-RAC
-- 1. 设置归档日志文件名称格式
alter system set log_archive_format ='primary_%t_%s_%r.arc' scope=spfile sid='*';
-- 2. 归档路径
alter system set log_archive_dest_1 ='LOCATION=/arch' scope=both sid='*';
alter system set standby_archive_dest = 'LOCATION=/arch' scope=both sid='*';
-- 3. 远程归档路径

参数说明
  1. log_archive_dest参数:使用log_archive_dest参数最多可设置2个归档路径,通过log_archive_dest设置一个主归档路径,通过LOG_ARCHIVE_DUPLEX_DEST 参数设置一个从归档路径。所有的路径必须是本地的
使用USE_DB_RECOVERY_FILE_DEST归档位置
alter system set log_archive_format='%t_%s_%r.arc' scope=spfile sid='*';
alter system set db_recovery_file_dest_size='102400M' scope=spfile sid='*';
alter system set db_recovery_file_dest='+data' scope=spfile sid='*';
alter system set log_archive_dest_1='location=USE_DB_RECOVERY_FILE_DEST VALID_FOR=(ALL_LOGFILES,ALL_ROLES) DB_UNIQUE_NAME=primary' scope=both sid='*';

create pfile='/home/oracle/init.ora' from spfile;
配置归档模式
RAC环境
-- 1. 关闭数据库
srvctl stop instance -d db_name -i instance_name1
srvctl stop instance -d db_name -i instance_name2

-- 2. 开启归档
srvctl start instance -d db_name -i instance_name1 -o mount
sqlplus -S "/ as sysdba" << EOF
alter database archivelog;
alter database open;
quit;
EOF
Non-RAC环境
-- 1. 关闭数据库
sqlplus -S "/ as sysdba" << EOF
alter system switch logfile;
/
alter system checkpoint;
/
shutdown immediate;
quit;
EOF

-- 2. 开启归档
sqlplus -S "/ as sysdba" << EOF
startup mount;
alter database archivelog;
alter database open;
quit;
EOF

force logging属性配置

-- 查看属性
select name, db_unique_name, force_logging from v$database;
-- 开启
alter database force logging;

语句执行可能需要相当长的时间才能完成,因为它会等待所有未记录的直接写入 I/O 完成

配置redo数据传输身份认证

Oracle Data Guard使用基于Oracle Net的会话在Data Guard成员间传输redo数据和控制消息。redo传输会话可以使用安全套接字层 (Secure Sockets Layer-SSL) 协议或远程登录密码文件进行身份验证。

以下情况使用SSL,用于验证2个数据库间的redo传输会话

如果不满足SSL身份认证要求,则必须为Data Guard的每个成员配置使用远程登录密码文件进行身份认证。并且配置中的每个物理备库必须是主库的最新的密码文件副本。

从Oracle12.2.0.1开始,对主库密码文件所做的更改会自动传输到备库。只有far sync instances是例外,密码文件的更新必须手动复制到far sync实例。一旦far sync实例更新后,redo数据将自动传输到从该far sync实例接收redo数据的备库。redo应用时,备库的密码文件会更新。

配置主库接收redo数据

如果首次配置添加备库时,最佳建议是在主库上配置接收redo数据。即创建standby redo log

  • standby redo log (SRL)与 online redo log(ORL) 日志组大小一致
  • 日志组数量要求:SRL = (maximum number of logfiles for each thread + 1) * maximum number of threads
  • SRL日志组只需要一个成员即可,需要考虑冗余
-- RAC 
alter database add standby logfile thread 1 group 20 '+SRL' size 1024M;
alter database add standby logfile thread 2 group 21 '+SRL' size 1024M;
......

-- NON-RAC
alter database add standby logfile group 20 size 1024M;
...

设置主库初始化参数

Database DB_UNIQUE_NAME Oracle Net Service Name
Primary primary tns_primary
Physical standby standby tns_standby
-- DG_CONFIG属性罗列同一个Data Guard中所有DB_UNIQUE_NAME(含primary db及standby db),以逗号分隔。
alter system set log_archive_config='DG_CONFIG=(primary,standby)' scope=both sid='*';

-- DB_NAME,数据库名字,需要保持同一个Data Guard 中所有数据库DB_NAME相同
-- DB_UNIQUE_NAME,对应数据库的实例名,每一个数据库需要指定一个唯一的名字
alter system set db_unique_name='primary' scope=spfile sid='*';

-- DG重做日志传输的主要参数,通常都是在主库中起作用,当然也会有例外,比如处理级联备库的场景;该参数也可用来指定由在线重做日志(ORL)或备库重做日志(SRL)产生的归档日志文件的传输目的地,
-- 不过随着10gR1版本中闪回恢复区的引入,本地归档的日志文件默认会放在闪回恢复区,所以在这种情况下就不需要再设置本地归档了

alter system set log_archive_dest_1='LOCATION=/arch VALID_FOR=(ALL_LOGFILES,ALL_ROLES) DB_UNIQUE_NAME=primary' scope=both sid='*';

alter system set log_archive_dest_2='SERVICE=tns_standby LGWR ASYNC VALID_FOR=(ONLINE_LOGFILES,PRIMARY_ROLE) DB_UNIQUE_NAME=standby' scope=both sid='*';

-- 激活定义的归档日志目录,允许redo 传输服务传输redo数据到指定的路径,默认就是enable
alter system set log_archive_dest_state_1=enable scope=both sid='*';
alter system set log_archive_dest_state_2=enable scope=both sid='*';

-- FAL_SERVER,备库端的参数,给出Oracle网络服务名,通常为指向主库的连接串
alter system set fal_server=tns_standby scope=both sid='*';

-- FAL_CLIENT,备库端的参数,给出Oracle网络服务名,通常为指向备库的连接串
alter system set fal_client=tns_primary scope=both sid='*';

-- DB_FILE_NAME_CONVERT,主数据库和备用数据库的数据文件转换目录对映(如果两数据库的目录结构不一样),如果有多个对映,逐一指明对映关系。
-- 如果两端数据库数据文件存储类型不同,则必须要将tempfile路径也要设置
alter system set db_file_name_convert='/standby/','/primary/' scope=spfile sid='*';

-- LOG_FILE_NAME_CONVERT,指明主数据库和备用数据库的在线日志文件转换目录对映
alter system set log_file_name_convert='/standby/','/primary/' scope=spfile sid='*';

-- STANDBY_FILE_MANAGEMENT,如果primary 数据库数据文件发生修改(如新建,重命名等)则按照本参数的设置在standby 中做相应修改。设为AUTO 表示自动管理。设为MANUAL表示需要手工管理
alter system set standby_file_management='AUTO' scope=spfile sid='*';

-- 用密码文件作为redo传输会话身份验证
alter system set REMOTE_LOGIN_PASSWORDFILE=EXCLUSIVE scope=spfile sid='*';
对上面例子中的初始参数配置说明
参数名 Recommended Setting
DB_NAME 在主数据库上,指定创建数据库时使用的名称。在物理备用数据库上使用相同的 DB_NAME
DB_UNIQUE_NAME 为每个数据库指定一个唯一的名称。主备角色切换时也不需更改。最多包含30个字符,有效:字母数字字符、下划线 (_)、数字符号 (#) 和美元符号 ($)
LOG_ARCHIVE_CONFIG 在 Oracle Data Guard 配置中必须显式设置 DG_CONFIG 属性,将 DG_CONFIG 设置为包含每个成员数据库的 DB_UNIQUE_NAME ,每个名称用逗号分隔。
LOG_ARCHIVE_DEST_n 指定redo数据在主备库上归档位置。
LOG_ARCHIVE_DEST_1将主库生成的redo数据ORL归档到指定的位置/arch
LOG_ARCHIVE_DEST_2 仅对当前数据库为primary role时,将redo数据传输到名为standby的远程物理备库位置上
REMOTE_LOGIN_PASSWORDFILE 如果密码文件用于验证redo传输会话,则必须设置此参数为EXCLUSIVE或SHARED
LOG_ARCHIVE_FORMAT 指定归档日志文件命名格式:thread (%t), sequence number (%s), and resetlogs ID (%r).
FAL_SERVER 指定FAL Server的Oracle Net 服务名称
DB_FILE_NAME_CONVERT 指定数据文件路径或名称转换关系,此参数可以指定多路径。例子中先定义standy端路径,然后是主库路径。
LOG_FILE_NAME_CONVERT 指定ORL文件路径或名称转换关系,此参数可以指定多路径。例子中先定义standy端路径,然后是主库路径。
STANDBY_FILE_MANAGEMENT 设置为 AUTO 以便在主数据库中添加或删除数据文件时,会自动对备用数据库进行相应的更改。

推荐配置

-- primary
alter system set db_block_checksum=TYPICAL scope=both sid='*';
alter system set db_block_checking=FULL scope=both sid='*';
alter system set db_lost_write_protect=TYPICAL scope=both sid='*';

主数据库和备用数据库上设置DB_BLOCK_CHECKSUM = FULL,这通常会导致系统上4%到5%的开销。对于OLTP工作负载,TYPICAL设置的开销范围为1%到2%,对重做应用性能的影响最小,但也提供较少的保护。如果测试显示在主数据库中使用FULL会导致不可接受的性能影响,请考虑将主数据库设置为TYPICAL,并将备用数据库设置为FULL以实现保护和性能之间的最佳权衡。

Standby 数据库配置(手动配置)

创建目录结构

su - oracle
DB_UNIQUE_NAME=standby
mkdir -p $(orabase)/admin/${DB_UNIQUE_NAME}/{adump,dpdump,pfile,scripts}
or
mkdir -p $(orabase)/admin/${DB_UNIQUE_NAME}/adump
mkdir -p $(orabase)/admin/${DB_UNIQUE_NAME}/dpdump
mkdir -p $(orabase)/admin/${DB_UNIQUE_NAME}/pfile
mkdir -p $(orabase)/admin/${DB_UNIQUE_NAME}/scripts

启动监听服务


创建密码文件

FS类型
# 若密码文件不存在,则创建
ls -l ${ORACLE_HOME}/dbs/orapw${ORACLE_SID} || orapwd file=${ORACLE_HOME}/dbs/orapw${ORACLE_SID} password=oracle entries=5

# 将密码文件传输到standby端所有节点及primary端另外的其它节点
scp ${ORACLE_HOME}/dbs/orapw${ORACLE_SID} oracle@standby:${ORACLE_HOME}/dbs/orapwstandby
ASM

Oracle 12C 支持密码文件存储在ASM中

$ srvctl config database -d albin
Database unique name: albin
Database name: albin
Oracle home: /oracle/app/oracle/product/12.2/db_1
Oracle user: oracle
Spfile: +DATA/ALBIN/PARAMETERFILE/spfile.1328.982582089
Password file: +DATA/ALBIN/PASSWORD/pwdalbin.1312.982581307
Domain: 
Start options: open
Stop options: immediate
Database role: PRIMARY
Management policy: AUTOMATIC
Server pools: 
Disk Groups: DATA
Mount point paths: 
Services: 
Type: RAC
Start concurrency: 
Stop concurrency: 
OSDBA group: dba
OSOPER group: dba
Database instances: albin1,albin2
Configured nodes: vm-zqol12c01-rac01,vm-zqol12c01-rac02
CSS critical: no
CPU count: 0
Memory target: 0
Maximum memory: 0
Default network number for database services: 
Database is administrator managed
方式1(dbms_file_transfer)
su - oracle
sqlplus "/ as sysdba"
create or replace directory source_dir as '+data/albin/password';
create or replace directory dest_dir as '/tmp';

set lines 168 pages 99
col DIRECTORY_NAME for a32
col owner for a18
col DIRECTORY_PATH for a80
select owner, DIRECTORY_NAME, DIRECTORY_PATH,ORIGIN_CON_ID from dba_directories;

begin
  dbms_file_transfer.copy_file( source_directory_object => 'source_dir',
  source_file_name => 'pwdalbin.1312.982581307',
  destination_directory_object => 'dest_dir',
  destination_file_name => 'orapwalbin');
end;
/
SQL> host ls -l /tmp/orapwalbin
方式2(asmcmd)
su - grid
asmcmd 
cd data/albin/password
cp pwdalbin.1312.982581307 /tmp/orapwalbin

# 传输到备端服务器节点1
scp /tmp/orapwalbin grid@vm-ora-N1:/tmp/orapwalbin
asmcmd -exec "cp /tmp/orapwalbin +data/albindg/password/orapwalbin"

# 获取spfile路径名称
asmcmd spget

创建pfile文件并传输到standby端

创建pfile
-- 在主库上生成pfile文件
CREATE PFILE='/tmp/init.ora' FROM SPFILE;
传输到standby端
scp /tmp/init.ora oracle@standby:/tmp/init.ora
修改物理备库初始化参数
vi /tmp/init.ora

*.audit_file_dest='/oracle/app/oracle/admin/standby/adump'
*.db_create_file_dest=/oradata
*.control_files='/data2/STANDBY/controlfile/current01.ctl','/data2/STANDBY/controlfile/current02.ctl'
*.fal_client='STANDBY'
*.fal_server='PRIMARY'
*.db_unique_name='standby'
*.log_archive_dest_1='LOCATION=/data2/standby/archivelog VALID_FOR=(ALL_LOGFILES,ALL_ROLES) DB_UNIQUE_NAME=standby'
*.log_archive_dest_2='SERVICE=tns_primary LGWR ASYNC VALID_FOR=(ONLINE_LOGFILES,PRIMARY_ROLE) DB_UNIQUE_NAME=primary'
*.db_file_name_convert='/primary/','/standby/'
*.log_file_name_convert='/primary/','/standby/'
*.local_listener='STANDBY'

确保备库的 COMPATIBLE 初始化参数与主库相同,否则可能无法将redo数据传输到备端

创建spfile
非RAC环境
sqlplus -S "/ as sysdba" << EOF
startup nomount pfile='/tmp/init.ora';
create spfile='/oracle/app/oracle/product/11.2.0/db_1/dbs/spfilestandby.ora' from pfile='/tmp/init.ora';
quit;
EOF
RAC环境
# 启动实例
srvctl start instance -db standby -i standby1 -o open,pfile='/tmp/init.ora'

# 创建spfile
create spfile='+DATADG/ORCLSTD/PARAMETERFILE/spfileorcl.ora' from pfile='/tmp/init.ora';
echo "SPFILE='+DATADG/ORCLSTD/PARAMETERFILE/spfileorcl.ora'" >$ORACLE_HOME/dbs/initorcl1.ora

初始化数据

duplicate rman方式(主备任一端执行都可以)

注意:RMAN duplicate需要确保关闭了data guard broker, 即dg_broker_start = FALSE

通用默认配置运行rman命令
rman target sys/oracle@orcl auxiliary sys/oracle@orcldg nocatalog
RMAN> duplicate target database for standby from active database;
自定义配置运行rman命令
cat> duplicate.rman <<EOF
run{
    allocate channel c1 device type disk;
    allocate channel c2 device type disk;
    allocate channel c3 device type disk;
    allocate channel c4 device type disk;
    allocate auxiliary channel aux1 device type disk;
    allocate auxiliary channel aux2 device type disk;
    allocate auxiliary channel aux3 device type disk;
    allocate auxiliary channel aux4 device type disk; 
    duplicate target database for standby from active database nofilenamecheck;
    release channel c1;
    release channel c2;
    release channel c3;
    release channel c4;
    release channel aux1;
    release channel aux2;
    release channel aux3;
    release channel aux4;
}
EOF

nohup rman target sys/oracle@orcl auxiliary sys/oracle@orcldg nocatalog cmdfile=duplicate.rman &
# ASM to ASM with different disk group names
rman <<EOF
connect target sys/<password>@<prim_scan>/srv_rman;
connect auxiliary sys/<password>@dup;
run {
duplicate target database for standby from active database
spfile
parameter_value_convert 'chicago','boston'
set db_file_name_convert '/u01/data/','+DATA'
set db_unique_name='boston'
SET CLUSTER_DATABASE='FALSE'
set db_create_online_log_dest_1='+DATA'
set db_create_file_dest='+DATA'
set db_recovery_file_dest='+RECO'
set log_file_name_convert '/u01/data/','+DATA','/u01/reco/','+RECO'
set control_files='+DATA/boston/standby.ctl'
set local_listener=’boston_local_listener’
set remote_listener=’stby-scan:1521’
set audit_file_dest='/u01/app/oracle/admin/boston/adump'
section size 5g;
}
EOF
手动rman方式
创建standby控制文件
export NLS_DATE_FORMAT='yyyy-mm-dd hh24:MI:SS';

rman target /
run
{
    allocate channel c1 type disk;
    backup as copy current controlfile for standby format '/tmp/standby.ctl';
    release channel c1;
}
传输standby控制文件到备端
scp /tmp/standby.ctl oracle@standby:/tmp/standby.ctl
rman备份主库数据文件和归档文件

可以使用NFS保存备份集

-- # backup as copy database format '/backup/oradata_%u.dbf'; 
# 创建rman脚本
vi backup_level0.sql
connect target /
run {
     allocate channel c1 type disk;
     allocate channel c2 type disk;
     allocate channel c3 type disk;
     allocate channel c4 type disk;
     backup
     incremental level=0
     filesperset 10
     format "/tmp/lev0_%d_%s_%I_%T_%t.bak" database;
     release channel c1;
     release channel c2;
     release channel c3;
     release channel c4;

     allocate channel c1 type disk;
     allocate channel c2 type disk;
     allocate channel c3 type disk;
     sql "alter system archive log thread 1 current";
     backup format '/tmp/arhc_%T_%t_%U' archivelog all delete all input;
     release channel c1;
     release channel c2;
     release channel c3;
}

# 2. 执行命令
EXE_PATH=/home/oracle/scripts
LOG_PATH=${EXEPATH}/logs
SCRIPT_FILE=${EXEPATH}/bakup_level0.sql
LOG_FILE=${LOGPATH}/bklevel0_$(date +%Y%m%d%H%M).log
# execute scripts
${ORACLE_HOME}/bin/rman cmdfile ${SCRIPT_FILE} msglog ${LOG_FILE}
传输备份集到standby端
scp /tmp/*.bak oracle@standby:/tmp/
备库启动到nomount
sqlplus -S "/ as sysdba" <<EOF
startup nomount;
quit;
EOF
还原控制文件

注意:必须先设置主库的dbid

rman target /
set dbid=1494027615
run
{
    restore standby controlfile from '/tmp/standby.ctl';
}
恢复数据
# 1. 启动到mount状态
rman target /
set dbid=1494027615
run
{
    sql 'alter database mount standby database';
}

# 2. 获取构造rename file sql 
select 'set newname for tempfile ' || file# || ' to ''/oradata/' ||
       (select value from v$parameter where name = 'db_unique_name') || '/' ||
       substr(name, instr(name, '/', -1) + 1) || ''';' sql_cmd
  from v$tempfile
union all
select 'set newname for datafile ' || file# || ' to ''/oradata/' ||
       (select value from v$parameter where name = 'db_unique_name') || '/' ||
       substr(name, instr(name, '/', -1) + 1) || ''';' sql_cmd
  from v$datafile;

# 3. 还原数据文件
cat> restore.sql <<EOF
connect target /
set dbid=1494027615
run
{
    allocate channel c1 type disk;
    allocate channel c2 type disk;
    allocate channel c3 type disk;
    allocate channel c4 type disk;
    set newname for tempfile 1 to '/oradata/standby/temp01.bdf';
    switch tempfile all;
    set newname for datafile 1 to '/oradata/standby/system01.dbf';
    set newname for datafile 2 to '/oradata/standby/sysaux01.dbf';
    set newname for datafile 3 to '/oradata/standby/undotbs01.dbf';
    set newname for datafile 4 to '/oradata/standby/users01.dbf';
    restore database;
    alter system archive log current;
    switch datafile all;
    recover database;
    release channel c1;
    release channel c2;
    release channel c3;
    release channel c4;
}
EOF

# 4. 执行命令
EXE_PATH=/home/oracle/scripts
LOG_PATH=${EXEPATH}/logs
SCRIPT_FILE=${EXEPATH}/restore.sql
LOG_FILE=${LOGPATH}/restore_$(date +%Y%m%d%H%M).log
# execute scripts
${ORACLE_HOME}/bin/rman cmdfile ${SCRIPT_FILE} msglog ${LOG_FILE}
开启日志应用
sqlplus -S "/ as sysdba"  <<EOF
alter database open read only;
alter database recover managed standby database using current logfile disconnect from session;
quit;
EOF

disconnect from session: 表示后台运行

后期配置
使用GI管理DB资源(可选)

当备库使用GI的环境中配置

11.2:

srvctl add database -d boston –o /u01/app/oracle/product/11.2.0/db_1 -x exa505 -i boston1

srvctl modify database –d boston –r physical_standby -p '+DATA/boston/spfileboston.ora'

12c :

srvctl add database -db boston -oraclehome /u01/app/oracle/product/12.2.0.1/dbhome_1 -node exa505 -instance boston1

srvctl modify database -db boston -role physical_standby -spfile '+DATA/boston/spfileboston.ora' -pwfile '+DATA/BOSTON/PASSWORD/pwboston'

srvctl add database -d orclstd -n orcl -c RAC -o ${ORACLE_HOME} -p '+DATADG/ORCLSTD/PARAMETERFILE/spfileorcl.ora' -r physical_standby
srvctl add instance -d orclstd -i orcl1 -n snode1
srvctl add instance -d orclstd -i orcl2 -n snode2
UNDOTBS表空间配置

当standby数据库与primary数据库运行的DB实例数量不一致时,需要配置UNDOTBS表空间

-- 在主库添加UNDOTBS2
create undo tablespace undotbs2 datafile '/u01/app/oracle/oradata/orasgl/undotbs02.dbf' size 100m;

-- standby端检查是否同步传输新添加UNDOTBS2
select TABLESPACE_NAME, FILE_NAME from dba_data_files;
当主库是单实例而备库是RAC时配置
-- 将数据库转换为rac模式(单实例->RAC)
alter system set cluster_database=true scope=spfile;
alter system set cluster_database_instances=2 scope=spfile;
alter system set instance_number=1 scope=spfile sid='orcl1';
alter system set instance_number=2 scope=spfile sid='orcl2';
alter system set thread=1 scope=spfile sid='orcl1';
alter system set thread=2 scope=spfile sid='orcl2';
alter system set undo_tablespace=1 scope=spfile sid='orcl1';
alter system set undo_tablespace=2 scope=spfile sid='orcl2';
物理备库配置自动应用日志

创建触发器

create or replace trigger dg_apply_log
after startup on database
begin
declare
database_role varchar(20);
begin
select database_role
into database_role
from v$database;
/* dbms_output.put_line('aa');*/
if database_role = 'PHYSICAL STANDBY'
then
execute immediate 'alter database recover managed standby database using current logfile disconnect from session';
dbms_output.put_line('bb');
else
dbms_output.put_line(database_role);
end if;
end;
end dg_apply_log;
/

检查确认物理备库运行正常

设置redo传输服务后,验证主库传输到备库是否正常

在备用数据库上,查询 V$MANAGED_STANDBY 视图以验证redo正在从主数据库传输并应用于备用数据库。

-- SELECT CLIENT_PROCESS, PROCESS, THREAD#, SEQUENCE#, STATUS FROM 
V$MANAGED_STANDBY;
SELECT CLIENT_PROCESS, PROCESS, THREAD#, SEQUENCE#, STATUS FROM 
V$MANAGED_STANDBY WHERE CLIENT_PROCESS='LGWR' OR PROCESS='MRP0';
 
CLIENT_PROCESS PROCESS   THREAD#    SEQUENCE#  STATUS
-------------- --------- ---------- ---------- ------------
N/A            MRP0      1          80         APPLYING_LOG
LGWR           RFS       1          80         IDLE
  • CLIENT_PROCESS 为 LGWR 表明redo传输正常运行,并且主重做线程正在发送到备用线程
  • 如果 MRP 状态显示为 APPLYING_LOG 并且 SEQUENCE# 等于主数据库当前发送的序列号,则备用数据库已解决所有间隙并且当前处于实时应用模式。

推荐配置

-- standby
alter system set db_block_checksum=FULL scope=both sid='*';
alter system set db_block_checking=FULL scope=both sid='*';
alter system set db_lost_write_protect=TYPICAL scope=both sid='*';

使用DBCA方式创建physical standby database

DBCA 只能用于为非多租户主数据库创建备用数据库。此外,它仅能创建单实例备用数据库

语法

dbca -createDuplicateDB 
    -gdbName global_database_name 
    -primaryDBConnectionString easy_connect_string_to_primary
    -sid database_system_identifier
    [-createAsStandby 
        [-dbUniqueName db_unique_name_for_standby]]
    [-customScripts scripts_list]

示例

dbca –silent -createDuplicateDB -primaryDBConnectionString  progs:1533/primary
-gdbName primary -sid standby -initParams instance_name=standby –createAsStandby

附录

参考文档

[Creating a Physical Standby using RMAN Duplicate (RAC or Non-RAC)](Doc ID 1617946.1)

[Creating a Physical Standby database using RMAN restore from service ](Doc ID 2283978.1)

[How to make log shipping to continue work without copying password file from primary to physical standby when changing sys password on primary?](Doc ID 1416595.1)

Creating a Physical Standby database using RMAN restore from service (Doc ID 2283978.1)

12.2先决条件

异构平台的支持

Data Guard Support for Heterogeneous Primary and Physical Standbys in Same Data Guard Configuration (Doc ID 413484.1)

Data Guard Support for Heterogeneous Primary and Logical Standbys in Same Data Guard Configuration (Doc ID 1085687.1)

脚本

Primary端

cat > ${HOME}/ora_adg_config_primary.sql <<EOF

REM 'oracle adg for primary db'

COLUMN dtime NEW_VALUE _dtime NOPRINT
SELECT TO_CHAR(SYSDATE,'YYYYMMDDhh24miss') dtime FROM dual;
create pfile='/home/oracle/pfile_before_&_dtime.ora' from spfile;

alter system set log_archive_format = '%t_%s_%r.arc' scope=spfile sid='*';

COLUMN db_uname NEW_VALUE _db_uname NOPRINT
COLUMN inst_name NEW_VALUE _inst_name NOPRINT
select value db_uname from v$parameter where name = 'db_unique_name';
select value inst_name from v$parameter where name = 'instance_name';
alter system set log_archive_dest_1 = 'LOCATION=+ARCH VALID_FOR=(ALL_LOGFILES,ALL_ROLES) DB_UNIQUE_NAME=&_db_uname' scope=both sid='*';

host srvctl stop database -d &_db_uname
host srvctl start instance -d &_db_uname -i &_inst_name -o mount

alter database archivelog;
alter database open;

REM 'force logging'
alter database force logging;

set lines 200 pages 100
col name for a16
col platform_name for a18
col db_unique_name for a10
col primary_db_unique_name for a16
select dbid, name, db_unique_name, TO_CHAR(created,'yyyy-mm-dd') created, log_mode, open_mode, protection_mode, database_role, force_logging, platform_id, platform_name, supplemental_log_data_min, primary_db_unique_name from v$database;
alter system set db_unique_name='&_db_uname' scope=spfile sid='*';

REM 'block change tracking'
alter database enable block change tracking using file '+DATADG';

col filename for a80
select * from v$block_change_tracking;

REM 'DG_CONFIG info'
COLUMN sdb_uname NEW_VALUE _sdb_uname NOPRINT
select trim('&_db_uname'||'std') sdb_uname from dual;
alter system set log_archive_config='DG_CONFIG=(&_db_uname,&_sdb_uname)' scope=both sid='*';
col value for a32
select name, value from v$parameter where name in ( 'log_archive_config', 'db_name', 'db_unique_name', 'instance_name' );

REM 'config log_archive_dest_2'
alter system set log_archive_dest_2 = 'SERVICE=&_sdb_uname LGWR ASYNC VALID_FOR=(ONLINE_LOGFILES,PRIMARY_ROLE) DB_UNIQUE_NAME=&_sdb_uname' scope=both sid='*';
alter system set log_archive_dest_state_2='defer' scope=both sid='*';
select name, value from v$parameter where name in ( 'log_archive_dest_2', 'log_archive_dest_state_2' );

REM 'config fal_server and fal_client'
alter system set fal_server='&_sdb_uname' scope=both sid='*';
alter system set fal_client='&_db_uname'  scope=both sid='*';
select name, value from v$parameter where name in ( 'fal_server', 'fal_client' );

REM 'config file_name_conver'
/*
-- COLUMN file_name_value NEW_VALUE _file_name_value
-- COLUMN sfile_name_value NEW_VALUE _sfile_name_value
-- COLUMN logname_value NEW_VALUE _logname_value
-- COLUMN slogname_value NEW_VALUE _slogname_value
-- select trim(dbfilepath||'&_db_uname') file_name_value, trim(dbfilepath||'&_sdb_uname') sfile_name_value from (select distinct(substr(name,1,instr(name,'&_db_uname',1,1)-1)) dbfilepath from v$datafile);
-- select trim(dbfilepath||'&_db_uname') logname_value, trim(dbfilepath||'&_sdb_uname') slogname_value from (select distinct(substr(MEMBER,1,instr(MEMBER,'&_db_uname',1,1)-1)) dbfilepath from v$logfile);
-- alter system set db_file_name_convert='&_file_name_value','&_sfile_name_value' scope=spfile sid='*';
-- alter system set log_file_name_convert='&_logname_value','&_slogname_value' scope=spfile sid='*';
**/

set heading off
spool filename_conver.sql
select 'alter system set db_file_name_convert=' || chr(39) || trim(dbfilepath||'&&_sdb_uname')|| chr(39)||','|| chr(39)|| trim(dbfilepath||'&&_db_uname') ||chr(39) ||' scope=spfile sid='||chr(39) ||'*'';' sql_cmd from (select distinct(substr(name,1,instr(name,'&_db_uname',1,1)-1)) dbfilepath from v$datafile)
union all
select 'alter system set log_file_name_convert=' || chr(39) || trim(dbfilepath||'&&_sdb_uname')|| chr(39)||','|| chr(39)|| trim(dbfilepath||'&&_db_uname') ||chr(39) ||' scope=spfile sid='||chr(39) ||'*'';' sql_cmd from (select distinct(substr(MEMBER,1,instr(MEMBER,'&_db_uname',1,1)-1)) dbfilepath from v$logfile);
spool off
set heading on
@@filename_conver.sql

alter system set standby_file_management='AUTO' scope=spfile sid='*';

REM 'config perf'
select name, value from v$parameter where name in ( 'db_block_checksum', 'db_block_checking' ,'db_lost_write_protect' );
alter system set db_block_checksum=TYPICAL scope=both sid='*';
alter system set db_block_checking=FULL scope=both sid='*';
alter system set db_lost_write_protect=TYPICAL scope=both sid='*';
select name, value from v$parameter where name in ( 'db_block_checksum', 'db_block_checking' ,'db_lost_write_protect' );

SELECT TO_CHAR(SYSDATE,'YYYYMMDDhh24miss') dtime FROM dual;
create pfile='/home/oracle/pfile_end_&_dtime.ora' from spfile;
host scp /home/oracle/pfile_end_&_dtime.ora 192.168.10.182:${HOME}

host export SDB_NAME='orcl'
host [[ -f "${ORACLE_HOME}/dbs/orapw${ORACLE_SID}" ]] && scp ${ORACLE_HOME}/dbs/orapw${ORACLE_SID} 192.168.10.182:${ORACLE_HOME}/dbs/orapw${SDB_NAME}std1

-- 重启DB后检查确认
set lines 200 pages 100
col name for a16
col platform_name for a18
col db_unique_name for a10
col primary_db_unique_name for a16
select dbid, name, db_unique_name, TO_CHAR(created,'yyyy-mm-dd') created, log_mode, open_mode, protection_mode, database_role, force_logging, platform_id, platform_name, supplemental_log_data_min, primary_db_unique_name from v$database;
col name for a32
col value for a100
select name, value from v$parameter where name in ( 'log_archive_config', 'db_name', 'db_unique_name', 'instance_name', 'log_archive_dest_1', 'log_archive_dest_state_1', 'log_archive_dest_2', 'log_archive_dest_state_2', 'fal_server', 'fal_client', 'standby_file_management', 'log_file_name_convert', 'db_file_name_convert', 'log_archive_format', 'db_block_checksum', 'db_block_checking', 'db_lost_write_protect') 
order by 1;

EOF

查看redo log 大小

set lines 200 pages 999
col member for a64
col INSTANCE_NAME for a15
col archived for a12
with redolog as (select inst_id, group#, thread#, sequence#, bytes, blocksize, archived, status, used from gv$standby_log 
union all
select inst_id, group#, thread#, sequence#, bytes, blocksize, archived, status, 0 used from gv$log
 )
SELECT
    i.instance_name
  , i.thread#
  , f.group#
  , sequence#  
  , f.member
  , f.type
  , l.status
  , round(l.bytes/1048576) init_size_mb 
  , round(l.used/1048576)  used_size_mb 
  , l.archived
FROM
    gv$logfile  f
  , redolog     l
  , gv$instance i
WHERE
      f.group#  = l.group#
--  AND l.thread# = i.thread#
  AND i.inst_id = f.inst_id
  AND f.inst_id = l.inst_id
ORDER BY
    i.instance_name
  , f.group#
  , f.member
/

查看当前归档日志序号

select  al.dest_id, al.thread#, al.sequence#, al.first_time, al.name, al.standby_dest
  from v$archived_log al
 where al.sequence# = (select max(sequence#) from v$archived_log);

备库重启自动启动日志应用

CREATE OR REPLACE TRIGGER startDgLogApply after startup on database
-- alter database recover managed standby database using current logfile disconnect from session;
DECLARE
    db_role VARCHAR2(30);
    db_open_mode VARCHAR2(64);
BEGIN
    SELECT DATABASE_ROLE INTO db_role FROM SYS.V$DATABASE;
    IF db_role = 'PHYSICAL STANDBY' THEN
        execute immediate 'alter database recover managed standby database using current logfile disconnect from session';
    END IF;
END;
/

CREATE OR REPLACE TRIGGER stopDgLogApply before shutdown on database
-- alter database recover managed standby database cancel;
DECLARE
    db_role VARCHAR2(30);
    db_open_mode VARCHAR2(64);
BEGIN
    SELECT DATABASE_ROLE, OPEN_MODE INTO db_role, db_open_mode FROM SYS.V$DATABASE;
    IF db_role = 'PHYSICAL STANDBY' and db_open_mode = 'READ ONLY WITH APPLY' THEN
        execute immediate 'alter database recover managed standby database cancel';
    END IF;
END;
/

自定义传输日志的用户,而不使用sys用户

How to make log shipping to continue work without copying password file from primary to physical standby when changing sys password on primary? (Doc ID 1416595.1)

在Oracle Data Guard 11.2 版本中,修改主库的sys密码时,必须手动复制密码文件到备库。否则,主库的alert日志便会抛出ora-16191的告警信息。

当使用密码文件作为redo数据传输会话身份验证方式时,在11.2+版本,新引入REDO_TRANSPORT_USER 初始化参数指定用于redo传输会话的用户名。该用户必须具有sysoper权限,而且在redo传输的两端使用相同的REDO_TRANSPORT_USER指定的用户密码。这样,当修改sys密码时,不再需要复制密码文件到备库。如果位置REDO_TRANSPORT_USER初始化参数,默认使用SYS用户。

GRANT SYSOPER to &USER;
ALTER SYSTEM SET REDO_TRANSPORT_USER = &USER SID='*';

标签:set,log,Standby,数据库,db,standby,Oracle,Physical
来源: https://www.cnblogs.com/binliubiao/p/15142469.html