NSQ 源碼閱讀 (四) diskqueue 檔案讀寫

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

引言

我們在這個系列第一篇文章中提到過,如果需要訊息落地而對儲存子系統的選擇上,從速度上來說 檔案系統>分布式KV(持久化)>Distributed File System>資料庫。而NSQ選擇了檔案系統作為儲存子系統。這篇文章將重點介紹nsq 對於檔案的操作。

何時寫入檔案?

在記憶體的msg chan buffer 已滿的時候,會將msg 寫入檔案,代碼如下:

func (c *Channel) put(m *Message) error {    select {    case c.memoryMsgChan <- m:    default:        b := bufferPoolGet()        err := writeMessageToBackend(b, m, c.backend)        bufferPoolPut(b)        c.ctx.nsqd.SetHealth(err)        if err != nil {            c.ctx.nsqd.logf(LOG_ERROR, "CHANNEL(%s): failed to write message to backend - %s",                c.name, err)            return err        }    }    return nil}

寫一條message

func (d *diskQueue) writeOne(data []byte) error {

diskQueue維護了寫檔案和寫檔案的offset

// diskQueue implements a filesystem backed FIFO queuetype diskQueue struct {    ...    writePos     int64    ...    writeFile *os.File    ...}

利用Seek 函數將寫檔案的位移量設定為writePos:

        if d.writePos > 0 {            _, err = d.writeFile.Seek(d.writePos, 0)

然後以二進位的方式寫入data的size:

dataLen := int32(len(data))d.writeBuf.Reset()err = binary.Write(&d.writeBuf, binary.BigEndian, dataLen)

此處的巧妙在於binary.Write會根據寫入資料的類型寫入一段固定大小的資料。此處dataLen 是int32,所以會寫入一段4個byte的資料來表示data的size。讀取的時候先讀一段4個byte的資料就知道了data的size。
之後寫入data:

_, err = d.writeBuf.Write(data)_, err = d.writeFile.Write(d.writeBuf.Bytes())

讀一條message

readOne函數以byte 數組的形式讀一條message 出來

func (d *diskQueue) readOne() ([]byte, error) {

diskQueue 維護了當前讀取的檔案和檔案的offset

// diskQueue implements a filesystem backed FIFO queuetype diskQueue struct {readPos      int64...readFile  *os.File

利用Seek 函數將當前檔案的位移量設定為readPos:

        if d.readPos > 0 {            _, err = d.readFile.Seek(d.readPos, 0)            if err != nil {                d.readFile.Close()                d.readFile = nil                return nil, err            }        }

先把一個message的大小讀出來:

err = binary.Read(d.reader, binary.BigEndian, &msgSize)

msgSize 和寫檔案時候的dataLen都是int32類型
有了msgSize, 定義一段msgSize大小的buffer,從檔案裡讀一段資料來填滿這個buffer,buffer裡面的資料就是一條message

    readBuf := make([]byte, msgSize)    _, err = io.ReadFull(d.reader, readBuf)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.