PostgresSQL配置ssl证书

PostgresSQL服务部署 本文系统介绍了PostgreSQL容器化部署的全流程方案。从基础环境规划、单实例快速配置,到生产级高可用部署、初始化管理,再到与全栈应用的集成实践。重点阐述了数据持久化、性能调优、安全加固等核心环节,提供了DockerCompose配置模板和目录结构规范。同时涵盖了监控运维、备份恢复等生产环境关键要素,并指出云原生演进方向。文中针对常见问题如权限配置、性能调优、网络延迟等给出具体解决方案,形成了一套从开发到生产的完整容器化部署方法论。 阅读详情

添加用户

useradd postgres
passwd postgres

mkdir -p /app/postgresql/{data,log}
chown -R postgres:postgres /app/postgresql

安装依赖包

yum -y install ncurses-devel readline-devel zlib zlib-devel perl-ExtUtils-Embed gcc libicu-devel build-essential libssl-dev

安装

./Anaconda3-2021.11-Linux-x86_64.sh

配置环境变量

su - postgres

export MYSQL_HOME=/app/mysql
export ANACONDA_HOME=/app/anaconda3
export PGHOME=/app/postgresql
export PGUSER=postgres
export PGPORT=5432
export PGDATA=/app/postgresql/data
export PGLOG=/app/postgresql/log/postgresql.log
# PGHOST 需要与unix_socket_directories对应
export PGHOST=/app/postgresql/data/tmp
export PATH=$ANACONDA_HOME/bin:$MYSQL_HOME/bin:$PGHOME/bin:$PATH:$HOME/bin
export LD_LIBRARY_PATH=$ANACONDA_HOME/lib:$MYSQL_HOME/lib:$PGHOME/lib:$LD_LIBRARY_PATH

编译安装

chown -R postgres:postgres /usr/MyWorkSpace/postgresql-15.0
su - postgres
conda init
conda create -n postgres python=3.9
exit 
su - postgres
conda activate postgres

./configure --prefix=/app/postgresql --with-perl --with-openssl --with-python --with-blocksize=32 --with-wal-blocksize=32 --with-segsize=10

make -j8
make install

cd contrib/

make -j8
make install

配置数据库

初始化数据库

su - postgres
# -k是否打开checksums
/app/postgresql/bin/initdb -k -D /app/postgresql/data/
/app/postgresql/bin/pg_resetwal --wal-segsize=64 /app/postgresql/data/

修改配置文件

vi /app/postgresql/data/pg_hba.conf

host    all             all             0.0.0.0/0               md5

vi /app/postgresql/data/postgresql.conf


# -----------------------------
# PostgreSQL configuration file
# -----------------------------
#
# This file consists of lines of the form:
#
#   name = value
#
# (The "=" is optional.)  Whitespace may be used.  Comments are introduced with
# "#" anywhere on a line.  The complete list of parameter names and allowed
# values can be found in the PostgreSQL documentation.
#
# The commented-out settings shown in this file represent the default values.
# Re-commenting a setting is NOT sufficient to revert it to the default value;
# you need to reload the server.
#
# This file is read on server startup and when the server receives a SIGHUP
# signal.  If you edit the file on a running system, you have to SIGHUP the
# server for the changes to take effect, run "pg_ctl reload", or execute
# "SELECT pg_reload_conf()".  Some parameters, which are marked below,
# require a server shutdown and restart to take effect.
#
# Any parameter can also be given as a command-line option to the server, e.g.,
# "postgres -c log_connections=on".  Some parameters can be changed at run time
# with the "SET" SQL command.
#
# Memory units:  B  = bytes            Time units:  us  = microseconds
#                kB = kilobytes                     ms  = milliseconds
#                MB = megabytes                     s   = seconds
#                GB = gigabytes                     min = minutes
#                TB = terabytes                     h   = hours
#                                                   d   = days


#------------------------------------------------------------------------------
# FILE LOCATIONS
#------------------------------------------------------------------------------

# The default values of these variables are driven from the -D command-line
# option or PGDATA environment variable, represented here as ConfigDir.

#data_directory = 'ConfigDir'		# use data in another directory
					# (change requires restart)
#hba_file = 'ConfigDir/pg_hba.conf'	# host-based authentication file
					# (change requires restart)
#ident_file = 'ConfigDir/pg_ident.conf'	# ident configuration file
					# (change requires restart)

# If external_pid_file is not explicitly set, no extra PID file is written.
#external_pid_file = ''			# write an extra PID file
					# (change requires restart)


#------------------------------------------------------------------------------
# CONNECTIONS AND AUTHENTICATION
#------------------------------------------------------------------------------

# - Connection Settings -

listen_addresses = '*'		# what IP address(es) to listen on;
					# comma-separated list of addresses;
					# defaults to 'localhost'; use '*' for all
					# (change requires restart)
port = 5432				# (change requires restart)
max_connections = 1500			# (change requires restart)
superuser_reserved_connections = 13	# (change requires restart)
unix_socket_directories = '/app/postgresql/data/tmp'	# comma-separated list of directories
					# (change requires restart)
#unix_socket_group = ''			# (change requires restart)
#unix_socket_permissions = 0777		# begin with 0 to use octal notation
					# (change requires restart)
#bonjour = off				# advertise server via Bonjour
					# (change requires restart)
#bonjour_name = ''			# defaults to the computer name
					# (change requires restart)

# - TCP settings -
# see "man tcp" for details

#tcp_keepalives_idle = 0		# TCP_KEEPIDLE, in seconds;
					# 0 selects the system default
#tcp_keepalives_interval = 0		# TCP_KEEPINTVL, in seconds;
					# 0 selects the system default
#tcp_keepalives_count = 0		# TCP_KEEPCNT;
					# 0 selects the system default
#tcp_user_timeout = 0			# TCP_USER_TIMEOUT, in milliseconds;
					# 0 selects the system default

#client_connection_check_interval = 0	# time between checks for client
					# disconnection while running queries;
					# 0 for never

# - Authentication -

#authentication_timeout = 1min		# 1s-600s
#password_encryption = scram-sha-256	# scram-sha-256 or md5
#db_user_namespace = off

# GSSAPI using Kerberos
#krb_server_keyfile = 'FILE:${sysconfdir}/krb5.keytab'
#krb_caseins_users = off

