Rails 5 开发进阶
  • Rails 6 开发进阶
  • Active Model 功能模块
    • Model - 核心
      • Validations
      • Validator
      • Errors
      • Validations 相关的 Callbacks
      • Conversion
      • Naming & Name
      • Translation
      • Lint Tests
    • Model 的增强模块
      • Attribute Assignment
      • Attribute Methods
      • Dirty
      • Secure Password
      • Forbidden Attributes Protection
      • Serialization
      • Callbacks - 快速提供 3 个回调方法
    • 其它
  • Active Record 数据库操作:增删查改
    • Relation
      • Relation 文件下的方法
      • Query Methods
        • Preload, Eagerload, Includes 和 Joins 等
        • Query Methods 读取、设置查询方法
        • 关联表复杂查询示例
      • Spawn Methods
      • Batches 批量查询
      • Finder Methods
      • Calculations 统计计算
      • 其它
    • Collection Proxy
    • Scoping
    • Attribute Methods
      • Attribute Methods 文件下的内容
      • Read & Write
      • Before Type Cast - 类型转换
      • Query - 后缀 '?' 问询
      • Serialization
      • Primary Key
      • 其它
    • Persistence
      • 数据更新方法对比
      • 对比,然后使用合适的方法
      • 多个 save 方法
    • Counter Cache 计数器
    • Querying
    • 其它
  • Active Record 数据库关联关系
    • Associations 文件 - 4 个关联方法
    • Aggregations - composed_of 方法
    • Builder - 功能的实现
      • Association
      • Singular Association
      • Collection Association
      • Has One
      • Belongs To
      • Has Many
      • Has And Belongs To Many
    • Reflection - 实现之关联两者
      • Abstract Reflection
      • Macro Reflection
      • Association Reflection
      • Aggregate Reflection
      • Has Many Reflection
      • Has One Reflection
      • Belongs To Reflection
      • Has And Belongs To Many Reflection
      • Through Reflection
      • Polymorphic Reflection
      • Runtime Reflection
    • Association 目录 - 实现之提供方法
      • Association
      • Belongs To Association
      • Belongs To Polymorphic Association
      • Collection Association
      • Foreign Association
      • Has Many Association
      • Has Many Through Association
      • Has One Association
      • Has One Through Association
      • Singular Association
      • Through Association
    • 4 个关联方法的使用
      • belongs_to
      • has_one
      • has_many
      • has_and_belongs_to_many
      • 关联方法的可选参数汇总
    • 4 个关联方法的补充
      • 使用关联方法后,Rails 自动生成了哪些方法
      • habtm vs has_many through
    • Nested Attributes 嵌套属性
    • Inheritance 单表继承
    • 其它
      • Autosave Association
      • Alias Tracker
      • Association Scope
      • Join Dependency
      • Preloader
      • Association Relation
  • Active Record 数据库特性及功能模块
    • Callbacks 回调
      • 回调及其顺序
      • 跳过回调
      • 可选参数
      • after_create 与 after_commit on create 各自存在的坑
    • Transactions 事务
    • Locking 锁
    • Enum 枚举
    • Store
    • Validations 校验
    • Secure Token
    • Integration
    • No Touching
    • Touch Later
    • Attributes
    • Readonly Attributes
    • Serialization
    • Suppressor
  • Active Record 数据库迁移:表/字段
    • Connection Handling 连接数据库
    • Migration 文件下的内容
      • 控制台里迁移、回滚等命令
      • say_with_time
    • Connection Adapters
      • Schema Statements
        • create_table
        • change_table
      • Table Definition
      • Table
      • Database Statements
    • Model Schema
    • Schema
    • 其它
      • schema_format
      • Schema Migration
  • Active Record 数据库连接:底层适配,约定、配置
    • Naming Conventions
    • Schema Conventions
    • Timestamps
    • Core
      • 获取 record 对象
    • Sanitization
    • Migration DatabaseTasks
    • Statement Cache
    • Collection Cache Key
    • Attribute Mutation Tracker
    • Attribute Decorators
    • 其它
  • Action View 布局、渲染相关
    • Layouts
    • Base - 为渲染打基础
    • 非 Rails 是如何渲染的
    • Rails 是如何渲染的
      • Rendering
    • 渲染器介绍
      • Renderer - 渲染的入口
      • 基类 Abstract Renderer
      • 子类 Template Renderer
      • 子类 Partial Renderer & Collection Caching
      • 子类 Streaming Template Renderer
    • Template 内容
      • template 本文件下的内容
      • template 目录
    • Lookup Context
      • View Paths
      • Details Key & Details Cache
    • view_context
      • Context
      • Output Flow & Streaming Flow
    • View Paths
    • 其它
      • Output Buffer & Streaming Buffer
  • Action View 提供的 Helper 方法
    • 与表单直接相关的辅助方法
      • Form Builder
        • 扩展 Form Builder
      • Form Helper
      • Form Options Helper
      • Form Tag Helper
    • 与表单非直接相关的辅助方法
      • Tag Helper
      • Url Helper
      • Asset Tag Helper
      • Cache Helper
        • 片段缓存和 Cache Key
      • Controller Helper
      • Asset Url Helper
      • Csrf Helper
      • Capture Helper
      • Debug Helper
      • Date Helper
      • JavaScript Helper
      • Number Helper
      • Output Safety Helper
      • Rendering Helper
      • Record Tag Helper
      • Sanitize Helper
      • Translation Helper
      • Text Helper
      • Atom Feed Helper
      • Active Model Instance Tag
    • 其它
  • Action View 其它类和模块
    • Record Identifier
    • Routing Url For
    • Model Naming
    • Digestor
      • Dependency Tracker
    • 其它
  • Action Dispatch Http 作用:请求、响应
    • Request
      • Request 文件下的内容
      • URL
      • Headers
      • Mime Negotiation
      • Parameters
      • Parameter Filter & Filter Parameters
      • Cache 之 Request
      • Uploaded File
      • Utils
    • Response
      • Response 文件下的内容
      • Filter Redirect
      • Cache 之 Response
    • 其它
      • Rack Cache
      • Mime Type register
      • Session
  • Action Dispatch Middleware 中间件
    • Middleware
      • Rack - Ruby Web server 接口
      • 查看项目用了哪些 Middleware
      • 定制 Middleware
      • Middleware Stack
    • 各个 Middleware 类
      • Static
      • SSL
      • Show Exceptions
      • Exception Wrapper
      • Public Exceptions
        • 定制 Public Exceptions
      • Debug Exceptions
      • Request Id
      • Remote Ip
      • Reloader
      • Params Parser
      • Flash
      • Cookies & ChainedCookieJars
      • Session
      • Callbacks
      • Load Interlock
      • Executor
      • Debug Locks
  • Action Dispatch Routing 路由顶层(表现形式)
    • Mapper
      • Base
      • Http Helpers
      • Scoping
        • scope
        • namespace
      • Concerns
      • Resources
      • Scope、Mapping、Constraints
      • Redirection
      • match 和 scope 方法 - 重中之重
      • 路由常用方法汇总
    • 其它
      • Polymorphic Routes
      • Url For
      • Routing 概述:生成、存储、识别
      • 一步步分析从请求到响应涉及到 Rails 的哪些模块
      • endpoint 和 inspector 文件
  • Action Dispatch RouteSet 路由底层(实现方式)
    • 实例对象和各个实例方法
    • Named Route Collection
    • Dispatcher
    • Generator
    • Routes Proxy
    • Journey
  • Abstract Controller
    • Base
      • 获取所有的 Controller 和 action
    • Helpers
    • Callbacks
    • Rendering
    • render 参数汇总与详解
      • 更多关于渲染
    • Translation
    • Collector
    • 其它
      • Asset Paths
      • Routes Helpers
      • Logger
      • Url For
    • Caching
    • Caching & Caching Fragments
      • 默认片段缓存策略
  • Action Controller - Rack 增强扩展
    • Metal - 增强的 Rack, 简陋的 Controller
      • Metal 文件下的内容
      • Middleware Stack
      • Metal 使用举例
    • API - Metal 的继承者
    • Base - Metal 的继承者
    • Metal 的扩展
      • Redirecting
      • Head
      • Conditional Get - HTTP Cache
        • Conditional Get 其它
      • Etag With Template Digest
      • Http Authentication
        • Basic
        • Digest
        • Token
      • Streaming
      • Live
      • Mime Responds & Collector
      • Renderers 增删渲染器
      • Params Wrapper
      • Request Forgery Protection
      • Parameters & Strong Parameters
      • Data Streaming
      • Force SSL
      • Flash
      • Helpers
      • Cookies
      • Implicit Render
      • Instrumentation
      • Rendering
      • Rescue
      • Url For
      • 其它
    • 其它
      • Form Builder
      • Renderer
      • Basic Implicit Render
      • Railties Helpers
  • Active Support 扩展:autoload 的类和模块
    • Autoload
      • autoload & eager_autoload 补充
    • Lazy Load Hooks
    • Concern
    • File Update Checker
    • Notifications
      • Rails 默认已有的 instrumenter
    • Subscriber
    • Log Subscriber
      • Action Mailer Log Subscriber
      • Action Controller Log Subscriber
      • Action View Log Subscriber
      • Active Record Log Subscriber
    • Rescuable
    • Descendants Tracker
    • Dependencies
  • Active Support 扩展:eager_autoload 的类和模块
    • Cache 缓存的源头
    • Callback 方法解释及使用
    • Callbacks 底层简要分析
    • Configurable
    • Ordered Hash 和 Ordered Options
    • Inflector
    • Key Generator 和 Caching Key Generator
    • Message Encryptor 和 Message Verifier
    • String Inquirer - Rails.env.production?
    • Array Inquirer
    • Tagged Logging
    • Gzip 与 JSON
    • Backtrace Cleaner
    • Number Helper
    • Benchmarkable
    • Xml Mini
    • Multibyte
    • Deprecation
    • 其它
  • Active Support 核心扩展
    • Array
    • Benchmark
    • Big Decimal
    • Class
    • Date
    • Time
    • Date Time
    • Duration
    • Time With Zone
    • Time Zone
    • Enumerable
    • File
    • Hash
    • Hash With Indifferent Access
    • Integer
    • Numeric
    • Kernel
    • Object
    • Module
      • alias_method_chain
    • Marshal
    • Range
    • Regexp
    • Secure Random
    • String
    • URI
    • Load Error
    • Name Error
    • Logger
    • Logger Silence
  • Active Support 其它类和模块
    • Security Utils
  • railties 核心:初始化、组件化
    • Railtie
      • Railtie 文件下的内容
      • Initializable
      • Configuration
      • 定制自己的 Railtie
    • Railtie 补充
      • Rails 默认组件都是 Railtie
    • Engine
      • Engine 文件下的内容
      • Configuration
      • Engine full vs mountable
      • 定制自己的 Engine
      • 其它
    • Application
      • Application 文件下的内容
      • Bootstrap
      • Finisher
      • Configuration
      • Default Middleware Stack
      • Rails 应用启动过程
    • Application 补充
      • Routes Reloader
      • rake & rails 命令
      • rails console 里的小技巧
      • 路径 - Root 和 Path
      • 提示信息页面
    • 其它
      • Rails 文件下的内容
      • Configuration Middleware Stack Proxy
      • AppName, Application. Engine, Railtie
      • Backtrace Cleaner
      • Rack Logger
      • Generators
  • Rails Configuration 配置
    • 一般常用配置项
    • Action Mailer
    • Active Record
    • Action Controller
    • Action Dispatch
    • Action View
    • Active Support
    • I18n
    • Generators
    • Assets
    • Environments
    • 设置项补充
    • Middleware
  • Rails Generators 代码生成器
    • Thor
    • generators 下的目录、文件
    • Base
    • Actions
    • Named Base
    • 其它
      • App Base
      • Generators 文件下的内容
      • Migration
      • Active Model
      • Resource Helpers
      • Model Helpers
      • Generated Attribute
  • Action Mailer 发邮件
    • Base
      • 拦截器 register_interceptor
      • 订阅者 register_observer
    • Mail Helper
    • Message Delivery
    • 其它
      • Delivery Methods
      • Previews & Preview
      • DeliveryJob
      • Collector
  • Active Job 异步任务
    • Active Job 使用
    • Active Job 补充
  • Action Cable 封装的 WebSockets
    • 服务端 - Ruby 代码
      • Channel
      • Channel 补充
      • Connection
      • Connection 补充
      • Server
      • Server 补充
      • Remote Connections
      • Action Cable Helper
      • Subscription Adapter
      • Subscription Adapter 补充
    • 客户端 - Coffee 脚本
      • Action Cable 文件下的内容
      • Consumer
      • Subscription
      • Connection
      • Subscriptions
      • Connection Monitor
    • 一些重要的东西
    • 其它
  • Active Storage 存储功能最小实现
  • 前端 Turbolinks
  • 前端 Webpacker
  • 测试 Testing
    • Active Support
    • Active Job
    • Action Mailer
    • Action Controller
    • Action Dispatch
    • Action View
    • Generators
    • rails-dom-testing
  • 测试 MiniTest
    • Spec DSL
    • Assertions
    • Mock
    • Unit
      • TestCase
      • Lifecycle Hooks
      • Guard
    • Expectations
    • 其它
  • 测试 Factory Girl
  • rails-guides 指南
  • 其它
    • 继承心得
    • Rails 源代码里一些常用方法
    • Rails assets precompile
    • Turbolinks 产生的原因
    • Turbolinks 3
    • Turbolinks 补充
    • Turbolinks 5
  • 后记
