go 언어로 구현된memcache 프로토콜 서비스 방법

4889 단어
본고의 실례는 고 언어가 실현하는memcache 프로토콜 서비스의 방법을 설명한다.여러분에게 참고하도록 공유하다.구체적으로 다음과 같다.
온전한 실례 코드는 여기를 클릭하여 본 사이트에서 다운로드하십시오.
1. Go 언어 코드는 다음과 같습니다.

   package memcachep 
  
import (
    "bufio"
    "fmt"
    "io"
    "strconv"
    "strings"
)
//mc request
type MCRequest struct {
    //
    Opcode CommandCode
    //key
    Key string
    //
    Value []byte
    //
    Flags int
    //
    Length int
    //
    Expires int64
}
//request to string
func (req *MCRequest) String() string {
    return fmt.Sprintf("{MCRequest opcode=%s, bodylen=%d, key='%s'}",
        req.Opcode, len(req.Value), req.Key)
}
// socket MCRequest
func (req *MCRequest) Receive(r *bufio.Reader) error {
    line, _, err := r.ReadLine()
    if err != nil || len(line) == 0 {
        return io.EOF
    }
    params := strings.Fields(string(line))
    command := CommandCode(params[0])
    switch command {
    case SET, ADD, REPLACE:
        req.Opcode = command
        req.Key = params[1]
        req.Length, _ = strconv.Atoi(params[4])
        value := make([]byte, req.Length+2)
        io.ReadFull(r, value)
        req.Value = make([]byte, req.Length)
        copy(req.Value, value)
    case GET:
        req.Opcode = command
        req.Key = params[1]
        RunStats["cmd_get"].(*CounterStat).Increment(1)
    case STATS:
        req.Opcode = command
        req.Key = ""
    case DELETE:
        req.Opcode = command
        req.Key = params[1]
    }
    return err
}

2. Go 언어 코드:

   package memcachep 
  
import (
    "fmt"
    "io"
)
type MCResponse struct {
    //
    Opcoed CommandCode
    //
    Status Status
    //key
    Key string
    //
    Value []byte
    //
    Flags int
    //
    Fatal bool
}
// response socket
func (res *MCResponse) Transmit(w io.Writer) (err error) {
    switch res.Opcoed {
    case STATS:
        _, err = w.Write(res.Value)
    case GET:
        if res.Status == SUCCESS {
            rs := fmt.Sprintf("VALUE %s %d %d\r
%s\r
END\r
", res.Key, res.Flags, len(res.Value), res.Value)
            _, err = w.Write([]byte(rs))
        } else {
            _, err = w.Write([]byte(res.Status.ToString()))
        }
    case SET, REPLACE:
        _, err = w.Write([]byte(res.Status.ToString()))
    case DELETE:
        _, err = w.Write([]byte("DELETED\r
"))
    }
    return
}

3. Go 언어 코드는 다음과 같습니다.

   package memcachep 
  
import (
    "fmt"
)
type action func(req *MCRequest, res *MCResponse)
var actions = map[CommandCode]action{
    STATS: StatsAction,
}
//
func waitDispatch(rc chan chanReq) {
    for {
        input :=         input.response     }
}
// action
func dispatch(req *MCRequest) (res *MCResponse) {
    if h, ok := actions[req.Opcode]; ok {
        res = &MCResponse{}
        h(req, res)
    } else {
        return notFound(req)
    }
    return
}
//
func notFound(req *MCRequest) *MCResponse {
    var response MCResponse
    response.Status = UNKNOWN_COMMAND
    return &response
}
// request
func BindAction(opcode CommandCode, h action) {
    actions[opcode] = h
}
//stats
func StatsAction(req *MCRequest, res *MCResponse) {
    res.Fatal = false
    stats := ""
    for key, value := range RunStats {
        stats += fmt.Sprintf("STAT %s %s\r
", key, value)
    }
    stats += "END\r
"
    res.Value = []byte(stats)
}

본고에서 서술한 것이 여러분의 Go 언어 프로그램 설계에 도움이 되었으면 합니다.

좋은 웹페이지 즐겨찾기