# - SSL -

#ssl = off
#ssl_ca_file = ''
#ssl_cert_file = 'server.crt'
#ssl_crl_file = ''
#ssl_crl_dir = ''
#ssl_key_file = 'server.key'
#ssl_ciphers = 'HIGH:MEDIUM:+3DES:!aNULL' # allowed SSL ciphers
#ssl_prefer_server_ciphers = on
#ssl_ecdh_curve = 'prime256v1'
#ssl_min_protocol_version = 'TLSv1.2'
#ssl_max_protocol_version = ''
#ssl_dh_params_file = ''
#ssl_passphrase_command = ''
#ssl_passphrase_command_supports_reload = off


#------------------------------------------------------------------------------
# RESOURCE USAGE (except WAL)
#------------------------------------------------------------------------------

# - Memory -

shared_buffers = 10GB			# min 128kB
					# (change requires restart)
huge_pages = try			# on, off, or try
					# (change requires restart)
#huge_page_size = 0			# zero for system default
					# (change requires restart)
#temp_buffers = 8MB			# min 800kB
#max_prepared_transactions = 0		# zero disables the feature
					# (change requires restart)
# Caution: it is not advisable to set max_prepared_transactions nonzero unless
# you actively intend to use prepared transactions.
work_mem = 8MB				# min 64kB
#hash_mem_multiplier = 2.0		# 1-1000.0 multiplier on hash table work_mem
maintenance_work_mem = 1GB		# min 1MB
#autovacuum_work_mem = -1		# min 1MB, or -1 to use maintenance_work_mem
#logical_decoding_work_mem = 64MB	# min 64kB
max_stack_depth = 4MB			# min 100kB
#shared_memory_type = mmap		# the default is the first option
					# supported by the operating system:
					#   mmap
					#   sysv
					#   windows
					# (change requires restart)
dynamic_shared_memory_type = posix	# the default is usually the first option
					# supported by the operating system:
					#   posix
					#   sysv
					#   windows
					#   mmap
					# (change requires restart)
#min_dynamic_shared_memory = 0MB	# (change requires restart)

# - Disk -

#temp_file_limit = -1			# limits per-process temp file space
					# in kilobytes, or -1 for no limit

# - Kernel Resources -

#max_files_per_process = 1000		# min 64
					# (change requires restart)

# - Cost-Based Vacuum Delay -

#vacuum_cost_delay = 0			# 0-100 milliseconds (0 disables)
#vacuum_cost_page_hit = 1		# 0-10000 credits
#vacuum_cost_page_miss = 2		# 0-10000 credits
#vacuum_cost_page_dirty = 20		# 0-10000 credits
vacuum_cost_limit = 500		# 1-10000 credits

# - Background Writer -

#bgwriter_delay = 200ms			# 10-10000ms between rounds
#bgwriter_lru_maxpages = 100		# max buffers written/round, 0 disables
#bgwriter_lru_multiplier = 2.0		# 0-10.0 multiplier on buffers scanned/round
#bgwriter_flush_after = 512kB		# measured in pages, 0 disables

# - Asynchronous Behavior -

#backend_flush_after = 0		# measured in pages, 0 disables
#effective_io_concurrency = 1		# 1-1000; 0 disables prefetching
#maintenance_io_concurrency = 10	# 1-1000; 0 disables prefetching
max_worker_processes = 128		# (change requires restart)
max_parallel_workers_per_gather = 10	# taken from max_parallel_workers
#max_parallel_maintenance_workers = 2	# taken from max_parallel_workers
#max_parallel_workers = 8		# maximum number of max_worker_processes that
					# can be used in parallel operations
#parallel_leader_participation = on
#old_snapshot_threshold = -1		# 1min-60d; -1 disables; 0 is immediate
					# (change requires restart)


#------------------------------------------------------------------------------
# WRITE-AHEAD LOG
#------------------------------------------------------------------------------

# - Settings -

wal_level = replica			# minimal, replica, or logical
					# (change requires restart)
#fsync = on				# flush data to disk for crash safety
					# (turning this off can cause
					# unrecoverable data corruption)
# synchronous_commit = on		# synchronization level;
					# off, local, remote_write, remote_apply, or on
#wal_sync_method = fsync		# the default is the first option
					# supported by the operating system:
					#   open_datasync
					#   fdatasync (default on Linux and FreeBSD)
					#   fsync
					#   fsync_writethrough
					#   open_sync
full_page_writes = on			# recover from partial page writes
#wal_log_hints = on			# also do full page writes of non-critical updates
					# (change requires restart)
#wal_compression = off			# enables compression of full-page writes;
					# off, pglz, lz4, zstd, or on
#wal_init_zero = on			# zero-fill new WAL files
#wal_recycle = on			# recycle WAL files
wal_buffers = -1			# min 32kB, -1 sets based on shared_buffers
					# (change requires restart)
#wal_writer_delay = 200ms		# 1-10000 milliseconds
#wal_writer_flush_after = 1MB		# measured in pages, 0 disables
#wal_skip_threshold = 2MB

#commit_delay = 0			# range 0-100000, in microseconds
#commit_siblings = 5			# range 1-1000

# - Checkpoints -

checkpoint_timeout = 10min		# range 30s-1d
#checkpoint_completion_target = 0.9	# checkpoint target duration, 0.0 - 1.0
#checkpoint_flush_after = 256kB		# measured in pages, 0 disables
#checkpoint_warning = 30s		# 0 disables
max_wal_size = 10GB
min_wal_size = 2GB

# - Prefetching during recovery -

#recovery_prefetch = try		# prefetch pages referenced in the WAL?
#wal_decode_buffer_size = 512kB		# lookahead window used for prefetching
					# (change requires restart)

# - Archiving -

archive_mode = on		# enables archiving; off, on, or always
				# (change requires restart)
#archive_library = ''		# library to use to archive a logfile segment
				# (empty string indicates archive_command should
				# be used)
archive_command = 'test ! -f /app/postgresql/arch/%f && cp %p /app/postgresql/arch/%f'		# command to use to archive a logfile segment
				# placeholders: %p = path of file to archive
				#               %f = file name only
				# e.g. 'test ! -f /mnt/server/archivedir/%f && cp %p /mnt/server/archivedir/%f'
