コード例 #1
0
func Server(conn net.Conn) error {
	var buf []byte
	data := make([]byte, 4096)
	n, err := conn.Read(data)
	buf = append(buf, data[:n]...)
	for n == 4096 {
		n, err = conn.Read(data)
		buf = append(buf, data[:n]...)
	}
	//	data:=make([]byte,4096)
	//	n,err:=conn.Read(data)
	if err == io.EOF {
		//fmt.Println("close conn")
		//conn.Close()
		return err
	}
	servlet := new(servlet.Servlet)
	servlet.Conn = conn
	protodata := new(protos.Command)
	proto.Unmarshal(buf, protodata)
	servlet.Command = protodata
	//fmt.Println("receive request:  "+protodata.String())
	//通过key的第一部分来确定分区
	key := protodata.GetKey()
	servlet.PartitionKey = key
	if key != "" {
		index := strings.Index(key, ".")
		if index != -1 {
			servlet.PartitionKey = key[:index]
		}
		server, _ := c.Get(servlet.PartitionKey)
		//fmt.Println("lookup node for key:"+cmd.PartitionKey+"->"+server)
		if server != hostname {
			fmt.Println("should never happen")
			//fmt.Println("forward to another node!")
			//Send(server,protodata)
		} else {
			requestChannel <- servlet
		}
	} else {
		requestChannel <- servlet
	}

	return nil
}
コード例 #2
0
func Execute(req *servlet.Servlet) {
	request := req.Command
	if request.Type.String() == "Get" {
		value := []string{kv[*request.Key]}
		response := protos.Response{
			Status: proto.Bool(true),
			Value:  value,
		}
		req.Response = &response
		responseChannel <- req
	}
	if request.Type.String() == "Set" {
		partitionKey := req.PartitionKey
		keys[partitionKey] = 1
		kv[*request.Key] = *request.Value
		response := protos.Response{
			Status: proto.Bool(true),
		}
		req.Response = &response
		responseChannel <- req
	}
	if request.Type.String() == "Add" {
		partitionKey := req.PartitionKey
		keys[partitionKey] = 1
		if kv[*request.Key] != "" && kv[*request.Key] != "0" {
			oper1, _ := strconv.ParseFloat(kv[*request.Key], 32)
			oper2, _ := strconv.ParseFloat(*request.Value, 32)
			sum := oper1 + oper2
			kv[*request.Key] = strconv.FormatFloat(sum, 'f', -1, 32)
		} else {
			kv[*request.Key] = *request.Value
		}
		response := protos.Response{
			Status: proto.Bool(true),
		}
		req.Response = &response
		responseChannel <- req
	}
	if request.Type.String() == "Iterate" {
		//一次取出所有的key吗?只取partitionKey
		response := protos.Response{
			Status: proto.Bool(true),
		}
		var iterate []string
		for k, _ := range keys {
			//			fmt.Println("key: "+k)
			iterate = append(iterate, k)
		}
		response.Value = iterate
		//fmt.Println("result:"+result)
		req.Response = &response
		responseChannel <- req
	}
	if request.Type.String() == "Flush" {
		if kv["Flush"] != "" && kv["Flush"] != "0" {
			sum, _ := strconv.Atoi(kv["Flush"])
			kv["Flush"] = strconv.Itoa(sum + 1)
		} else {
			kv["Flush"] = "1"
		}
		if kv["Flush"] == strconv.Itoa(len(servers)) {
			Accumulator()
			kv["Flush"] = "0"
		}
		response := protos.Response{
			Status: proto.Bool(true),
		}
		req.Response = &response
		responseChannel <- req
	}
}