Open Source Billing部署优化:生产环境性能调优终极指南 [特殊字符]
Open Source Billing部署优化生产环境性能调优终极指南 【免费下载链接】open-source-billingOpen Source Billing a super simple way to create and send invoices and receive payments online.项目地址: https://gitcode.com/gh_mirrors/op/open-source-billingOpen Source Billing是一款功能强大的开源发票和支付管理平台专为企业提供简单高效的在线发票创建、发送和收款解决方案。在生产环境中部署时合理的性能调优能够显著提升系统稳定性和用户体验。本文将为您提供完整的Open Source Billing生产环境部署优化指南。为什么需要性能调优 Open Source Billing作为一款企业级发票管理系统在处理大量发票数据、支付记录和客户信息时性能优化尤为重要。通过合理的配置您可以提升系统响应速度减少用户等待时间提高并发处理能力支持更多用户同时访问降低服务器资源消耗节省运营成本增强系统稳定性减少宕机风险数据库优化配置 ️数据库是Open Source Billing的核心组件正确的配置可以大幅提升性能。MySQL数据库优化在config/database.yml.copy文件中生产环境配置需要进行以下优化production: adapter: mysql2 encoding: utf8mb4 reconnect: false database: osb_production pool: % ENV.fetch(RAILS_MAX_THREADS) { 16 } % username: osb_prod_user password: % ENV[DB_PASSWORD] % host: % ENV[DB_HOST] || localhost % port: % ENV[DB_PORT] || 3306 % variables: sql_mode: TRADITIONAL wait_timeout: 28800 interactive_timeout: 28800关键优化点使用utf8mb4编码支持完整Unicode字符集连接池大小根据应用线程数动态调整使用环境变量管理敏感信息增加连接超时设置防止连接中断数据库索引优化为常用查询字段添加索引在db/migrate/目录下的迁移文件中# 为发票表添加索引 add_index :invoices, [:company_id, :status, :invoice_date] add_index :invoices, :client_id add_index :invoices, :invoice_number, unique: true # 为支付表添加索引 add_index :payments, [:invoice_id, :payment_date] add_index :payments, :client_id # 为客户表添加索引 add_index :clients, [:company_id, :organization_name]应用服务器配置优化 ⚡Puma服务器优化修改config/puma.rb文件以获得更好的性能# 根据服务器CPU核心数设置worker数量 workers ENV.fetch(WEB_CONCURRENCY) { 4 } # 根据可用内存设置线程数 max_threads_count ENV.fetch(RAILS_MAX_THREADS) { 16 } min_threads_count ENV.fetch(RAILS_MIN_THREADS) { max_threads_count } threads min_threads_count, max_threads_count # 预加载应用代码 preload_app! # 启用集群模式 rackup DefaultRackup port ENV.fetch(PORT) { 3000 } environment ENV.fetch(RAILS_ENV) { production } # 设置PID文件路径 pidfile ENV.fetch(PIDFILE) { tmp/pids/puma.pid } state_path tmp/pids/puma.state # 启用守护进程模式 daemonize true # 工作目录 directory /var/www/opensourcebilling/current # 标准输出重定向 stdout_redirect log/puma.stdout.log, log/puma.stderr.log, true # 设置worker超时时间 worker_timeout 60 # 设置worker启动间隔 worker_boot_timeout 30生产环境配置优化在config/environments/production.rb中启用以下关键配置# 启用缓存 config.cache_store :redis_cache_store, { url: ENV.fetch(REDIS_URL) { redis://localhost:6379/1 }, expires_in: 1.day, compress: true, pool_size: ENV.fetch(RAILS_MAX_THREADS) { 5 }, pool_timeout: 5 } # 启用静态文件服务 config.public_file_server.enabled true config.public_file_server.headers { Cache-Control public, max-age#{1.year.to_i} } # 启用SSL config.force_ssl true # 优化日志配置 config.log_level :info config.log_formatter ::Logger::Formatter.new # 启用资产压缩 config.assets.css_compressor :sass config.assets.js_compressor :uglifier config.assets.compile false config.assets.digest true # 配置邮件发送 config.action_mailer.delivery_method :smtp config.action_mailer.smtp_settings { address: ENV[SMTP_ADDRESS], port: ENV[SMTP_PORT], user_name: ENV[SMTP_USERNAME], password: ENV[SMTP_PASSWORD], authentication: :plain, enable_starttls_auto: true }缓存策略优化 Redis缓存配置在config/initializers/cache_store.rb中配置Redis缓存# 配置Redis作为缓存存储 if ENV[REDIS_URL].present? Rails.application.config.cache_store :redis_cache_store, { url: ENV[REDIS_URL], namespace: osb_cache, expires_in: 1.day, compress: true, pool_size: 5, pool_timeout: 5 } else Rails.application.config.cache_store :memory_store, { size: 64.megabytes } end页面片段缓存在控制器中添加缓存策略# app/controllers/invoices_controller.rb class InvoicesController ApplicationController # 缓存发票列表页面 caches_page :index, if: - { request.format.html? } # 缓存发票详情页面 caches_action :show, expires_in: 1.hour, unless: - { current_user.admin? } def index invoices Rails.cache.fetch(invoices/#{current_company.id}/#{params[:page]}, expires_in: 5.minutes) do current_company.invoices.includes(:client, :payments).page(params[:page]).per(20) end end end资产预编译优化 生产环境资产配置创建config/initializers/assets.rb优化配置# 启用资产版本控制 Rails.application.config.assets.version 1.0 # 预编译额外的资产文件 Rails.application.config.assets.precompile %w[ *.png *.jpg *.jpeg *.gif *.svg *.eot *.woff *.ttf admin.js admin.css invoices.js invoices.css payments.js payments.css ] # 启用资产压缩 Rails.application.config.assets.compress true Rails.application.config.assets.compile false Rails.application.config.assets.digest true # 设置资产主机 Rails.application.config.action_controller.asset_host ENV[ASSET_HOST] if ENV[ASSET_HOST].present?部署时资产预编译在部署脚本中添加资产预编译优化# 预编译资产时跳过不必要的内容 RAILS_ENVproduction bundle exec rake assets:precompile \ --trace \ --no-debug \ --no-color \ --quiet监控和日志优化 应用性能监控配置应用性能监控工具# config/initializers/newrelic.rb if ENV[NEW_RELIC_LICENSE_KEY].present? NewRelic::Agent.manual_start( app_name: ENV.fetch(NEW_RELIC_APP_NAME, OpenSourceBilling), license_key: ENV[NEW_RELIC_LICENSE_KEY], log_level: info, capture_params: true, transaction_tracer: { enabled: true, transaction_threshold: apdex_f, record_sql: obfuscated, stack_trace_threshold: 0.5 }, error_collector: { enabled: true, capture_source: true } ) end结构化日志配置在config/environments/production.rb中配置结构化日志# 配置JSON格式日志 require lograge config.lograge.enabled true config.lograge.formatter Lograge::Formatters::Json.new config.lograge.custom_options lambda do |event| { time: event.time, host: event.payload[:host], request_id: event.payload[:request_id], user_id: event.payload[:user_id], company_id: event.payload[:company_id], params: event.payload[:params].except(:controller, :action, :format, :utf8), duration: event.duration, view: event.payload[:view_runtime], db: event.payload[:db_runtime] } end # 输出到标准输出 config.logger ActiveSupport::TaggedLogging.new(Logger.new(STDOUT))安全优化配置 安全头部配置在config/initializers/security_headers.rb中添加安全头部# 启用安全HTTP头部 Rails.application.config.middleware.insert_before 0, Rack::Cors do allow do origins * resource *, headers: :any, methods: [:get, :post, :put, :patch, :delete, :options, :head] end end # 添加安全头部 Rails.application.config.middleware.use Rack::Attack Rails.application.config.middleware.insert_before 0, Rack::Protection::FrameOptions Rails.application.config.middleware.use Rack::Protection::HttpOrigin环境变量安全配置创建.env.production文件管理敏感配置# 数据库配置 DB_HOSTlocalhost DB_PORT3306 DB_NAMEosb_production DB_USERNAMEosb_prod_user DB_PASSWORDyour_secure_password_here # Redis配置 REDIS_URLredis://localhost:6379/1 REDIS_PASSWORDyour_redis_password # 应用配置 SECRET_KEY_BASEyour_secret_key_base_here RAILS_MAX_THREADS16 WEB_CONCURRENCY4 RAILS_SERVE_STATIC_FILEStrue # 邮件配置 SMTP_ADDRESSsmtp.gmail.com SMTP_PORT587 SMTP_USERNAMEyour_emailgmail.com SMTP_PASSWORDyour_app_specific_password # 第三方服务 PAYPAL_CLIENT_IDyour_paypal_client_id PAYPAL_CLIENT_SECRETyour_paypal_client_secret STRIPE_PUBLISHABLE_KEYyour_stripe_publishable_key STRIPE_SECRET_KEYyour_stripe_secret_key部署脚本优化 Capistrano部署配置优化config/deploy.rb部署脚本# 设置部署配置 set :application, opensourcebilling set :repo_url, https://gitcode.com/gh_mirrors/op/open-source-billing.git set :branch, master set :deploy_to, /var/www/opensourcebilling # 设置共享文件和目录 append :linked_files, config/database.yml, config/secrets.yml, .env.production, config/puma.rb append :linked_dirs, log, tmp/pids, tmp/cache, tmp/sockets, vendor/bundle, public/system, public/uploads # 设置RVM set :rvm_type, :user set :rvm_ruby_version, 2.7.1 # 设置Puma set :puma_init_active_record, true set :puma_preload_app, true set :puma_worker_timeout, nil set :puma_threads, [4, 16] # 部署任务 namespace :deploy do desc 重启应用 after :publishing, :restart desc 数据库迁移 after :updated, :migrate desc 重启Puma task :restart do on roles(:app) do execute :sudo, :systemctl, :restart, puma end end desc 运行数据库迁移 task :migrate do on roles(:db) do within release_path do execute :bundle, :exec, :rake, db:migrate end end end desc 预编译资产 after :updated, :compile_assets do on roles(:web) do within release_path do with rails_env: fetch(:rails_env) do execute :bundle, :exec, :rake, assets:precompile end end end end end性能监控和调优工具 ️安装性能监控工具# 安装必要的监控工具 sudo apt-get install -y htop nmon iotop iftop # 安装数据库监控工具 sudo apt-get install -y mytop innotop # 安装网络监控工具 sudo apt-get install -y nethogs bmon创建性能监控脚本创建scripts/monitor.sh监控脚本#!/bin/bash # 监控系统资源 echo 系统资源监控 echo CPU使用率: top -bn1 | grep Cpu(s) | awk {print $2} | cut -d% -f1 echo 内存使用率: free -m | awk NR2{printf %.2f%%, $3*100/$2} echo 磁盘使用率: df -h / | awk NR2{print $5} # 监控应用进程 echo -e \n 应用进程监控 ps aux | grep puma | grep -v grep ps aux | grep sidekiq | grep -v grep # 监控数据库连接 echo -e \n 数据库连接监控 mysql -u root -p -e SHOW PROCESSLIST; | wc -l # 监控Redis状态 echo -e \n Redis监控 redis-cli info | grep -E (connected_clients|used_memory_human|instantaneous_ops_per_sec)总结与最佳实践 通过以上优化配置您的Open Source Billing生产环境将获得显著的性能提升。以下是关键优化要点总结数据库优化合理配置连接池、添加必要索引、使用环境变量管理敏感信息应用服务器优化配置Puma多worker模式、启用预加载、优化线程数缓存策略使用Redis作为缓存后端、实现页面和片段缓存资产优化预编译静态资产、启用压缩和CDN分发监控配置实现结构化日志、应用性能监控、系统资源监控安全加固配置安全HTTP头部、使用环境变量管理密钥、启用SSL记住性能优化是一个持续的过程。定期监控系统性能根据实际负载调整配置参数才能确保Open Source Billing在生产环境中始终保持最佳状态。 专业提示在实施任何优化更改之前请务必在测试环境中进行充分的测试确保所有功能正常运行然后再应用到生产环境。通过遵循本指南中的优化策略您将能够构建一个高性能、稳定可靠的Open Source Billing生产环境为您的企业提供卓越的发票和支付管理体验【免费下载链接】open-source-billingOpen Source Billing a super simple way to create and send invoices and receive payments online.项目地址: https://gitcode.com/gh_mirrors/op/open-source-billing创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考