archive_timeout = 600		# force a logfile segment switch after this
				# number of seconds; 0 disables

# - Archive Recovery -

# These are only used in recovery mode.

#restore_command = ''		# command to use to restore an archived logfile segment
				# placeholders: %p = path of file to restore
				#               %f = file name only
				# e.g. 'cp /mnt/server/archivedir/%f %p'
#archive_cleanup_command = ''	# command to execute at every restartpoint
#recovery_end_command = ''	# command to execute at completion of recovery

# - Recovery Target -

# Set these only when performing a targeted recovery.

#recovery_target = ''		# 'immediate' to end recovery as soon as a
                                # consistent state is reached
				# (change requires restart)
#recovery_target_name = ''	# the named restore point to which recovery will proceed
				# (change requires restart)
#recovery_target_time = ''	# the time stamp up to which recovery will proceed
				# (change requires restart)
#recovery_target_xid = ''	# the transaction ID up to which recovery will proceed
				# (change requires restart)
#recovery_target_lsn = ''	# the WAL LSN up to which recovery will proceed
				# (change requires restart)
#recovery_target_inclusive = on # Specifies whether to stop:
				# just after the specified recovery target (on)
				# just before the recovery target (off)
				# (change requires restart)
#recovery_target_timeline = 'latest'	# 'current', 'latest', or timeline ID
				# (change requires restart)
#recovery_target_action = 'pause'	# 'pause', 'promote', 'shutdown'
				# (change requires restart)


#------------------------------------------------------------------------------
# REPLICATION
#------------------------------------------------------------------------------

# - Sending Servers -

# Set these on the primary and on any standby that will send replication data.

# max_wal_senders = 10		# max number of walsender processes
				# (change requires restart)
#max_replication_slots = 10	# max number of replication slots
				# (change requires restart)
#wal_keep_size = 0		# in megabytes; 0 disables
#max_slot_wal_keep_size = -1	# in megabytes; -1 disables
#wal_sender_timeout = 60s	# in milliseconds; 0 disables
#track_commit_timestamp = off	# collect timestamp of transaction commit
				# (change requires restart)

# - Primary Server -

# These settings are ignored on a standby server.

# synchronous_standby_names = 'ANY 1 (postgresql2)'	# standby servers that provide sync rep
				# method to choose sync standbys, number of sync standbys,
				# and comma-separated list of application_name
				# from standby(s); '*' = all
#vacuum_defer_cleanup_age = 0	# number of xacts by which cleanup is delayed

# - Standby Servers -

# These settings are ignored on a primary server.

#primary_conninfo = ''			# connection string to sending server
#primary_slot_name = ''			# replication slot on sending server
#promote_trigger_file = ''		# file name whose presence ends recovery
# hot_standby = on			# "off" disallows queries during recovery
					# (change requires restart)
#max_standby_archive_delay = 30s	# max delay before canceling queries
					# when reading WAL from archive;
					# -1 allows indefinite delay
#max_standby_streaming_delay = 30s	# max delay before canceling queries
					# when reading streaming WAL;
					# -1 allows indefinite delay
#wal_receiver_create_temp_slot = off	# create temp slot if primary_slot_name
					# is not set
#wal_receiver_status_interval = 10s	# send replies at least this often
					# 0 disables
#hot_standby_feedback = true		# send info from standby to prevent
					# query conflicts
#wal_receiver_timeout = 60s		# time that receiver waits for
					# communication from primary
					# in milliseconds; 0 disables
#wal_retrieve_retry_interval = 5s	# time to wait before retrying to
					# retrieve WAL after a failed attempt
#recovery_min_apply_delay = 0		# minimum delay for applying changes during recovery

# - Subscribers -

# These settings are ignored on a publisher.

#max_logical_replication_workers = 4	# taken from max_worker_processes
					# (change requires restart)
#max_sync_workers_per_subscription = 2	# taken from max_logical_replication_workers


#------------------------------------------------------------------------------
# QUERY TUNING
#------------------------------------------------------------------------------

# - Planner Method Configuration -

#enable_async_append = on
#enable_bitmapscan = on
#enable_gathermerge = on
#enable_hashagg = on
#enable_hashjoin = on
#enable_incremental_sort = on
#enable_indexscan = on
#enable_indexonlyscan = on
#enable_material = on
#enable_memoize = on
#enable_mergejoin = on
#enable_nestloop = on
#enable_parallel_append = on
#enable_parallel_hash = on
#enable_partition_pruning = on
#enable_partitionwise_join = off
#enable_partitionwise_aggregate = off
#enable_seqscan = on
#enable_sort = on
#enable_tidscan = on

# - Planner Cost Constants -

#seq_page_cost = 1.0			# measured on an arbitrary scale
#random_page_cost = 4.0			# same scale as above
#cpu_tuple_cost = 0.01			# same scale as above
#cpu_index_tuple_cost = 0.005		# same scale as above
#cpu_operator_cost = 0.0025		# same scale as above
#parallel_setup_cost = 1000.0	# same scale as above
#parallel_tuple_cost = 0.1		# same scale as above
#min_parallel_table_scan_size = 8MB
#min_parallel_index_scan_size = 512kB
effective_cache_size = 10GB

#jit_above_cost = 100000		# perform JIT compilation if available
					# and query more expensive than this;
					# -1 disables
#jit_inline_above_cost = 500000		# inline small functions if query is
					# more expensive than this; -1 disables
#jit_optimize_above_cost = 500000	# use expensive JIT optimizations if
					# query is more expensive than this;
					# -1 disables

# - Genetic Query Optimizer -

#geqo = on
#geqo_threshold = 12
#geqo_effort = 5			# range 1-10
#geqo_pool_size = 0			# selects default based on effort
#geqo_generations = 0			# selects default based on effort
#geqo_selection_bias = 2.0		# range 1.5-2.0
#geqo_seed = 0.0			# range 0.0-1.0

# - Other Planner Options -

#default_statistics_target = 100	# range 1-10000
#constraint_exclusion = partition	# on, off, or partition
#cursor_tuple_fraction = 0.1		# range 0.0-1.0
#from_collapse_limit = 8
#jit = on				# allow JIT compilation
#join_collapse_limit = 8		# 1 disables collapsing of explicit
					# JOIN clauses