由 GitBook 提供支持
在本页
  • 悲观锁(Pessimistic)
  • 特性
  • 实现
  • Rails 的悲观锁
  • 使用注意
  • 乐观锁(Optimistic)
  • 特性
  • 实现
  • Rails 的乐观锁

这有帮助吗?

  1. Active Record 数据库特性及功能模块

Locking 锁

锁,分为悲观锁(Pessimistic)和乐观锁(Optimistic). 对比的话,可以笼统的理解悲观锁是数据库层面,而乐观锁是应用层面。

悲观锁(Pessimistic)

特性

强烈的独占和排他。

它指的是对数据被外界(包括本系统当前的其他事务,以及来自外部系统的事务处理)修改持保守态度,因此,在整个数据处理过程中,将数据处于锁定状态。

实现

往往依靠数据库提供的锁机制(也只有数据库层提供的锁机制才能真正保证数据访问的排他性,否则,即使在本系统中实现了加锁机制,也无法保证外部系统不会修改数据)。

一个典型的依赖数据库的悲观锁调用:

select * from account where name="Erica" for update;

这条 sql 语句锁定了 account 表中所有符合检索条件(name="Erica")的记录。 本次事务提交之前(事务提交时会释放事务过程中的锁),外界无法修改这些记录。

注意:根据 name 是否有索引、是否是唯一索引、是否是主键,决定锁全表、区间、单个记录。

