A relational database, like mysql, provides transactions to wrap several operations in one unit, make them all pass or all fail. All isolation levels except READ UNCOMMITTED don't allow read data changes until they are committed in other transaction. If you don't realize it, you probably introduce some unexpected errors.

Before

It's common to generate a background job to send emails, tweets or post to facebook wall, like

class Notification < ActiveRecord::Base
after_create :asyns_send_notification def async_send_notification
NotificationWorker.async_send_notification({:notification_id => id})
end
end class NotificationWorker < Workling::Base
def send_notification(params)
notification = Notification.find(params[:notification_id])
user = notification.user
# send notification to user's friends by email
end
end

It looks fine, every time it creates a notification, generates an asynchronous worker, assigns notification_id to the worker, in the worker it finds the notification by id, then sends notification by email.

You won't see any issue in development, as local db can commit fast. But in production server, db traffic might be huge, worker probably finish faster than transaction commit. e.g.

main process worker process
BEGIN  
INSERT INTO notifications(message, user_id) values('notification message', 1)  
# return id 10 for newly-created notification  
  SELECT * FROM notifications WHERE id = 10
COMMIT  

In this case, the worker process query the newly-created notification before main process commits the transaction, it will raise NotFoundError, because transaction in worker process can't read uncommitted notification from transaction in main process.

Refactor

So we should tell activerecord to generate notification worker after notification insertion transaction committed.

class Notification < ActiveRecord::Base
after_commit :asyns_send_notification, :on => :create def async_send_notification
NotificationWorker.async_send_notification({:notification_id => id})
end
end

Now the transactions order becomes

main process worker process
BEGIN  
INSERT INTO notifications(message, user_id) values('notification message', 1)  
# return id 10 for newly-created notification  
COMMIT  
  SELECT * FROM notifications WHERE id = 10

Worker process won't receive NotFoundErrors any more.

For those callbacks that no need to execute in one transaction, you should always use after_commit to avoid unexpected errors.

after_commit is introduced from rails 3, if you use rails 2, please check out after_commit gem instead.

after_create and after_commit的更多相关文章

  1. 开发新手最容易犯的50个 Ruby on Rails 错误(1)

    [编者按]本文最早发布与 JETRuby 博客,主要介绍了开发新手最容易犯的 Ruby 错误.文章系国内 ITOM 管理平台 OneAPM 编译呈现. 一年前,我们创立了以 "Rubyboo ...

  2. Bullet:MySQL增强半同步参数rpl_semi_sync_master_wait_point值AFTER_SYNC和AFTER_COMMIT的对比实验

    MySQL 5.7.22启用增强半同步复制 MySQL对该参数值的描述 Semisync can wait for slave ACKs at one of two points, AFTER_SYN ...

  3. 《Ruby on Rails教程》学习笔记

    本文是我在阅读 Ruby on Rails 教程的简体中文版时所做的摘录,以及学习时寻找的补充知识.补充知识主要来自于 Ruby on Rails 實戰聖經. Asset Pipeline 在最新版 ...

  4. Rails5 Model Document

    创建: 2017/06/09 更新: 2017/06/21 更新: 2017/06/23 对待未完成的追加# TODO: 更新: 2017/06/29 修正文件名db/seed.rb ---> ...

  5. [MySQL Reference Manual] 18 复制

    18 复制 18 复制 18.1 复制配置 18.1.1 基于Binary Log的数据库复制配置 18.1.2 配置基于Binary log的复制 18.1.2.1 设置复制master的配置 18 ...

  6. mysql半同步(semi-sync)源码实现

    mysql复制简单介绍了mysql semi-sync的出现的原因,并说明了semi-sync如何保证不丢数据.这篇文章主要侧重于semi-sync的实现,结合源码将semi-sync的实现过程展现给 ...

  7. MySQL 5.7 Replication 相关新功能说明

    背景: MySQL5.7在主从复制上面相对之前版本多了一些新特性,包括多源复制.基于组提交的并行复制.在线修改Replication Filter.GTID增强.半同步复制增强等.因为都是和复制相关, ...

  8. MySQL 半同步复制+MMM架构

    200 ? "200px" : this.width)!important;} --> 介绍 上篇文章介绍了MMM架构的实现方法,但是上篇文章的MMM方案的复制是异步复制,异 ...

  9. MySQL半同步复制

    从MySQL5.5开始,MySQL以插件的形式支持半同步复制.如何理解半同步呢?首先我们来看看异步,全同步的概念 异步复制(Asynchronous replication) MySQL默认的复制即是 ...

随机推荐

  1. 安卓读写INI文件

    安卓读写INI文件 uses System.IoUtils procedure TForm1.Button1Click(Sender: TObject);var IniFile:TIniFile; C ...

  2. MYC编译器源码之语法分析

    MyC编译器采用自顶向下的方法进行语法解析,这种语法解析方式,一般是从最左边的Token开始,然后自顶向下看哪一条语法规则可能包含这个Token,如果包含这个Token,则自左向右根据这条语法规则逐一 ...

  3. MSSQL 全库搜索 指定字符串

    平时在在MSSql中查询数据的时候,想查找,某个字段在数据库中是否存在,并且查询出在哪个表中,哪个字段下面,在不知道的情况下,操作起来会很麻烦,然后就写了一个sql语句,使用起来感觉挺方便的.当然了, ...

  4. Unity3d ugui 实现image代码换图

    核心脚本代码 Image IMGE = transform.Find("IMGE").GetComponent<Image>();Sprite sprite1 = Re ...

  5. Angular6 学习笔记——内容投影, ViewChild和ContentChild

    angular6.x系列的学习笔记记录,仍在不断完善中,学习地址: https://www.angular.cn/guide/template-syntax http://www.ngfans.net ...

  6. (C#)字符串反转

    方法一: public static string Reverse(string name) {     if (String.IsNullOrEmpty(name))       {        ...

  7. C#字符串转UNICODE

    public static string StringToUnicode(string s)//字符串转UNICODE代码 { char[] charbuffers = s.ToCharArray() ...

  8. JEECG(三) JEECG minidao如何封装自己的 多表联合查询 分页查询

    JEECG确实是一款实实在在的促进生产力的工具好处我想看到此文章的人应该都有所体会了 言归正传 JEECG框架自带的查询确实很省事,但是多表联合查询 分页查询 是我们开发业务系统当中不可避免的这时框架 ...

  9. asp.net core读取appsetting.json文件

    1.在Startup.cs文件中注入,ConfigureServices方法 services.Configure<MyConfig>(Configuration.GetSection(& ...

  10. JavaWeb -学生信息管理实践(JDBC+web+三层架构+DBUtil构造思路)

    前言: 1 该程序使用动态web项目 2 该程序使用SQL server需导入对应包( 具体可看前篇----JDBC的使用) 3 三层架构思想: ①表示层 前台:jsp/html等 作为前台与用户交互 ...