#plan_cache_mode = auto			# auto, force_generic_plan or
					# force_custom_plan
#recursive_worktable_factor = 10.0	# range 0.001-1000000


#------------------------------------------------------------------------------
# REPORTING AND LOGGING
#------------------------------------------------------------------------------

# - Where to Log -

#log_destination = 'stderr'		# Valid values are combinations of
					# stderr, csvlog, jsonlog, syslog, and
					# eventlog, depending on platform.
					# csvlog and jsonlog require
					# logging_collector to be on.

# This is used when logging to stderr:
#logging_collector = off		# Enable capturing of stderr, jsonlog,
					# and csvlog into log files. Required
					# to be on for csvlogs and jsonlogs.
					# (change requires restart)

# These are only used if logging_collector is on:
#log_directory = 'log'			# directory where log files are written,
					# can be absolute or relative to PGDATA
#log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log'	# log file name pattern,
					# can include strftime() escapes
#log_file_mode = 0600			# creation mode for log files,
					# begin with 0 to use octal notation
#log_rotation_age = 1d			# Automatic rotation of logfiles will
					# happen after that time.  0 disables.
#log_rotation_size = 10MB		# Automatic rotation of logfiles will
					# happen after that much log output.
					# 0 disables.
log_truncate_on_rotation = on		# If on, an existing log file with the
					# same name as the new log file will be
					# truncated rather than appended to.
					# But such truncation only occurs on
					# time-driven rotation, not on restarts
					# or size-driven rotation.  Default is
					# off, meaning append to existing files
					# in all cases.

# These are relevant when logging to syslog:
#syslog_facility = 'LOCAL0'
#syslog_ident = 'postgres'
#syslog_sequence_numbers = on
#syslog_split_messages = on

# This is only relevant when logging to eventlog (Windows):
# (change requires restart)
#event_source = 'PostgreSQL'

# - When to Log -

#log_min_messages = warning		# values in order of decreasing detail:
					#   debug5
					#   debug4
					#   debug3
					#   debug2
					#   debug1
					#   info
					#   notice
					#   warning
					#   error
					#   log
					#   fatal
					#   panic

#log_min_error_statement = error	# values in order of decreasing detail:
					#   debug5
					#   debug4
					#   debug3
					#   debug2
					#   debug1
					#   info
					#   notice
					#   warning
					#   error
					#   log
					#   fatal
					#   panic (effectively off)

#log_min_duration_statement = -1	# -1 is disabled, 0 logs all statements
					# and their durations, > 0 logs only
					# statements running at least this number
					# of milliseconds

#log_min_duration_sample = -1		# -1 is disabled, 0 logs a sample of statements
					# and their durations, > 0 logs only a sample of
					# statements running at least this number
					# of milliseconds;
					# sample fraction is determined by log_statement_sample_rate

#log_statement_sample_rate = 1.0	# fraction of logged statements exceeding
					# log_min_duration_sample to be logged;
					# 1.0 logs all such statements, 0.0 never logs


#log_transaction_sample_rate = 0.0	# fraction of transactions whose statements
					# are logged regardless of their duration; 1.0 logs all
					# statements from all transactions, 0.0 never logs

#log_startup_progress_interval = 10s	# Time between progress updates for
					# long-running startup operations.
					# 0 disables the feature, > 0 indicates
					# the interval in milliseconds.

# - What to Log -

#debug_print_parse = off
#debug_print_rewritten = off
#debug_print_plan = off
#debug_pretty_print = on
#log_autovacuum_min_duration = 10min	# log autovacuum activity;
					# -1 disables, 0 logs all actions and
					# their durations, > 0 logs only
					# actions running at least this number
					# of milliseconds.
#log_checkpoints = on
#log_connections = off
#log_disconnections = off
#log_duration = off
#log_error_verbosity = default		# terse, default, or verbose messages
#log_hostname = off
#log_line_prefix = '%m [%p] '		# special values:
					#   %a = application name
					#   %u = user name
					#   %d = database name
					#   %r = remote host and port
					#   %h = remote host
					#   %b = backend type
					#   %p = process ID
					#   %P = process ID of parallel group leader
					#   %t = timestamp without milliseconds
					#   %m = timestamp with milliseconds
					#   %n = timestamp with milliseconds (as a Unix epoch)
					#   %Q = query ID (0 if none or not computed)
					#   %i = command tag
					#   %e = SQL state
					#   %c = session ID
					#   %l = session line number
					#   %s = session start timestamp
					#   %v = virtual transaction ID
					#   %x = transaction ID (0 if none)
					#   %q = stop here in non-session
					#        processes
					#   %% = '%'
					# e.g. '<%u%%%d> '
#log_lock_waits = off			# log lock waits >= deadlock_timeout
#log_recovery_conflict_waits = off	# log standby recovery conflict waits
					# >= deadlock_timeout
#log_parameter_max_length = -1		# when logging statements, limit logged
					# bind-parameter values to N bytes;
					# -1 means print in full, 0 disables
#log_parameter_max_length_on_error = 0	# when logging an error, limit logged
					# bind-parameter values to N bytes;
					# -1 means print in full, 0 disables
#log_statement = 'none'			# none, ddl, mod, all
#log_replication_commands = off
#log_temp_files = -1			# log temporary files equal or larger
					# than the specified size in kilobytes;
					# -1 disables, 0 logs all temp files
log_timezone = 'Asia/Shanghai'


#------------------------------------------------------------------------------
# PROCESS TITLE
#------------------------------------------------------------------------------

#cluster_name = ''			# added to process titles if nonempty
					# (change requires restart)
#update_process_title = on


#------------------------------------------------------------------------------
# STATISTICS
#------------------------------------------------------------------------------

# - Cumulative Query and Index Statistics -

#track_activities = on
#track_activity_query_size = 1024	# (change requires restart)
#track_counts = on
#track_io_timing = off
#track_wal_io_timing = off
#track_functions = none			# none, pl, all
#stats_fetch_consistency = cache


# - Monitoring -

#compute_query_id = auto
#log_statement_stats = off
#log_parser_stats = off
#log_planner_stats = off
#log_executor_stats = off


#------------------------------------------------------------------------------
# AUTOVACUUM
#------------------------------------------------------------------------------

#autovacuum = on			# Enable autovacuum subprocess?  'on'
					# requires track_counts to also be on.