Rails 的悲观锁

相关方法有:lock、lock! 和 with_lock.

其中,lock 和 with_lock 都是封装 lock! 而来。

lock 相当于 lock! 的别名,但调用者可以是 relation 对象。 with_lock 和事务捆绑在一起,并且参数可以是代码块。

使用举例:

# 使用 lock,注意生成的 SQL
Account.lock.find(1)
# SELECT `accounts`.* FROM `accounts` WHERE `accounts`.`id` = 1 LIMIT 1 FOR UPDATE

# lock 结合 transaction 一起使用
Account.transaction do
  # select * from accounts where name = 'shugo' limit 1 for update
  shugo = Account.where("name = 'shugo'").lock(true).first
  yuko = Account.where("name = 'yuko'").lock(true).first
  shugo.balance -= 100
  shugo.save!
  yuko.balance += 100
  yuko.save!
end

# 使用 lock!
Account.transaction do
  # select * from accounts where ...
  accounts = Account.where(...)
  account1 = accounts.detect { |account| ... }
  account2 = accounts.detect { |account| ... }

  # account1 和 account2 只能是单个对象
  # select * from accounts where id=? for update
  account1.lock!
  account2.lock!
  account1.balance -= 100
  account1.save!
  account2.balance += 100
  account2.save!
end

