Пример #1
0
void MyCacheWorker::run()
{
	LOG4CXX_INFO(logger, "[" << name_ << "] worker started");

	//  Tell backend we're ready for work
    socket_->send("READY", 5);

	while (!s_interrupted)
	{
		try 
		{
			//  Read and save all frames until we get an empty frame
	        //  In this example there is only 1 but it could be more
	       	zmq::message_t client_addr_msg;
	       	socket_->recv(&client_addr_msg);

	       	//  Empty Frame
	       	{
		       	zmq::message_t empty;
		       	socket_->recv(&empty);
	       	}
	  
	        //  Get request, send reply
	        zmq::message_t request;
	        socket_->recv(&request);

	        //std::cout << "Worker: " << (char*)request.data() << std::endl;

	        // Do the Request
	        std::string reply;
	    	uint64_t id = 0;
	    	uint8_t cmd = 0;
	    	std::string msgbody;
	    	std::string clientid((char*)client_addr_msg.data(), client_addr_msg.size());
	    	if (MyCache::parseBinMsg(request, id, cmd, msgbody))
	    	{
	    		#if 0
	    		LOG4CXX_INFO(logger, "[" << name_ << "] [" << clientid << "] " 
	    			<< (char)cmd << " : "
	    			<< id << " : " 
	    			<< msgbody.size());
	    		#endif

	    		MsgHandler* handler = MsgHandler::createByType(cmd);
				if (handler)
				{
					handler->worker = this;
					handler->doMsg(reply, msgbody);
					delete handler;
				}
	    	}
	    	else
	    	{
	    		LOG4CXX_WARN(logger, "[" << name_ << "] [" << clientid << "] " 
	    			<< (char)cmd << " : "
	    			<< id << " : parse msg failed");
	    	}

			//reply = "FUCKYOU";
			
			// Reply
			{
				zmq::message_t empty;
		        socket_->send(client_addr_msg, ZMQ_SNDMORE);
		        socket_->send(empty, ZMQ_SNDMORE);
		        
		        zmq::message_t replymsg;
		        MyCache::packBinMsg(replymsg, id, cmd, reply);
		        socket_->send(replymsg);
	    	}
		}
		catch(const std::exception& err)
		{
			LOG4CXX_ERROR(logger, "[" << name_ << "] worker error : " << err.what());
			break;
		}
	}

	LOG4CXX_INFO(logger, "[" << name_ << "] worker finished");

	delete this;
}