#autovacuum_max_workers = 3		# max number of autovacuum subprocesses
					# (change requires restart)
#autovacuum_naptime = 1min		# time between autovacuum runs
#autovacuum_vacuum_threshold = 50	# min number of row updates before
					# vacuum
#autovacuum_vacuum_insert_threshold = 1000	# min number of row inserts
					# before vacuum; -1 disables insert
					# vacuums
#autovacuum_analyze_threshold = 50	# min number of row updates before
					# analyze
#autovacuum_vacuum_scale_factor = 0.2	# fraction of table size before vacuum
#autovacuum_vacuum_insert_scale_factor = 0.2	# fraction of inserts over table
					# size before insert vacuum
#autovacuum_analyze_scale_factor = 0.1	# fraction of table size before analyze
#autovacuum_freeze_max_age = 200000000	# maximum XID age before forced vacuum
					# (change requires restart)
#autovacuum_multixact_freeze_max_age = 400000000	# maximum multixact age
					# before forced vacuum
					# (change requires restart)
#autovacuum_vacuum_cost_delay = 2ms	# default vacuum cost delay for
					# autovacuum, in milliseconds;
					# -1 means use vacuum_cost_delay
#autovacuum_vacuum_cost_limit = -1	# default vacuum cost limit for
					# autovacuum, -1 means use
					# vacuum_cost_limit


#------------------------------------------------------------------------------
# CLIENT CONNECTION DEFAULTS
#------------------------------------------------------------------------------

# - Statement Behavior -

#client_min_messages = notice		# values in order of decreasing detail:
					#   debug5
					#   debug4
					#   debug3
					#   debug2
					#   debug1
					#   log
					#   notice
					#   warning
					#   error
#search_path = '"$user", public'	# schema names
#row_security = on
#default_table_access_method = 'heap'
#default_tablespace = ''		# a tablespace name, '' uses the default
#default_toast_compression = 'pglz'	# 'pglz' or 'lz4'
#temp_tablespaces = ''			# a list of tablespace names, '' uses
					# only default tablespace
#check_function_bodies = on
#default_transaction_isolation = 'read committed'
#default_transaction_read_only = off
#default_transaction_deferrable = off
#session_replication_role = 'origin'
#statement_timeout = 0			# in milliseconds, 0 is disabled
#lock_timeout = 0			# in milliseconds, 0 is disabled
#idle_in_transaction_session_timeout = 0	# in milliseconds, 0 is disabled
#idle_session_timeout = 0		# in milliseconds, 0 is disabled
#vacuum_freeze_table_age = 150000000
#vacuum_freeze_min_age = 50000000
#vacuum_failsafe_age = 1600000000
#vacuum_multixact_freeze_table_age = 150000000
#vacuum_multixact_freeze_min_age = 5000000
#vacuum_multixact_failsafe_age = 1600000000
#bytea_output = 'hex'			# hex, escape
#xmlbinary = 'base64'
#xmloption = 'content'
#gin_pending_list_limit = 4MB

# - Locale and Formatting -

datestyle = 'iso, mdy'
#intervalstyle = 'postgres'
timezone = 'Asia/Shanghai'
#timezone_abbreviations = 'Default'     # Select the set of available time zone
					# abbreviations.  Currently, there are
					#   Default
					#   Australia (historical usage)
					#   India
					# You can create your own file in
					# share/timezonesets/.
#extra_float_digits = 1			# min -15, max 3; any value >0 actually
					# selects precise output mode
#client_encoding = sql_ascii		# actually, defaults to database
					# encoding

# These settings are initialized by initdb, but they can be changed.
lc_messages = 'en_US.UTF-8'			# locale for system error message
					# strings
lc_monetary = 'en_US.UTF-8'			# locale for monetary formatting
lc_numeric = 'en_US.UTF-8'			# locale for number formatting
lc_time = 'en_US.UTF-8'				# locale for time formatting

# default configuration for text search
default_text_search_config = 'pg_catalog.english'

# - Shared Library Preloading -

#local_preload_libraries = ''
#session_preload_libraries = ''
shared_preload_libraries = 'pg_stat_statements'	# (change requires restart)
#jit_provider = 'llvmjit'		# JIT library to use

# - Other Defaults -

#dynamic_library_path = '$libdir'
#gin_fuzzy_search_limit = 0


#------------------------------------------------------------------------------
# LOCK MANAGEMENT
#------------------------------------------------------------------------------

#deadlock_timeout = 1s
#max_locks_per_transaction = 64		# min 10
					# (change requires restart)
#max_pred_locks_per_transaction = 64	# min 10
					# (change requires restart)
#max_pred_locks_per_relation = -2	# negative values mean
					# (max_pred_locks_per_transaction
					#  / -max_pred_locks_per_relation) - 1
#max_pred_locks_per_page = 2            # min 0


#------------------------------------------------------------------------------
# VERSION AND PLATFORM COMPATIBILITY
#------------------------------------------------------------------------------

# - Previous PostgreSQL Versions -

#array_nulls = on
#backslash_quote = safe_encoding	# on, off, or safe_encoding
#escape_string_warning = on
#lo_compat_privileges = off
#quote_all_identifiers = off
#standard_conforming_strings = on
#synchronize_seqscans = on

# - Other Platforms and Clients -

#transform_null_equals = off


#------------------------------------------------------------------------------
# ERROR HANDLING
#------------------------------------------------------------------------------

#exit_on_error = off			# terminate session on any error?
#restart_after_crash = on		# reinitialize after backend crash?
#data_sync_retry = off			# retry or panic on failure to fsync
					# data?
					# (change requires restart)
#recovery_init_sync_method = fsync	# fsync, syncfs (Linux 5.8+)


#------------------------------------------------------------------------------
# CONFIG FILE INCLUDES
#------------------------------------------------------------------------------

# These options allow settings to be loaded from files other than the
# default postgresql.conf.  Note that these are directives, not variable
# assignments, so they can usefully be given more than once.

#include_dir = '...'			# include files ending in '.conf' from
					# a directory, e.g., 'conf.d'
#include_if_exists = '...'		# include file only if it exists
#include = '...'			# include file


#------------------------------------------------------------------------------
# CUSTOMIZED OPTIONS
#------------------------------------------------------------------------------