# 使用 with_lock!
account = Account.first

# account 加上了锁,代码块加上了事务
account.with_lock do
  account.balance -= 100
  account.save!
end

使用注意

  1. 锁表,一个地方执行写的时候,另一个地方不能同时执行写操作,这没问题。但问题是,你也不能执行读操作。

  2. 一个地方读数据,并赋值给对象。另一个地方在这之后执行了写操作,这个对象(脏数据)会覆盖已经更新过的数据,而不是报错。

Note: 它是数据库级别的锁。

乐观锁(Optimistic)

特性

乐观锁(Optimistic Locking) 相对悲观锁而言,乐观锁机制采取了更加宽松的加锁机制。

悲观锁大多数情况下依靠数据库的锁机制实现,以保证操作最大程度的独占性。但随之而来的就是数据库性能的大量开销,特别是对长事务而言,这样的开销往往无法承受。而乐观锁机制在一定程度上解决了这个问题。

实现

大多是基于数据版本(Version)记录机制实现。

何谓数据版本?即为数据增加一个版本标识,在基于数据库表的版本解决方案中,一般是通过为数据库表增加一个 "version" 字段来实现。读取出数据时,将此版本号一同读出,之后更新时,对此版本号 +1. 此时,将提交数据的版本数据与数据库表对应记录的当前版本信息进行比对,如果提交的数据版本号大于数据库表当前版本号,则予以更新,否则认为是过期数据。

Rails 的乐观锁

使用举例:

  1. 给表添加 :lock_version 属性。

add_column :products, :lock_version, :integer, :default => 0, :null => false
  1. 在表单里使用此属性。(此处略)

  2. 已经生效。如果更新的是脏数据,会报错 StaleObjectError,可根据这个做相应处理。

p1 = Product.find(1)
p2 = Product.find(1)

p1.name = "Michael"
p1.save

p2.name = "should fail"
p2.save
# 如果别人想再次更改,(脏数据)不会覆盖已经更新过的数据,而是会报错。
# => Raises a ActiveRecord::StaleObjectError

更改约定:

  1. 默认标识字段是 lock_version,当包含此属性时,按照约定乐观锁会"自动生效"。有时候(比如:遗留项目已经使用此字段,但却不是用于"锁"),我们可能需要拒绝"自动生效",可以配置:

ActiveRecord::Base.lock_optimistically = false

# 或,只针对某个 model
ClassName.lock_optimistically = false
  1. 可以用 locking_column 更换默认的标识字段,如:

class Person < ActiveRecord::Base
  self.locking_column = :lock_person
end

Note: 它是应用级别的锁。

上一页Transactions 事务下一页Enum 枚举

最后更新于3年前

这有帮助吗?