# Add settings for extensions here

启动数据库

su - postgres
mkdir -p /app/postgresql/data/tmp/
/app/postgresql/bin/pg_ctl -D /app/postgresql/data -l /app/postgresql/log/logfile start

重新加载配置文件

/app/postgresql/bin/pg_ctl -D /app/postgresql/data -l /app/postgresql/log/logfile reload

基本数据库设置

# 修改默认
ALTER USER postgres WITH PASSWORD 'postgres';
ALTER USER postgres WITH PASSWORD 'Postgres#12345';
create user sonar with password 'sonar';

基本调优参数

listen_addresses = '*'
port = 5432
unix_socket_directories = '/app/postgresql/data/tmp'	# 客户端连接PGSQL的文件地址
max_connections = 1500 # 系统允许的最大连接数,上限跟服务器配置相关
shared_buffers = 10GB # PostgreSQL缓存(数据库缓冲区),建议内存的1/4,不超过内存的1/2
huge_pages = try # 应用大页,建议shared_buffers超过32GB时开启
wal_buffers = -1
full_page_writes = on
maintenance_work_mem = 1GB # 维护时可以使用的内存大小,这里定义的内存是被VACUUM等消耗资源较多的命令调用时应用,把该值调大,能放慢命令的执行,建议大于256MB
superuser_reserved_connections = 13 # 为超级用户保留的连接数
work_mem = 8MB # 设置在写入临时磁盘文件之前查询操作(例如排序或哈希表)可使用的最大内存容量。如果指定值时没有单位,则以KB为单位。默认是4MB
effective_cache_size = 10GB # 可用OS的缓存大小,缓存值1/3~1/2
max_stack_depth = 4MB # 进程STACK所占的空间的最大值,复杂操作建议配置8MB 
vacuum_cost_limit = 500 # 清理delete后的空间,此时对io影响较大,增加该值可以缩小对性能的影响
max_worker_processes = 128 # 最大并发过程数,parallel worker等都是worker process,该值需要设置的足够大
max_parallel_workers_per_gather = 10 # 每个执行节点的最大并行处理过程数,应用并行查询时设置该值大于1,不建议超过主机cores-2
max_parallel_workers = 8 # 并行查询时,最大线程数
max_wal_size = 10G  # 该值越小,wal日志写入量越大,wal日志恢复时间越长
min_wal_size = 2G # 建议值shared_buffers/2
checkpoint_timeout = 10min # checkpoint超时,wal查看写入磁盘时间,视情况可以加大。
log_truncate_on_rotation = on # 文本日志收集

pgsql启动ssl验证

  1. 生成自签名证书

    创建 CA 证书
    首先,您需要创建一个 CA(Certificate Authority)证书,用于签署服务器和客户端证书。

     bash
     复制代码
     # 生成 CA 私钥
     openssl genpkey -algorithm RSA -out ca.key
     
     # 生成 CA 证书
     openssl req -new -x509 -days 3650 -key ca.key -out ca.crt -subj "/CN=PostgreSQLCA"
    

    创建服务器证书
    使用 CA 证书签署服务器证书。

     bash
     复制代码
     # 生成服务器私钥
     openssl genpkey -algorithm RSA -out server.key
     
     # 生成服务器证书请求
     openssl req -new -key server.key -out server.csr -subj "/CN=your_server_hostname"
     
     # 使用 CA 证书签署服务器证书
     openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 365
    

    创建客户端证书
    类似地,创建一个客户端证书。

     bash
     复制代码
     # 生成客户端私钥
     openssl genpkey -algorithm RSA -out client.key
     
     # 生成客户端证书请求
     openssl req -new -key client.key -out client.csr -subj "/CN=jdbcclient"
    
     # 使用 CA 证书签署客户端证书
     openssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client.crt -days 365
    
     # 生成DH参数文件
     openssl dhparam -out dhparams.pem 2048
    
  2. 配置 PostgreSQL

    将生成的服务器证书和私钥复制到 PostgreSQL 的数据目录,并设置适当的权限。可以放在任意目录然后配置中写绝对路径

     bash
     复制代码
     # 假设 PostgreSQL 数据目录为 /var/lib/postgresql/data
     sudo cp server.crt /var/lib/postgresql/data/
     sudo cp server.key /var/lib/postgresql/data/
     sudo cp ca.crt /var/lib/postgresql/data/
     
     # 设置文件权限
     sudo chown postgres:postgres /var/lib/postgresql/data/server.crt /var/lib/postgresql/data/server.key /var/lib/postgresql/data/ca.crt
     sudo chmod 600 /var/lib/postgresql/data/server.key
     sudo chmod 644 /var/lib/postgresql/data/server.crt /var/lib/postgresql/data/ca.crt
     编辑 PostgreSQL 配置文件 postgresql.conf 以启用 SSL。
     
     bash
     复制代码
     # 打开 postgresql.conf 文件
     sudo nano /var/lib/postgresql/data/postgresql.conf
    
     
     # 添加或修改以下行
     ssl = on
     ssl_ca_file = '/app/postgresql/cert/ca.crt'
     ssl_cert_file = '/app/postgresql/cert/server.crt'
     ssl_key_file = '/app/postgresql/cert/server.key'
     ssl_ciphers = 'HIGH:MEDIUM:+3DES:!aNULL'
     ssl_prefer_server_ciphers = on
     ssl_ecdh_curve = 'prime256v1'
     ssl_min_protocol_version = 'TLSv1.2'
     ssl_max_protocol_version = ''
     ssl_dh_params_file = '/app/postgresql/cert/dhparams.pem'
    
  3. 重启 PostgreSQL

    应用配置更改需要重启 PostgreSQL 服务。

     bash
     复制代码
     sudo systemctl restart postgresql
    
  4. 配置客户端

    确保客户端连接使用 SSL。在客户端配置文件(例如 pg_hba.conf)中,添加一条条目以要求使用 SSL。

     bash
     复制代码
     # 打开 pg_hba.conf 文件
     sudo nano /var/lib/postgresql/data/pg_hba.conf
     
     # 添加或修改以下行
     hostssl    all             all             0.0.0.0/0               md5
    
  5. 验证是否配置成功

     psql "host=your_server_hostname dbname=your_db_name user=your_username sslmode=verify-full sslrootcert=/path/to/certificates/ca.crt sslcert=/path/to/certificates/client.crt sslkey=/path/to/certificates/client.key"
    
  6. 自动刷新证书脚本

     #!/bin/bash
     
     # 定义证书目录和文件名
     CERT_DIR="/path/to/certificates"
     CA_KEY="$CERT_DIR/ca.key"
     CA_CERT="$CERT_DIR/ca.crt"
     SERVER_KEY="$CERT_DIR/server.key"
     SERVER_CSR="$CERT_DIR/server.csr"
     SERVER_CERT="$CERT_DIR/server.crt"
     DAYS=365
     
     # 生成新的 CA 证书(如果需要)
     # openssl req -new -x509 -days $DAYS -keyout $CA_KEY -out $CA_CERT -subj "/CN=MyCA"
     
     # 生成新的服务器私钥
     openssl genpkey -algorithm RSA -out $SERVER_KEY
     
     # 生成新的服务器证书请求
     openssl req -new -key $SERVER_KEY -out $SERVER_CSR -subj "/CN=your_server_hostname"
     
     # 使用 CA 证书签署新的服务器证书
     openssl x509 -req -in $SERVER_CSR -CA $CA_CERT -CAkey $CA_KEY -CAcreateserial -out $SERVER_CERT -days $DAYS
     
     # 设置证书文件权限
     chown postgres:postgres $SERVER_KEY $SERVER_CERT
     chmod 600 $SERVER_KEY
     chmod 644 $SERVER_CERT
     
     # 重新加载 PostgreSQL 配置
     sudo systemctl reload postgresql
     
     # 可选:如果需要重启 PostgreSQL,可以使用下面的命令
     # sudo systemctl restart postgresql
    
等保: Postgresql配置ssl链接 等保: postgresql配置ssl链接完整方案和避坑指南 阅读详情

相关推荐

Postgres 源码编译安装

基于 WSL 安装的 Debian 操作系统 源码编译安装 Postgres

weixin_42176639的博客 2563

postgresql配置ssl

官网 参考 openssl创建证书 PostgreSQL支持使用SSL连接加密客户端/服务器通信,以提高安全性。这要求在客户端和服务器系统上都安装OpenSSL,并且在构建时启用PostgreSQL中的ssl支持(使用源码安装时的--with-openssl参数)。 服务端侧 首先为了使ssl工作起来,服务端首先需要配置三个参数: ssl = on ssl_cert_file = ...

深海微澜 7060

LINUX7 安装PG15所需依赖包,libzstd-1.5.2

yum install -y postgresql15-server --> Finished Dependency Resolution Error: Package: postgresql15-15.0-1PGDG.rhel7.x86_64 (pgdg15) Requires: libzstd >= 1.4.0 Error: Package: postgresql15-server-15.0-1PGDG.rhel7.x86_64

PostgreSQL安装和开启SSL加密连接【配置单/双向认证】

服务端按需求配置postgres.conf、pg_hba.conf两个配置文件,并放入相关证书文件,客户端对应配置即可打开SSL单/双向认证连接

schwein_van的博客 1万+

AI Agent在保险行业落地:从智能客服到核保理赔的实践路径

AI Agent作为大模型技术的核心应用形态,正从通用对话走向垂直行业深度落地。其本质是让机器理解自然语言、处理非结构化文档,并在复杂业务流程中辅助人类完成信息抽取、内容生成与多轮交互。在保险这一强监管、高客单价的行业中,智能客服与销售助手率先验证了降本增效的价值,核保与理赔环节则进一步展示了AI在文档理解与风控辅助上的高价值潜力。从技术原理到商业闭环,垂直场景正在成为AI应用的主战场。本文以保险行业为样本,剖析AI Agent如何嵌入真实业务流程,梳理可复用的三阶段落地路径,为企业在医疗、金融等类似高文本

weixin_29039773的博客 370

【RF】Receiver Function接收函数:从理论到实践的深度解析

本文深入解析地震学中的接收函数(Receiver Function, RF)技术,从理论原理到实践操作。文章将RF比作地球的“听诊器”,详细阐述了其通过反褶积剥离震源影响、揭示地下结构(如莫霍面)的核心机制,并提供了使用Python和rf库进行数据处理、计算、动校正与叠加的完整实战流程,同时探讨了其应用、局限性与常见问题的解决方案。

Jerry的专栏 127

Obsidian Local REST API安全配置实战手册:5步构建企业级保护方案

Obsidian Local REST API是一款为你的笔记库提供安全REST API和MCP服务器功能的插件,通过HTTPS加密传输和API密钥认证,为脚本、浏览器扩展和AI代理提供安全的自动化接口。本文将深入解析如何配置企业级安全保护,确保你的Obsidian数据在自动化流程中得到全面防护。 ## 安全挑战与解决方案框架 在自动化笔记管理过程中,我们面临三大核心安全挑战:**数据传输安全

gitblog_00905的博客 336

TortoiseGit之配置密钥

基于github的开发必须要用到rsa密钥,因此需要用到TortoiseGit的putty key generator工具,来生成既适用于github的rsa密钥也适用于TortoiseGit的ppk密钥。

欧文的博客 2103

终极邮件服务器解决方案:5个步骤轻松搭建企业级邮件系统

还在为自建邮件服务器而烦恼吗?配置复杂、垃圾邮件泛滥、安全漏洞频出、运维成本高昂……这些痛点让很多企业望而却步。今天,我将为您介绍一个开箱即用的企业级邮件服务器解决方案——mailcow-dockerized,让您在5个简单步骤内搭建稳定、安全、高效的邮件系统! mailcow-dockerized是一个基于Docker容器化的开源邮件服务器套件,它将Postfix、Dovecot、Nginx、

gitblog_00571的博客 487

海康视觉平台VisionMaster使用学习笔记(1)

双击图像源设置图像源的属性,像素格式分为Mono8和RDB24分别对应导入的图像是彩色还是黑白。打开相机驱动软件MVS,对连接的相机进行属性上的配置,先对相机的IP进行对应的设置。将自动触发的使能打开,保存配置好的相机属性,默认保存到用户集1中。点击MVS软件中的触发按钮,查看相机是否进行正常的触发拍照。打开VM软件添加一个图像源,选择图像源选项拖出图像源。回到VM软件中将选择相机选项选择到配置好参数的相机。取图方式也可以调整为相机取图,将图像源改为相机。双击相机进行连接后对相机的属性进行配置。

A567852的博客 1万+

国科大学习资料--自然语言处理(宗成庆)-2019期末考试题

国科大学习资料–自然语言处理(宗成庆)-2019期末考试题 国科大学习资料–自然语言处理(宗成庆)-2019期末考试题 国科大学习资料–自然语言处理(宗成庆)-2019期末考试题

无名何许人的博客 2444

系统公告 | MemFire Cloud应用管理全新升级,实时数据库等你来体验~

拿来即用,应用开发人员再也不用为撰写API而发愁。MemFire Cloud 为开发者提供了简单易用的云数据库(表编辑器、自动生成API、SQL编辑器、备份恢复、托管运维),很大地降低开发者的使用门槛。

NimbleX_的博客 467

ABAP RAP 行为建模深入学习:从 Behavior Definition 到 Behavior Implementation 的完整实践指南

ABAP RAP开发指南:业务行为定义与实现 本文介绍SAP RAP框架中业务对象行为的开发方法: 分层设计 Behavior Definition声明业务能力(增删改查、校验、动作等) Behavior Implementation在ABAP类中编写具体逻辑 核心组件 使用BDL定义业务行为 通过FOR BEHAVIOR OF绑定行为池类(ABP) 在本地类实现校验/确定/动作逻辑 关键特性 支持managed/unmanaged两种实现模式 提供草稿表、并发控制等企业级功能 通过EML以别名访问实体 开

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 425

在Ubuntu 22.04上安装PostgreSQL 15

PostgreSQL作为一种现代化的数据库,在市场份额上逐年上升。本人长期使用MySQL 5.6版本,也想体验一把现代数据库的优越性。。为了使能在本机(Win 11)上访问Ubuntu下的PostgreSQL,需要配置其相关的参数,包括账号用户名及网络。以下是本人在实践过程中的配置过程。

carrophoto的博客 2392

DRV8311HRRWR直流无刷(BLDC)电机驱动原理图设计

DRV8311HRRWR集成三个MOSFET 半H桥,用于驱动三相无刷直流电机(BLDC),适用于5V、9V、12V或18V直流电源轨或1S至4S电池供电应用。内部集成三个具有集成电流感测功能的电流感测放大器(CSA),可感测BLDC电机的三相电流,从而实现FOC和电流控制系统设计方案。集成保护特性:VM 欠压锁定 (UVLO)、 电荷泵欠压 (CPUV)、过流保护 (OCP)、热警告和热关断 (OTW/OTSD)、故障条件指示引脚 (nFAULT)支持 1.8V、3.3V 和 5V 逻辑输入。

zhusl6688的博客 1236

『OPEN3D』1.2 mesh处理 python篇

介绍open3d对mesh的基本处理操作

NNNNNathan的博客 4653

ubuntu 安装pg15-vector

pg

windows_2006的专栏 627

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

PostgreSQL15 16 编译安装+问题解决

postgresql16 15 14在linux系统的编译安装

ziqibit的博客 7784

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

postgresql之ssl

1、PostgreSql之SSL ? PostgreSQL支持使用SSL连接加密客户端/服务器通信,以提高链路安全性。这要求在客户端和服务器系统上都安装OpenSSL,并且在构建时启用PostgreSQL中的ssl支持(使用源码安装时的--with-openssl参数)。 2、什么是OpenSSL? OpenSSL是一个工具包,用于Transport Layer Security(TLS)和Secure Sockets Layer(SSL)协议。它也是一个通用的密码学库。 Open...

深海微澜 2878

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

postgresql数据库配置ssl

pg配置ssl

nmxiaocui的博客 2892

postgresql数据库配置主从并配置ssl加密

3、正常连接无误后,将root.crt、server.crt、server.key复制到从数据库节点的存储data目录下,与主节点相同配置postgresql.conf、pg_hba.conf配置文件。2、在主节点配置ssl加密,使用navicat测试是否可以连接。4、配置完成后,使用navicat测试ssl加密连接。1、先将postgresql数据库主从配置好。

nmxiaocui的博客 870

Ubuntu源码安装PostgreSQL

Ubuntu源码安装PostgreSQL

随便写写,随便写写 1107

PostgreSQL 用户及授权管理 06:启用 SSL 及验证

最后,如果配置得当,服务器可以通过 SSL 处理网络连接,从而加密所有网络流量和数据。如果在外企工作的话,那么他们对安全要求是非常严格的,在他们那里:安全第一,业务第二。在国内的企业可能要求的就没那么高了。这一节里面介绍的内容在国内企业用的虽然不多,但是这节的内容非常重要,推荐大家掌握。虽然国内企业不那么重视安全,但我们却不能不重视。

cc20100608的专栏 2773

Ubuntu下PostgreSQL的安装与使用

已经有另一个 PostgreSQL 服务器实例正在运行,由于在实验过程中我使用了Xshell远程连接服务器,通过其对服务器上的PG进行操作,同时我还通过pycharm远程连接了服务器,在程序中使用psycopg2进行连接时,使用的用户名也是超级用户,即使pycharm已经断开连接,还是会造成服务器实例的占用。如果你当前的用户名不是‘postgres’,且数据库集群中没有和你当前用户名同名的数据库,就会报数据库不存在的错误,如何你数据集群里未创建任何数据库,就使用‘psql postgres’

m0_51709342的博客 1万+

Ubuntu18.04源码安装PostgreSQL11

最近在看项目源码时候,发现使用了PostgreSQL,发现思路非常之清晰,安装测试下吧 一、Ubuntu18 网络设置不生效问题 本次采用的Ubuntu环境为18.04,Ubuntu18和之前的版本不太一样,我这里出现了网络设置总是出错的问题,最后找到了这篇文章Ubuntu Server 18.04 网络设置不生效的解决,思路是一样的。 首先通过ifconfig查看网卡设置: 我这里有两个网...

我的梦 3824

PostgreSQL 编译安装通用步骤

postgresql,源码编译,通用步骤

丘处机的专栏 3392
上一篇: vault正式环境安装部署
下一篇: postgreSQL16添加审计功能
ciqingloveless
博客等级 码龄18年 136粉丝 248原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值