Support muti-thread compile in build.sh

Support muti-thread compile in build.sh
diff --git a/.clang-format b/.clang-format
index 9d807c3..7904cdf 100644
--- a/.clang-format
+++ b/.clang-format
@@ -1,7 +1,3 @@
 BasedOnStyle: Chromium
 ColumnLimit: 120
-IndentWidth: 4
-DerivePointerAlignment: false
-IndentCaseLabels: false
-PointerAlignment: Right
-SpaceAfterCStyleCast: true
+TabWidth: 2
diff --git a/CMakeLists.txt b/CMakeLists.txt
index e9d5ca2..b158f57 100755
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -33,7 +33,7 @@
 endif()
 
 # First, declare project (important for prerequisite checks).
-project(all)
+project(rocketmq-client-cpp)
 if(NOT CMAKE_BUILD_TYPE)
     set(CMAKE_BUILD_TYPE "Release")
 endif()
diff --git a/example/AsyncProducer.cpp b/example/AsyncProducer.cpp
old mode 100755
new mode 100644
index 3a5d0af..dae0459
--- a/example/AsyncProducer.cpp
+++ b/example/AsyncProducer.cpp
@@ -57,13 +57,10 @@
       g_finished.notify_one();
     }
   }
-  virtual void onException(MQException& e) {
-    std::cout << "send Exception" << e << "\n";
-  }
+  virtual void onException(MQException& e) { std::cout << "send Exception" << e << "\n"; }
 };
 
-void AsyncProducerWorker(RocketmqSendAndConsumerArgs* info,
-                         DefaultMQProducer* producer) {
+void AsyncProducerWorker(RocketmqSendAndConsumerArgs* info, DefaultMQProducer* producer) {
   while (!g_quit.load()) {
     if (g_msgCount.load() <= 0) {
       std::unique_lock<std::mutex> lck(g_mtx);
@@ -99,7 +96,8 @@
 
   PrintRocketmqSendAndConsumerArgs(info);
 
-  if (!info.namesrv.empty()) producer.setNamesrvAddr(info.namesrv);
+  if (!info.namesrv.empty())
+    producer.setNamesrvAddr(info.namesrv);
 
   producer.setGroupName(info.groupname);
   producer.setInstanceName(info.groupname);
@@ -110,8 +108,7 @@
   auto start = std::chrono::system_clock::now();
   int msgcount = g_msgCount.load();
   for (int j = 0; j < info.thread_count; j++) {
-    std::shared_ptr<std::thread> th =
-        std::make_shared<std::thread>(AsyncProducerWorker, &info, &producer);
+    std::shared_ptr<std::thread> th = std::make_shared<std::thread>(AsyncProducerWorker, &info, &producer);
     work_pool.push_back(th);
   }
 
@@ -122,12 +119,10 @@
   }
 
   auto end = std::chrono::system_clock::now();
-  auto duration =
-      std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
+  auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
 
-  std::cout
-      << "per msg time: " << duration.count() / (double)msgcount << "ms \n"
-      << "========================finished==============================\n";
+  std::cout << "per msg time: " << duration.count() / (double)msgcount << "ms \n"
+            << "========================finished==============================\n";
 
   producer.shutdown();
   for (size_t th = 0; th != work_pool.size(); ++th) {
diff --git a/example/AsyncPushConsumer.cpp b/example/AsyncPushConsumer.cpp
old mode 100755
new mode 100644
index 093d61d..9f0a955
--- a/example/AsyncPushConsumer.cpp
+++ b/example/AsyncPushConsumer.cpp
@@ -37,7 +37,7 @@
   MyMsgListener() {}
   virtual ~MyMsgListener() {}
 
-  virtual ConsumeStatus consumeMessage(const std::vector<MQMessageExt> &msgs) {
+  virtual ConsumeStatus consumeMessage(const std::vector<MQMessageExt>& msgs) {
     g_msgCount.store(g_msgCount.load() - msgs.size());
     for (size_t i = 0; i < msgs.size(); ++i) {
       g_tps.Increment();
@@ -51,7 +51,7 @@
   }
 };
 
-int main(int argc, char *argv[]) {
+int main(int argc, char* argv[]) {
   RocketmqSendAndConsumerArgs info;
   if (!ParseArgs(argc, argv, &info)) {
     exit(-1);
@@ -82,7 +82,7 @@
 
   try {
     consumer.start();
-  } catch (MQClientException &e) {
+  } catch (MQClientException& e) {
     cout << e << endl;
   }
   g_tps.start();
@@ -95,7 +95,7 @@
 
     try {
       producer.send(msg);
-    } catch (MQException &e) {
+    } catch (MQException& e) {
       std::cout << e << endl;  // if catch excepiton , need re-send this msg by
                                // service
     }
diff --git a/example/BatchProducer.cpp b/example/BatchProducer.cpp
index 3788422..d889ea9 100644
--- a/example/BatchProducer.cpp
+++ b/example/BatchProducer.cpp
@@ -34,97 +34,91 @@
 std::condition_variable g_finished;
 TpsReportService g_tps;
 
-void SyncProducerWorker(RocketmqSendAndConsumerArgs* info,
-                        DefaultMQProducer* producer) {
-    while (!g_quit.load()) {
-        if (g_msgCount.load() <= 0) {
-            std::unique_lock<std::mutex> lck(g_mtx);
-            g_finished.notify_one();
-            break;
-        }
-
-        vector<MQMessage> msgs;
-        MQMessage msg1(info->topic, "*", info->body);
-        msg1.setProperty("property1", "value1");
-        MQMessage msg2(info->topic, "*", info->body);
-        msg2.setProperty("property1", "value1");
-        msg2.setProperty("property2", "value2");
-        MQMessage msg3(info->topic, "*", info->body);
-        msg3.setProperty("property1", "value1");
-        msg3.setProperty("property2", "value2");
-        msg3.setProperty("property3", "value3");
-        msgs.push_back(msg1);
-        msgs.push_back(msg2);
-        msgs.push_back(msg3);
-        try {
-            auto start = std::chrono::system_clock::now();
-            SendResult sendResult = producer->send(msgs);
-            g_tps.Increment();
-            --g_msgCount;
-            auto end = std::chrono::system_clock::now();
-            auto duration =
-                    std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
-            if (duration.count() >= 500) {
-                std::cout << "send RT more than: " << duration.count()
-                          << " ms with msgid: " << sendResult.getMsgId() << endl;
-            }
-        } catch (const MQException& e) {
-            std::cout << "send failed: " << e.what() << std::endl;
-            std::unique_lock<std::mutex> lck(g_mtx);
-            g_finished.notify_one();
-            return;
-        }
+void SyncProducerWorker(RocketmqSendAndConsumerArgs* info, DefaultMQProducer* producer) {
+  while (!g_quit.load()) {
+    if (g_msgCount.load() <= 0) {
+      std::unique_lock<std::mutex> lck(g_mtx);
+      g_finished.notify_one();
+      break;
     }
+
+    vector<MQMessage> msgs;
+    MQMessage msg1(info->topic, "*", info->body);
+    msg1.setProperty("property1", "value1");
+    MQMessage msg2(info->topic, "*", info->body);
+    msg2.setProperty("property1", "value1");
+    msg2.setProperty("property2", "value2");
+    MQMessage msg3(info->topic, "*", info->body);
+    msg3.setProperty("property1", "value1");
+    msg3.setProperty("property2", "value2");
+    msg3.setProperty("property3", "value3");
+    msgs.push_back(msg1);
+    msgs.push_back(msg2);
+    msgs.push_back(msg3);
+    try {
+      auto start = std::chrono::system_clock::now();
+      SendResult sendResult = producer->send(msgs);
+      g_tps.Increment();
+      --g_msgCount;
+      auto end = std::chrono::system_clock::now();
+      auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
+      if (duration.count() >= 500) {
+        std::cout << "send RT more than: " << duration.count() << " ms with msgid: " << sendResult.getMsgId() << endl;
+      }
+    } catch (const MQException& e) {
+      std::cout << "send failed: " << e.what() << std::endl;
+      std::unique_lock<std::mutex> lck(g_mtx);
+      g_finished.notify_one();
+      return;
+    }
+  }
 }
 
 int main(int argc, char* argv[]) {
-    RocketmqSendAndConsumerArgs info;
-    if (!ParseArgs(argc, argv, &info)) {
-        exit(-1);
-    }
-    PrintRocketmqSendAndConsumerArgs(info);
-    DefaultMQProducer producer("please_rename_unique_group_name");
-    producer.setNamesrvAddr(info.namesrv);
-    producer.setNamesrvDomain(info.namesrv_domain);
-    producer.setGroupName(info.groupname);
-    producer.setInstanceName(info.groupname);
-    producer.setSessionCredentials("mq acesskey", "mq secretkey", "ALIYUN");
-    producer.setSendMsgTimeout(500);
-    producer.setTcpTransportTryLockTimeout(1000);
-    producer.setTcpTransportConnectTimeout(400);
+  RocketmqSendAndConsumerArgs info;
+  if (!ParseArgs(argc, argv, &info)) {
+    exit(-1);
+  }
+  PrintRocketmqSendAndConsumerArgs(info);
+  DefaultMQProducer producer("please_rename_unique_group_name");
+  producer.setNamesrvAddr(info.namesrv);
+  producer.setNamesrvDomain(info.namesrv_domain);
+  producer.setGroupName(info.groupname);
+  producer.setInstanceName(info.groupname);
+  producer.setSessionCredentials("mq acesskey", "mq secretkey", "ALIYUN");
+  producer.setSendMsgTimeout(500);
+  producer.setTcpTransportTryLockTimeout(1000);
+  producer.setTcpTransportConnectTimeout(400);
 
-    producer.start();
-    std::vector<std::shared_ptr<std::thread>> work_pool;
-    auto start = std::chrono::system_clock::now();
-    int msgcount = g_msgCount.load();
-    g_tps.start();
+  producer.start();
+  std::vector<std::shared_ptr<std::thread>> work_pool;
+  auto start = std::chrono::system_clock::now();
+  int msgcount = g_msgCount.load();
+  g_tps.start();
 
-    int threadCount = info.thread_count;
-    for (int j = 0; j < threadCount; j++) {
-        std::shared_ptr<std::thread> th =
-                std::make_shared<std::thread>(SyncProducerWorker, &info, &producer);
-        work_pool.push_back(th);
-    }
+  int threadCount = info.thread_count;
+  for (int j = 0; j < threadCount; j++) {
+    std::shared_ptr<std::thread> th = std::make_shared<std::thread>(SyncProducerWorker, &info, &producer);
+    work_pool.push_back(th);
+  }
 
-    {
-        std::unique_lock<std::mutex> lck(g_mtx);
-        g_finished.wait(lck);
-        g_quit.store(true);
-    }
+  {
+    std::unique_lock<std::mutex> lck(g_mtx);
+    g_finished.wait(lck);
+    g_quit.store(true);
+  }
 
-    auto end = std::chrono::system_clock::now();
-    auto duration =
-            std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
+  auto end = std::chrono::system_clock::now();
+  auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
 
-    std::cout
-            << "per msg time: " << duration.count() / (double)msgcount << "ms \n"
+  std::cout << "per msg time: " << duration.count() / (double)msgcount << "ms \n"
             << "========================finished==============================\n";
 
-    for (size_t th = 0; th != work_pool.size(); ++th) {
-        work_pool[th]->join();
-    }
+  for (size_t th = 0; th != work_pool.size(); ++th) {
+    work_pool[th]->join();
+  }
 
-    producer.shutdown();
+  producer.shutdown();
 
-    return 0;
+  return 0;
 }
diff --git a/example/CAsyncProducer.c b/example/CAsyncProducer.c
index db4a957..2d2af61 100644
--- a/example/CAsyncProducer.c
+++ b/example/CAsyncProducer.c
@@ -29,61 +29,60 @@
 
 void thread_sleep(unsigned milliseconds) {
 #ifdef _WIN32
-    Sleep(milliseconds);
+  Sleep(milliseconds);
 #else
-    usleep(milliseconds * 1000);  // takes microseconds
+  usleep(milliseconds * 1000);  // takes microseconds
 #endif
 }
 
-void SendSuccessCallback(CSendResult result){
-    printf("async send success, msgid:%s\n", result.msgId);
+void SendSuccessCallback(CSendResult result) {
+  printf("async send success, msgid:%s\n", result.msgId);
 }
 
-void SendExceptionCallback(CMQException e){
-    char msg[1024];
-    snprintf(msg, sizeof(msg), "error:%d, msg:%s, file:%s:%d", e.error, e.msg, e.file, e.line);
-    printf("async send exception %s\n", msg);
+void SendExceptionCallback(CMQException e) {
+  char msg[1024];
+  snprintf(msg, sizeof(msg), "error:%d, msg:%s, file:%s:%d", e.error, e.msg, e.file, e.line);
+  printf("async send exception %s\n", msg);
 }
 
-void StartSendMessage(CProducer *producer) {
-    int i = 0;
-    int ret_code = 0;
-    char body[128];
-    CMessage *msg = CreateMessage("T_TestTopic");
-    SetMessageTags(msg, "Test_Tag");
-    SetMessageKeys(msg, "Test_Keys");
-    for (i = 0; i < 10; i++) {
-        memset(body, 0, sizeof(body));
-        snprintf(body, sizeof(body), "new message body, index %d", i);
-        SetMessageBody(msg, body);
-        ret_code = SendMessageAsync(producer, msg, SendSuccessCallback , SendExceptionCallback);
-        printf("async send message[%d] return code: %d\n", i, ret_code);
-        thread_sleep(1000);
-    }
-    DestroyMessage(msg);
+void StartSendMessage(CProducer* producer) {
+  int i = 0;
+  int ret_code = 0;
+  char body[128];
+  CMessage* msg = CreateMessage("T_TestTopic");
+  SetMessageTags(msg, "Test_Tag");
+  SetMessageKeys(msg, "Test_Keys");
+  for (i = 0; i < 10; i++) {
+    memset(body, 0, sizeof(body));
+    snprintf(body, sizeof(body), "new message body, index %d", i);
+    SetMessageBody(msg, body);
+    ret_code = SendMessageAsync(producer, msg, SendSuccessCallback, SendExceptionCallback);
+    printf("async send message[%d] return code: %d\n", i, ret_code);
+    thread_sleep(1000);
+  }
+  DestroyMessage(msg);
 }
 
-void CreateProducerAndStartSendMessage(int i){
-    printf("Producer Initializing.....\n");
-    CProducer *producer = CreateProducer("Group_producer");
-    SetProducerNameServerAddress(producer, "127.0.0.1:9876");
-    if(i == 1){
-        SetProducerSendMsgTimeout(producer , 3);
-    }
-    StartProducer(producer);
-    printf("Producer start.....\n");
-    StartSendMessage(producer);
-    ShutdownProducer(producer);
-    DestroyProducer(producer);
-    printf("Producer Shutdown!\n");
+void CreateProducerAndStartSendMessage(int i) {
+  printf("Producer Initializing.....\n");
+  CProducer* producer = CreateProducer("Group_producer");
+  SetProducerNameServerAddress(producer, "127.0.0.1:9876");
+  if (i == 1) {
+    SetProducerSendMsgTimeout(producer, 3);
+  }
+  StartProducer(producer);
+  printf("Producer start.....\n");
+  StartSendMessage(producer);
+  ShutdownProducer(producer);
+  DestroyProducer(producer);
+  printf("Producer Shutdown!\n");
 }
 
-int main(int argc, char *argv[]) {
-    printf("Send Async successCallback.....\n");
-    CreateProducerAndStartSendMessage(0);
+int main(int argc, char* argv[]) {
+  printf("Send Async successCallback.....\n");
+  CreateProducerAndStartSendMessage(0);
 
-    printf("Send Async exceptionCallback.....\n");
-    CreateProducerAndStartSendMessage(1);
-    return 0;
+  printf("Send Async exceptionCallback.....\n");
+  CreateProducerAndStartSendMessage(1);
+  return 0;
 }
-
diff --git a/example/CBatchProducer.c b/example/CBatchProducer.c
new file mode 100644
index 0000000..32d6a7a
--- /dev/null
+++ b/example/CBatchProducer.c
@@ -0,0 +1,62 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdio.h>
+#include "CBatchMessage.h"
+#include "CCommon.h"
+#include "CMessage.h"
+#include "CProducer.h"
+#include "CSendResult.h"
+
+void StartSendMessage(CProducer* producer) {
+  int i = 0;
+  int ret_code = 0;
+  char body[128];
+  CBatchMessage* batchMessage = CreateBatchMessage("T_TestTopic");
+
+  for (i = 0; i < 10; i++) {
+    CMessage* msg = CreateMessage("T_TestTopic");
+    SetMessageTags(msg, "Test_Tag");
+    SetMessageKeys(msg, "Test_Keys");
+    memset(body, 0, sizeof(body));
+    snprintf(body, sizeof(body), "new message body, index %d", i);
+    SetMessageBody(msg, body);
+    AddMessage(batchMessage, msg);
+  }
+  CSendResult result;
+  int ok = SendBatchMessage(producer, batchMessage, &result);
+  printf("SendBatchMessage is %s .....\n", ok == 0 ? "Success" : ok == 11 ? "FAILED" : " It is null value");
+  DestroyBatchMessage(batchMessage);
+}
+
+void CreateProducerAndStartSendMessage() {
+  printf("Producer Initializing.....\n");
+  CProducer* producer = CreateProducer("Group_producer");
+  SetProducerNameServerAddress(producer, "127.0.0.1:9876");
+  StartProducer(producer);
+  printf("Producer start.....\n");
+  StartSendMessage(producer);
+  ShutdownProducer(producer);
+  DestroyProducer(producer);
+  printf("Producer Shutdown!\n");
+}
+
+int main(int argc, char* argv[]) {
+  printf("Send Batch.....\n");
+  CreateProducerAndStartSendMessage();
+  return 0;
+}
diff --git a/example/COrderlyAsyncProducer.c b/example/COrderlyAsyncProducer.c
index f841878..48a822c 100644
--- a/example/COrderlyAsyncProducer.c
+++ b/example/COrderlyAsyncProducer.c
@@ -29,68 +29,65 @@
 
 void thread_sleep(unsigned milliseconds) {
 #ifdef _WIN32
-    Sleep(milliseconds);
+  Sleep(milliseconds);
 #else
-    usleep(milliseconds * 1000);  // takes microseconds
+  usleep(milliseconds * 1000);  // takes microseconds
 #endif
 }
 
-void SendSuccessCallback(CSendResult result){
-    printf("async send success, msgid:%s\n", result.msgId);
+void SendSuccessCallback(CSendResult result) {
+  printf("async send success, msgid:%s\n", result.msgId);
 }
 
-void SendExceptionCallback(CMQException e){
-    char msg[1024];
-    snprintf(msg, sizeof(msg), "error:%d, msg:%s, file:%s:%d", e.error, e.msg, e.file, e.line);
-    printf("async send exception %s\n", msg);
+void SendExceptionCallback(CMQException e) {
+  char msg[1024];
+  snprintf(msg, sizeof(msg), "error:%d, msg:%s, file:%s:%d", e.error, e.msg, e.file, e.line);
+  printf("async send exception %s\n", msg);
 }
 
-int aQueueSelectorCallback(int size, CMessage *msg, void *arg){
-    return 0;
+int aQueueSelectorCallback(int size, CMessage* msg, void* arg) {
+  return 0;
 };
 
-void StartSendMessage(CProducer *producer) {
-    int i = 0;
-    int ret_code = 0;
-    char body[128];
-    CMessage *msg = CreateMessage("topic_COrderlyAsyncProducer");
-    SetMessageTags(msg, "Test_Tag");
-    SetMessageKeys(msg, "Test_Keys");
-    for (i = 0; i < 10; i++) {
-        memset(body, 0, sizeof(body));
-        snprintf(body, sizeof(body), "new message body, index %d", i);
-        SetMessageBody(msg, body);
-        ret_code = SendMessageOrderlyAsync(producer, msg,
-        aQueueSelectorCallback,
-        (void*)&i,
-         SendSuccessCallback , SendExceptionCallback);
-        printf("async send message[%d] return code: %d\n", i, ret_code);
-        thread_sleep(1000);
-    }
-    DestroyMessage(msg);
+void StartSendMessage(CProducer* producer) {
+  int i = 0;
+  int ret_code = 0;
+  char body[128];
+  CMessage* msg = CreateMessage("topic_COrderlyAsyncProducer");
+  SetMessageTags(msg, "Test_Tag");
+  SetMessageKeys(msg, "Test_Keys");
+  for (i = 0; i < 10; i++) {
+    memset(body, 0, sizeof(body));
+    snprintf(body, sizeof(body), "new message body, index %d", i);
+    SetMessageBody(msg, body);
+    ret_code = SendMessageOrderlyAsync(producer, msg, aQueueSelectorCallback, (void*)&i, SendSuccessCallback,
+                                       SendExceptionCallback);
+    printf("async send message[%d] return code: %d\n", i, ret_code);
+    thread_sleep(1000);
+  }
+  DestroyMessage(msg);
 }
 
-void CreateProducerAndStartSendMessage(int i){
-    printf("Producer Initializing.....\n");
-    CProducer *producer = CreateProducer("FooBarGroup1");
-    SetProducerNameServerAddress(producer, "192.168.0.149:9876");
-    if(i == 1){
-        SetProducerSendMsgTimeout(producer , 3);
-    }
-    StartProducer(producer);
-    printf("Producer start.....\n");
-    StartSendMessage(producer);
-    ShutdownProducer(producer);
-    DestroyProducer(producer);
-    printf("Producer Shutdown!\n");
+void CreateProducerAndStartSendMessage(int i) {
+  printf("Producer Initializing.....\n");
+  CProducer* producer = CreateProducer("FooBarGroup1");
+  SetProducerNameServerAddress(producer, "192.168.0.149:9876");
+  if (i == 1) {
+    SetProducerSendMsgTimeout(producer, 3);
+  }
+  StartProducer(producer);
+  printf("Producer start.....\n");
+  StartSendMessage(producer);
+  ShutdownProducer(producer);
+  DestroyProducer(producer);
+  printf("Producer Shutdown!\n");
 }
 
-int main(int argc, char *argv[]) {
-    printf("COrderlyAsyncProducer successCallback.....\n");
-    CreateProducerAndStartSendMessage(0);
+int main(int argc, char* argv[]) {
+  printf("COrderlyAsyncProducer successCallback.....\n");
+  CreateProducerAndStartSendMessage(0);
 
-    printf("COrderlyAsyncProducer exceptionCallback.....\n");
-    CreateProducerAndStartSendMessage(1);
-    return 0;
+  printf("COrderlyAsyncProducer exceptionCallback.....\n");
+  CreateProducerAndStartSendMessage(1);
+  return 0;
 }
-
diff --git a/example/OrderProducer.cpp b/example/OrderProducer.cpp
old mode 100755
new mode 100644
index ba46363..613add4
--- a/example/OrderProducer.cpp
+++ b/example/OrderProducer.cpp
@@ -34,9 +34,8 @@
 
 class SelectMessageQueueByHash : public MessageQueueSelector {
  public:
-  MQMessageQueue select(const std::vector<MQMessageQueue> &mqs,
-                        const MQMessage &msg, void *arg) {
-    int orderId = *static_cast<int *>(arg);
+  MQMessageQueue select(const std::vector<MQMessageQueue>& mqs, const MQMessage& msg, void* arg) {
+    int orderId = *static_cast<int*>(arg);
     int index = orderId % mqs.size();
     return mqs[index];
   }
@@ -44,8 +43,7 @@
 
 SelectMessageQueueByHash g_mySelector;
 
-void ProducerWorker(RocketmqSendAndConsumerArgs *info,
-                    DefaultMQProducer *producer) {
+void ProducerWorker(RocketmqSendAndConsumerArgs* info, DefaultMQProducer* producer) {
   while (!g_quit.load()) {
     if (g_msgCount.load() <= 0) {
       std::unique_lock<std::mutex> lck(g_mtx);
@@ -57,13 +55,12 @@
 
     int orderId = 1;
     SendResult sendResult =
-        producer->send(msg, &g_mySelector, static_cast<void *>(&orderId),
-                       info->retrytimes, info->SelectUnactiveBroker);
+        producer->send(msg, &g_mySelector, static_cast<void*>(&orderId), info->retrytimes, info->SelectUnactiveBroker);
     --g_msgCount;
   }
 }
 
-int main(int argc, char *argv[]) {
+int main(int argc, char* argv[]) {
   RocketmqSendAndConsumerArgs info;
   if (!ParseArgs(argc, argv, &info)) {
     exit(-1);
@@ -84,8 +81,7 @@
 
   int threadCount = info.thread_count;
   for (int j = 0; j < threadCount; j++) {
-    std::shared_ptr<std::thread> th =
-        std::make_shared<std::thread>(ProducerWorker, &info, &producer);
+    std::shared_ptr<std::thread> th = std::make_shared<std::thread>(ProducerWorker, &info, &producer);
     work_pool.push_back(th);
   }
 
@@ -97,12 +93,10 @@
   }
 
   auto end = std::chrono::system_clock::now();
-  auto duration =
-      std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
+  auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
 
-  std::cout
-      << "per msg time: " << duration.count() / (double)msgcount << "ms \n"
-      << "========================finished==============================\n";
+  std::cout << "per msg time: " << duration.count() / (double)msgcount << "ms \n"
+            << "========================finished==============================\n";
 
   for (size_t th = 0; th != work_pool.size(); ++th) {
     work_pool[th]->join();
diff --git a/example/OrderlyPushConsumer.cpp b/example/OrderlyPushConsumer.cpp
old mode 100755
new mode 100644
index 81ad533..c8a9eaa
--- a/example/OrderlyPushConsumer.cpp
+++ b/example/OrderlyPushConsumer.cpp
@@ -40,7 +40,7 @@
   MyMsgListener() {}
   virtual ~MyMsgListener() {}
 
-  virtual ConsumeStatus consumeMessage(const vector<MQMessageExt> &msgs) {
+  virtual ConsumeStatus consumeMessage(const vector<MQMessageExt>& msgs) {
     if (g_consumedCount.load() >= g_msgCount) {
       std::unique_lock<std::mutex> lK(g_mtx);
       g_quit.store(true);
@@ -54,7 +54,7 @@
   }
 };
 
-int main(int argc, char *argv[]) {
+int main(int argc, char* argv[]) {
   RocketmqSendAndConsumerArgs info;
   if (!ParseArgs(argc, argv, &info)) {
     exit(-1);
@@ -74,7 +74,8 @@
   consumer.subscribe(info.topic, "*");
   consumer.setConsumeThreadCount(info.thread_count);
   consumer.setConsumeMessageBatchMaxSize(31);
-  if (info.syncpush) consumer.setAsyncPull(false);
+  if (info.syncpush)
+    consumer.setAsyncPull(false);
 
   MyMsgListener msglistener;
   consumer.registerMessageListener(&msglistener);
@@ -82,7 +83,7 @@
 
   try {
     consumer.start();
-  } catch (MQClientException &e) {
+  } catch (MQClientException& e) {
     std::cout << e << std::endl;
   }
 
@@ -94,7 +95,7 @@
 
     try {
       producer.send(msg);
-    } catch (MQException &e) {
+    } catch (MQException& e) {
       std::cout << e << endl;  // if catch excepiton , need re-send this msg by
                                // service
     }
diff --git a/example/Producer.c b/example/Producer.c
index cfffd77..d2ec426 100644
--- a/example/Producer.c
+++ b/example/Producer.c
@@ -29,40 +29,39 @@
 
 void thread_sleep(unsigned milliseconds) {
 #ifdef _WIN32
-    Sleep(milliseconds);
+  Sleep(milliseconds);
 #else
-    usleep(milliseconds * 1000);  // takes microseconds
+  usleep(milliseconds * 1000);  // takes microseconds
 #endif
 }
 
-void StartSendMessage(CProducer *producer) {
-    int i = 0;
-    char body[256];
-    CMessage *msg = CreateMessage("T_TestTopic");
-    SetMessageTags(msg, "Test_Tag");
-    SetMessageKeys(msg, "Test_Keys");
-    CSendResult result;
-    for (i = 0; i < 10; i++) {
-        memset(body, 0, sizeof(body));
-        snprintf(body, sizeof(body), "new message body, index %d", i);
-        SetMessageBody(msg, body);
-        SendMessageSync(producer, msg, &result);
-        printf("send message[%d] result status:%d, msgId:%s\n", i, (int)result.sendStatus, result.msgId);
-        thread_sleep(1000);
-    }
-    DestroyMessage(msg);
+void StartSendMessage(CProducer* producer) {
+  int i = 0;
+  char body[256];
+  CMessage* msg = CreateMessage("T_TestTopic");
+  SetMessageTags(msg, "Test_Tag");
+  SetMessageKeys(msg, "Test_Keys");
+  CSendResult result;
+  for (i = 0; i < 10; i++) {
+    memset(body, 0, sizeof(body));
+    snprintf(body, sizeof(body), "new message body, index %d", i);
+    SetMessageBody(msg, body);
+    SendMessageSync(producer, msg, &result);
+    printf("send message[%d] result status:%d, msgId:%s\n", i, (int)result.sendStatus, result.msgId);
+    thread_sleep(1000);
+  }
+  DestroyMessage(msg);
 }
 
-int main(int argc, char *argv[]) {
-    printf("Producer Initializing.....\n");
-    CProducer *producer = CreateProducer("Group_producer");
-    SetProducerNameServerAddress(producer, "127.0.0.1:9876");
-    StartProducer(producer);
-    printf("Producer start.....\n");
-    StartSendMessage(producer);
-    ShutdownProducer(producer);
-    DestroyProducer(producer);
-    printf("Producer Shutdown!\n");
-    return 0;
+int main(int argc, char* argv[]) {
+  printf("Producer Initializing.....\n");
+  CProducer* producer = CreateProducer("Group_producer");
+  SetProducerNameServerAddress(producer, "127.0.0.1:9876");
+  StartProducer(producer);
+  printf("Producer start.....\n");
+  StartSendMessage(producer);
+  ShutdownProducer(producer);
+  DestroyProducer(producer);
+  printf("Producer Shutdown!\n");
+  return 0;
 }
-
diff --git a/example/PullConsumeMessage.c b/example/PullConsumeMessage.c
index 657370f..0868d08 100644
--- a/example/PullConsumeMessage.c
+++ b/example/PullConsumeMessage.c
@@ -30,65 +30,66 @@
 
 void thread_sleep(unsigned milliseconds) {
 #ifdef _WIN32
-    Sleep(milliseconds);
+  Sleep(milliseconds);
 #else
-    usleep(milliseconds * 1000);  // takes microseconds
+  usleep(milliseconds * 1000);  // takes microseconds
 #endif
 }
 
-int main(int argc, char *argv[]) {
-    int i = 0, j = 0;
-    int ret = 0;
-    int size = 0;
-    CMessageQueue *mqs = NULL;
-    printf("PullConsumer Initializing....\n");
-    CPullConsumer *consumer = CreatePullConsumer("Group_Consumer_Test");
-    SetPullConsumerNameServerAddress(consumer, "172.17.0.2:9876");
-    StartPullConsumer(consumer);
-    printf("Pull Consumer Start...\n");
-    for (i = 1; i <= 5; i++) {
-        printf("FetchSubscriptionMessageQueues : %d times\n", i);
-        ret = FetchSubscriptionMessageQueues(consumer, "T_TestTopic", &mqs, &size);
-        if(ret != OK) {
-            printf("Get MQ Queue Failed,ErrorCode:%d\n", ret);
-        }
-        printf("Get MQ Size:%d\n", size);
-        for (j = 0; j < size; j++) {
-            int noNewMsg = 0;
-            long long tmpoffset = 0;
-            printf("Pull Message For Topic:%s,Queue:%s,QueueId:%d\n", mqs[j].topic, mqs[j].brokerName, mqs[j].queueId);
-            do {
-                int k = 0;
-                CPullResult pullResult = Pull(consumer, &mqs[j], "*", tmpoffset, 32);
-                if (pullResult.pullStatus != E_BROKER_TIMEOUT) {
-                    tmpoffset = pullResult.nextBeginOffset;
-                }
-                printf("PullStatus:%d,MaxOffset:%lld,MinOffset:%lld,NextBegainOffset:%lld", pullResult.pullStatus,
-                       pullResult.maxOffset, pullResult.minOffset, pullResult.nextBeginOffset);
-                switch (pullResult.pullStatus) {
-                    case E_FOUND:
-                        printf("Get Message Size:%d\n", pullResult.size);
-                        for (k = 0; k < pullResult.size; ++k) {
-                            printf("Got Message ID:%s,Body:%s\n", GetMessageId(pullResult.msgFoundList[k]),GetMessageBody(pullResult.msgFoundList[k]));
-                        }
-                        break;
-                    case E_NO_MATCHED_MSG:
-                        noNewMsg = 1;
-                        break;
-                    default:
-                        noNewMsg = 0;
-                }
-                ReleasePullResult(pullResult);
-                thread_sleep(100);
-            } while (noNewMsg == 0);
-            thread_sleep(1000);
-        }
-        thread_sleep(2000);
-        ReleaseSubscriptionMessageQueue(mqs);
+int main(int argc, char* argv[]) {
+  int i = 0, j = 0;
+  int ret = 0;
+  int size = 0;
+  CMessageQueue* mqs = NULL;
+  printf("PullConsumer Initializing....\n");
+  CPullConsumer* consumer = CreatePullConsumer("Group_Consumer_Test");
+  SetPullConsumerNameServerAddress(consumer, "172.17.0.2:9876");
+  StartPullConsumer(consumer);
+  printf("Pull Consumer Start...\n");
+  for (i = 1; i <= 5; i++) {
+    printf("FetchSubscriptionMessageQueues : %d times\n", i);
+    ret = FetchSubscriptionMessageQueues(consumer, "T_TestTopic", &mqs, &size);
+    if (ret != OK) {
+      printf("Get MQ Queue Failed,ErrorCode:%d\n", ret);
     }
-    thread_sleep(5000);
-    ShutdownPullConsumer(consumer);
-    DestroyPullConsumer(consumer);
-    printf("PullConsumer Shutdown!\n");
-    return 0;
+    printf("Get MQ Size:%d\n", size);
+    for (j = 0; j < size; j++) {
+      int noNewMsg = 0;
+      long long tmpoffset = 0;
+      printf("Pull Message For Topic:%s,Queue:%s,QueueId:%d\n", mqs[j].topic, mqs[j].brokerName, mqs[j].queueId);
+      do {
+        int k = 0;
+        CPullResult pullResult = Pull(consumer, &mqs[j], "*", tmpoffset, 32);
+        if (pullResult.pullStatus != E_BROKER_TIMEOUT) {
+          tmpoffset = pullResult.nextBeginOffset;
+        }
+        printf("PullStatus:%d,MaxOffset:%lld,MinOffset:%lld,NextBegainOffset:%lld", pullResult.pullStatus,
+               pullResult.maxOffset, pullResult.minOffset, pullResult.nextBeginOffset);
+        switch (pullResult.pullStatus) {
+          case E_FOUND:
+            printf("Get Message Size:%d\n", pullResult.size);
+            for (k = 0; k < pullResult.size; ++k) {
+              printf("Got Message ID:%s,Body:%s\n", GetMessageId(pullResult.msgFoundList[k]),
+                     GetMessageBody(pullResult.msgFoundList[k]));
+            }
+            break;
+          case E_NO_MATCHED_MSG:
+            noNewMsg = 1;
+            break;
+          default:
+            noNewMsg = 0;
+        }
+        ReleasePullResult(pullResult);
+        thread_sleep(100);
+      } while (noNewMsg == 0);
+      thread_sleep(1000);
+    }
+    thread_sleep(2000);
+    ReleaseSubscriptionMessageQueue(mqs);
+  }
+  thread_sleep(5000);
+  ShutdownPullConsumer(consumer);
+  DestroyPullConsumer(consumer);
+  printf("PullConsumer Shutdown!\n");
+  return 0;
 }
diff --git a/example/PullConsumer.cpp b/example/PullConsumer.cpp
old mode 100755
new mode 100644
index 857ed74..52e9094
--- a/example/PullConsumer.cpp
+++ b/example/PullConsumer.cpp
@@ -42,7 +42,7 @@
   return 0;
 }
 
-int main(int argc, char *argv[]) {
+int main(int argc, char* argv[]) {
   RocketmqSendAndConsumerArgs info;
   if (!ParseArgs(argc, argv, &info)) {
     exit(-1);
@@ -63,7 +63,7 @@
     for (; iter != mqs.end(); ++iter) {
       std::cout << "mq:" << (*iter).toString() << endl;
     }
-  } catch (MQException &e) {
+  } catch (MQException& e) {
     std::cout << e << endl;
   }
 
@@ -79,8 +79,7 @@
     bool noNewMsg = false;
     do {
       try {
-        PullResult result =
-            consumer.pull(mq, "*", getMessageQueueOffset(mq), 32);
+        PullResult result = consumer.pull(mq, "*", getMessageQueueOffset(mq), 32);
         g_msgCount += result.msgFoundList.size();
         std::cout << result.msgFoundList.size() << std::endl;
         // if pull request timeout or received NULL response, pullStatus will be
@@ -104,21 +103,18 @@
           default:
             break;
         }
-      } catch (MQClientException &e) {
+      } catch (MQClientException& e) {
         std::cout << e << std::endl;
       }
     } while (!noNewMsg);
   }
 
   auto end = std::chrono::system_clock::now();
-  auto duration =
-      std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
+  auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
 
   std::cout << "msg count: " << g_msgCount.load() << "\n";
-  std::cout
-      << "per msg time: " << duration.count() / (double)g_msgCount.load()
-      << "ms \n"
-      << "========================finished==============================\n";
+  std::cout << "per msg time: " << duration.count() / (double)g_msgCount.load() << "ms \n"
+            << "========================finished==============================\n";
 
   consumer.shutdown();
   return 0;
diff --git a/example/PushConsumeMessage.c b/example/PushConsumeMessage.c
index 81bcbc1..2cb9c3f 100644
--- a/example/PushConsumeMessage.c
+++ b/example/PushConsumeMessage.c
@@ -28,36 +28,36 @@
 
 void thread_sleep(unsigned milliseconds) {
 #ifdef _WIN32
-    Sleep(milliseconds);
+  Sleep(milliseconds);
 #else
-    usleep(milliseconds * 1000);  // takes microseconds
+  usleep(milliseconds * 1000);  // takes microseconds
 #endif
 }
 
-int doConsumeMessage(struct CPushConsumer *consumer, CMessageExt *msgExt) {
-    printf("Hello,doConsumeMessage by Application!\n");
-    printf("Msg Topic:%s\n", GetMessageTopic(msgExt));
-    printf("Msg Tags:%s\n", GetMessageTags(msgExt));
-    printf("Msg Keys:%s\n", GetMessageKeys(msgExt));
-    printf("Msg Body:%s\n", GetMessageBody(msgExt));
-    return E_CONSUME_SUCCESS;
+int doConsumeMessage(struct CPushConsumer* consumer, CMessageExt* msgExt) {
+  printf("Hello,doConsumeMessage by Application!\n");
+  printf("Msg Topic:%s\n", GetMessageTopic(msgExt));
+  printf("Msg Tags:%s\n", GetMessageTags(msgExt));
+  printf("Msg Keys:%s\n", GetMessageKeys(msgExt));
+  printf("Msg Body:%s\n", GetMessageBody(msgExt));
+  return E_CONSUME_SUCCESS;
 }
 
-int main(int argc, char *argv[]) {
-    int i = 0;
-    printf("PushConsumer Initializing....\n");
-    CPushConsumer *consumer = CreatePushConsumer("Group_Consumer_Test");
-    SetPushConsumerNameServerAddress(consumer, "172.17.0.2:9876");
-    Subscribe(consumer, "T_TestTopic", "*");
-    RegisterMessageCallback(consumer, doConsumeMessage);
-    StartPushConsumer(consumer);
-    printf("Push Consumer Start...\n");
-    for (i = 0; i < 10; i++) {
-        printf("Now Running : %d S\n", i * 10);
-        thread_sleep(10000);
-    }
-    ShutdownPushConsumer(consumer);
-    DestroyPushConsumer(consumer);
-    printf("PushConsumer Shutdown!\n");
-    return 0;
+int main(int argc, char* argv[]) {
+  int i = 0;
+  printf("PushConsumer Initializing....\n");
+  CPushConsumer* consumer = CreatePushConsumer("Group_Consumer_Test");
+  SetPushConsumerNameServerAddress(consumer, "172.17.0.2:9876");
+  Subscribe(consumer, "T_TestTopic", "*");
+  RegisterMessageCallback(consumer, doConsumeMessage);
+  StartPushConsumer(consumer);
+  printf("Push Consumer Start...\n");
+  for (i = 0; i < 10; i++) {
+    printf("Now Running : %d S\n", i * 10);
+    thread_sleep(10000);
+  }
+  ShutdownPushConsumer(consumer);
+  DestroyPushConsumer(consumer);
+  printf("PushConsumer Shutdown!\n");
+  return 0;
 }
diff --git a/example/PushConsumer.cpp b/example/PushConsumer.cpp
old mode 100755
new mode 100644
index 119b7f2..f0d4926
--- a/example/PushConsumer.cpp
+++ b/example/PushConsumer.cpp
@@ -39,7 +39,7 @@
   MyMsgListener() {}
   virtual ~MyMsgListener() {}
 
-  virtual ConsumeStatus consumeMessage(const std::vector<MQMessageExt> &msgs) {
+  virtual ConsumeStatus consumeMessage(const std::vector<MQMessageExt>& msgs) {
     g_msgCount.store(g_msgCount.load() - msgs.size());
     for (size_t i = 0; i < msgs.size(); ++i) {
       g_tps.Increment();
@@ -54,7 +54,7 @@
   }
 };
 
-int main(int argc, char *argv[]) {
+int main(int argc, char* argv[]) {
   RocketmqSendAndConsumerArgs info;
   if (!ParseArgs(argc, argv, &info)) {
     exit(-1);
@@ -62,8 +62,7 @@
   PrintRocketmqSendAndConsumerArgs(info);
   DefaultMQPushConsumer consumer("please_rename_unique_group_name");
   DefaultMQProducer producer("please_rename_unique_group_name");
-  producer.setSessionCredentials("AccessKey",
-                                 "SecretKey", "ALIYUN");
+  producer.setSessionCredentials("AccessKey", "SecretKey", "ALIYUN");
   producer.setTcpTransportTryLockTimeout(1000);
   producer.setTcpTransportConnectTimeout(400);
   producer.setNamesrvDomain(info.namesrv_domain);
@@ -73,13 +72,13 @@
 
   consumer.setNamesrvAddr(info.namesrv);
   consumer.setGroupName(info.groupname);
-  consumer.setSessionCredentials("AccessKey",
-                                 "SecretKey", "ALIYUN");
+  consumer.setSessionCredentials("AccessKey", "SecretKey", "ALIYUN");
   consumer.setConsumeThreadCount(info.thread_count);
   consumer.setNamesrvDomain(info.namesrv_domain);
   consumer.setConsumeFromWhere(CONSUME_FROM_LAST_OFFSET);
 
-  if (info.syncpush) consumer.setAsyncPull(false);  // set sync pull
+  if (info.syncpush)
+    consumer.setAsyncPull(false);  // set sync pull
   if (info.broadcasting) {
     consumer.setMessageModel(rocketmq::BROADCASTING);
   }
@@ -96,7 +95,7 @@
 
   try {
     consumer.start();
-  } catch (MQClientException &e) {
+  } catch (MQClientException& e) {
     cout << e << endl;
   }
   g_tps.start();
@@ -110,7 +109,7 @@
     //    std::this_thread::sleep_for(std::chrono::seconds(100000));
     try {
       producer.send(msg);
-    } catch (MQException &e) {
+    } catch (MQException& e) {
       std::cout << e << endl;  // if catch excepiton , need re-send this msg by
                                // service
     }
diff --git a/example/PushConsumerOrderly.c b/example/PushConsumerOrderly.c
index 63ca527..4b2c2bb 100644
--- a/example/PushConsumerOrderly.c
+++ b/example/PushConsumerOrderly.c
@@ -22,35 +22,30 @@
 #include "CCommon.h"
 #include "CMessageExt.h"
 
-
-int doConsumeMessage(struct CPushConsumer * consumer, CMessageExt * msgExt)
-{
-    printf("Hello,doConsumeMessage by Application!\n");
-    printf("Msg Topic:%s\n",GetMessageTopic(msgExt));
-    printf("Msg Tags:%s\n",GetMessageTags(msgExt));
-    printf("Msg Keys:%s\n",GetMessageKeys(msgExt));
-    printf("Msg Body:%s\n",GetMessageBody(msgExt));
-    return E_CONSUME_SUCCESS;
+int doConsumeMessage(struct CPushConsumer* consumer, CMessageExt* msgExt) {
+  printf("Hello,doConsumeMessage by Application!\n");
+  printf("Msg Topic:%s\n", GetMessageTopic(msgExt));
+  printf("Msg Tags:%s\n", GetMessageTags(msgExt));
+  printf("Msg Keys:%s\n", GetMessageKeys(msgExt));
+  printf("Msg Body:%s\n", GetMessageBody(msgExt));
+  return E_CONSUME_SUCCESS;
 }
 
-
-int main(int argc,char * argv [])
-{
-    int i = 0;
-    printf("PushConsumer Initializing....\n");
-    CPushConsumer* consumer = CreatePushConsumer("Group_Consumer_Test");
-    SetPushConsumerNameServerAddress(consumer,"127.0.0.1:9876");
-    Subscribe(consumer,"test","*");
-    RegisterMessageCallbackOrderly(consumer,doConsumeMessage);
-    StartPushConsumer(consumer);
-    printf("Push Consumer Start...\n");
-    for( i=0; i<10; i++)
-    {
-        printf("Now Running : %d S\n",i*10);
-        sleep(10);
-    }
-    ShutdownPushConsumer(consumer);
-    DestroyPushConsumer(consumer);
-    printf("PushConsumer Shutdown!\n");
-    return 0;
+int main(int argc, char* argv[]) {
+  int i = 0;
+  printf("PushConsumer Initializing....\n");
+  CPushConsumer* consumer = CreatePushConsumer("Group_Consumer_Test");
+  SetPushConsumerNameServerAddress(consumer, "127.0.0.1:9876");
+  Subscribe(consumer, "test", "*");
+  RegisterMessageCallbackOrderly(consumer, doConsumeMessage);
+  StartPushConsumer(consumer);
+  printf("Push Consumer Start...\n");
+  for (i = 0; i < 10; i++) {
+    printf("Now Running : %d S\n", i * 10);
+    sleep(10);
+  }
+  ShutdownPushConsumer(consumer);
+  DestroyPushConsumer(consumer);
+  printf("PushConsumer Shutdown!\n");
+  return 0;
 }
diff --git a/example/SendDelayMsg.cpp b/example/SendDelayMsg.cpp
old mode 100755
new mode 100644
diff --git a/example/SyncProducer.cpp b/example/SyncProducer.cpp
old mode 100755
new mode 100644
index f5682a6..0edb6dc
--- a/example/SyncProducer.cpp
+++ b/example/SyncProducer.cpp
@@ -35,8 +35,7 @@
 std::condition_variable g_finished;
 TpsReportService g_tps;
 
-void SyncProducerWorker(RocketmqSendAndConsumerArgs* info,
-                        DefaultMQProducer* producer) {
+void SyncProducerWorker(RocketmqSendAndConsumerArgs* info, DefaultMQProducer* producer) {
   while (!g_quit.load()) {
     if (g_msgCount.load() <= 0) {
       std::unique_lock<std::mutex> lck(g_mtx);
@@ -51,11 +50,9 @@
       g_tps.Increment();
       --g_msgCount;
       auto end = std::chrono::system_clock::now();
-      auto duration =
-          std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
+      auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
       if (duration.count() >= 500) {
-        std::cout << "send RT more than: " << duration.count()
-                  << " ms with msgid: " << sendResult.getMsgId() << endl;
+        std::cout << "send RT more than: " << duration.count() << " ms with msgid: " << sendResult.getMsgId() << endl;
       }
     } catch (const MQException& e) {
       std::cout << "send failed: " << std::endl;
@@ -87,8 +84,7 @@
 
   int threadCount = info.thread_count;
   for (int j = 0; j < threadCount; j++) {
-    std::shared_ptr<std::thread> th =
-        std::make_shared<std::thread>(SyncProducerWorker, &info, &producer);
+    std::shared_ptr<std::thread> th = std::make_shared<std::thread>(SyncProducerWorker, &info, &producer);
     work_pool.push_back(th);
   }
 
@@ -99,12 +95,10 @@
   }
 
   auto end = std::chrono::system_clock::now();
-  auto duration =
-      std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
+  auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
 
-  std::cout
-      << "per msg time: " << duration.count() / (double)msgcount << "ms \n"
-      << "========================finished==============================\n";
+  std::cout << "per msg time: " << duration.count() / (double)msgcount << "ms \n"
+            << "========================finished==============================\n";
 
   for (size_t th = 0; th != work_pool.size(); ++th) {
     work_pool[th]->join();
diff --git a/example/TransactionProducer.cpp b/example/TransactionProducer.cpp
new file mode 100644
index 0000000..1aabb08
--- /dev/null
+++ b/example/TransactionProducer.cpp
@@ -0,0 +1,135 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <atomic>
+#include <condition_variable>
+#include <iomanip>
+#include <iostream>
+#include <mutex>
+#include <thread>
+#include "TransactionListener.h"
+#include "TransactionMQProducer.h"
+#include "TransactionSendResult.h"
+#include "common.h"
+
+using namespace rocketmq;
+
+std::atomic<bool> g_quit;
+std::mutex g_mtx;
+std::condition_variable g_finished;
+TpsReportService g_tps;
+
+class MyTransactionListener : public TransactionListener {
+  virtual LocalTransactionState executeLocalTransaction(const MQMessage& msg, void* arg) {
+    if (!arg) {
+      std::cout << "executeLocalTransaction transactionId:" << msg.getTransactionId()
+                << ", return state: COMMIT_MESAGE " << endl;
+      return LocalTransactionState::COMMIT_MESSAGE;
+    }
+
+    LocalTransactionState state = (LocalTransactionState)(*(int*)arg % 3);
+    std::cout << "executeLocalTransaction transactionId:" << msg.getTransactionId() << ", return state: " << state
+              << endl;
+    return state;
+  }
+
+  virtual LocalTransactionState checkLocalTransaction(const MQMessageExt& msg) {
+    std::cout << "checkLocalTransaction enter msg:" << msg.toString() << endl;
+    return LocalTransactionState::COMMIT_MESSAGE;
+  }
+};
+
+void SyncProducerWorker(RocketmqSendAndConsumerArgs* info, TransactionMQProducer* producer) {
+  while (!g_quit.load()) {
+    if (g_msgCount.load() <= 0) {
+      std::this_thread::sleep_for(std::chrono::seconds(60));
+      std::unique_lock<std::mutex> lck(g_mtx);
+      g_finished.notify_one();
+      break;
+    }
+
+    MQMessage msg(info->topic,  // topic
+                  "*",          // tag
+                  info->body);  // body
+    try {
+      auto start = std::chrono::system_clock::now();
+      std::cout << "before sendMessageInTransaction" << endl;
+      LocalTransactionState state = LocalTransactionState::UNKNOWN;
+      TransactionSendResult sendResult = producer->sendMessageInTransaction(msg, &state);
+      std::cout << "after sendMessageInTransaction msgId: " << sendResult.getMsgId() << endl;
+      g_tps.Increment();
+      --g_msgCount;
+      auto end = std::chrono::system_clock::now();
+      auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
+      if (duration.count() >= 500) {
+        std::cout << "send RT more than: " << duration.count() << " ms with msgid: " << sendResult.getMsgId() << endl;
+      }
+    } catch (const MQException& e) {
+      std::cout << "send failed: " << e.what() << std::endl;
+    }
+  }
+}
+
+int main(int argc, char* argv[]) {
+  RocketmqSendAndConsumerArgs info;
+  if (!ParseArgs(argc, argv, &info)) {
+    exit(-1);
+  }
+  PrintRocketmqSendAndConsumerArgs(info);
+  TransactionMQProducer producer("please_rename_unique_group_name");
+  producer.setNamesrvAddr(info.namesrv);
+  producer.setNamesrvDomain(info.namesrv_domain);
+  producer.setGroupName(info.groupname);
+  producer.setInstanceName(info.groupname);
+  producer.setSessionCredentials("mq acesskey", "mq secretkey", "ALIYUN");
+  producer.setSendMsgTimeout(500);
+  producer.setTcpTransportTryLockTimeout(1000);
+  producer.setTcpTransportConnectTimeout(400);
+  producer.setLogLevel(eLOG_LEVEL_DEBUG);
+  producer.setTransactionListener(new MyTransactionListener());
+  producer.start();
+  std::vector<std::shared_ptr<std::thread>> work_pool;
+  auto start = std::chrono::system_clock::now();
+  int msgcount = g_msgCount.load();
+  g_tps.start();
+
+  int threadCount = info.thread_count;
+  for (int j = 0; j < threadCount; j++) {
+    std::shared_ptr<std::thread> th = std::make_shared<std::thread>(SyncProducerWorker, &info, &producer);
+    work_pool.push_back(th);
+  }
+
+  {
+    std::unique_lock<std::mutex> lck(g_mtx);
+    g_finished.wait(lck);
+    g_quit.store(true);
+  }
+
+  auto end = std::chrono::system_clock::now();
+  auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
+
+  std::cout << "per msg time: " << duration.count() / (double)msgcount << "ms \n"
+            << "========================finished==============================\n";
+
+  for (size_t th = 0; th != work_pool.size(); ++th) {
+    work_pool[th]->join();
+  }
+
+  producer.shutdown();
+
+  return 0;
+}
diff --git a/example/common.h b/example/common.h
old mode 100755
new mode 100644
index 21d2ba0..5b674c3
--- a/example/common.h
+++ b/example/common.h
@@ -66,20 +66,20 @@
   TpsReportService() : tps_interval_(1), quit_flag_(false), tps_count_(0) {}
   void start() {
     if (tps_thread_ == NULL) {
-        std::cout << "tps_thread_ is null" << std::endl;
-        return;
+      std::cout << "tps_thread_ is null" << std::endl;
+      return;
     }
-    tps_thread_.reset(
-        new boost::thread(boost::bind(&TpsReportService::TpsReport, this)));
+    tps_thread_.reset(new boost::thread(boost::bind(&TpsReportService::TpsReport, this)));
   }
 
   ~TpsReportService() {
     quit_flag_.store(true);
     if (tps_thread_ == NULL) {
-        std::cout << "tps_thread_ is null" << std::endl;
-        return;
+      std::cout << "tps_thread_ is null" << std::endl;
+      return;
     }
-    if (tps_thread_->joinable()) tps_thread_->join();
+    if (tps_thread_->joinable())
+      tps_thread_->join();
   }
 
   void Increment() { ++tps_count_; }
@@ -112,17 +112,14 @@
   std::cout << result->toString() << std::endl;
   if (result->pullStatus == rocketmq::FOUND) {
     std::cout << result->toString() << endl;
-    std::vector<rocketmq::MQMessageExt>::iterator it =
-        result->msgFoundList.begin();
+    std::vector<rocketmq::MQMessageExt>::iterator it = result->msgFoundList.begin();
     for (; it != result->msgFoundList.end(); ++it) {
-      cout << "=======================================================" << endl
-           << (*it).toString() << endl;
+      cout << "=======================================================" << endl << (*it).toString() << endl;
     }
   }
 }
 
-static void PrintRocketmqSendAndConsumerArgs(
-    const RocketmqSendAndConsumerArgs& info) {
+static void PrintRocketmqSendAndConsumerArgs(const RocketmqSendAndConsumerArgs& info) {
   std::cout << "nameserver: " << info.namesrv << endl
             << "topic: " << info.topic << endl
             << "groupname: " << info.groupname << endl
@@ -132,27 +129,25 @@
 }
 
 static void help() {
-  std::cout
-      << "need option,like follow: \n"
-      << "-n nameserver addr, if not set -n and -i ,no nameSrv will be got \n"
-         "-i nameserver domain name,  if not set -n and -i ,no nameSrv will be "
-         "got \n"
-         "-g groupname \n"
-         "-t  msg topic \n"
-         "-m messagecout(default value: 1) \n"
-         "-c content(default value: only test ) \n"
-         "-b (BROADCASTING model, default value: CLUSTER) \n"
-         "-s sync push(default is async push)\n"
-         "-r setup retry times(default value: 5 times)\n"
-         "-u select active broker to send msg(default value: false)\n"
-         "-d use AutoDeleteSendcallback by cpp client(defalut value: false) \n"
-         "-T thread count of send msg or consume msg(defalut value: system cpu "
-         "core number) \n"
-         "-v print more details information \n";
+  std::cout << "need option,like follow: \n"
+            << "-n nameserver addr, if not set -n and -i ,no nameSrv will be got \n"
+               "-i nameserver domain name,  if not set -n and -i ,no nameSrv will be "
+               "got \n"
+               "-g groupname \n"
+               "-t  msg topic \n"
+               "-m messagecout(default value: 1) \n"
+               "-c content(default value: only test ) \n"
+               "-b (BROADCASTING model, default value: CLUSTER) \n"
+               "-s sync push(default is async push)\n"
+               "-r setup retry times(default value: 5 times)\n"
+               "-u select active broker to send msg(default value: false)\n"
+               "-d use AutoDeleteSendcallback by cpp client(defalut value: false) \n"
+               "-T thread count of send msg or consume msg(defalut value: system cpu "
+               "core number) \n"
+               "-v print more details information \n";
 }
 
-static bool ParseArgs(int argc, char* argv[],
-                      RocketmqSendAndConsumerArgs* info) {
+static bool ParseArgs(int argc, char* argv[], RocketmqSendAndConsumerArgs* info) {
 #ifndef WIN32
   int ch;
   while ((ch = getopt(argc, argv, "n:i:g:t:m:c:b:s:h:r:T:bu")) != -1) {
@@ -209,18 +204,20 @@
   info->topic = arg_help.get_option_value("-t");
   info->broadcasting = atoi(arg_help.get_option_value("-b").c_str());
   string msgContent(arg_help.get_option_value("-c"));
-  if (!msgContent.empty()) info->body = msgContent;
+  if (!msgContent.empty())
+    info->body = msgContent;
   info->syncpush = atoi(arg_help.get_option_value("-s").c_str());
   int retrytimes = atoi(arg_help.get_option_value("-r").c_str());
-  if (retrytimes > 0) info->retrytimes = retrytimes;
+  if (retrytimes > 0)
+    info->retrytimes = retrytimes;
   info->SelectUnactiveBroker = atoi(arg_help.get_option_value("-u").c_str());
   int thread_count = atoi(arg_help.get_option_value("-T").c_str());
-  if (thread_count > 0) info->thread_count = thread_count;
+  if (thread_count > 0)
+    info->thread_count = thread_count;
   info->PrintMoreInfo = atoi(arg_help.get_option_value("-v").c_str());
   g_msgCount = atoi(arg_help.get_option_value("-m").c_str());
 #endif
-  if (info->groupname.empty() || info->topic.empty() ||
-      (info->namesrv_domain.empty() && info->namesrv.empty())) {
+  if (info->groupname.empty() || info->topic.empty() || (info->namesrv_domain.empty() && info->namesrv.empty())) {
     std::cout << "please use -g to setup groupname and -t setup topic \n";
     help();
     return false;
diff --git a/format.sh b/format.sh
index 0e8e269..f46c5f2 100755
--- a/format.sh
+++ b/format.sh
@@ -17,7 +17,7 @@
 
 
 TMPFILE=".clang_format_file.tmp"
-FORMAT="{BasedOnStyle: Google,IndentWidth: 2,ColumnLimit: 80}"
+FORMAT="{BasedOnStyle: Chromium, ColumnLimit: 120, TabWidth: 2}"
 
 function Usage
 {
@@ -62,7 +62,7 @@
 for file in $files
 do
     echo $file
-    clang-format -style="$FORMAT" $file > $TMPFILE
+    clang-format $file > $TMPFILE
 
     if [ -e $TMPFILE ];then
         filesize=`wc -c $TMPFILE |cut -d " " -f1`
diff --git a/include/Arg_helper.h b/include/Arg_helper.h
old mode 100755
new mode 100644
diff --git a/include/AsyncCallback.h b/include/AsyncCallback.h
old mode 100755
new mode 100644
index 2e5caeb..0b657ce
--- a/include/AsyncCallback.h
+++ b/include/AsyncCallback.h
@@ -27,38 +27,30 @@
 //<!***************************************************************************

 struct AsyncCallback {};

 //<!***************************************************************************

-typedef enum sendCallbackType {

-  noAutoDeleteSendCallback = 0,

-  autoDeleteSendCallback = 1

-} sendCallbackType;

+typedef enum sendCallbackType { noAutoDeleteSendCallback = 0, autoDeleteSendCallback = 1 } sendCallbackType;

 

 class ROCKETMQCLIENT_API SendCallback : public AsyncCallback {

  public:

   virtual ~SendCallback() {}

   virtual void onSuccess(SendResult& sendResult) = 0;

   virtual void onException(MQException& e) = 0;

-  virtual sendCallbackType getSendCallbackType() {

-    return noAutoDeleteSendCallback;

-  }

+  virtual sendCallbackType getSendCallbackType() { return noAutoDeleteSendCallback; }

 };

 

-//async SendCallback will be deleted automatically by rocketmq cpp after invoke callback interface

+// async SendCallback will be deleted automatically by rocketmq cpp after invoke callback interface

 class ROCKETMQCLIENT_API AutoDeleteSendCallBack : public SendCallback {

  public:

   virtual ~AutoDeleteSendCallBack() {}

   virtual void onSuccess(SendResult& sendResult) = 0;

   virtual void onException(MQException& e) = 0;

-  virtual sendCallbackType getSendCallbackType() {

-    return autoDeleteSendCallback;

-  }

+  virtual sendCallbackType getSendCallbackType() { return autoDeleteSendCallback; }

 };

 

 //<!************************************************************************

 class ROCKETMQCLIENT_API PullCallback : public AsyncCallback {

  public:

   virtual ~PullCallback() {}

-  virtual void onSuccess(MQMessageQueue& mq, PullResult& result,

-                         bool bProducePullRequest) = 0;

+  virtual void onSuccess(MQMessageQueue& mq, PullResult& result, bool bProducePullRequest) = 0;

   virtual void onException(MQException& e) = 0;

 };

 //<!***************************************************************************

diff --git a/include/BatchMessage.h b/include/BatchMessage.h
index 9c52d2d..16ec515 100644
--- a/include/BatchMessage.h
+++ b/include/BatchMessage.h
@@ -3,10 +3,10 @@
 #include "MQMessage.h"
 #include <string>
 namespace rocketmq {
-    class BatchMessage : public MQMessage {
-    public:
-        static std::string encode(std::vector <MQMessage> &msgs);
-        static std::string encode(MQMessage &message);
-    };
+class BatchMessage : public MQMessage {
+ public:
+  static std::string encode(std::vector<MQMessage>& msgs);
+  static std::string encode(MQMessage& message);
+};
 }
 #endif
\ No newline at end of file
diff --git a/include/CBatchMessage.h b/include/CBatchMessage.h
new file mode 100644
index 0000000..6409a55
--- /dev/null
+++ b/include/CBatchMessage.h
@@ -0,0 +1,36 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __C_BATCHMESSAGE_H__
+#define __C_BATCHMESSAGE_H__
+#include "CCommon.h"
+#include "CMessage.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct CBatchMessage CBatchMessage;
+
+ROCKETMQCLIENT_API CBatchMessage* CreateBatchMessage();
+ROCKETMQCLIENT_API int AddMessage(CBatchMessage* batchMsg, CMessage* msg);
+ROCKETMQCLIENT_API int DestroyBatchMessage(CBatchMessage* batchMsg);
+
+#ifdef __cplusplus
+};
+#endif
+#endif  //__C_BATCHMESSAGE_H__
diff --git a/include/CCommon.h b/include/CCommon.h
index a1864b9..a765184 100644
--- a/include/CCommon.h
+++ b/include/CCommon.h
@@ -26,36 +26,36 @@
 #define MAX_TOPIC_LENGTH 512
 #define MAX_BROKER_NAME_ID_LENGTH 256
 typedef enum _CStatus_ {
-    // Success
-    OK = 0,
-    // Failed, null pointer value
-    NULL_POINTER = 1,
-    MALLOC_FAILED = 2,
-    PRODUCER_ERROR_CODE_START = 10,
-    PRODUCER_START_FAILED = 10,
-    PRODUCER_SEND_SYNC_FAILED = 11,
-    PRODUCER_SEND_ONEWAY_FAILED = 12,
-    PRODUCER_SEND_ORDERLY_FAILED = 13,
-	PRODUCER_SEND_ASYNC_FAILED = 14,
-    PRODUCER_SEND_ORDERLYASYNC_FAILED = 15,
+  // Success
+  OK = 0,
+  // Failed, null pointer value
+  NULL_POINTER = 1,
+  MALLOC_FAILED = 2,
+  PRODUCER_ERROR_CODE_START = 10,
+  PRODUCER_START_FAILED = 10,
+  PRODUCER_SEND_SYNC_FAILED = 11,
+  PRODUCER_SEND_ONEWAY_FAILED = 12,
+  PRODUCER_SEND_ORDERLY_FAILED = 13,
+  PRODUCER_SEND_ASYNC_FAILED = 14,
+  PRODUCER_SEND_ORDERLYASYNC_FAILED = 15,
 
-    PUSHCONSUMER_ERROR_CODE_START = 20,
-    PUSHCONSUMER_START_FAILED = 20,
+  PUSHCONSUMER_ERROR_CODE_START = 20,
+  PUSHCONSUMER_START_FAILED = 20,
 
-    PULLCONSUMER_ERROR_CODE_START = 30,
-    PULLCONSUMER_START_FAILED = 30,
-    PULLCONSUMER_FETCH_MQ_FAILED = 31,
-    PULLCONSUMER_FETCH_MESSAGE_FAILED = 32
+  PULLCONSUMER_ERROR_CODE_START = 30,
+  PULLCONSUMER_START_FAILED = 30,
+  PULLCONSUMER_FETCH_MQ_FAILED = 31,
+  PULLCONSUMER_FETCH_MESSAGE_FAILED = 32
 } CStatus;
 
 typedef enum _CLogLevel_ {
-    E_LOG_LEVEL_FATAL = 1,
-    E_LOG_LEVEL_ERROR = 2,
-    E_LOG_LEVEL_WARN = 3,
-    E_LOG_LEVEL_INFO = 4,
-    E_LOG_LEVEL_DEBUG = 5,
-    E_LOG_LEVEL_TRACE = 6,
-    E_LOG_LEVEL_LEVEL_NUM = 7
+  E_LOG_LEVEL_FATAL = 1,
+  E_LOG_LEVEL_ERROR = 2,
+  E_LOG_LEVEL_WARN = 3,
+  E_LOG_LEVEL_INFO = 4,
+  E_LOG_LEVEL_DEBUG = 5,
+  E_LOG_LEVEL_TRACE = 6,
+  E_LOG_LEVEL_LEVEL_NUM = 7
 } CLogLevel;
 
 #ifdef WIN32
diff --git a/include/CErrorMessage.h b/include/CErrorMessage.h
new file mode 100644
index 0000000..1bcb527
--- /dev/null
+++ b/include/CErrorMessage.h
@@ -0,0 +1,33 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#ifndef __C_CLIENT_ERROR_H__
+#define __C_CLIENT_ERROR_H__
+
+#include "CCommon.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+	 
+	ROCKETMQCLIENT_API const char *GetLatestErrorMessage();  // Return the last error message
+
+#ifdef __cplusplus
+};
+#endif
+#endif //__C_CLIENT_ERROR_H__
\ No newline at end of file
diff --git a/include/CMQException.h b/include/CMQException.h
index 69706e8..51f9560 100644
--- a/include/CMQException.h
+++ b/include/CMQException.h
@@ -22,15 +22,15 @@
 extern "C" {
 #endif
 
-#define MAX_EXEPTION_MSG_LENGTH  512
+#define MAX_EXEPTION_MSG_LENGTH 512
 #define MAX_EXEPTION_FILE_LENGTH 256
 #define MAX_EXEPTION_TYPE_LENGTH 128
-typedef struct _CMQException_{
-    int error;
-    int line;
-    char file[MAX_EXEPTION_FILE_LENGTH];
-    char msg[MAX_EXEPTION_MSG_LENGTH];
-    char type[MAX_EXEPTION_TYPE_LENGTH];
+typedef struct _CMQException_ {
+  int error;
+  int line;
+  char file[MAX_EXEPTION_FILE_LENGTH];
+  char msg[MAX_EXEPTION_MSG_LENGTH];
+  char type[MAX_EXEPTION_TYPE_LENGTH];
 
 } CMQException;
 
diff --git a/include/CMessage.h b/include/CMessage.h
index cef7889..f1b057b 100644
--- a/include/CMessage.h
+++ b/include/CMessage.h
@@ -23,21 +23,20 @@
 extern "C" {
 #endif
 
-//typedef struct _CMessage_ CMessage;
+// typedef struct _CMessage_ CMessage;
 typedef struct CMessage CMessage;
 
-
-ROCKETMQCLIENT_API CMessage *  CreateMessage(const char *topic);
-ROCKETMQCLIENT_API int DestroyMessage(CMessage *msg);
-ROCKETMQCLIENT_API int SetMessageTopic(CMessage *msg, const char *topic);
-ROCKETMQCLIENT_API int SetMessageTags(CMessage *msg, const char *tags);
-ROCKETMQCLIENT_API int SetMessageKeys(CMessage *msg, const char *keys);
-ROCKETMQCLIENT_API int SetMessageBody(CMessage *msg, const char *body);
-ROCKETMQCLIENT_API int SetByteMessageBody(CMessage *msg, const char *body, int len);
-ROCKETMQCLIENT_API int SetMessageProperty(CMessage *msg, const char *key, const char *value);
-ROCKETMQCLIENT_API int SetDelayTimeLevel(CMessage *msg, int level);
+ROCKETMQCLIENT_API CMessage* CreateMessage(const char* topic);
+ROCKETMQCLIENT_API int DestroyMessage(CMessage* msg);
+ROCKETMQCLIENT_API int SetMessageTopic(CMessage* msg, const char* topic);
+ROCKETMQCLIENT_API int SetMessageTags(CMessage* msg, const char* tags);
+ROCKETMQCLIENT_API int SetMessageKeys(CMessage* msg, const char* keys);
+ROCKETMQCLIENT_API int SetMessageBody(CMessage* msg, const char* body);
+ROCKETMQCLIENT_API int SetByteMessageBody(CMessage* msg, const char* body, int len);
+ROCKETMQCLIENT_API int SetMessageProperty(CMessage* msg, const char* key, const char* value);
+ROCKETMQCLIENT_API int SetDelayTimeLevel(CMessage* msg, int level);
 
 #ifdef __cplusplus
 };
 #endif
-#endif //__C_MESSAGE_H__
+#endif  //__C_MESSAGE_H__
diff --git a/include/CMessageExt.h b/include/CMessageExt.h
index 26336aa..acd85e3 100644
--- a/include/CMessageExt.h
+++ b/include/CMessageExt.h
@@ -24,26 +24,26 @@
 extern "C" {
 #endif
 
-//typedef struct _CMessageExt_ _CMessageExt;
+// typedef struct _CMessageExt_ _CMessageExt;
 typedef struct CMessageExt CMessageExt;
 
-ROCKETMQCLIENT_API const char *GetMessageTopic(CMessageExt *msgExt);
-ROCKETMQCLIENT_API const char *GetMessageTags(CMessageExt *msgExt);
-ROCKETMQCLIENT_API const char *GetMessageKeys(CMessageExt *msgExt);
-ROCKETMQCLIENT_API const char *GetMessageBody(CMessageExt *msgExt);
-ROCKETMQCLIENT_API const char *GetMessageProperty(CMessageExt *msgExt, const char *key);
-ROCKETMQCLIENT_API const char *GetMessageId(CMessageExt *msgExt);
-ROCKETMQCLIENT_API int GetMessageDelayTimeLevel(CMessageExt *msgExt);
-ROCKETMQCLIENT_API int GetMessageQueueId(CMessageExt *msgExt);
-ROCKETMQCLIENT_API int GetMessageReconsumeTimes(CMessageExt *msgExt);
-ROCKETMQCLIENT_API int GetMessageStoreSize(CMessageExt *msgExt);
-ROCKETMQCLIENT_API long long GetMessageBornTimestamp(CMessageExt *msgExt);
-ROCKETMQCLIENT_API long long GetMessageStoreTimestamp(CMessageExt *msgExt);
-ROCKETMQCLIENT_API long long GetMessageQueueOffset(CMessageExt *msgExt);
-ROCKETMQCLIENT_API long long GetMessageCommitLogOffset(CMessageExt *msgExt);
-ROCKETMQCLIENT_API long long GetMessagePreparedTransactionOffset(CMessageExt *msgExt);
+ROCKETMQCLIENT_API const char* GetMessageTopic(CMessageExt* msgExt);
+ROCKETMQCLIENT_API const char* GetMessageTags(CMessageExt* msgExt);
+ROCKETMQCLIENT_API const char* GetMessageKeys(CMessageExt* msgExt);
+ROCKETMQCLIENT_API const char* GetMessageBody(CMessageExt* msgExt);
+ROCKETMQCLIENT_API const char* GetMessageProperty(CMessageExt* msgExt, const char* key);
+ROCKETMQCLIENT_API const char* GetMessageId(CMessageExt* msgExt);
+ROCKETMQCLIENT_API int GetMessageDelayTimeLevel(CMessageExt* msgExt);
+ROCKETMQCLIENT_API int GetMessageQueueId(CMessageExt* msgExt);
+ROCKETMQCLIENT_API int GetMessageReconsumeTimes(CMessageExt* msgExt);
+ROCKETMQCLIENT_API int GetMessageStoreSize(CMessageExt* msgExt);
+ROCKETMQCLIENT_API long long GetMessageBornTimestamp(CMessageExt* msgExt);
+ROCKETMQCLIENT_API long long GetMessageStoreTimestamp(CMessageExt* msgExt);
+ROCKETMQCLIENT_API long long GetMessageQueueOffset(CMessageExt* msgExt);
+ROCKETMQCLIENT_API long long GetMessageCommitLogOffset(CMessageExt* msgExt);
+ROCKETMQCLIENT_API long long GetMessagePreparedTransactionOffset(CMessageExt* msgExt);
 
 #ifdef __cplusplus
 };
 #endif
-#endif //__C_MESSAGE_EXT_H__
+#endif  //__C_MESSAGE_EXT_H__
diff --git a/include/CMessageQueue.h b/include/CMessageQueue.h
index 273f536..c514f9d 100644
--- a/include/CMessageQueue.h
+++ b/include/CMessageQueue.h
@@ -25,12 +25,12 @@
 #endif
 
 typedef struct _CMessageQueue_ {
-    char      topic[MAX_TOPIC_LENGTH];
-    char      brokerName[MAX_BROKER_NAME_ID_LENGTH];
-    int       queueId;
+  char topic[MAX_TOPIC_LENGTH];
+  char brokerName[MAX_BROKER_NAME_ID_LENGTH];
+  int queueId;
 } CMessageQueue;
 
 #ifdef __cplusplus
 };
 #endif
-#endif //__C_MESSAGE_H__
+#endif  //__C_MESSAGE_H__
diff --git a/include/CProducer.h b/include/CProducer.h
index c542dc2..6b00575 100644
--- a/include/CProducer.h
+++ b/include/CProducer.h
@@ -18,6 +18,7 @@
 #ifndef __C_PRODUCER_H__
 #define __C_PRODUCER_H__
 
+#include "CBatchMessage.h"
 #include "CMessage.h"
 #include "CSendResult.h"
 #include "CMQException.h"
@@ -26,40 +27,58 @@
 extern "C" {
 #endif
 
-//typedef struct _CProducer_ _CProducer;
+// typedef struct _CProducer_ _CProducer;
 typedef struct CProducer CProducer;
-typedef int(*QueueSelectorCallback)(int size, CMessage *msg, void *arg);
-typedef void(*CSendSuccessCallback)(CSendResult result);
-typedef void(*CSendExceptionCallback)(CMQException e);
+typedef int (*QueueSelectorCallback)(int size, CMessage* msg, void* arg);
+typedef void (*CSendSuccessCallback)(CSendResult result);
+typedef void (*CSendExceptionCallback)(CMQException e);
 
-ROCKETMQCLIENT_API CProducer *CreateProducer(const char *groupId);
-ROCKETMQCLIENT_API int DestroyProducer(CProducer *producer);
-ROCKETMQCLIENT_API int StartProducer(CProducer *producer);
-ROCKETMQCLIENT_API int ShutdownProducer(CProducer *producer);
+ROCKETMQCLIENT_API CProducer* CreateProducer(const char* groupId);
+ROCKETMQCLIENT_API int DestroyProducer(CProducer* producer);
+ROCKETMQCLIENT_API int StartProducer(CProducer* producer);
+ROCKETMQCLIENT_API int ShutdownProducer(CProducer* producer);
 
-ROCKETMQCLIENT_API int SetProducerNameServerAddress(CProducer *producer, const char *namesrv);
-ROCKETMQCLIENT_API int SetProducerNameServerDomain(CProducer *producer, const char *domain);
-ROCKETMQCLIENT_API int SetProducerGroupName(CProducer *producer, const char *groupName);
-ROCKETMQCLIENT_API int SetProducerInstanceName(CProducer *producer, const char *instanceName);
-ROCKETMQCLIENT_API int SetProducerSessionCredentials(CProducer *producer, const char *accessKey, const char *secretKey,
-                                  const char *onsChannel);
-ROCKETMQCLIENT_API int SetProducerLogPath(CProducer *producer, const char *logPath);
-ROCKETMQCLIENT_API int SetProducerLogFileNumAndSize(CProducer *producer, int fileNum, long fileSize);
-ROCKETMQCLIENT_API int SetProducerLogLevel(CProducer *producer, CLogLevel level);
-ROCKETMQCLIENT_API int SetProducerSendMsgTimeout(CProducer *producer, int timeout);
-ROCKETMQCLIENT_API int SetProducerCompressLevel(CProducer *producer, int level);
-ROCKETMQCLIENT_API int SetProducerMaxMessageSize(CProducer *producer, int size);
+ROCKETMQCLIENT_API int SetProducerNameServerAddress(CProducer* producer, const char* namesrv);
+ROCKETMQCLIENT_API int SetProducerNameServerDomain(CProducer* producer, const char* domain);
+ROCKETMQCLIENT_API int SetProducerGroupName(CProducer* producer, const char* groupName);
+ROCKETMQCLIENT_API int SetProducerInstanceName(CProducer* producer, const char* instanceName);
+ROCKETMQCLIENT_API int SetProducerSessionCredentials(CProducer* producer,
+                                                     const char* accessKey,
+                                                     const char* secretKey,
+                                                     const char* onsChannel);
+ROCKETMQCLIENT_API int SetProducerLogPath(CProducer* producer, const char* logPath);
+ROCKETMQCLIENT_API int SetProducerLogFileNumAndSize(CProducer* producer, int fileNum, long fileSize);
+ROCKETMQCLIENT_API int SetProducerLogLevel(CProducer* producer, CLogLevel level);
+ROCKETMQCLIENT_API int SetProducerSendMsgTimeout(CProducer* producer, int timeout);
+ROCKETMQCLIENT_API int SetProducerCompressLevel(CProducer* producer, int level);
+ROCKETMQCLIENT_API int SetProducerMaxMessageSize(CProducer* producer, int size);
 
-ROCKETMQCLIENT_API int SendMessageSync(CProducer *producer, CMessage *msg, CSendResult *result);
-ROCKETMQCLIENT_API int SendMessageAsync(CProducer *producer, CMessage *msg, CSendSuccessCallback cSendSuccessCallback , CSendExceptionCallback cSendExceptionCallback);
-ROCKETMQCLIENT_API int SendMessageOneway(CProducer *producer,CMessage *msg);
-ROCKETMQCLIENT_API int SendMessageOnewayOrderly(CProducer *producer,CMessage *msg, QueueSelectorCallback selector, void* arg);
-ROCKETMQCLIENT_API int SendMessageOrderly(CProducer *producer, CMessage *msg, QueueSelectorCallback callback, void *arg, int autoRetryTimes, CSendResult *result);
+ROCKETMQCLIENT_API int SendMessageSync(CProducer* producer, CMessage* msg, CSendResult* result);
+ROCKETMQCLIENT_API int SendBatchMessage(CProducer* producer, CBatchMessage* msg, CSendResult* result);
+ROCKETMQCLIENT_API int SendMessageAsync(CProducer* producer,
+                                        CMessage* msg,
+                                        CSendSuccessCallback cSendSuccessCallback,
+                                        CSendExceptionCallback cSendExceptionCallback);
+ROCKETMQCLIENT_API int SendMessageOneway(CProducer* producer, CMessage* msg);
+ROCKETMQCLIENT_API int SendMessageOnewayOrderly(CProducer* producer,
+                                                CMessage* msg,
+                                                QueueSelectorCallback selector,
+                                                void* arg);
+ROCKETMQCLIENT_API int SendMessageOrderly(CProducer* producer,
+                                          CMessage* msg,
+                                          QueueSelectorCallback callback,
+                                          void* arg,
+                                          int autoRetryTimes,
+                                          CSendResult* result);
 
-
-ROCKETMQCLIENT_API int SendMessageOrderlyAsync(CProducer *producer,CMessage *msg,QueueSelectorCallback callback,void *arg,CSendSuccessCallback cSendSuccessCallback,CSendExceptionCallback cSendExceptionCallback );
+ROCKETMQCLIENT_API int SendMessageOrderlyAsync(CProducer* producer,
+                                               CMessage* msg,
+                                               QueueSelectorCallback callback,
+                                               void* arg,
+                                               CSendSuccessCallback cSendSuccessCallback,
+                                               CSendExceptionCallback cSendExceptionCallback);
 
 #ifdef __cplusplus
 };
 #endif
-#endif //__C_PRODUCER_H__
+#endif  //__C_PRODUCER_H__
\ No newline at end of file
diff --git a/include/CPullConsumer.h b/include/CPullConsumer.h
index a4c4f5a..0157108 100644
--- a/include/CPullConsumer.h
+++ b/include/CPullConsumer.h
@@ -27,32 +27,35 @@
 extern "C" {
 #endif
 
-
 typedef struct CPullConsumer CPullConsumer;
 
+ROCKETMQCLIENT_API CPullConsumer* CreatePullConsumer(const char* groupId);
+ROCKETMQCLIENT_API int DestroyPullConsumer(CPullConsumer* consumer);
+ROCKETMQCLIENT_API int StartPullConsumer(CPullConsumer* consumer);
+ROCKETMQCLIENT_API int ShutdownPullConsumer(CPullConsumer* consumer);
+ROCKETMQCLIENT_API int SetPullConsumerGroupID(CPullConsumer* consumer, const char* groupId);
+ROCKETMQCLIENT_API const char* GetPullConsumerGroupID(CPullConsumer* consumer);
+ROCKETMQCLIENT_API int SetPullConsumerNameServerAddress(CPullConsumer* consumer, const char* namesrv);
+ROCKETMQCLIENT_API int SetPullConsumerNameServerDomain(CPullConsumer* consumer, const char* domain);
+ROCKETMQCLIENT_API int SetPullConsumerSessionCredentials(CPullConsumer* consumer,
+                                                         const char* accessKey,
+                                                         const char* secretKey,
+                                                         const char* channel);
+ROCKETMQCLIENT_API int SetPullConsumerLogPath(CPullConsumer* consumer, const char* logPath);
+ROCKETMQCLIENT_API int SetPullConsumerLogFileNumAndSize(CPullConsumer* consumer, int fileNum, long fileSize);
+ROCKETMQCLIENT_API int SetPullConsumerLogLevel(CPullConsumer* consumer, CLogLevel level);
 
-ROCKETMQCLIENT_API CPullConsumer *CreatePullConsumer(const char *groupId);
-ROCKETMQCLIENT_API int DestroyPullConsumer(CPullConsumer *consumer);
-ROCKETMQCLIENT_API int StartPullConsumer(CPullConsumer *consumer);
-ROCKETMQCLIENT_API int ShutdownPullConsumer(CPullConsumer *consumer);
-ROCKETMQCLIENT_API int SetPullConsumerGroupID(CPullConsumer *consumer, const char *groupId);
-ROCKETMQCLIENT_API const char *GetPullConsumerGroupID(CPullConsumer *consumer);
-ROCKETMQCLIENT_API int SetPullConsumerNameServerAddress(CPullConsumer *consumer, const char *namesrv);
-ROCKETMQCLIENT_API int SetPullConsumerNameServerDomain(CPullConsumer *consumer, const char *domain);
-ROCKETMQCLIENT_API int SetPullConsumerSessionCredentials(CPullConsumer *consumer, const char *accessKey, const char *secretKey,
-                                      const char *channel);
-ROCKETMQCLIENT_API int SetPullConsumerLogPath(CPullConsumer *consumer, const char *logPath);
-ROCKETMQCLIENT_API int SetPullConsumerLogFileNumAndSize(CPullConsumer *consumer, int fileNum, long fileSize);
-ROCKETMQCLIENT_API int SetPullConsumerLogLevel(CPullConsumer *consumer, CLogLevel level);
-
-ROCKETMQCLIENT_API int FetchSubscriptionMessageQueues(CPullConsumer *consumer, const char *topic, CMessageQueue **mqs, int *size);
-ROCKETMQCLIENT_API int ReleaseSubscriptionMessageQueue(CMessageQueue *mqs);
+ROCKETMQCLIENT_API int FetchSubscriptionMessageQueues(CPullConsumer* consumer,
+                                                      const char* topic,
+                                                      CMessageQueue** mqs,
+                                                      int* size);
+ROCKETMQCLIENT_API int ReleaseSubscriptionMessageQueue(CMessageQueue* mqs);
 
 ROCKETMQCLIENT_API CPullResult
-Pull(CPullConsumer *consumer, const CMessageQueue *mq, const char *subExpression, long long offset, int maxNums);
+Pull(CPullConsumer* consumer, const CMessageQueue* mq, const char* subExpression, long long offset, int maxNums);
 ROCKETMQCLIENT_API int ReleasePullResult(CPullResult pullResult);
 
 #ifdef __cplusplus
 };
 #endif
-#endif //__C_PUSH_CONSUMER_H__
+#endif  //__C_PUSH_CONSUMER_H__
diff --git a/include/CPullResult.h b/include/CPullResult.h
index e22fd9e..2ab174f 100644
--- a/include/CPullResult.h
+++ b/include/CPullResult.h
@@ -25,24 +25,24 @@
 extern "C" {
 #endif
 typedef enum E_CPullStatus {
-    E_FOUND,
-    E_NO_NEW_MSG,
-    E_NO_MATCHED_MSG,
-    E_OFFSET_ILLEGAL,
-    E_BROKER_TIMEOUT   //indicate pull request timeout or received NULL response
+  E_FOUND,
+  E_NO_NEW_MSG,
+  E_NO_MATCHED_MSG,
+  E_OFFSET_ILLEGAL,
+  E_BROKER_TIMEOUT  // indicate pull request timeout or received NULL response
 } CPullStatus;
 
 typedef struct _CPullResult_ {
-    CPullStatus pullStatus;
-    long long nextBeginOffset;
-    long long minOffset;
-    long long maxOffset;
-    CMessageExt **msgFoundList;
-    int size;
-    void *pData;
+  CPullStatus pullStatus;
+  long long nextBeginOffset;
+  long long minOffset;
+  long long maxOffset;
+  CMessageExt** msgFoundList;
+  int size;
+  void* pData;
 } CPullResult;
 
 #ifdef __cplusplus
 };
 #endif
-#endif //__C_PULL_RESULT_H__
+#endif  //__C_PULL_RESULT_H__
diff --git a/include/CPushConsumer.h b/include/CPushConsumer.h
index 49cbf96..10b5587 100644
--- a/include/CPushConsumer.h
+++ b/include/CPushConsumer.h
@@ -25,39 +25,39 @@
 extern "C" {
 #endif
 
-//typedef struct _CConsumer_ _CConsumer;
+// typedef struct _CConsumer_ _CConsumer;
 typedef struct CPushConsumer CPushConsumer;
 
-typedef enum E_CConsumeStatus{
-    E_CONSUME_SUCCESS = 0,
-    E_RECONSUME_LATER = 1
-} CConsumeStatus;
+typedef enum E_CConsumeStatus { E_CONSUME_SUCCESS = 0, E_RECONSUME_LATER = 1 } CConsumeStatus;
 
-typedef int(*MessageCallBack)(CPushConsumer *, CMessageExt *);
+typedef int (*MessageCallBack)(CPushConsumer*, CMessageExt*);
 
-ROCKETMQCLIENT_API CPushConsumer *CreatePushConsumer(const char *groupId);
-ROCKETMQCLIENT_API int DestroyPushConsumer(CPushConsumer *consumer);
-ROCKETMQCLIENT_API int StartPushConsumer(CPushConsumer *consumer);
-ROCKETMQCLIENT_API int ShutdownPushConsumer(CPushConsumer *consumer);
-ROCKETMQCLIENT_API int SetPushConsumerGroupID(CPushConsumer *consumer, const char *groupId);
-ROCKETMQCLIENT_API const char *GetPushConsumerGroupID(CPushConsumer *consumer);
-ROCKETMQCLIENT_API int SetPushConsumerNameServerAddress(CPushConsumer *consumer, const char *namesrv);
-ROCKETMQCLIENT_API int SetPushConsumerNameServerDomain(CPushConsumer *consumer, const char *domain);
-ROCKETMQCLIENT_API int Subscribe(CPushConsumer *consumer, const char *topic, const char *expression);
-ROCKETMQCLIENT_API int RegisterMessageCallbackOrderly(CPushConsumer *consumer, MessageCallBack pCallback);
-ROCKETMQCLIENT_API int RegisterMessageCallback(CPushConsumer *consumer, MessageCallBack pCallback);
-ROCKETMQCLIENT_API int UnregisterMessageCallbackOrderly(CPushConsumer *consumer);
-ROCKETMQCLIENT_API int UnregisterMessageCallback(CPushConsumer *consumer);
-ROCKETMQCLIENT_API int SetPushConsumerThreadCount(CPushConsumer *consumer, int threadCount);
-ROCKETMQCLIENT_API int SetPushConsumerMessageBatchMaxSize(CPushConsumer *consumer, int batchSize);
-ROCKETMQCLIENT_API int SetPushConsumerInstanceName(CPushConsumer *consumer, const char *instanceName);
-ROCKETMQCLIENT_API int SetPushConsumerSessionCredentials(CPushConsumer *consumer, const char *accessKey, const char *secretKey,const char *channel);                    
-ROCKETMQCLIENT_API int SetPushConsumerLogPath(CPushConsumer *consumer, const char *logPath);
-ROCKETMQCLIENT_API int SetPushConsumerLogFileNumAndSize(CPushConsumer *consumer, int fileNum, long fileSize);
-ROCKETMQCLIENT_API int SetPushConsumerLogLevel(CPushConsumer *consumer, CLogLevel level);
-ROCKETMQCLIENT_API int SetPushConsumerMessageModel(CPushConsumer *consumer, CMessageModel messageModel);
-  
+ROCKETMQCLIENT_API CPushConsumer* CreatePushConsumer(const char* groupId);
+ROCKETMQCLIENT_API int DestroyPushConsumer(CPushConsumer* consumer);
+ROCKETMQCLIENT_API int StartPushConsumer(CPushConsumer* consumer);
+ROCKETMQCLIENT_API int ShutdownPushConsumer(CPushConsumer* consumer);
+ROCKETMQCLIENT_API int SetPushConsumerGroupID(CPushConsumer* consumer, const char* groupId);
+ROCKETMQCLIENT_API const char* GetPushConsumerGroupID(CPushConsumer* consumer);
+ROCKETMQCLIENT_API int SetPushConsumerNameServerAddress(CPushConsumer* consumer, const char* namesrv);
+ROCKETMQCLIENT_API int SetPushConsumerNameServerDomain(CPushConsumer* consumer, const char* domain);
+ROCKETMQCLIENT_API int Subscribe(CPushConsumer* consumer, const char* topic, const char* expression);
+ROCKETMQCLIENT_API int RegisterMessageCallbackOrderly(CPushConsumer* consumer, MessageCallBack pCallback);
+ROCKETMQCLIENT_API int RegisterMessageCallback(CPushConsumer* consumer, MessageCallBack pCallback);
+ROCKETMQCLIENT_API int UnregisterMessageCallbackOrderly(CPushConsumer* consumer);
+ROCKETMQCLIENT_API int UnregisterMessageCallback(CPushConsumer* consumer);
+ROCKETMQCLIENT_API int SetPushConsumerThreadCount(CPushConsumer* consumer, int threadCount);
+ROCKETMQCLIENT_API int SetPushConsumerMessageBatchMaxSize(CPushConsumer* consumer, int batchSize);
+ROCKETMQCLIENT_API int SetPushConsumerInstanceName(CPushConsumer* consumer, const char* instanceName);
+ROCKETMQCLIENT_API int SetPushConsumerSessionCredentials(CPushConsumer* consumer,
+                                                         const char* accessKey,
+                                                         const char* secretKey,
+                                                         const char* channel);
+ROCKETMQCLIENT_API int SetPushConsumerLogPath(CPushConsumer* consumer, const char* logPath);
+ROCKETMQCLIENT_API int SetPushConsumerLogFileNumAndSize(CPushConsumer* consumer, int fileNum, long fileSize);
+ROCKETMQCLIENT_API int SetPushConsumerLogLevel(CPushConsumer* consumer, CLogLevel level);
+ROCKETMQCLIENT_API int SetPushConsumerMessageModel(CPushConsumer* consumer, CMessageModel messageModel);
+
 #ifdef __cplusplus
 };
 #endif
-#endif //__C_PUSH_CONSUMER_H__
+#endif  //__C_PUSH_CONSUMER_H__
diff --git a/include/CSendResult.h b/include/CSendResult.h
index 14100b4..fa640ca 100644
--- a/include/CSendResult.h
+++ b/include/CSendResult.h
@@ -23,20 +23,20 @@
 extern "C" {
 #endif
 
-typedef enum E_CSendStatus_{
-    E_SEND_OK = 0,
-    E_SEND_FLUSH_DISK_TIMEOUT = 1,
-    E_SEND_FLUSH_SLAVE_TIMEOUT = 2,
-    E_SEND_SLAVE_NOT_AVAILABLE = 3
+typedef enum E_CSendStatus_ {
+  E_SEND_OK = 0,
+  E_SEND_FLUSH_DISK_TIMEOUT = 1,
+  E_SEND_FLUSH_SLAVE_TIMEOUT = 2,
+  E_SEND_SLAVE_NOT_AVAILABLE = 3
 } CSendStatus;
 
 typedef struct _SendResult_ {
-    CSendStatus sendStatus;
-    char        msgId[MAX_MESSAGE_ID_LENGTH];
-    long long   offset;
+  CSendStatus sendStatus;
+  char msgId[MAX_MESSAGE_ID_LENGTH];
+  long long offset;
 } CSendResult;
 
 #ifdef __cplusplus
 };
 #endif
-#endif //__C_PRODUCER_H__
+#endif  //__C_PRODUCER_H__
diff --git a/include/ConsumeType.h b/include/ConsumeType.h
old mode 100755
new mode 100644
index f804655..c404a3a
--- a/include/ConsumeType.h
+++ b/include/ConsumeType.h
@@ -14,7 +14,7 @@
  * See the License for the specific language governing permissions and

  * limitations under the License.

  */

- 

+

 #ifndef __CONSUMETYPE_H__

 #define __CONSUMETYPE_H__

 

@@ -28,8 +28,8 @@
 //<!***************************************************************************

 enum ConsumeFromWhere {

   /**

-  *new consumer will consume from end offset of queue, 

-  * and then consume from last consumed offset of queue follow-up 

+  *new consumer will consume from end offset of queue,

+  * and then consume from last consumed offset of queue follow-up

   */

   CONSUME_FROM_LAST_OFFSET,

 

@@ -40,13 +40,13 @@
   // @Deprecated

   CONSUME_FROM_MAX_OFFSET,

   /**

-  *new consumer will consume from first offset of queue, 

-  * and then consume from last consumed offset of queue follow-up 

+  *new consumer will consume from first offset of queue,

+  * and then consume from last consumed offset of queue follow-up

   */

   CONSUME_FROM_FIRST_OFFSET,

   /**

-  *new consumer will consume from the queue offset specified by timestamp, 

-  * and then consume from last consumed offset of queue follow-up 

+  *new consumer will consume from the queue offset specified by timestamp,

+  * and then consume from last consumed offset of queue follow-up

   */

   CONSUME_FROM_TIMESTAMP,

 };

diff --git a/include/DefaultMQProducer.h b/include/DefaultMQProducer.h
old mode 100755
new mode 100644
index 17be13f..df3f22a
--- a/include/DefaultMQProducer.h
+++ b/include/DefaultMQProducer.h
@@ -39,26 +39,23 @@
   //<! begin MQProducer;

   virtual SendResult send(MQMessage& msg, bool bSelectActiveBroker = false);

   virtual SendResult send(MQMessage& msg, const MQMessageQueue& mq);

-  virtual SendResult send(MQMessage& msg, MessageQueueSelector* selector,

-                          void* arg);

-  virtual SendResult send(MQMessage& msg, MessageQueueSelector* selector,

-                          void* arg, int autoRetryTimes,

+  virtual SendResult send(MQMessage& msg, MessageQueueSelector* selector, void* arg);

+  virtual SendResult send(MQMessage& msg,

+                          MessageQueueSelector* selector,

+                          void* arg,

+                          int autoRetryTimes,

                           bool bActiveBroker = false);

   virtual SendResult send(std::vector<MQMessage>& msgs);

   virtual SendResult send(std::vector<MQMessage>& msgs, const MQMessageQueue& mq);

-  virtual void send(MQMessage& msg, SendCallback* pSendCallback,

-                    bool bSelectActiveBroker = false);

-  virtual void send(MQMessage& msg, const MQMessageQueue& mq,

-                    SendCallback* pSendCallback);

-  virtual void send(MQMessage& msg, MessageQueueSelector* selector, void* arg,

-                    SendCallback* pSendCallback);

+  virtual void send(MQMessage& msg, SendCallback* pSendCallback, bool bSelectActiveBroker = false);

+  virtual void send(MQMessage& msg, const MQMessageQueue& mq, SendCallback* pSendCallback);

+  virtual void send(MQMessage& msg, MessageQueueSelector* selector, void* arg, SendCallback* pSendCallback);

   virtual void sendOneway(MQMessage& msg, bool bSelectActiveBroker = false);

   virtual void sendOneway(MQMessage& msg, const MQMessageQueue& mq);

-  virtual void sendOneway(MQMessage& msg, MessageQueueSelector* selector,

-                          void* arg);

+  virtual void sendOneway(MQMessage& msg, MessageQueueSelector* selector, void* arg);

   //<! end MQProducer;

 

-  //set and get timeout of per msg

+  // set and get timeout of per msg

   int getSendMsgTimeout() const;

   void setSendMsgTimeout(int sendMsgTimeout);

 

@@ -70,12 +67,12 @@
   void setCompressMsgBodyOverHowmuch(int compressMsgBodyOverHowmuch);

   int getCompressLevel() const;

   void setCompressLevel(int compressLevel);

-  

-  //if msgbody size larger than maxMsgBodySize, exception will be throwed

+

+  // if msgbody size larger than maxMsgBodySize, exception will be throwed

   int getMaxMessageSize() const;

   void setMaxMessageSize(int maxMessageSize);

 

-  //set msg max retry times, default retry times is 5

+  // set msg max retry times, default retry times is 5

   int getRetryTimes() const;

   void setRetryTimes(int times);

 

@@ -85,18 +82,24 @@
  protected:

   SendResult sendAutoRetrySelectImpl(MQMessage& msg,

                                      MessageQueueSelector* pSelector,

-                                     void* pArg, int communicationMode,

+                                     void* pArg,

+                                     int communicationMode,

                                      SendCallback* pSendCallback,

                                      int retryTimes,

                                      bool bActiveBroker = false);

-  SendResult sendSelectImpl(MQMessage& msg, MessageQueueSelector* pSelector,

-                            void* pArg, int communicationMode,

+  SendResult sendSelectImpl(MQMessage& msg,

+                            MessageQueueSelector* pSelector,

+                            void* pArg,

+                            int communicationMode,

                             SendCallback* sendCallback);

-  SendResult sendDefaultImpl(MQMessage& msg, int communicationMode,

+  SendResult sendDefaultImpl(MQMessage& msg,

+                             int communicationMode,

                              SendCallback* pSendCallback,

                              bool bActiveBroker = false);

-  SendResult sendKernelImpl(MQMessage& msg, const MQMessageQueue& mq,

-                            int communicationMode, SendCallback* pSendCallback);

+  SendResult sendKernelImpl(MQMessage& msg,

+                            const MQMessageQueue& mq,

+                            int communicationMode,

+                            SendCallback* pSendCallback);

   bool tryToCompressMessage(MQMessage& msg);

   BatchMessage buildBatchMessage(std::vector<MQMessage>& msgs);

 

@@ -104,10 +107,10 @@
   int m_sendMsgTimeout;

   int m_compressMsgBodyOverHowmuch;

   int m_maxMessageSize;  //<! default:128K;

-  //bool m_retryAnotherBrokerWhenNotStoreOK;

+  // bool m_retryAnotherBrokerWhenNotStoreOK;

   int m_compressLevel;

   int m_retryTimes;

-  int m_retryTimes4Async;  

+  int m_retryTimes4Async;

 };

 //<!***************************************************************************

 }  //<!end namespace;

diff --git a/include/DefaultMQPullConsumer.h b/include/DefaultMQPullConsumer.h
old mode 100755
new mode 100644
index 30599a2..2e463bb
--- a/include/DefaultMQPullConsumer.h
+++ b/include/DefaultMQPullConsumer.h
@@ -44,13 +44,11 @@
 

   //<!begin MQConsumer

   virtual void sendMessageBack(MQMessageExt& msg, int delayLevel);

-  virtual void fetchSubscribeMessageQueues(const std::string& topic,

-                                           std::vector<MQMessageQueue>& mqs);

+  virtual void fetchSubscribeMessageQueues(const std::string& topic, std::vector<MQMessageQueue>& mqs);

   virtual void doRebalance();

   virtual void persistConsumerOffset();

   virtual void persistConsumerOffsetByResetOffset();

-  virtual void updateTopicSubscribeInfo(const std::string& topic,

-                                        std::vector<MQMessageQueue>& info);

+  virtual void updateTopicSubscribeInfo(const std::string& topic, std::vector<MQMessageQueue>& info);

   virtual ConsumeType getConsumeType();

   virtual ConsumeFromWhere getConsumeFromWhere();

   virtual void getSubscriptions(std::vector<SubscriptionData>&);

@@ -60,8 +58,7 @@
   virtual Rebalance* getRebalance() const;

   //<!end MQConsumer;

 

-  void registerMessageQueueListener(const std::string& topic,

-                                    MQueueListener* pListener);

+  void registerMessageQueueListener(const std::string& topic, MQueueListener* pListener);

   /**

   * pull msg from specified queue, if no msg in queue, return directly

   *

@@ -75,13 +72,15 @@
   *            specify the started pull offset

   * @param maxNums

   *            specify max msg num by per pull

-  * @return  

+  * @return

   *            accroding to PullResult

   */

-  virtual PullResult pull(const MQMessageQueue& mq, const std::string& subExpression,

-                          int64 offset, int maxNums);

-  virtual void pull(const MQMessageQueue& mq, const std::string& subExpression,

-                    int64 offset, int maxNums, PullCallback* pPullCallback);

+  virtual PullResult pull(const MQMessageQueue& mq, const std::string& subExpression, int64 offset, int maxNums);

+  virtual void pull(const MQMessageQueue& mq,

+                    const std::string& subExpression,

+                    int64 offset,

+                    int maxNums,

+                    PullCallback* pPullCallback);

 

   /**

   * pull msg from specified queue, if no msg, broker will suspend the pull request 20s

@@ -96,15 +95,15 @@
   *            specify the started pull offset

   * @param maxNums

   *            specify max msg num by per pull

-  * @return  

+  * @return

   *            accroding to PullResult

   */

-  PullResult pullBlockIfNotFound(const MQMessageQueue& mq,

-                                 const std::string& subExpression, int64 offset,

-                                 int maxNums);

+  PullResult pullBlockIfNotFound(const MQMessageQueue& mq, const std::string& subExpression, int64 offset, int maxNums);

   void pullBlockIfNotFound(const MQMessageQueue& mq,

-                           const std::string& subExpression, int64 offset,

-                           int maxNums, PullCallback* pPullCallback);

+                           const std::string& subExpression,

+                           int64 offset,

+                           int maxNums,

+                           PullCallback* pPullCallback);

 

   virtual ConsumerRunningInfo* getConsumerRunningInfo() { return NULL; }

   /**

@@ -122,8 +121,7 @@
   *            ÏûÏ¢Topic

   * @return ·µ»Ø¶ÓÁм¯ºÏ

   */

-  void fetchMessageQueuesInBalance(const std::string& topic,

-                                   std::vector<MQMessageQueue> mqs);

+  void fetchMessageQueuesInBalance(const std::string& topic, std::vector<MQMessageQueue> mqs);

 

   // temp persist consumer offset interface, only valid with

   // RemoteBrokerOffsetStore, updateConsumeOffset should be called before.

@@ -133,11 +131,17 @@
   void checkConfig();

   void copySubscription();

 

-  PullResult pullSyncImpl(const MQMessageQueue& mq, const std::string& subExpression,

-                          int64 offset, int maxNums, bool block);

+  PullResult pullSyncImpl(const MQMessageQueue& mq,

+                          const std::string& subExpression,

+                          int64 offset,

+                          int maxNums,

+                          bool block);

 

-  void pullAsyncImpl(const MQMessageQueue& mq, const std::string& subExpression,

-                     int64 offset, int maxNums, bool block,

+  void pullAsyncImpl(const MQMessageQueue& mq,

+                     const std::string& subExpression,

+                     int64 offset,

+                     int maxNums,

+                     bool block,

                      PullCallback* pPullCallback);

 

   void subscriptionAutomatically(const std::string& topic);

diff --git a/include/DefaultMQPushConsumer.h b/include/DefaultMQPushConsumer.h
old mode 100755
new mode 100644
index 4051c77..e1292bf
--- a/include/DefaultMQPushConsumer.h
+++ b/include/DefaultMQPushConsumer.h
@@ -56,25 +56,24 @@
 

   //<!begin MQConsumer

   virtual void sendMessageBack(MQMessageExt& msg, int delayLevel);

-  virtual void fetchSubscribeMessageQueues(const std::string& topic,

-                                           std::vector<MQMessageQueue>& mqs);

+  virtual void fetchSubscribeMessageQueues(const std::string& topic, std::vector<MQMessageQueue>& mqs);

   virtual void doRebalance();

   virtual void persistConsumerOffset();

   virtual void persistConsumerOffsetByResetOffset();

-  virtual void updateTopicSubscribeInfo(const std::string& topic,

-                                        std::vector<MQMessageQueue>& info);

+  virtual void updateTopicSubscribeInfo(const std::string& topic, std::vector<MQMessageQueue>& info);

   virtual ConsumeType getConsumeType();

   virtual ConsumeFromWhere getConsumeFromWhere();

   void setConsumeFromWhere(ConsumeFromWhere consumeFromWhere);

   virtual void getSubscriptions(std::vector<SubscriptionData>&);

   virtual void updateConsumeOffset(const MQMessageQueue& mq, int64 offset);

   virtual void removeConsumeOffset(const MQMessageQueue& mq);

-  virtual PullResult pull(const MQMessageQueue& mq, const std::string& subExpression,

-                          int64 offset, int maxNums) {

+  virtual PullResult pull(const MQMessageQueue& mq, const std::string& subExpression, int64 offset, int maxNums) {

     return PullResult();

   }

-  virtual void pull(const MQMessageQueue& mq, const std::string& subExpression,

-                    int64 offset, int maxNums,

+  virtual void pull(const MQMessageQueue& mq,

+                    const std::string& subExpression,

+                    int64 offset,

+                    int maxNums,

                     PullCallback* pPullCallback) {}

   virtual ConsumerRunningInfo* getConsumerRunningInfo();

   //<!end MQConsumer;

@@ -88,14 +87,12 @@
   ConsumeMsgService* getConsumerMsgService() const;

 

   virtual void producePullMsgTask(PullRequest*);

-  void triggerNextPullRequest(boost::asio::deadline_timer* t,

-                              PullRequest* request);

+  void triggerNextPullRequest(boost::asio::deadline_timer* t, PullRequest* request);

   void runPullMsgQueue(TaskQueue* pTaskQueue);

   void pullMessage(PullRequest* pullrequest);       // sync pullMsg

   void pullMessageAsync(PullRequest* pullrequest);  // async pullMsg

   void setAsyncPull(bool asyncFlag);

-  AsyncPullCallback* getAsyncPullCallBack(PullRequest* request,

-                                          MQMessageQueue msgQueue);

+  AsyncPullCallback* getAsyncPullCallBack(PullRequest* request, MQMessageQueue msgQueue);

   void shutdownAsyncPullCallBack();

 

   /*

diff --git a/include/MQClient.h b/include/MQClient.h
old mode 100755
new mode 100644
index 5ef5ae5..6c86946
--- a/include/MQClient.h
+++ b/include/MQClient.h
@@ -60,7 +60,7 @@
   //<!groupName;

   const std::string& getGroupName() const;

   void setGroupName(const std::string& groupname);

-  

+

   /**

   * no realization

   */

@@ -122,8 +122,7 @@
   * @return

   *            according to QueryResult

   */

-  QueryResult queryMessage(const std::string& topic, const std::string& key, int maxNum,

-                           int64 begin, int64 end);

+  QueryResult queryMessage(const std::string& topic, const std::string& key, int maxNum, int64 begin, int64 end);

 

   std::vector<MQMessageQueue> getTopicMessageQueueInfo(const std::string& topic);

 

@@ -131,8 +130,7 @@
   // log file num is 3, each log size is 100M

   void setLogLevel(elogLevel inputLevel);

   elogLevel getLogLevel();

-  void setLogFileSizeAndNum(int fileNum,

-                                 long perFileSize);  // perFileSize is MB unit

+  void setLogFileSizeAndNum(int fileNum, long perFileSize);  // perFileSize is MB unit

 

   /** set TcpTransport pull thread num, which dermine the num of threads to

  distribute network data,

diff --git a/include/MQClientException.h b/include/MQClientException.h
old mode 100755
new mode 100644
index 85749f1..ad642cb
--- a/include/MQClientException.h
+++ b/include/MQClientException.h
@@ -28,54 +28,54 @@
 namespace rocketmq {
 //<!***************************************************************************
 class ROCKETMQCLIENT_API MQException : public std::exception {
-   public:
-    MQException(const std::string &msg, int error, const char *file, int line) throw()
-        : m_error(error), m_line(line), m_file(file) {
-        try {
-            std::stringstream ss;
-            ss << "msg: " << msg << ",error:" << error << ",in file <" << file << "> line:" << line;
-            m_msg = ss.str();
-        } catch (...) {
-        }
+ public:
+  MQException(const std::string& msg, int error, const char* file, int line) throw()
+      : m_error(error), m_line(line), m_file(file) {
+    try {
+      std::stringstream ss;
+      ss << "msg: " << msg << ",error:" << error << ",in file <" << file << "> line:" << line;
+      m_msg = ss.str();
+    } catch (...) {
     }
+  }
 
-    MQException(const std::string &msg, int error, const char *file, const char *type, int line) throw()
-        : m_error(error), m_line(line), m_file(file), m_type(type) {
-        try {
-            std::stringstream ss;
-            ss << "msg: " << msg << ",error:" << error << ",in file <" << file << "> line:" << line;
-            m_msg = ss.str();
-        } catch (...) {
-        }
+  MQException(const std::string& msg, int error, const char* file, const char* type, int line) throw()
+      : m_error(error), m_line(line), m_file(file), m_type(type) {
+    try {
+      std::stringstream ss;
+      ss << "msg: " << msg << ",error:" << error << ",in file <" << file << "> line:" << line;
+      m_msg = ss.str();
+    } catch (...) {
     }
+  }
 
-    virtual ~MQException() throw() {}
-    const char *what() const throw() { return m_msg.c_str(); }
-    int GetError() const throw() { return m_error; }
-    virtual const char *GetType() const throw() { return m_type.c_str(); }
-    int GetLine() { return m_line; }
-    const char *GetFile() { return m_file.c_str(); }
+  virtual ~MQException() throw() {}
+  const char* what() const throw() { return m_msg.c_str(); }
+  int GetError() const throw() { return m_error; }
+  virtual const char* GetType() const throw() { return m_type.c_str(); }
+  int GetLine() { return m_line; }
+  const char* GetFile() { return m_file.c_str(); }
 
-   protected:
-    int m_error;
-    int m_line;
-    std::string m_msg;
-    std::string m_file;
-    std::string m_type;
+ protected:
+  int m_error;
+  int m_line;
+  std::string m_msg;
+  std::string m_file;
+  std::string m_type;
 };
 
-inline std::ostream &operator<<(std::ostream &os, const MQException &e) {
-    os << "Type: " << e.GetType() << " , " << e.what();
-    return os;
+inline std::ostream& operator<<(std::ostream& os, const MQException& e) {
+  os << "Type: " << e.GetType() << " , " << e.what();
+  return os;
 }
 
-#define DEFINE_MQCLIENTEXCEPTION(name)                                              \
-    class ROCKETMQCLIENT_API name : public MQException {                            \
-       public:                                                                      \
-        name(const std::string &msg, int error, const char *file, int line) throw() \
-            : MQException(msg, error, file, #name, line) {}                         \
-        virtual const char *GetType() const throw() { return m_type.c_str(); }      \
-    };
+#define DEFINE_MQCLIENTEXCEPTION(name)                                          \
+  class ROCKETMQCLIENT_API name : public MQException {                          \
+   public:                                                                      \
+    name(const std::string& msg, int error, const char* file, int line) throw() \
+        : MQException(msg, error, file, #name, line) {}                         \
+    virtual const char* GetType() const throw() { return m_type.c_str(); }      \
+  };
 
 DEFINE_MQCLIENTEXCEPTION(MQClientException)
 DEFINE_MQCLIENTEXCEPTION(MQBrokerException)
diff --git a/include/MQConsumer.h b/include/MQConsumer.h
old mode 100755
new mode 100644
index 89763a8..9950519
--- a/include/MQConsumer.h
+++ b/include/MQConsumer.h
@@ -33,33 +33,29 @@
  public:

   virtual ~MQConsumer() {}

   virtual void sendMessageBack(MQMessageExt& msg, int delayLevel) = 0;

-  virtual void fetchSubscribeMessageQueues(const std::string& topic,

-                                           std::vector<MQMessageQueue>& mqs) = 0;

+  virtual void fetchSubscribeMessageQueues(const std::string& topic, std::vector<MQMessageQueue>& mqs) = 0;

   virtual void doRebalance() = 0;

   virtual void persistConsumerOffset() = 0;

   virtual void persistConsumerOffsetByResetOffset() = 0;

-  virtual void updateTopicSubscribeInfo(const std::string& topic,

-                                        std::vector<MQMessageQueue>& info) = 0;

-  virtual void updateConsumeOffset(const MQMessageQueue& mq,

-                                   int64 offset) = 0;

+  virtual void updateTopicSubscribeInfo(const std::string& topic, std::vector<MQMessageQueue>& info) = 0;

+  virtual void updateConsumeOffset(const MQMessageQueue& mq, int64 offset) = 0;

   virtual void removeConsumeOffset(const MQMessageQueue& mq) = 0;

   virtual ConsumeType getConsumeType() = 0;

   virtual ConsumeFromWhere getConsumeFromWhere() = 0;

   virtual void getSubscriptions(std::vector<SubscriptionData>&) = 0;

   virtual void producePullMsgTask(PullRequest*) = 0;

   virtual Rebalance* getRebalance() const = 0;

-  virtual PullResult pull(const MQMessageQueue& mq, const std::string& subExpression,

-                          int64 offset, int maxNums) = 0;

-  virtual void pull(const MQMessageQueue& mq, const std::string& subExpression,

-                    int64 offset, int maxNums,

+  virtual PullResult pull(const MQMessageQueue& mq, const std::string& subExpression, int64 offset, int maxNums) = 0;

+  virtual void pull(const MQMessageQueue& mq,

+                    const std::string& subExpression,

+                    int64 offset,

+                    int maxNums,

                     PullCallback* pPullCallback) = 0;

   virtual ConsumerRunningInfo* getConsumerRunningInfo() = 0;

 

  public:

   MessageModel getMessageModel() const { return m_messageModel; }

-  void setMessageModel(MessageModel messageModel) {

-    m_messageModel = messageModel;

-  }

+  void setMessageModel(MessageModel messageModel) { m_messageModel = messageModel; }

 

  protected:

   MessageModel m_messageModel;

diff --git a/include/MQMessage.h b/include/MQMessage.h
old mode 100755
new mode 100644
index e6f2298..70fab36
--- a/include/MQMessage.h
+++ b/include/MQMessage.h
@@ -26,31 +26,33 @@
 namespace rocketmq {
 //<!***************************************************************************
 class ROCKETMQCLIENT_API MQMessage {
-
  public:
   MQMessage();
   MQMessage(const std::string& topic, const std::string& body);
   MQMessage(const std::string& topic, const std::string& tags, const std::string& body);
-  MQMessage(const std::string& topic, const std::string& tags, const std::string& keys,
-            const std::string& body);
-  MQMessage(const std::string& topic, const std::string& tags, const std::string& keys,
-            const int flag, const std::string& body, bool waitStoreMsgOK);
+  MQMessage(const std::string& topic, const std::string& tags, const std::string& keys, const std::string& body);
+  MQMessage(const std::string& topic,
+            const std::string& tags,
+            const std::string& keys,
+            const int flag,
+            const std::string& body,
+            bool waitStoreMsgOK);
 
   virtual ~MQMessage();
   MQMessage(const MQMessage& other);
   MQMessage& operator=(const MQMessage& other);
 
-  void setProperty(const std::string& name, const std::string& value) ;
-  const std::string & getProperty(const std::string& name) const;
+  void setProperty(const std::string& name, const std::string& value);
+  const std::string& getProperty(const std::string& name) const;
 
-  const std::string &getTopic() const;
+  const std::string& getTopic() const;
   void setTopic(const std::string& topic);
   void setTopic(const char* body, int len);
 
-  const std::string &getTags() const;
+  const std::string& getTags() const;
   void setTags(const std::string& tags);
 
-  const std::string &getKeys() const;
+  const std::string& getKeys() const;
   void setKeys(const std::string& keys);
   void setKeys(const std::vector<std::string>& keys);
 
@@ -66,19 +68,21 @@
   int getSysFlag() const;
   void setSysFlag(int sysFlag);
 
-  const std::string &getBody() const;
+  const std::string& getBody() const;
 
   void setBody(const char* body, int len);
   void setBody(const std::string& body);
 
+  void setTransactionId(const std::string& id) { m_transactionId = id; }
+  std::string getTransactionId() const { return m_transactionId; }
+
   std::map<std::string, std::string> getProperties() const;
   void setProperties(std::map<std::string, std::string>& properties);
 
   const std::string toString() const {
     std::stringstream ss;
     std::string tags = getTags();
-    ss << "Message [topic=" << m_topic << ", flag=" << m_flag
-       << ", tag=" << tags << "]";
+    ss << "Message [topic=" << m_topic << ", flag=" << m_flag << ", tag=" << tags << "]";
     return ss.str();
   }
 
@@ -87,8 +91,12 @@
   void setPropertyInternal(const std::string& name, const std::string& value);
   void setPropertiesInternal(std::map<std::string, std::string>& properties);
 
-  void Init(const std::string& topic, const std::string& tags, const std::string& keys,
-            const int flag, const std::string& body, bool waitStoreMsgOK);
+  void Init(const std::string& topic,
+            const std::string& tags,
+            const std::string& keys,
+            const int flag,
+            const std::string& body,
+            bool waitStoreMsgOK);
 
  public:
   static const std::string PROPERTY_KEYS;
@@ -102,7 +110,7 @@
   static const std::string PROPERTY_PRODUCER_GROUP;
   static const std::string PROPERTY_MIN_OFFSET;
   static const std::string PROPERTY_MAX_OFFSET;
-  
+
   static const std::string PROPERTY_BUYER_ID;
   static const std::string PROPERTY_ORIGIN_MESSAGE_ID;
   static const std::string PROPERTY_TRANSFER_FLAG;
@@ -127,6 +135,7 @@
   std::string m_topic;
   int m_flag;
   std::string m_body;
+  std::string m_transactionId;
   std::map<std::string, std::string> m_properties;
 };
 //<!***************************************************************************
diff --git a/include/MQMessageExt.h b/include/MQMessageExt.h
old mode 100755
new mode 100644
index fb48dae..c5d60e2
--- a/include/MQMessageExt.h
+++ b/include/MQMessageExt.h
@@ -33,8 +33,12 @@
 class ROCKETMQCLIENT_API MQMessageExt : public MQMessage {
  public:
   MQMessageExt();
-  MQMessageExt(int queueId, int64 bornTimestamp, sockaddr bornHost,
-               int64 storeTimestamp, sockaddr storeHost, std::string msgId);
+  MQMessageExt(int queueId,
+               int64 bornTimestamp,
+               sockaddr bornHost,
+               int64 storeTimestamp,
+               sockaddr storeHost,
+               std::string msgId);
 
   virtual ~MQMessageExt();
 
@@ -84,16 +88,12 @@
 
   std::string toString() const {
     std::stringstream ss;
-    ss << "MessageExt [queueId=" << m_queueId << ", storeSize=" << m_storeSize
-       << ", queueOffset=" << m_queueOffset << ", sysFlag=" << m_sysFlag
-       << ", bornTimestamp=" << m_bornTimestamp
-       << ", bornHost=" << getBornHostString()
-       << ", storeTimestamp=" << m_storeTimestamp
-       << ", storeHost=" << getStoreHostString() << ", msgId=" << m_msgId
+    ss << "MessageExt [queueId=" << m_queueId << ", storeSize=" << m_storeSize << ", queueOffset=" << m_queueOffset
+       << ", sysFlag=" << m_sysFlag << ", bornTimestamp=" << m_bornTimestamp << ", bornHost=" << getBornHostString()
+       << ", storeTimestamp=" << m_storeTimestamp << ", storeHost=" << getStoreHostString() << ", msgId=" << m_msgId
        << ", commitLogOffset=" << m_commitLogOffset << ", bodyCRC=" << m_bodyCRC
-       << ", reconsumeTimes=" << m_reconsumeTimes
-       << ", preparedTransactionOffset=" << m_preparedTransactionOffset << ",  "
-       << MQMessage::toString() << "]";
+       << ", reconsumeTimes=" << m_reconsumeTimes << ", preparedTransactionOffset=" << m_preparedTransactionOffset
+       << ",  " << MQMessage::toString() << "]";
     return ss.str();
   }
 
diff --git a/include/MQMessageListener.h b/include/MQMessageListener.h
old mode 100755
new mode 100644
index 63bd74d..84fdb48
--- a/include/MQMessageListener.h
+++ b/include/MQMessageListener.h
@@ -24,9 +24,9 @@
 namespace rocketmq {

 //<!***************************************************************************

 enum ConsumeStatus {

-  //consume success, msg will be cleard from memory

+  // consume success, msg will be cleard from memory

   CONSUME_SUCCESS,

-  //consume fail, but will be re-consume by call messageLisenter again

+  // consume fail, but will be re-consume by call messageLisenter again

   RECONSUME_LATER

 };

 

@@ -50,39 +50,28 @@
 // SUSPEND_CURRENT_QUEUE_A_MOMENT

 /*};*/

 

-enum MessageListenerType {

-  messageListenerDefaultly = 0,

-  messageListenerOrderly = 1,

-  messageListenerConcurrently = 2

-};

+enum MessageListenerType { messageListenerDefaultly = 0, messageListenerOrderly = 1, messageListenerConcurrently = 2 };

 

 //<!***************************************************************************

 class ROCKETMQCLIENT_API MQMessageListener {

  public:

   virtual ~MQMessageListener() {}

   virtual ConsumeStatus consumeMessage(const std::vector<MQMessageExt>& msgs) = 0;

-  virtual MessageListenerType getMessageListenerType() {

-    return messageListenerDefaultly;

-  }

+  virtual MessageListenerType getMessageListenerType() { return messageListenerDefaultly; }

 };

 

 class ROCKETMQCLIENT_API MessageListenerOrderly : public MQMessageListener {

  public:

   virtual ~MessageListenerOrderly() {}

   virtual ConsumeStatus consumeMessage(const std::vector<MQMessageExt>& msgs) = 0;

-  virtual MessageListenerType getMessageListenerType() {

-    return messageListenerOrderly;

-  }

+  virtual MessageListenerType getMessageListenerType() { return messageListenerOrderly; }

 };

 

-class ROCKETMQCLIENT_API MessageListenerConcurrently

-    : public MQMessageListener {

+class ROCKETMQCLIENT_API MessageListenerConcurrently : public MQMessageListener {

  public:

   virtual ~MessageListenerConcurrently() {}

   virtual ConsumeStatus consumeMessage(const std::vector<MQMessageExt>& msgs) = 0;

-  virtual MessageListenerType getMessageListenerType() {

-    return messageListenerConcurrently;

-  }

+  virtual MessageListenerType getMessageListenerType() { return messageListenerConcurrently; }

 };

 

 //<!***************************************************************************

diff --git a/include/MQMessageQueue.h b/include/MQMessageQueue.h
old mode 100755
new mode 100644
index bb1c4ae..555a9b3
--- a/include/MQMessageQueue.h
+++ b/include/MQMessageQueue.h
@@ -48,8 +48,7 @@
 

   const std::string toString() const {

     std::stringstream ss;

-    ss << "MessageQueue [topic=" << m_topic << ", brokerName=" << m_brokerName

-       << ", queueId=" << m_queueId << "]";

+    ss << "MessageQueue [topic=" << m_topic << ", brokerName=" << m_brokerName << ", queueId=" << m_queueId << "]";

 

     return ss.str();

   }

diff --git a/include/MQProducer.h b/include/MQProducer.h
old mode 100755
new mode 100644
index 2673931..74be0e3
--- a/include/MQProducer.h
+++ b/include/MQProducer.h
@@ -36,28 +36,25 @@
   virtual SendResult send(MQMessage& msg, const MQMessageQueue& mq) = 0;

   // strict order msg, if send failed on seleted MessageQueue, throw exception

   // to up layer

-  virtual SendResult send(MQMessage& msg, MessageQueueSelector* selector,

-                          void* arg) = 0;

+  virtual SendResult send(MQMessage& msg, MessageQueueSelector* selector, void* arg) = 0;

   // non-strict order msg, if send failed on seleted MessageQueue, will auto

   // retry others Broker queues with autoRetryTimes;

   // if setted bActiveBroker, if send failed on seleted MessageQueue, , and then

   // search brokers with best service state, lastly will search brokers that had

   // been sent failed by last time;

-  virtual SendResult send(MQMessage& msg, MessageQueueSelector* selector,

-                          void* arg, int autoRetryTimes,

+  virtual SendResult send(MQMessage& msg,

+                          MessageQueueSelector* selector,

+                          void* arg,

+                          int autoRetryTimes,

                           bool bActiveBroker = false) = 0;

-  virtual void send(MQMessage& msg, SendCallback* sendCallback,

-                    bool bSelectActiveBroker = false) = 0;

-  virtual void send(MQMessage& msg, const MQMessageQueue& mq,

-                    SendCallback* sendCallback) = 0;

-  virtual void send(MQMessage& msg, MessageQueueSelector* selector, void* arg,

-                    SendCallback* sendCallback) = 0;

+  virtual void send(MQMessage& msg, SendCallback* sendCallback, bool bSelectActiveBroker = false) = 0;

+  virtual void send(MQMessage& msg, const MQMessageQueue& mq, SendCallback* sendCallback) = 0;

+  virtual void send(MQMessage& msg, MessageQueueSelector* selector, void* arg, SendCallback* sendCallback) = 0;

   virtual SendResult send(std::vector<MQMessage>& msgs) = 0;

   virtual SendResult send(std::vector<MQMessage>& msgs, const MQMessageQueue& mq) = 0;

   virtual void sendOneway(MQMessage& msg, bool bSelectActiveBroker = false) = 0;

   virtual void sendOneway(MQMessage& msg, const MQMessageQueue& mq) = 0;

-  virtual void sendOneway(MQMessage& msg, MessageQueueSelector* selector,

-                          void* arg) = 0;

+  virtual void sendOneway(MQMessage& msg, MessageQueueSelector* selector, void* arg) = 0;

 };

 //<!***************************************************************************

 }  //<!end namespace;

diff --git a/include/MQSelector.h b/include/MQSelector.h
old mode 100755
new mode 100644
index 77309b8..5d1ae04
--- a/include/MQSelector.h
+++ b/include/MQSelector.h
@@ -25,8 +25,7 @@
 class ROCKETMQCLIENT_API MessageQueueSelector {

  public:

   virtual ~MessageQueueSelector() {}

-  virtual MQMessageQueue select(const std::vector<MQMessageQueue>& mqs,

-                                const MQMessage& msg, void* arg) = 0;

+  virtual MQMessageQueue select(const std::vector<MQMessageQueue>& mqs, const MQMessage& msg, void* arg) = 0;

 };

 //<!***************************************************************************

 }  //<!end namespace;

diff --git a/include/MQueueListener.h b/include/MQueueListener.h
old mode 100755
new mode 100644
diff --git a/include/PullResult.h b/include/PullResult.h
old mode 100755
new mode 100644
index 69a6aef..a5cddf0
--- a/include/PullResult.h
+++ b/include/PullResult.h
@@ -31,29 +31,28 @@
   BROKER_TIMEOUT  // indicate pull request timeout or received NULL response

 };

 

-static const char* EnumStrings[] = {"FOUND", "NO_NEW_MSG", "NO_MATCHED_MSG",

-                                    "OFFSET_ILLEGAL", "BROKER_TIMEOUT"};

+static const char* EnumStrings[] = {"FOUND", "NO_NEW_MSG", "NO_MATCHED_MSG", "OFFSET_ILLEGAL", "BROKER_TIMEOUT"};

 

 //<!***************************************************************************

 class ROCKETMQCLIENT_API PullResult {

  public:

   PullResult();

   PullResult(PullStatus status);

-  PullResult(PullStatus pullStatus, int64 nextBeginOffset,

-             int64 minOffset, int64 maxOffset);

+  PullResult(PullStatus pullStatus, int64 nextBeginOffset, int64 minOffset, int64 maxOffset);

 

-  PullResult(PullStatus pullStatus, int64 nextBeginOffset,

-             int64 minOffset, int64 maxOffset,

+  PullResult(PullStatus pullStatus,

+             int64 nextBeginOffset,

+             int64 minOffset,

+             int64 maxOffset,

              const std::vector<MQMessageExt>& src);

 

   virtual ~PullResult();

 

   std::string toString() {

     std::stringstream ss;

-    ss << "PullResult [ pullStatus=" << EnumStrings[pullStatus]

-       << ", nextBeginOffset=" << nextBeginOffset << ", minOffset=" << minOffset

-       << ", maxOffset=" << maxOffset

-       << ", msgFoundList=" << msgFoundList.size() << " ]";

+    ss << "PullResult [ pullStatus=" << EnumStrings[pullStatus] << ", nextBeginOffset=" << nextBeginOffset

+       << ", minOffset=" << minOffset << ", maxOffset=" << maxOffset << ", msgFoundList=" << msgFoundList.size()

+       << " ]";

     return ss.str();

   }

 

diff --git a/include/QueryResult.h b/include/QueryResult.h
old mode 100755
new mode 100644
index c9861a0..7b3ec08
--- a/include/QueryResult.h
+++ b/include/QueryResult.h
@@ -24,8 +24,7 @@
 //<!************************************************************************

 class ROCKETMQCLIENT_API QueryResult {

  public:

-  QueryResult(uint64 indexLastUpdateTimestamp,

-              const std::vector<MQMessageExt*>& messageList) {

+  QueryResult(uint64 indexLastUpdateTimestamp, const std::vector<MQMessageExt*>& messageList) {

     m_indexLastUpdateTimestamp = indexLastUpdateTimestamp;

     m_messageList = messageList;

   }

diff --git a/include/RocketMQClient.h b/include/RocketMQClient.h
old mode 100755
new mode 100644
diff --git a/include/SendMessageHook.h b/include/SendMessageHook.h
old mode 100755
new mode 100644
diff --git a/include/SendResult.h b/include/SendResult.h
old mode 100755
new mode 100644
index 239f07a..870d03b
--- a/include/SendResult.h
+++ b/include/SendResult.h
@@ -23,29 +23,32 @@
 namespace rocketmq {

 //<!***************************************************************************

 //<!all to Master;

-enum SendStatus {

-  SEND_OK,

-  SEND_FLUSH_DISK_TIMEOUT,

-  SEND_FLUSH_SLAVE_TIMEOUT,

-  SEND_SLAVE_NOT_AVAILABLE

-};

+enum SendStatus { SEND_OK, SEND_FLUSH_DISK_TIMEOUT, SEND_FLUSH_SLAVE_TIMEOUT, SEND_SLAVE_NOT_AVAILABLE };

 

 //<!***************************************************************************

 class ROCKETMQCLIENT_API SendResult {

  public:

   SendResult();

-  SendResult(const SendStatus& sendStatus, const std::string& msgId, const std::string& offsetMsgId,

-             const MQMessageQueue& messageQueue, int64 queueOffset);

+  SendResult(const SendStatus& sendStatus,

+             const std::string& msgId,

+             const std::string& offsetMsgId,

+             const MQMessageQueue& messageQueue,

+             int64 queueOffset);

 

   virtual ~SendResult();

   SendResult(const SendResult& other);

   SendResult& operator=(const SendResult& other);

 

+  void setTransactionId(const std::string& id) { m_transactionId = id; }

+

+  std::string getTransactionId() { return m_transactionId; }

+

   const std::string& getMsgId() const;

   const std::string& getOffsetMsgId() const;

   SendStatus getSendStatus() const;

   MQMessageQueue getMessageQueue() const;

   int64 getQueueOffset() const;

+  std::string toString() const;

 

  private:

   SendStatus m_sendStatus;

@@ -53,8 +56,9 @@
   std::string m_offsetMsgId;

   MQMessageQueue m_messageQueue;

   int64 m_queueOffset;

+  std::string m_transactionId;

 };

 

 //<!***************************************************************************

-}  //<!end namespace;

+}  // namespace rocketmq

 #endif

diff --git a/include/SessionCredentials.h b/include/SessionCredentials.h
old mode 100755
new mode 100644
index 0a5706e..cbab0a1
--- a/include/SessionCredentials.h
+++ b/include/SessionCredentials.h
@@ -14,7 +14,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
- 
+
 #ifndef __SESSIONCREDENTIALS_H__
 #define __SESSIONCREDENTIALS_H__
 
@@ -30,11 +30,8 @@
   static const std::string SignatureMethod;
   static const std::string ONSChannelKey;
 
-  SessionCredentials(std::string input_accessKey, std::string input_secretKey,
-                     const std::string& input_authChannel)
-      : accessKey(input_accessKey),
-        secretKey(input_secretKey),
-        authChannel(input_authChannel) {}
+  SessionCredentials(std::string input_accessKey, std::string input_secretKey, const std::string& input_authChannel)
+      : accessKey(input_accessKey), secretKey(input_secretKey), authChannel(input_authChannel) {}
   SessionCredentials() : authChannel("ALIYUN") {}
   ~SessionCredentials() {}
 
@@ -52,9 +49,7 @@
 
   std::string getSignatureMethod() const { return signatureMethod; }
 
-  void setSignatureMethod(std::string input_signatureMethod) {
-    signatureMethod = input_signatureMethod;
-  }
+  void setSignatureMethod(std::string input_signatureMethod) { signatureMethod = input_signatureMethod; }
 
   std::string getAuthChannel() const { return authChannel; }
 
diff --git a/include/TransactionListener.h b/include/TransactionListener.h
new file mode 100644
index 0000000..6756e96
--- /dev/null
+++ b/include/TransactionListener.h
@@ -0,0 +1,48 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __TRANSACTIONLISTENER_H__
+#define __TRANSACTIONLISTENER_H__
+
+#include "MQMessage.h"
+#include "MQMessageExt.h"
+#include "TransactionSendResult.h"
+
+namespace rocketmq {
+class ROCKETMQCLIENT_API TransactionListener {
+ public:
+  virtual ~TransactionListener() {}
+  /**
+   * When send transactional prepare(half) message succeed, this method will be invoked to execute local transaction.
+   *
+   * @param msg Half(prepare) message
+   * @param arg Custom business parameter
+   * @return Transaction state
+   */
+  virtual LocalTransactionState executeLocalTransaction(const MQMessage& msg, void* arg) = 0;
+
+  /**
+   * When no response to prepare(half) message. broker will send check message to check the transaction status, and this
+   * method will be invoked to get local transaction status.
+   *
+   * @param msg Check message
+   * @return Transaction state
+   */
+  virtual LocalTransactionState checkLocalTransaction(const MQMessageExt& msg) = 0;
+};
+}  // namespace rocketmq
+#endif
diff --git a/include/TransactionMQProducer.h b/include/TransactionMQProducer.h
new file mode 100644
index 0000000..fcd9a7c
--- /dev/null
+++ b/include/TransactionMQProducer.h
@@ -0,0 +1,74 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __TRANSACTIONMQPRODUCER_H__
+#define __TRANSACTIONMQPRODUCER_H__
+
+#include <boost/asio.hpp>
+#include <boost/asio/io_service.hpp>
+#include <boost/bind.hpp>
+#include <boost/date_time/posix_time/posix_time.hpp>
+#include <boost/weak_ptr.hpp>
+#include <memory>
+#include <string>
+#include "DefaultMQProducer.h"
+#include "MQMessageExt.h"
+#include "TransactionListener.h"
+#include "TransactionSendResult.h"
+
+namespace rocketmq {
+
+class ROCKETMQCLIENT_API TransactionMQProducer : public DefaultMQProducer {
+ public:
+  TransactionMQProducer(const std::string& producerGroup)
+      : DefaultMQProducer(producerGroup), m_thread_num(1), m_ioServiceWork(m_ioService) {}
+  virtual ~TransactionMQProducer() {}
+  void start();
+  void shutdown();
+  std::shared_ptr<TransactionListener> getTransactionListener() { return m_transactionListener; }
+  void setTransactionListener(TransactionListener* listener) { m_transactionListener.reset(listener); }
+  TransactionSendResult sendMessageInTransaction(MQMessage& msg, void* arg);
+  void checkTransactionState(const std::string& addr,
+                             const MQMessageExt& message,
+                             long tranStateTableOffset,
+                             long commitLogOffset,
+                             const std::string& msgId,
+                             const std::string& transactionId,
+                             const std::string& offsetMsgId);
+
+ private:
+  void initTransactionEnv();
+  void destroyTransactionEnv();
+  void endTransaction(SendResult& sendResult, LocalTransactionState& localTransactionState);
+  void checkTransactionStateImpl(const std::string& addr,
+                                 const MQMessageExt& message,
+                                 long tranStateTableOffset,
+                                 long commitLogOffset,
+                                 const std::string& msgId,
+                                 const std::string& transactionId,
+                                 const std::string& offsetMsgId);
+
+ private:
+  std::shared_ptr<TransactionListener> m_transactionListener;
+  int m_thread_num;
+  boost::thread_group m_threadpool;
+  boost::asio::io_service m_ioService;
+  boost::asio::io_service::work m_ioServiceWork;
+};
+}  // namespace rocketmq
+
+#endif
diff --git a/include/TransactionSendResult.h b/include/TransactionSendResult.h
new file mode 100644
index 0000000..0bb1e48
--- /dev/null
+++ b/include/TransactionSendResult.h
@@ -0,0 +1,48 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __TRANSACTIONSENDRESULT_H__
+#define __TRANSACTIONSENDRESULT_H__
+
+#include "SendResult.h"
+
+namespace rocketmq {
+
+enum LocalTransactionState { COMMIT_MESSAGE, ROLLBACK_MESSAGE, UNKNOWN };
+
+class ROCKETMQCLIENT_API TransactionSendResult : public SendResult {
+ public:
+  TransactionSendResult() {}
+
+  TransactionSendResult(const SendStatus& sendStatus,
+                        const std::string& msgId,
+                        const std::string& offsetMsgId,
+                        const MQMessageQueue& messageQueue,
+                        int64 queueOffset)
+      : SendResult(sendStatus, msgId, offsetMsgId, messageQueue, queueOffset) {}
+
+  LocalTransactionState getLocalTransactionState() { return m_localTransactionState; }
+
+  void setLocalTransactionState(LocalTransactionState localTransactionState) {
+    m_localTransactionState = localTransactionState;
+  }
+
+ private:
+  LocalTransactionState m_localTransactionState;
+};
+}  // namespace rocketmq
+#endif
\ No newline at end of file
diff --git a/libs/signature/include/base64.h b/libs/signature/include/base64.h
old mode 100755
new mode 100644
index 35d4cdd..9e2d133
--- a/libs/signature/include/base64.h
+++ b/libs/signature/include/base64.h
@@ -16,35 +16,31 @@
  */
 
 #ifndef BASE64_H
-# define BASE64_H
+#define BASE64_H
 
 /* Get size_t. */
-# include <stddef.h>
+#include <stddef.h>
 
 /* Get bool. */
-# include <stdbool.h>
-
+#include <stdbool.h>
 
 #ifdef __cplusplus
-namespace rocketmqSignature{
+namespace rocketmqSignature {
 #endif
 
-		/* This uses that the expression (n+(k-1))/k means the smallest
-			 integer >= n/k, i.e., the ceiling of n/k.  */
-# define BASE64_LENGTH(inlen) ((((inlen) + 2) / 3) * 4)
+/* This uses that the expression (n+(k-1))/k means the smallest
+   integer >= n/k, i.e., the ceiling of n/k.  */
+#define BASE64_LENGTH(inlen) ((((inlen) + 2) / 3) * 4)
 
 extern bool isbase64(char ch);
 
-extern void base64_encode(const char *in, size_t inlen,
-	char *out, size_t outlen);
+extern void base64_encode(const char* in, size_t inlen, char* out, size_t outlen);
 
-extern size_t base64_encode_alloc(const char *in, size_t inlen, char **out);
+extern size_t base64_encode_alloc(const char* in, size_t inlen, char** out);
 
-extern bool base64_decode(const char *in, size_t inlen,
-	char *out, size_t *outlen);
+extern bool base64_decode(const char* in, size_t inlen, char* out, size_t* outlen);
 
-extern bool base64_decode_alloc(const char *in, size_t inlen,
-	char **out, size_t *outlen);
+extern bool base64_decode_alloc(const char* in, size_t inlen, char** out, size_t* outlen);
 
 #ifdef __cplusplus
 }
diff --git a/libs/signature/include/hmac.h b/libs/signature/include/hmac.h
old mode 100755
new mode 100644
index 2b7515f..889ad7d
--- a/libs/signature/include/hmac.h
+++ b/libs/signature/include/hmac.h
@@ -25,15 +25,15 @@
 #include <sys/types.h>
 
 #ifndef SHA1_DIGEST_LEN
-#define SHA1_DIGEST_LEN		20
+#define SHA1_DIGEST_LEN 20
 #endif
 
 #ifndef SHA256_DIGEST_LEN
-#define SHA256_DIGEST_LEN	32
+#define SHA256_DIGEST_LEN 32
 #endif
 
 #ifndef SHA512_DIGEST_LEN
-#define SHA512_DIGEST_LEN	64
+#define SHA512_DIGEST_LEN 64
 #endif
 
 /*
@@ -51,13 +51,13 @@
  */
 
 #ifdef __cplusplus
-namespace rocketmqSignature{
+namespace rocketmqSignature {
 
 #endif
 
-extern int hmac_sha1(const void *key, size_t key_len, const void *data, size_t data_len, void *ret_buf);
-extern int hmac_sha256(const void *key, size_t key_len, const void *data, size_t data_len, void *ret_buf);
-extern int hmac_sha512(const void *key, size_t key_len, const void *data, size_t data_len, void *ret_buf);
+extern int hmac_sha1(const void* key, size_t key_len, const void* data, size_t data_len, void* ret_buf);
+extern int hmac_sha256(const void* key, size_t key_len, const void* data, size_t data_len, void* ret_buf);
+extern int hmac_sha512(const void* key, size_t key_len, const void* data, size_t data_len, void* ret_buf);
 
 #ifdef __cplusplus
 }
@@ -68,4 +68,3 @@
 #endif
 
 #endif
-
diff --git a/libs/signature/include/param_list.h b/libs/signature/include/param_list.h
old mode 100755
new mode 100644
index 8622204..afe87b0
--- a/libs/signature/include/param_list.h
+++ b/libs/signature/include/param_list.h
@@ -23,26 +23,25 @@
 #endif
 
 #ifdef __cplusplus
-namespace rocketmqSignature{
+namespace rocketmqSignature {
 #endif
 
-
 typedef struct _spas_param_node {
-	char *name;
-	char *value;
-	struct _spas_param_node *pnext;
+  char* name;
+  char* value;
+  struct _spas_param_node* pnext;
 } SPAS_PARAM_NODE;
 
 typedef struct _spas_param_list {
-	SPAS_PARAM_NODE *phead;
-	unsigned int length; /* count of nodes */
-	unsigned int size; /* total size of string presentation */
+  SPAS_PARAM_NODE* phead;
+  unsigned int length; /* count of nodes */
+  unsigned int size;   /* total size of string presentation */
 } SPAS_PARAM_LIST;
 
-extern SPAS_PARAM_LIST * create_param_list(void);
-extern int add_param_to_list(SPAS_PARAM_LIST *list, const char *name, const char *value);
-extern void free_param_list(SPAS_PARAM_LIST *list);
-extern char * param_list_to_str(const SPAS_PARAM_LIST *list);
+extern SPAS_PARAM_LIST* create_param_list(void);
+extern int add_param_to_list(SPAS_PARAM_LIST* list, const char* name, const char* value);
+extern void free_param_list(SPAS_PARAM_LIST* list);
+extern char* param_list_to_str(const SPAS_PARAM_LIST* list);
 
 #ifdef __cplusplus
 }
@@ -53,4 +52,3 @@
 #endif
 
 #endif
-
diff --git a/libs/signature/include/sha1.h b/libs/signature/include/sha1.h
old mode 100755
new mode 100644
index 997610d..789d411
--- a/libs/signature/include/sha1.h
+++ b/libs/signature/include/sha1.h
@@ -16,10 +16,10 @@
  */
 
 #ifndef SHA1_H
-# define SHA1_H 1
+#define SHA1_H 1
 
-# include <stdio.h>
-# include <stdint.h>
+#include <stdio.h>
+#include <stdint.h>
 
 #ifdef __cplusplus
 namespace rocketmqSignature {
@@ -28,8 +28,7 @@
 #define SHA1_DIGEST_SIZE 20
 
 /* Structure to save state of computation between the single steps.  */
-struct sha1_ctx
-{
+struct sha1_ctx {
   uint32_t A;
   uint32_t B;
   uint32_t C;
@@ -41,48 +40,42 @@
   uint32_t buffer[32];
 };
 
-
 /* Initialize structure containing state of computation. */
-extern void sha1_init_ctx (struct sha1_ctx *ctx);
+extern void sha1_init_ctx(struct sha1_ctx* ctx);
 
 /* Starting with the result of former calls of this function (or the
    initialization function update the context for the next LEN bytes
    starting at BUFFER.
    It is necessary that LEN is a multiple of 64!!! */
-extern void sha1_process_block (const void *buffer, size_t len,
-				struct sha1_ctx *ctx);
+extern void sha1_process_block(const void* buffer, size_t len, struct sha1_ctx* ctx);
 
 /* Starting with the result of former calls of this function (or the
    initialization function update the context for the next LEN bytes
    starting at BUFFER.
    It is NOT required that LEN is a multiple of 64.  */
-extern void sha1_process_bytes (const void *buffer, size_t len,
-				struct sha1_ctx *ctx);
+extern void sha1_process_bytes(const void* buffer, size_t len, struct sha1_ctx* ctx);
 
 /* Process the remaining bytes in the buffer and put result from CTX
    in first 20 bytes following RESBUF.  The result is always in little
    endian byte order, so that a byte-wise output yields to the wanted
    ASCII representation of the message digest.  */
-extern void *sha1_finish_ctx (struct sha1_ctx *ctx, void *resbuf);
-
+extern void* sha1_finish_ctx(struct sha1_ctx* ctx, void* resbuf);
 
 /* Put result from CTX in first 20 bytes following RESBUF.  The result is
    always in little endian byte order, so that a byte-wise output yields
    to the wanted ASCII representation of the message digest.  */
-extern void *sha1_read_ctx (const struct sha1_ctx *ctx, void *resbuf);
-
+extern void* sha1_read_ctx(const struct sha1_ctx* ctx, void* resbuf);
 
 /* Compute SHA1 message digest for bytes read from STREAM.  The
    resulting message digest number will be written into the 20 bytes
    beginning at RESBLOCK.  */
-extern int sha1_stream (FILE *stream, void *resblock);
-
+extern int sha1_stream(FILE* stream, void* resblock);
 
 /* Compute SHA1 message digest for LEN bytes beginning at BUFFER.  The
    result is always in little endian byte order, so that a byte-wise
    output yields to the wanted ASCII representation of the message
    digest.  */
-extern void *sha1_buffer (const char *buffer, size_t len, void *resblock);
+extern void* sha1_buffer(const char* buffer, size_t len, void* resblock);
 
 #ifdef __cplusplus
 }
diff --git a/libs/signature/include/sha256.h b/libs/signature/include/sha256.h
old mode 100755
new mode 100644
index 2dfb880..1726b60
--- a/libs/signature/include/sha256.h
+++ b/libs/signature/include/sha256.h
@@ -16,18 +16,17 @@
  */
 
 #ifndef SHA256_H
-# define SHA256_H 1
+#define SHA256_H 1
 
-# include <stdio.h>
-# include <stdint.h>
+#include <stdio.h>
+#include <stdint.h>
 
 #ifdef __cplusplus
-namespace rocketmqSignature{
+namespace rocketmqSignature {
 #endif
 
 /* Structure to save state of computation between the single steps.  */
-struct sha256_ctx
-{
+struct sha256_ctx {
   uint32_t state[8];
 
   uint32_t total[2];
@@ -39,53 +38,49 @@
 enum { SHA256_DIGEST_SIZE = 32 };
 
 /* Initialize structure containing state of computation. */
-extern void sha256_init_ctx (struct sha256_ctx *ctx);
-extern void sha224_init_ctx (struct sha256_ctx *ctx);
+extern void sha256_init_ctx(struct sha256_ctx* ctx);
+extern void sha224_init_ctx(struct sha256_ctx* ctx);
 
 /* Starting with the result of former calls of this function (or the
    initialization function update the context for the next LEN bytes
    starting at BUFFER.
    It is necessary that LEN is a multiple of 64!!! */
-extern void sha256_process_block (const void *buffer, size_t len,
-				  struct sha256_ctx *ctx);
+extern void sha256_process_block(const void* buffer, size_t len, struct sha256_ctx* ctx);
 
 /* Starting with the result of former calls of this function (or the
    initialization function update the context for the next LEN bytes
    starting at BUFFER.
    It is NOT required that LEN is a multiple of 64.  */
-extern void sha256_process_bytes (const void *buffer, size_t len,
-				  struct sha256_ctx *ctx);
+extern void sha256_process_bytes(const void* buffer, size_t len, struct sha256_ctx* ctx);
 
 /* Process the remaining bytes in the buffer and put result from CTX
    in first 32 (28) bytes following RESBUF.  The result is always in little
    endian byte order, so that a byte-wise output yields to the wanted
    ASCII representation of the message digest.  */
-extern void *sha256_finish_ctx (struct sha256_ctx *ctx, void *resbuf);
-extern void *sha224_finish_ctx (struct sha256_ctx *ctx, void *resbuf);
-
+extern void* sha256_finish_ctx(struct sha256_ctx* ctx, void* resbuf);
+extern void* sha224_finish_ctx(struct sha256_ctx* ctx, void* resbuf);
 
 /* Put result from CTX in first 32 (28) bytes following RESBUF.  The result is
    always in little endian byte order, so that a byte-wise output yields
    to the wanted ASCII representation of the message digest.  */
-extern void *sha256_read_ctx (const struct sha256_ctx *ctx, void *resbuf);
-extern void *sha224_read_ctx (const struct sha256_ctx *ctx, void *resbuf);
-
+extern void* sha256_read_ctx(const struct sha256_ctx* ctx, void* resbuf);
+extern void* sha224_read_ctx(const struct sha256_ctx* ctx, void* resbuf);
 
 /* Compute SHA256 (SHA224) message digest for bytes read from STREAM.  The
    resulting message digest number will be written into the 32 (28) bytes
    beginning at RESBLOCK.  */
-extern int sha256_stream (FILE *stream, void *resblock);
-extern int sha224_stream (FILE *stream, void *resblock);
+extern int sha256_stream(FILE* stream, void* resblock);
+extern int sha224_stream(FILE* stream, void* resblock);
 
 /* Compute SHA256 (SHA224) message digest for LEN bytes beginning at BUFFER.  The
    result is always in little endian byte order, so that a byte-wise
    output yields to the wanted ASCII representation of the message
    digest.  */
-extern void *sha256_buffer (const char *buffer, size_t len, void *resblock);
-extern void *sha224_buffer (const char *buffer, size_t len, void *resblock);
+extern void* sha256_buffer(const char* buffer, size_t len, void* resblock);
+extern void* sha224_buffer(const char* buffer, size_t len, void* resblock);
 
 #ifdef __cplusplus
 }
-#endif 
+#endif
 
 #endif
diff --git a/libs/signature/include/sha512.h b/libs/signature/include/sha512.h
old mode 100755
new mode 100644
index 43d6bdc..38328a1
--- a/libs/signature/include/sha512.h
+++ b/libs/signature/include/sha512.h
@@ -16,19 +16,18 @@
  */
 
 #ifndef SHA512_H
-# define SHA512_H 1
+#define SHA512_H 1
 
-# include <stdio.h>
+#include <stdio.h>
 
-# include "u64.h"
+#include "u64.h"
 
 #ifdef __cplusplus
-namespace rocketmqSignature{
+namespace rocketmqSignature {
 #endif
 
 /* Structure to save state of computation between the single steps.  */
-struct sha512_ctx
-{
+struct sha512_ctx {
   u64 state[8];
 
   u64 total[2];
@@ -40,30 +39,27 @@
 enum { SHA512_DIGEST_SIZE = 64 };
 
 /* Initialize structure containing state of computation. */
-extern void sha512_init_ctx (struct sha512_ctx *ctx);
-extern void sha384_init_ctx (struct sha512_ctx *ctx);
+extern void sha512_init_ctx(struct sha512_ctx* ctx);
+extern void sha384_init_ctx(struct sha512_ctx* ctx);
 
 /* Starting with the result of former calls of this function (or the
    initialization function update the context for the next LEN bytes
    starting at BUFFER.
    It is necessary that LEN is a multiple of 128!!! */
-extern void sha512_process_block (const void *buffer, size_t len,
-				  struct sha512_ctx *ctx);
+extern void sha512_process_block(const void* buffer, size_t len, struct sha512_ctx* ctx);
 
 /* Starting with the result of former calls of this function (or the
    initialization function update the context for the next LEN bytes
    starting at BUFFER.
    It is NOT required that LEN is a multiple of 128.  */
-extern void sha512_process_bytes (const void *buffer, size_t len,
-				  struct sha512_ctx *ctx);
+extern void sha512_process_bytes(const void* buffer, size_t len, struct sha512_ctx* ctx);
 
 /* Process the remaining bytes in the buffer and put result from CTX
    in first 64 (48) bytes following RESBUF.  The result is always in little
    endian byte order, so that a byte-wise output yields to the wanted
    ASCII representation of the message digest.  */
-extern void *sha512_finish_ctx (struct sha512_ctx *ctx, void *resbuf);
-extern void *sha384_finish_ctx (struct sha512_ctx *ctx, void *resbuf);
-
+extern void* sha512_finish_ctx(struct sha512_ctx* ctx, void* resbuf);
+extern void* sha384_finish_ctx(struct sha512_ctx* ctx, void* resbuf);
 
 /* Put result from CTX in first 64 (48) bytes following RESBUF.  The result is
    always in little endian byte order, so that a byte-wise output yields
@@ -71,22 +67,21 @@
 
    IMPORTANT: On some systems it is required that RESBUF is correctly
    aligned for a 32 bits value.  */
-extern void *sha512_read_ctx (const struct sha512_ctx *ctx, void *resbuf);
-extern void *sha384_read_ctx (const struct sha512_ctx *ctx, void *resbuf);
-
+extern void* sha512_read_ctx(const struct sha512_ctx* ctx, void* resbuf);
+extern void* sha384_read_ctx(const struct sha512_ctx* ctx, void* resbuf);
 
 /* Compute SHA512 (SHA384) message digest for bytes read from STREAM.  The
    resulting message digest number will be written into the 64 (48) bytes
    beginning at RESBLOCK.  */
-extern int sha512_stream (FILE *stream, void *resblock);
-extern int sha384_stream (FILE *stream, void *resblock);
+extern int sha512_stream(FILE* stream, void* resblock);
+extern int sha384_stream(FILE* stream, void* resblock);
 
 /* Compute SHA512 (SHA384) message digest for LEN bytes beginning at BUFFER.  The
    result is always in little endian byte order, so that a byte-wise
    output yields to the wanted ASCII representation of the message
    digest.  */
-extern void *sha512_buffer (const char *buffer, size_t len, void *resblock);
-extern void *sha384_buffer (const char *buffer, size_t len, void *resblock);
+extern void* sha512_buffer(const char* buffer, size_t len, void* resblock);
+extern void* sha384_buffer(const char* buffer, size_t len, void* resblock);
 
 #ifdef __cplusplus
 }
diff --git a/libs/signature/include/spas_client.h b/libs/signature/include/spas_client.h
old mode 100755
new mode 100644
index 9eb5143..7bf6aae
--- a/libs/signature/include/spas_client.h
+++ b/libs/signature/include/spas_client.h
@@ -28,14 +28,15 @@
 namespace rocketmqSignature {
 #endif
 
-#define SPAS_MAX_KEY_LEN 128            /* max access_key/secret_key length */
-#define SPAS_MAX_PATH 256               /* max credential file path length */
-#define SPAS_ACCESS_KEY_TAG "accessKey" /* access_key tag in credential file \
-                                           */
-#define SPAS_SECRET_KEY_TAG "secretKey" /* secret_key tag in credential file \
-                                           */
-#define SPAS_CREDENTIAL_ENV \
-  "SPAS_CREDENTIAL" /* credential file environment variable */
+#define SPAS_MAX_KEY_LEN 128 /* max access_key/secret_key length */
+#define SPAS_MAX_PATH 256    /* max credential file path length */
+#define SPAS_ACCESS_KEY_TAG                        \
+  "accessKey" /* access_key tag in credential file \
+                 */
+#define SPAS_SECRET_KEY_TAG                                                        \
+  "secretKey"                                 /* secret_key tag in credential file \
+                                                 */
+#define SPAS_CREDENTIAL_ENV "SPAS_CREDENTIAL" /* credential file environment variable */
 
 typedef enum {
   SIGN_HMACSHA1 = 0,   /* HmacSHA1 */
@@ -67,31 +68,29 @@
   char secret_key[SPAS_MAX_KEY_LEN];
 } SPAS_CREDENTIAL;
 
-extern int spas_load_credential(char *path, CREDENTIAL_UPDATE_MODE mode);
-extern int spas_set_access_key(char *key);
-extern int spas_set_secret_key(char *key);
-extern char *spas_get_access_key(void);
-extern char *spas_get_secret_key(void);
-extern SPAS_CREDENTIAL *spas_get_credential(void);
+extern int spas_load_credential(char* path, CREDENTIAL_UPDATE_MODE mode);
+extern int spas_set_access_key(char* key);
+extern int spas_set_secret_key(char* key);
+extern char* spas_get_access_key(void);
+extern char* spas_get_secret_key(void);
+extern SPAS_CREDENTIAL* spas_get_credential(void);
 
 #ifdef SPAS_MT
 
-extern int spas_load_thread_credential(char *path);
-extern int spas_set_thread_access_key(char *key);
-extern int spas_set_thread_secret_key(char *key);
-extern char *spas_get_thread_access_key(void);
-extern char *spas_get_thread_secret_key(void);
+extern int spas_load_thread_credential(char* path);
+extern int spas_set_thread_access_key(char* key);
+extern int spas_set_thread_secret_key(char* key);
+extern char* spas_get_thread_access_key(void);
+extern char* spas_get_thread_secret_key(void);
 
 #endif
 
-extern char *spas_get_signature(const SPAS_PARAM_LIST *list, const char *key);
-extern char *spas_get_signature2(const SPAS_PARAM_LIST *list, const char *key,
-                                 SPAS_SIGN_ALGORITHM algorithm);
-extern char *spas_sign(const char *data, size_t size, const char *key);
-extern char *spas_sign2(const char *data, size_t size, const char *key,
-                        SPAS_SIGN_ALGORITHM algorithm);
-extern void spas_mem_free(char *pSignature);
-extern char *spas_get_version(void);
+extern char* spas_get_signature(const SPAS_PARAM_LIST* list, const char* key);
+extern char* spas_get_signature2(const SPAS_PARAM_LIST* list, const char* key, SPAS_SIGN_ALGORITHM algorithm);
+extern char* spas_sign(const char* data, size_t size, const char* key);
+extern char* spas_sign2(const char* data, size_t size, const char* key, SPAS_SIGN_ALGORITHM algorithm);
+extern void spas_mem_free(char* pSignature);
+extern char* spas_get_version(void);
 
 #ifdef __cplusplus
 }
diff --git a/libs/signature/include/u64.h b/libs/signature/include/u64.h
index 612b044..e7580e5 100644
--- a/libs/signature/include/u64.h
+++ b/libs/signature/include/u64.h
@@ -19,42 +19,42 @@
 #include <stdint.h>
 
 /* Return X rotated left by N bits, where 0 < N < 64.  */
-#define u64rol(x, n) u64or (u64shl (x, n), u64shr (x, 64 - n))
+#define u64rol(x, n) u64or(u64shl(x, n), u64shr(x, 64 - n))
 
 #ifdef UINT64_MAX
 
 /* Native implementations are trivial.  See below for comments on what
    these operations do.  */
 typedef uint64_t u64;
-# define u64hilo(hi, lo) ((u64) (((u64) (hi) << 32) + (lo)))
-# define u64init(hi, lo) u64hilo (hi, lo)
-# define u64lo(x) ((u64) (x))
-# define u64lt(x, y) ((x) < (y))
-# define u64and(x, y) ((x) & (y))
-# define u64or(x, y) ((x) | (y))
-# define u64xor(x, y) ((x) ^ (y))
-# define u64plus(x, y) ((x) + (y))
-# define u64shl(x, n) ((x) << (n))
-# define u64shr(x, n) ((x) >> (n))
+#define u64hilo(hi, lo) ((u64)(((u64)(hi) << 32) + (lo)))
+#define u64init(hi, lo) u64hilo(hi, lo)
+#define u64lo(x) ((u64)(x))
+#define u64lt(x, y) ((x) < (y))
+#define u64and(x, y) ((x) & (y))
+#define u64or(x, y) ((x) | (y))
+#define u64xor(x, y) ((x) ^ (y))
+#define u64plus(x, y) ((x) + (y))
+#define u64shl(x, n) ((x) << (n))
+#define u64shr(x, n) ((x) >> (n))
 
 #else
 
 /* u64 is a 64-bit unsigned integer value.
    u64init (HI, LO), is like u64hilo (HI, LO), but for use in
    initializer contexts.  */
-# ifdef WORDS_BIGENDIAN
+#ifdef WORDS_BIGENDIAN
 typedef struct { uint32_t hi, lo; } u64;
-#  define u64init(hi, lo) { hi, lo }
-# else
+#define u64init(hi, lo) \
+  { hi, lo }
+#else
 typedef struct { uint32_t lo, hi; } u64;
-#  define u64init(hi, lo) { lo, hi }
-# endif
+#define u64init(hi, lo) \
+  { lo, hi }
+#endif
 
 /* Given the high and low-order 32-bit quantities HI and LO, return a u64
    value representing (HI << 32) + LO.  */
-static inline u64
-u64hilo (uint32_t hi, uint32_t lo)
-{
+static inline u64 u64hilo(uint32_t hi, uint32_t lo) {
   u64 r;
   r.hi = hi;
   r.lo = lo;
@@ -62,9 +62,7 @@
 }
 
 /* Return a u64 value representing LO.  */
-static inline u64
-u64lo (uint32_t lo)
-{
+static inline u64 u64lo(uint32_t lo) {
   u64 r;
   r.hi = 0;
   r.lo = lo;
@@ -72,16 +70,12 @@
 }
 
 /* Return X < Y.  */
-static inline int
-u64lt (u64 x, u64 y)
-{
+static inline int u64lt(u64 x, u64 y) {
   return x.hi < y.hi || (x.hi == y.hi && x.lo < y.lo);
 }
 
 /* Return X & Y.  */
-static inline u64
-u64and (u64 x, u64 y)
-{
+static inline u64 u64and(u64 x, u64 y) {
   u64 r;
   r.hi = x.hi & y.hi;
   r.lo = x.lo & y.lo;
@@ -89,9 +83,7 @@
 }
 
 /* Return X | Y.  */
-static inline u64
-u64or (u64 x, u64 y)
-{
+static inline u64 u64or(u64 x, u64 y) {
   u64 r;
   r.hi = x.hi | y.hi;
   r.lo = x.lo | y.lo;
@@ -99,9 +91,7 @@
 }
 
 /* Return X ^ Y.  */
-static inline u64
-u64xor (u64 x, u64 y)
-{
+static inline u64 u64xor(u64 x, u64 y) {
   u64 r;
   r.hi = x.hi ^ y.hi;
   r.lo = x.lo ^ y.lo;
@@ -109,9 +99,7 @@
 }
 
 /* Return X + Y.  */
-static inline u64
-u64plus (u64 x, u64 y)
-{
+static inline u64 u64plus(u64 x, u64 y) {
   u64 r;
   r.lo = x.lo + y.lo;
   r.hi = x.hi + y.hi + (r.lo < x.lo);
@@ -119,38 +107,28 @@
 }
 
 /* Return X << N.  */
-static inline u64
-u64shl (u64 x, int n)
-{
+static inline u64 u64shl(u64 x, int n) {
   u64 r;
-  if (n < 32)
-    {
-      r.hi = (x.hi << n) | (x.lo >> (32 - n));
-      r.lo = x.lo << n;
-    }
-  else
-    {
-      r.hi = x.lo << (n - 32);
-      r.lo = 0;
-    }
+  if (n < 32) {
+    r.hi = (x.hi << n) | (x.lo >> (32 - n));
+    r.lo = x.lo << n;
+  } else {
+    r.hi = x.lo << (n - 32);
+    r.lo = 0;
+  }
   return r;
 }
 
 /* Return X >> N.  */
-static inline u64
-u64shr (u64 x, int n)
-{
+static inline u64 u64shr(u64 x, int n) {
   u64 r;
-  if (n < 32)
-    {
-      r.hi = x.hi >> n;
-      r.lo = (x.hi << (32 - n)) | (x.lo >> n);
-    }
-  else
-    {
-      r.hi = 0;
-      r.lo = x.hi >> (n - 32);
-    }
+  if (n < 32) {
+    r.hi = x.hi >> n;
+    r.lo = (x.hi << (32 - n)) | (x.lo >> n);
+  } else {
+    r.hi = 0;
+    r.lo = x.hi >> (n - 32);
+  }
   return r;
 }
 
diff --git a/project/CMakeLists.txt b/project/CMakeLists.txt
index a1cdc71..87d5184 100755
--- a/project/CMakeLists.txt
+++ b/project/CMakeLists.txt
@@ -14,7 +14,7 @@
 # limitations under the License.
 
 # source files
-project(rocketmq4cpp)
+project(rocketmq-client)
 
 file(GLOB_RECURSE SRC_FILES   ${CMAKE_SOURCE_DIR}/src/*)
 list(REMOVE_ITEM  SRC_FILES   ${CMAKE_SOURCE_DIR}/src/dllmain.cpp)
diff --git a/src/MQClientAPIImpl.cpp b/src/MQClientAPIImpl.cpp
index 8ec426d..f890968 100644
--- a/src/MQClientAPIImpl.cpp
+++ b/src/MQClientAPIImpl.cpp
@@ -27,25 +27,20 @@
 
 namespace rocketmq {
 //<!************************************************************************
-MQClientAPIImpl::MQClientAPIImpl(
-    const string& mqClientId, ClientRemotingProcessor* clientRemotingProcessor,
-    int pullThreadNum, uint64_t tcpConnectTimeout,
-    uint64_t tcpTransportTryLockTimeout, string unitName)
+MQClientAPIImpl::MQClientAPIImpl(const string& mqClientId,
+                                 ClientRemotingProcessor* clientRemotingProcessor,
+                                 int pullThreadNum,
+                                 uint64_t tcpConnectTimeout,
+                                 uint64_t tcpTransportTryLockTimeout,
+                                 string unitName)
     : m_firstFetchNameSrv(true), m_mqClientId(mqClientId) {
-  m_pRemotingClient.reset(new TcpRemotingClient(
-      pullThreadNum, tcpConnectTimeout, tcpTransportTryLockTimeout));
-  m_pRemotingClient->registerProcessor(CHECK_TRANSACTION_STATE,
-                                       clientRemotingProcessor);
-  m_pRemotingClient->registerProcessor(RESET_CONSUMER_CLIENT_OFFSET,
-                                       clientRemotingProcessor);
-  m_pRemotingClient->registerProcessor(GET_CONSUMER_STATUS_FROM_CLIENT,
-                                       clientRemotingProcessor);
-  m_pRemotingClient->registerProcessor(GET_CONSUMER_RUNNING_INFO,
-                                       clientRemotingProcessor);
-  m_pRemotingClient->registerProcessor(NOTIFY_CONSUMER_IDS_CHANGED,
-                                       clientRemotingProcessor);
-  m_pRemotingClient->registerProcessor(CONSUME_MESSAGE_DIRECTLY,
-                                       clientRemotingProcessor);
+  m_pRemotingClient.reset(new TcpRemotingClient(pullThreadNum, tcpConnectTimeout, tcpTransportTryLockTimeout));
+  m_pRemotingClient->registerProcessor(CHECK_TRANSACTION_STATE, clientRemotingProcessor);
+  m_pRemotingClient->registerProcessor(RESET_CONSUMER_CLIENT_OFFSET, clientRemotingProcessor);
+  m_pRemotingClient->registerProcessor(GET_CONSUMER_STATUS_FROM_CLIENT, clientRemotingProcessor);
+  m_pRemotingClient->registerProcessor(GET_CONSUMER_RUNNING_INFO, clientRemotingProcessor);
+  m_pRemotingClient->registerProcessor(NOTIFY_CONSUMER_IDS_CHANGED, clientRemotingProcessor);
+  m_pRemotingClient->registerProcessor(CONSUME_MESSAGE_DIRECTLY, clientRemotingProcessor);
 
   m_topAddressing.reset(new TopAddressing(unitName));
 }
@@ -59,9 +54,9 @@
   m_pRemotingClient->stopAllTcpTransportThread();
 }
 
-bool MQClientAPIImpl::writeDataToFile(string filename, string data,
-                                      bool isSync) {
-  if (data.size() == 0) return false;
+bool MQClientAPIImpl::writeDataToFile(string filename, string data, bool isSync) {
+  if (data.size() == 0)
+    return false;
 
   FILE* pFd = fopen(filename.c_str(), "w+");
   if (NULL == pFd) {
@@ -76,8 +71,8 @@
     byte_write = fwrite(pData, sizeof(char), byte_left, pFd);
     if (byte_write == byte_left) {
       if (ferror(pFd)) {
-        LOG_ERROR("write data fail, data len:" SIZET_FMT ", file:%s, msg:%s",
-                  data.size(), filename.c_str(), strerror(errno));
+        LOG_ERROR("write data fail, data len:" SIZET_FMT ", file:%s, msg:%s", data.size(), filename.c_str(),
+                  strerror(errno));
         fclose(pFd);
         return false;
       }
@@ -142,12 +137,12 @@
         m_firstFetchNameSrv = false;
       }
       if (addrs.compare(m_nameSrvAddr) != 0) {
-        LOG_INFO("name server address changed, old: %s, new: %s",
-                 m_nameSrvAddr.c_str(), addrs.c_str());
+        LOG_INFO("name server address changed, old: %s, new: %s", m_nameSrvAddr.c_str(), addrs.c_str());
         updateNameServerAddr(addrs);
         m_nameSrvAddr = addrs;
       } else {
-        if (!m_firstFetchNameSrv) return m_nameSrvAddr;
+        if (!m_firstFetchNameSrv)
+          return m_nameSrvAddr;
       }
       // update the snapshot local file if nameSrv changes or
       // m_firstFetchNameSrv==true
@@ -174,18 +169,19 @@
     m_pRemotingClient->updateNameServerAddressList(addrs);
 }
 
-void MQClientAPIImpl::callSignatureBeforeRequest(
-    const string& addr, RemotingCommand& request,
-    const SessionCredentials& session_credentials) {
+void MQClientAPIImpl::callSignatureBeforeRequest(const string& addr,
+                                                 RemotingCommand& request,
+                                                 const SessionCredentials& session_credentials) {
   ClientRPCHook rpcHook(session_credentials);
   rpcHook.doBeforeRequest(addr, request);
 }
 
 // Note: all request rules: throw exception if got broker error response,
 // exclude getTopicRouteInfoFromNameServer and unregisterClient
-void MQClientAPIImpl::createTopic(
-    const string& addr, const string& defaultTopic, TopicConfig topicConfig,
-    const SessionCredentials& sessionCredentials) {
+void MQClientAPIImpl::createTopic(const string& addr,
+                                  const string& defaultTopic,
+                                  TopicConfig topicConfig,
+                                  const SessionCredentials& sessionCredentials) {
   string topicWithProjectGroup = topicConfig.getTopicName();
   CreateTopicRequestHeader* requestHeader = new CreateTopicRequestHeader();
   requestHeader->topic = (topicWithProjectGroup);
@@ -199,8 +195,7 @@
   callSignatureBeforeRequest(addr, request, sessionCredentials);
   request.Encode();
 
-  unique_ptr<RemotingCommand> response(
-      m_pRemotingClient->invokeSync(addr, request));
+  unique_ptr<RemotingCommand> response(m_pRemotingClient->invokeSync(addr, request));
 
   if (response) {
     switch (response->getCode()) {
@@ -209,17 +204,32 @@
       default:
         break;
     }
-    THROW_MQEXCEPTION(MQBrokerException, response->getRemark(),
-                      response->getCode());
+    THROW_MQEXCEPTION(MQBrokerException, response->getRemark(), response->getCode());
   }
   THROW_MQEXCEPTION(MQBrokerException, "response is null", -1);
 }
 
-SendResult MQClientAPIImpl::sendMessage(
-    const string& addr, const string& brokerName, const MQMessage& msg,
-    SendMessageRequestHeader* pRequestHeader, int timeoutMillis, int maxRetrySendTimes,
-    int communicationMode, SendCallback* pSendCallback,
-    const SessionCredentials& sessionCredentials) {
+void MQClientAPIImpl::endTransactionOneway(std::string addr,
+                                           EndTransactionRequestHeader* requestHeader,
+                                           std::string remark,
+                                           const SessionCredentials& sessionCredentials) {
+  RemotingCommand request(END_TRANSACTION, requestHeader);
+  request.setRemark(remark);
+  callSignatureBeforeRequest(addr, request, sessionCredentials);
+  request.Encode();
+  m_pRemotingClient->invokeOneway(addr, request);
+  return;
+}
+
+SendResult MQClientAPIImpl::sendMessage(const string& addr,
+                                        const string& brokerName,
+                                        const MQMessage& msg,
+                                        SendMessageRequestHeader* pRequestHeader,
+                                        int timeoutMillis,
+                                        int maxRetrySendTimes,
+                                        int communicationMode,
+                                        SendCallback* pSendCallback,
+                                        const SessionCredentials& sessionCredentials) {
   RemotingCommand request(SEND_MESSAGE, pRequestHeader);
   string body = msg.getBody();
   request.SetBody(body.c_str(), body.length());
@@ -242,9 +252,9 @@
   return SendResult();
 }
 
-void MQClientAPIImpl::sendHearbeat(
-    const string& addr, HeartbeatData* pHeartbeatData,
-    const SessionCredentials& sessionCredentials) {
+void MQClientAPIImpl::sendHearbeat(const string& addr,
+                                   HeartbeatData* pHeartbeatData,
+                                   const SessionCredentials& sessionCredentials) {
   RemotingCommand request(HEART_BEAT, NULL);
 
   string body;
@@ -259,18 +269,17 @@
   }
 }
 
-void MQClientAPIImpl::unregisterClient(
-    const string& addr, const string& clientID, const string& producerGroup,
-    const string& consumerGroup, const SessionCredentials& sessionCredentials) {
+void MQClientAPIImpl::unregisterClient(const string& addr,
+                                       const string& clientID,
+                                       const string& producerGroup,
+                                       const string& consumerGroup,
+                                       const SessionCredentials& sessionCredentials) {
   LOG_INFO("unregisterClient to broker:%s", addr.c_str());
-  RemotingCommand request(UNREGISTER_CLIENT,
-                          new UnregisterClientRequestHeader(
-                              clientID, producerGroup, consumerGroup));
+  RemotingCommand request(UNREGISTER_CLIENT, new UnregisterClientRequestHeader(clientID, producerGroup, consumerGroup));
   callSignatureBeforeRequest(addr, request, sessionCredentials);
   request.Encode();
 
-  unique_ptr<RemotingCommand> response(
-      m_pRemotingClient->invokeSync(addr, request));
+  unique_ptr<RemotingCommand> response(m_pRemotingClient->invokeSync(addr, request));
 
   if (response) {
     switch (response->getCode()) {
@@ -280,26 +289,22 @@
       default:
         break;
     }
-    LOG_WARN("unregisterClient fail:%s,%d", response->getRemark().c_str(),
-             response->getCode());
+    LOG_WARN("unregisterClient fail:%s,%d", response->getRemark().c_str(), response->getCode());
   }
 }
 
 // return NULL if got no response or error response
-TopicRouteData* MQClientAPIImpl::getTopicRouteInfoFromNameServer(
-    const string& topic, int timeoutMillis,
-    const SessionCredentials& sessionCredentials) {
-  RemotingCommand request(GET_ROUTEINTO_BY_TOPIC,
-                          new GetRouteInfoRequestHeader(topic));
+TopicRouteData* MQClientAPIImpl::getTopicRouteInfoFromNameServer(const string& topic,
+                                                                 int timeoutMillis,
+                                                                 const SessionCredentials& sessionCredentials) {
+  RemotingCommand request(GET_ROUTEINTO_BY_TOPIC, new GetRouteInfoRequestHeader(topic));
   callSignatureBeforeRequest("", request, sessionCredentials);
   request.Encode();
 
-  unique_ptr<RemotingCommand> pResponse(
-      m_pRemotingClient->invokeSync("", request, timeoutMillis));
+  unique_ptr<RemotingCommand> pResponse(m_pRemotingClient->invokeSync("", request, timeoutMillis));
 
   if (pResponse != NULL) {
-    if (((*(pResponse->GetBody())).getSize() == 0) ||
-        ((*(pResponse->GetBody())).getData() != NULL)) {
+    if (((*(pResponse->GetBody())).getSize() == 0) || ((*(pResponse->GetBody())).getData() != NULL)) {
       switch (pResponse->getCode()) {
         case SUCCESS_VALUE: {
           const MemoryBlock* pbody = pResponse->GetBody();
@@ -321,17 +326,14 @@
   return NULL;
 }
 
-TopicList* MQClientAPIImpl::getTopicListFromNameServer(
-    const SessionCredentials& sessionCredentials) {
+TopicList* MQClientAPIImpl::getTopicListFromNameServer(const SessionCredentials& sessionCredentials) {
   RemotingCommand request(GET_ALL_TOPIC_LIST_FROM_NAMESERVER, NULL);
   callSignatureBeforeRequest("", request, sessionCredentials);
   request.Encode();
 
-  unique_ptr<RemotingCommand> pResponse(
-      m_pRemotingClient->invokeSync("", request));
+  unique_ptr<RemotingCommand> pResponse(m_pRemotingClient->invokeSync("", request));
   if (pResponse != NULL) {
-    if (((*(pResponse->GetBody())).getSize() == 0) ||
-        ((*(pResponse->GetBody())).getData() != NULL)) {
+    if (((*(pResponse->GetBody())).getSize() == 0) || ((*(pResponse->GetBody())).getData() != NULL)) {
       switch (pResponse->getCode()) {
         case SUCCESS_VALUE: {
           const MemoryBlock* pbody = pResponse->GetBody();
@@ -344,30 +346,21 @@
           break;
       }
 
-      THROW_MQEXCEPTION(MQClientException, pResponse->getRemark(),
-                        pResponse->getCode());
+      THROW_MQEXCEPTION(MQClientException, pResponse->getRemark(), pResponse->getCode());
     }
   }
   return NULL;
 }
 
-int MQClientAPIImpl::wipeWritePermOfBroker(const string& namesrvAddr,
-                                           const string& brokerName,
-                                           int timeoutMillis) {
+int MQClientAPIImpl::wipeWritePermOfBroker(const string& namesrvAddr, const string& brokerName, int timeoutMillis) {
   return 0;
 }
 
-void MQClientAPIImpl::deleteTopicInBroker(const string& addr,
-                                          const string& topic,
-                                          int timeoutMillis) {}
+void MQClientAPIImpl::deleteTopicInBroker(const string& addr, const string& topic, int timeoutMillis) {}
 
-void MQClientAPIImpl::deleteTopicInNameServer(const string& addr,
-                                              const string& topic,
-                                              int timeoutMillis) {}
+void MQClientAPIImpl::deleteTopicInNameServer(const string& addr, const string& topic, int timeoutMillis) {}
 
-void MQClientAPIImpl::deleteSubscriptionGroup(const string& addr,
-                                              const string& groupName,
-                                              int timeoutMillis) {}
+void MQClientAPIImpl::deleteSubscriptionGroup(const string& addr, const string& groupName, int timeoutMillis) {}
 
 string MQClientAPIImpl::getKVConfigByValue(const string& projectNamespace,
                                            const string& projectGroup,
@@ -375,8 +368,7 @@
   return "";
 }
 
-KVTable MQClientAPIImpl::getKVListByNamespace(const string& projectNamespace,
-                                              int timeoutMillis) {
+KVTable MQClientAPIImpl::getKVListByNamespace(const string& projectNamespace, int timeoutMillis) {
   return KVTable();
 }
 
@@ -390,13 +382,12 @@
                                             RemotingCommand& request,
                                             int timeoutMillis) {
   //<!block util response;
-  unique_ptr<RemotingCommand> pResponse(
-      m_pRemotingClient->invokeSync(addr, request, timeoutMillis));
+  unique_ptr<RemotingCommand> pResponse(m_pRemotingClient->invokeSync(addr, request, timeoutMillis));
   if (pResponse != NULL) {
     try {
-      LOG_DEBUG("sendMessageSync success:%s to addr:%s,brokername:%s",
-                msg.toString().c_str(), addr.c_str(), brokerName.c_str());
       SendResult result = processSendResponse(brokerName, msg, pResponse.get());
+      LOG_DEBUG("sendMessageSync success:%s to addr:%s,brokername:%s, send status:%d", msg.toString().c_str(),
+                addr.c_str(), brokerName.c_str(), (int)result.getSendStatus());
       return result;
     } catch (...) {
       LOG_ERROR("send error");
@@ -417,30 +408,30 @@
   //<!delete in future;
   AsyncCallbackWrap* cbw = new SendCallbackWrap(brokerName, msg, pSendCallback, this);
 
-  LOG_DEBUG("sendMessageAsync request:%s, timeout:%lld, maxRetryTimes:%d retrySendTimes:%d", request.ToString().data(), timeoutMilliseconds, maxRetryTimes, retrySendTimes);
-  
-  if (m_pRemotingClient->invokeAsync(addr, request, cbw, timeoutMilliseconds, maxRetryTimes, retrySendTimes) ==
-    false) {
-    LOG_WARN("invokeAsync failed to addr:%s,topic:%s, timeout:%lld, maxRetryTimes:%d, retrySendTimes:%d", 
-      addr.c_str(), msg.getTopic().data(), timeoutMilliseconds, maxRetryTimes, retrySendTimes);
-      //when getTcp return false, need consider retrySendTimes
-      int retry_time = retrySendTimes + 1;
-      int64 time_out = timeoutMilliseconds - (UtilAll::currentTimeMillis() - begin_time);
-      while (retry_time < maxRetryTimes && time_out > 0) {
-          begin_time = UtilAll::currentTimeMillis();
-          if (m_pRemotingClient->invokeAsync(addr, request, cbw, time_out, maxRetryTimes, retry_time) == false) {
-              retry_time += 1;
-              time_out = time_out - (UtilAll::currentTimeMillis() - begin_time);
-              LOG_WARN("invokeAsync retry failed to addr:%s,topic:%s, timeout:%lld, maxRetryTimes:%d, retrySendTimes:%d", 
-                addr.c_str(), msg.getTopic().data(), time_out, maxRetryTimes, retry_time);
-              continue;
-          } else {
-              return; //invokeAsync success
-          }
-      }
+  LOG_DEBUG("sendMessageAsync request:%s, timeout:%lld, maxRetryTimes:%d retrySendTimes:%d", request.ToString().data(),
+            timeoutMilliseconds, maxRetryTimes, retrySendTimes);
 
-    LOG_ERROR("sendMessageAsync failed to addr:%s,topic:%s, timeout:%lld, maxRetryTimes:%d, retrySendTimes:%d", 
-      addr.c_str(), msg.getTopic().data(), time_out, maxRetryTimes, retrySendTimes);
+  if (m_pRemotingClient->invokeAsync(addr, request, cbw, timeoutMilliseconds, maxRetryTimes, retrySendTimes) == false) {
+    LOG_WARN("invokeAsync failed to addr:%s,topic:%s, timeout:%lld, maxRetryTimes:%d, retrySendTimes:%d", addr.c_str(),
+             msg.getTopic().data(), timeoutMilliseconds, maxRetryTimes, retrySendTimes);
+    // when getTcp return false, need consider retrySendTimes
+    int retry_time = retrySendTimes + 1;
+    int64 time_out = timeoutMilliseconds - (UtilAll::currentTimeMillis() - begin_time);
+    while (retry_time < maxRetryTimes && time_out > 0) {
+      begin_time = UtilAll::currentTimeMillis();
+      if (m_pRemotingClient->invokeAsync(addr, request, cbw, time_out, maxRetryTimes, retry_time) == false) {
+        retry_time += 1;
+        time_out = time_out - (UtilAll::currentTimeMillis() - begin_time);
+        LOG_WARN("invokeAsync retry failed to addr:%s,topic:%s, timeout:%lld, maxRetryTimes:%d, retrySendTimes:%d",
+                 addr.c_str(), msg.getTopic().data(), time_out, maxRetryTimes, retry_time);
+        continue;
+      } else {
+        return;  // invokeAsync success
+      }
+    }
+
+    LOG_ERROR("sendMessageAsync failed to addr:%s,topic:%s, timeout:%lld, maxRetryTimes:%d, retrySendTimes:%d",
+              addr.c_str(), msg.getTopic().data(), time_out, maxRetryTimes, retrySendTimes);
 
     if (cbw) {
       cbw->onException();
@@ -451,14 +442,13 @@
   }
 }
 
-void MQClientAPIImpl::deleteOpaqueForDropPullRequest(const MQMessageQueue& mq, int opaque) {
-    m_pRemotingClient->deleteOpaqueForDropPullRequest(mq, opaque);
-}
-
-PullResult* MQClientAPIImpl::pullMessage(
-    const string& addr, PullMessageRequestHeader* pRequestHeader,
-    int timeoutMillis, int communicationMode, PullCallback* pullCallback,
-    void* pArg, const SessionCredentials& sessionCredentials) {
+PullResult* MQClientAPIImpl::pullMessage(const string& addr,
+                                         PullMessageRequestHeader* pRequestHeader,
+                                         int timeoutMillis,
+                                         int communicationMode,
+                                         PullCallback* pullCallback,
+                                         void* pArg,
+                                         const SessionCredentials& sessionCredentials) {
   RemotingCommand request(PULL_MESSAGE, pRequestHeader);
   callSignatureBeforeRequest(addr, request, sessionCredentials);
   request.Encode();
@@ -481,42 +471,26 @@
 void MQClientAPIImpl::pullMessageAsync(const string& addr,
                                        RemotingCommand& request,
                                        int timeoutMillis,
-                                       PullCallback* pullCallback, void* pArg) {
+                                       PullCallback* pullCallback,
+                                       void* pArg) {
   //<!delete in future;
   AsyncCallbackWrap* cbw = new PullCallbackWarp(pullCallback, this, pArg);
-  MQMessageQueue mq;
-  AsyncArg* pAsyncArg = static_cast<AsyncArg*>(pArg);
-  if (pAsyncArg && pAsyncArg->pPullRequest) {
-    mq = pAsyncArg->mq;
-    pAsyncArg->pPullRequest->setLatestPullRequestOpaque(request.getOpaque());
-    LOG_DEBUG("pullMessageAsync set opaque:%d, mq:%s", 
-        pAsyncArg->pPullRequest->getLatestPullRequestOpaque(),mq.toString().c_str());
-  }
-
-  if (m_pRemotingClient->invokeAsync(addr, request, cbw, timeoutMillis) ==
-      false) {
-    LOG_ERROR("pullMessageAsync failed of addr:%s, opaque:%d, mq:%s", addr.c_str(), request.getOpaque(), mq.toString().data());
-    if (pAsyncArg && pAsyncArg->pPullRequest) {
-        pAsyncArg->pPullRequest->setLatestPullRequestOpaque(0);
-    }
+  if (m_pRemotingClient->invokeAsync(addr, request, cbw, timeoutMillis) == false) {
+    LOG_ERROR("pullMessageAsync failed of addr:%s, mq:%s", addr.c_str(),
+              static_cast<AsyncArg*>(pArg)->mq.toString().data());
     deleteAndZero(cbw);
     THROW_MQEXCEPTION(MQClientException, "pullMessageAsync failed", -1);
   }
 }
 
-PullResult* MQClientAPIImpl::pullMessageSync(const string& addr,
-                                             RemotingCommand& request,
-                                             int timeoutMillis) {
-  unique_ptr<RemotingCommand> pResponse(
-      m_pRemotingClient->invokeSync(addr, request, timeoutMillis));
+PullResult* MQClientAPIImpl::pullMessageSync(const string& addr, RemotingCommand& request, int timeoutMillis) {
+  unique_ptr<RemotingCommand> pResponse(m_pRemotingClient->invokeSync(addr, request, timeoutMillis));
   if (pResponse != NULL) {
-    if (((*(pResponse->GetBody())).getSize() == 0) ||
-        ((*(pResponse->GetBody())).getData() != NULL)) {
+    if (((*(pResponse->GetBody())).getSize() == 0) || ((*(pResponse->GetBody())).getData() != NULL)) {
       try {
-        PullResult* pullResult =
-            processPullResponse(pResponse.get());  // pullMessage will handle
-                                                   // exception from
-                                                   // processPullResponse
+        PullResult* pullResult = processPullResponse(pResponse.get());  // pullMessage will handle
+                                                                        // exception from
+                                                                        // processPullResponse
         return pullResult;
       } catch (MQException& e) {
         LOG_ERROR(e.what());
@@ -550,18 +524,14 @@
       break;
   }
   if (res == 0) {
-    SendMessageResponseHeader* responseHeader =
-        (SendMessageResponseHeader*)pResponse->getCommandHeader();
-    MQMessageQueue messageQueue(msg.getTopic(), brokerName,
-                                responseHeader->queueId);
+    SendMessageResponseHeader* responseHeader = (SendMessageResponseHeader*)pResponse->getCommandHeader();
+    MQMessageQueue messageQueue(msg.getTopic(), brokerName, responseHeader->queueId);
     string unique_msgId = msg.getProperty(MQMessage::PROPERTY_UNIQ_CLIENT_MESSAGE_ID_KEYIDX);
-    return SendResult(sendStatus, unique_msgId, responseHeader->msgId, messageQueue,
-                      responseHeader->queueOffset);
+    return SendResult(sendStatus, unique_msgId, responseHeader->msgId, messageQueue, responseHeader->queueOffset);
   }
-  LOG_ERROR("processSendResponse error remark:%s, error code:%d",
-            (pResponse->getRemark()).c_str(), pResponse->getCode());
-  THROW_MQEXCEPTION(MQClientException, pResponse->getRemark(),
-                    pResponse->getCode());
+  LOG_ERROR("processSendResponse error remark:%s, error code:%d", (pResponse->getRemark()).c_str(),
+            pResponse->getCode());
+  THROW_MQEXCEPTION(MQClientException, pResponse->getRemark(), pResponse->getCode());
 }
 
 PullResult* MQClientAPIImpl::processPullResponse(RemotingCommand* pResponse) {
@@ -580,46 +550,38 @@
       pullStatus = OFFSET_ILLEGAL;
       break;
     default:
-      THROW_MQEXCEPTION(MQBrokerException, pResponse->getRemark(),
-                        pResponse->getCode());
+      THROW_MQEXCEPTION(MQBrokerException, pResponse->getRemark(), pResponse->getCode());
       break;
   }
 
-  PullMessageResponseHeader* responseHeader =
-      static_cast<PullMessageResponseHeader*>(pResponse->getCommandHeader());
+  PullMessageResponseHeader* responseHeader = static_cast<PullMessageResponseHeader*>(pResponse->getCommandHeader());
 
   if (!responseHeader) {
     LOG_ERROR("processPullResponse:responseHeader is NULL");
-    THROW_MQEXCEPTION(MQClientException,
-                      "processPullResponse:responseHeader is NULL", -1);
+    THROW_MQEXCEPTION(MQClientException, "processPullResponse:responseHeader is NULL", -1);
   }
   //<!get body,delete outsite;
-  MemoryBlock bodyFromResponse =
-      *(pResponse->GetBody());  // response data judgement had been done outside
-                                // of processPullResponse
+  MemoryBlock bodyFromResponse = *(pResponse->GetBody());  // response data judgement had been done outside
+                                                           // of processPullResponse
   if (bodyFromResponse.getSize() == 0) {
     if (pullStatus != FOUND) {
-      return new PullResultExt(pullStatus, responseHeader->nextBeginOffset,
-                               responseHeader->minOffset,
-                               responseHeader->maxOffset,
-                               (int)responseHeader->suggestWhichBrokerId);
+      return new PullResultExt(pullStatus, responseHeader->nextBeginOffset, responseHeader->minOffset,
+                               responseHeader->maxOffset, (int)responseHeader->suggestWhichBrokerId);
     } else {
-      THROW_MQEXCEPTION(MQClientException,
-                        "memoryBody size is 0, but pullStatus equals found",
-                        -1);
+      THROW_MQEXCEPTION(MQClientException, "memoryBody size is 0, but pullStatus equals found", -1);
     }
   } else {
-    return new PullResultExt(
-        pullStatus, responseHeader->nextBeginOffset, responseHeader->minOffset,
-        responseHeader->maxOffset, (int)responseHeader->suggestWhichBrokerId,
-        bodyFromResponse);
+    return new PullResultExt(pullStatus, responseHeader->nextBeginOffset, responseHeader->minOffset,
+                             responseHeader->maxOffset, (int)responseHeader->suggestWhichBrokerId, bodyFromResponse);
   }
 }
 
 //<!***************************************************************************
-int64 MQClientAPIImpl::getMinOffset(
-    const string& addr, const string& topic, int queueId, int timeoutMillis,
-    const SessionCredentials& sessionCredentials) {
+int64 MQClientAPIImpl::getMinOffset(const string& addr,
+                                    const string& topic,
+                                    int queueId,
+                                    int timeoutMillis,
+                                    const SessionCredentials& sessionCredentials) {
   GetMinOffsetRequestHeader* pRequestHeader = new GetMinOffsetRequestHeader();
   pRequestHeader->topic = topic;
   pRequestHeader->queueId = queueId;
@@ -628,14 +590,12 @@
   callSignatureBeforeRequest(addr, request, sessionCredentials);
   request.Encode();
 
-  unique_ptr<RemotingCommand> response(
-      m_pRemotingClient->invokeSync(addr, request, timeoutMillis));
+  unique_ptr<RemotingCommand> response(m_pRemotingClient->invokeSync(addr, request, timeoutMillis));
 
   if (response) {
     switch (response->getCode()) {
       case SUCCESS_VALUE: {
-        GetMinOffsetResponseHeader* responseHeader =
-            (GetMinOffsetResponseHeader*)response->getCommandHeader();
+        GetMinOffsetResponseHeader* responseHeader = (GetMinOffsetResponseHeader*)response->getCommandHeader();
 
         int64 offset = responseHeader->offset;
         return offset;
@@ -643,15 +603,16 @@
       default:
         break;
     }
-    THROW_MQEXCEPTION(MQBrokerException, response->getRemark(),
-                      response->getCode());
+    THROW_MQEXCEPTION(MQBrokerException, response->getRemark(), response->getCode());
   }
   THROW_MQEXCEPTION(MQBrokerException, "response is null", -1);
 }
 
-int64 MQClientAPIImpl::getMaxOffset(
-    const string& addr, const string& topic, int queueId, int timeoutMillis,
-    const SessionCredentials& sessionCredentials) {
+int64 MQClientAPIImpl::getMaxOffset(const string& addr,
+                                    const string& topic,
+                                    int queueId,
+                                    int timeoutMillis,
+                                    const SessionCredentials& sessionCredentials) {
   GetMaxOffsetRequestHeader* pRequestHeader = new GetMaxOffsetRequestHeader();
   pRequestHeader->topic = topic;
   pRequestHeader->queueId = queueId;
@@ -660,14 +621,12 @@
   callSignatureBeforeRequest(addr, request, sessionCredentials);
   request.Encode();
 
-  unique_ptr<RemotingCommand> response(
-      m_pRemotingClient->invokeSync(addr, request, timeoutMillis));
+  unique_ptr<RemotingCommand> response(m_pRemotingClient->invokeSync(addr, request, timeoutMillis));
 
   if (response) {
     switch (response->getCode()) {
       case SUCCESS_VALUE: {
-        GetMaxOffsetResponseHeader* responseHeader =
-            (GetMaxOffsetResponseHeader*)response->getCommandHeader();
+        GetMaxOffsetResponseHeader* responseHeader = (GetMaxOffsetResponseHeader*)response->getCommandHeader();
 
         int64 offset = responseHeader->offset;
         return offset;
@@ -675,15 +634,17 @@
       default:
         break;
     }
-    THROW_MQEXCEPTION(MQBrokerException, response->getRemark(),
-                      response->getCode());
+    THROW_MQEXCEPTION(MQBrokerException, response->getRemark(), response->getCode());
   }
   THROW_MQEXCEPTION(MQBrokerException, "response is null", -1);
 }
 
-int64 MQClientAPIImpl::searchOffset(
-    const string& addr, const string& topic, int queueId, uint64_t timestamp,
-    int timeoutMillis, const SessionCredentials& sessionCredentials) {
+int64 MQClientAPIImpl::searchOffset(const string& addr,
+                                    const string& topic,
+                                    int queueId,
+                                    uint64_t timestamp,
+                                    int timeoutMillis,
+                                    const SessionCredentials& sessionCredentials) {
   SearchOffsetRequestHeader* pRequestHeader = new SearchOffsetRequestHeader();
   pRequestHeader->topic = topic;
   pRequestHeader->queueId = queueId;
@@ -693,14 +654,12 @@
   callSignatureBeforeRequest(addr, request, sessionCredentials);
   request.Encode();
 
-  unique_ptr<RemotingCommand> response(
-      m_pRemotingClient->invokeSync(addr, request, timeoutMillis));
+  unique_ptr<RemotingCommand> response(m_pRemotingClient->invokeSync(addr, request, timeoutMillis));
 
   if (response) {
     switch (response->getCode()) {
       case SUCCESS_VALUE: {
-        SearchOffsetResponseHeader* responseHeader =
-            (SearchOffsetResponseHeader*)response->getCommandHeader();
+        SearchOffsetResponseHeader* responseHeader = (SearchOffsetResponseHeader*)response->getCommandHeader();
 
         int64 offset = responseHeader->offset;
         return offset;
@@ -708,15 +667,15 @@
       default:
         break;
     }
-    THROW_MQEXCEPTION(MQBrokerException, response->getRemark(),
-                      response->getCode());
+    THROW_MQEXCEPTION(MQBrokerException, response->getRemark(), response->getCode());
   }
   THROW_MQEXCEPTION(MQBrokerException, "response is null", -1);
 }
 
-MQMessageExt* MQClientAPIImpl::viewMessage(
-    const string& addr, int64 phyoffset, int timeoutMillis,
-    const SessionCredentials& sessionCredentials) {
+MQMessageExt* MQClientAPIImpl::viewMessage(const string& addr,
+                                           int64 phyoffset,
+                                           int timeoutMillis,
+                                           const SessionCredentials& sessionCredentials) {
   ViewMessageRequestHeader* pRequestHeader = new ViewMessageRequestHeader();
   pRequestHeader->offset = phyoffset;
 
@@ -724,8 +683,7 @@
   callSignatureBeforeRequest(addr, request, sessionCredentials);
   request.Encode();
 
-  unique_ptr<RemotingCommand> response(
-      m_pRemotingClient->invokeSync(addr, request, timeoutMillis));
+  unique_ptr<RemotingCommand> response(m_pRemotingClient->invokeSync(addr, request, timeoutMillis));
 
   if (response) {
     switch (response->getCode()) {
@@ -734,17 +692,17 @@
       default:
         break;
     }
-    THROW_MQEXCEPTION(MQBrokerException, response->getRemark(),
-                      response->getCode());
+    THROW_MQEXCEPTION(MQBrokerException, response->getRemark(), response->getCode());
   }
   THROW_MQEXCEPTION(MQBrokerException, "response is null", -1);
 }
 
-int64 MQClientAPIImpl::getEarliestMsgStoretime(
-    const string& addr, const string& topic, int queueId, int timeoutMillis,
-    const SessionCredentials& sessionCredentials) {
-  GetEarliestMsgStoretimeRequestHeader* pRequestHeader =
-      new GetEarliestMsgStoretimeRequestHeader();
+int64 MQClientAPIImpl::getEarliestMsgStoretime(const string& addr,
+                                               const string& topic,
+                                               int queueId,
+                                               int timeoutMillis,
+                                               const SessionCredentials& sessionCredentials) {
+  GetEarliestMsgStoretimeRequestHeader* pRequestHeader = new GetEarliestMsgStoretimeRequestHeader();
   pRequestHeader->topic = topic;
   pRequestHeader->queueId = queueId;
 
@@ -752,15 +710,13 @@
   callSignatureBeforeRequest(addr, request, sessionCredentials);
   request.Encode();
 
-  unique_ptr<RemotingCommand> response(
-      m_pRemotingClient->invokeSync(addr, request, timeoutMillis));
+  unique_ptr<RemotingCommand> response(m_pRemotingClient->invokeSync(addr, request, timeoutMillis));
 
   if (response) {
     switch (response->getCode()) {
       case SUCCESS_VALUE: {
         GetEarliestMsgStoretimeResponseHeader* responseHeader =
-            (GetEarliestMsgStoretimeResponseHeader*)
-                response->getCommandHeader();
+            (GetEarliestMsgStoretimeResponseHeader*)response->getCommandHeader();
 
         int64 timestamp = responseHeader->timestamp;
         return timestamp;
@@ -768,29 +724,27 @@
       default:
         break;
     }
-    THROW_MQEXCEPTION(MQBrokerException, response->getRemark(),
-                      response->getCode());
+    THROW_MQEXCEPTION(MQBrokerException, response->getRemark(), response->getCode());
   }
   THROW_MQEXCEPTION(MQBrokerException, "response is null", -1);
 }
 
-void MQClientAPIImpl::getConsumerIdListByGroup(
-    const string& addr, const string& consumerGroup, vector<string>& cids,
-    int timeoutMillis, const SessionCredentials& sessionCredentials) {
-  GetConsumerListByGroupRequestHeader* pRequestHeader =
-      new GetConsumerListByGroupRequestHeader();
+void MQClientAPIImpl::getConsumerIdListByGroup(const string& addr,
+                                               const string& consumerGroup,
+                                               vector<string>& cids,
+                                               int timeoutMillis,
+                                               const SessionCredentials& sessionCredentials) {
+  GetConsumerListByGroupRequestHeader* pRequestHeader = new GetConsumerListByGroupRequestHeader();
   pRequestHeader->consumerGroup = consumerGroup;
 
   RemotingCommand request(GET_CONSUMER_LIST_BY_GROUP, pRequestHeader);
   callSignatureBeforeRequest(addr, request, sessionCredentials);
   request.Encode();
 
-  unique_ptr<RemotingCommand> pResponse(
-      m_pRemotingClient->invokeSync(addr, request, timeoutMillis));
+  unique_ptr<RemotingCommand> pResponse(m_pRemotingClient->invokeSync(addr, request, timeoutMillis));
 
   if (pResponse != NULL) {
-    if ((pResponse->GetBody()->getSize() == 0) ||
-        (pResponse->GetBody()->getData() != NULL)) {
+    if ((pResponse->GetBody()->getSize() == 0) || (pResponse->GetBody()->getData() != NULL)) {
       switch (pResponse->getCode()) {
         case SUCCESS_VALUE: {
           const MemoryBlock* pbody = pResponse->GetBody();
@@ -802,22 +756,21 @@
         default:
           break;
       }
-      THROW_MQEXCEPTION(MQBrokerException, pResponse->getRemark(),
-                        pResponse->getCode());
+      THROW_MQEXCEPTION(MQBrokerException, pResponse->getRemark(), pResponse->getCode());
     }
   }
   THROW_MQEXCEPTION(MQBrokerException, "response is null", -1);
 }
 
-int64 MQClientAPIImpl::queryConsumerOffset(
-    const string& addr, QueryConsumerOffsetRequestHeader* pRequestHeader,
-    int timeoutMillis, const SessionCredentials& sessionCredentials) {
+int64 MQClientAPIImpl::queryConsumerOffset(const string& addr,
+                                           QueryConsumerOffsetRequestHeader* pRequestHeader,
+                                           int timeoutMillis,
+                                           const SessionCredentials& sessionCredentials) {
   RemotingCommand request(QUERY_CONSUMER_OFFSET, pRequestHeader);
   callSignatureBeforeRequest(addr, request, sessionCredentials);
   request.Encode();
 
-  unique_ptr<RemotingCommand> response(
-      m_pRemotingClient->invokeSync(addr, request, timeoutMillis));
+  unique_ptr<RemotingCommand> response(m_pRemotingClient->invokeSync(addr, request, timeoutMillis));
 
   if (response) {
     switch (response->getCode()) {
@@ -830,22 +783,21 @@
       default:
         break;
     }
-    THROW_MQEXCEPTION(MQBrokerException, response->getRemark(),
-                      response->getCode());
+    THROW_MQEXCEPTION(MQBrokerException, response->getRemark(), response->getCode());
   }
   THROW_MQEXCEPTION(MQBrokerException, "response is null", -1);
   return -1;
 }
 
-void MQClientAPIImpl::updateConsumerOffset(
-    const string& addr, UpdateConsumerOffsetRequestHeader* pRequestHeader,
-    int timeoutMillis, const SessionCredentials& sessionCredentials) {
+void MQClientAPIImpl::updateConsumerOffset(const string& addr,
+                                           UpdateConsumerOffsetRequestHeader* pRequestHeader,
+                                           int timeoutMillis,
+                                           const SessionCredentials& sessionCredentials) {
   RemotingCommand request(UPDATE_CONSUMER_OFFSET, pRequestHeader);
   callSignatureBeforeRequest(addr, request, sessionCredentials);
   request.Encode();
 
-  unique_ptr<RemotingCommand> response(
-      m_pRemotingClient->invokeSync(addr, request, timeoutMillis));
+  unique_ptr<RemotingCommand> response(m_pRemotingClient->invokeSync(addr, request, timeoutMillis));
 
   if (response) {
     switch (response->getCode()) {
@@ -855,15 +807,15 @@
       default:
         break;
     }
-    THROW_MQEXCEPTION(MQBrokerException, response->getRemark(),
-                      response->getCode());
+    THROW_MQEXCEPTION(MQBrokerException, response->getRemark(), response->getCode());
   }
   THROW_MQEXCEPTION(MQBrokerException, "response is null", -1);
 }
 
-void MQClientAPIImpl::updateConsumerOffsetOneway(
-    const string& addr, UpdateConsumerOffsetRequestHeader* pRequestHeader,
-    int timeoutMillis, const SessionCredentials& sessionCredentials) {
+void MQClientAPIImpl::updateConsumerOffsetOneway(const string& addr,
+                                                 UpdateConsumerOffsetRequestHeader* pRequestHeader,
+                                                 int timeoutMillis,
+                                                 const SessionCredentials& sessionCredentials) {
   RemotingCommand request(UPDATE_CONSUMER_OFFSET, pRequestHeader);
   callSignatureBeforeRequest(addr, request, sessionCredentials);
   request.Encode();
@@ -871,11 +823,12 @@
   m_pRemotingClient->invokeOneway(addr, request);
 }
 
-void MQClientAPIImpl::consumerSendMessageBack(
-    MQMessageExt& msg, const string& consumerGroup, int delayLevel,
-    int timeoutMillis, const SessionCredentials& sessionCredentials) {
-  ConsumerSendMsgBackRequestHeader* pRequestHeader =
-      new ConsumerSendMsgBackRequestHeader();
+void MQClientAPIImpl::consumerSendMessageBack(MQMessageExt& msg,
+                                              const string& consumerGroup,
+                                              int delayLevel,
+                                              int timeoutMillis,
+                                              const SessionCredentials& sessionCredentials) {
+  ConsumerSendMsgBackRequestHeader* pRequestHeader = new ConsumerSendMsgBackRequestHeader();
   pRequestHeader->group = consumerGroup;
   pRequestHeader->offset = msg.getCommitLogOffset();
   pRequestHeader->delayLevel = delayLevel;
@@ -885,8 +838,7 @@
   callSignatureBeforeRequest(addr, request, sessionCredentials);
   request.Encode();
 
-  unique_ptr<RemotingCommand> response(
-      m_pRemotingClient->invokeSync(addr, request, timeoutMillis));
+  unique_ptr<RemotingCommand> response(m_pRemotingClient->invokeSync(addr, request, timeoutMillis));
 
   if (response) {
     switch (response->getCode()) {
@@ -896,16 +848,16 @@
       default:
         break;
     }
-    THROW_MQEXCEPTION(MQBrokerException, response->getRemark(),
-                      response->getCode());
+    THROW_MQEXCEPTION(MQBrokerException, response->getRemark(), response->getCode());
   }
   THROW_MQEXCEPTION(MQBrokerException, "response is null", -1);
 }
 
-void MQClientAPIImpl::lockBatchMQ(
-    const string& addr, LockBatchRequestBody* requestBody,
-    vector<MQMessageQueue>& mqs, int timeoutMillis,
-    const SessionCredentials& sessionCredentials) {
+void MQClientAPIImpl::lockBatchMQ(const string& addr,
+                                  LockBatchRequestBody* requestBody,
+                                  vector<MQMessageQueue>& mqs,
+                                  int timeoutMillis,
+                                  const SessionCredentials& sessionCredentials) {
   RemotingCommand request(LOCK_BATCH_MQ, NULL);
   string body;
   requestBody->Encode(body);
@@ -914,12 +866,10 @@
   callSignatureBeforeRequest(addr, request, sessionCredentials);
   request.Encode();
 
-  unique_ptr<RemotingCommand> pResponse(
-      m_pRemotingClient->invokeSync(addr, request, timeoutMillis));
+  unique_ptr<RemotingCommand> pResponse(m_pRemotingClient->invokeSync(addr, request, timeoutMillis));
 
   if (pResponse != NULL) {
-    if (((*(pResponse->GetBody())).getSize() == 0) ||
-        ((*(pResponse->GetBody())).getData() != NULL)) {
+    if (((*(pResponse->GetBody())).getSize() == 0) || ((*(pResponse->GetBody())).getData() != NULL)) {
       switch (pResponse->getCode()) {
         case SUCCESS_VALUE: {
           const MemoryBlock* pbody = pResponse->GetBody();
@@ -931,16 +881,16 @@
         default:
           break;
       }
-      THROW_MQEXCEPTION(MQBrokerException, pResponse->getRemark(),
-                        pResponse->getCode());
+      THROW_MQEXCEPTION(MQBrokerException, pResponse->getRemark(), pResponse->getCode());
     }
   }
   THROW_MQEXCEPTION(MQBrokerException, "response is null", -1);
 }
 
-void MQClientAPIImpl::unlockBatchMQ(
-    const string& addr, UnlockBatchRequestBody* requestBody, int timeoutMillis,
-    const SessionCredentials& sessionCredentials) {
+void MQClientAPIImpl::unlockBatchMQ(const string& addr,
+                                    UnlockBatchRequestBody* requestBody,
+                                    int timeoutMillis,
+                                    const SessionCredentials& sessionCredentials) {
   RemotingCommand request(UNLOCK_BATCH_MQ, NULL);
   string body;
   requestBody->Encode(body);
@@ -949,8 +899,7 @@
   callSignatureBeforeRequest(addr, request, sessionCredentials);
   request.Encode();
 
-  unique_ptr<RemotingCommand> pResponse(
-      m_pRemotingClient->invokeSync(addr, request, timeoutMillis));
+  unique_ptr<RemotingCommand> pResponse(m_pRemotingClient->invokeSync(addr, request, timeoutMillis));
 
   if (pResponse != NULL) {
     switch (pResponse->getCode()) {
@@ -960,11 +909,10 @@
       default:
         break;
     }
-    THROW_MQEXCEPTION(MQBrokerException, pResponse->getRemark(),
-                      pResponse->getCode());
+    THROW_MQEXCEPTION(MQBrokerException, pResponse->getRemark(), pResponse->getCode());
   }
   THROW_MQEXCEPTION(MQBrokerException, "response is null", -1);
 }
 
 //<!************************************************************************
-}  //<!end namespace;
+}  // namespace rocketmq
diff --git a/src/MQClientAPIImpl.h b/src/MQClientAPIImpl.h
index f2ac273..763e45d 100644
--- a/src/MQClientAPIImpl.h
+++ b/src/MQClientAPIImpl.h
@@ -14,6 +14,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 #ifndef __MQCLIENTAPIIMPL_H__
 #define __MQCLIENTAPIIMPL_H__
 #include "AsyncCallback.h"
@@ -41,99 +42,114 @@
 //<!************************************************************************
 class MQClientAPIImpl {
  public:
-  MQClientAPIImpl(const string& mqClientId, ClientRemotingProcessor* clientRemotingProcessor,
-                  int pullThreadNum, uint64_t tcpConnectTimeout,
-                  uint64_t tcpTransportTryLockTimeout, string unitName);
+  MQClientAPIImpl(const string& mqClientId,
+                  ClientRemotingProcessor* clientRemotingProcessor,
+                  int pullThreadNum,
+                  uint64_t tcpConnectTimeout,
+                  uint64_t tcpTransportTryLockTimeout,
+                  string unitName);
   virtual ~MQClientAPIImpl();
   void stopAllTcpTransportThread();
   bool writeDataToFile(string filename, string data, bool isSync);
   string fetchNameServerAddr(const string& NSDomain);
   void updateNameServerAddr(const string& addrs);
 
-  void callSignatureBeforeRequest(
-      const string& addr, RemotingCommand& request,
-      const SessionCredentials& session_credentials);
-  void createTopic(const string& addr, const string& defaultTopic,
+  void callSignatureBeforeRequest(const string& addr,
+                                  RemotingCommand& request,
+                                  const SessionCredentials& session_credentials);
+  void createTopic(const string& addr,
+                   const string& defaultTopic,
                    TopicConfig topicConfig,
                    const SessionCredentials& sessionCredentials);
+  void endTransactionOneway(std::string addr,
+                            EndTransactionRequestHeader* requestHeader,
+                            std::string remark,
+                            const SessionCredentials& sessionCredentials);
 
-  SendResult sendMessage(const string& addr, const string& brokerName,
+  SendResult sendMessage(const string& addr,
+                         const string& brokerName,
                          const MQMessage& msg,
                          SendMessageRequestHeader* pRequestHeader,
-                         int timeoutMillis, int maxRetrySendTimes,
+                         int timeoutMillis,
+                         int maxRetrySendTimes,
                          int communicationMode,
                          SendCallback* pSendCallback,
                          const SessionCredentials& sessionCredentials);
 
   PullResult* pullMessage(const string& addr,
                           PullMessageRequestHeader* pRequestHeader,
-                          int timeoutMillis, int communicationMode,
-                          PullCallback* pullCallback, void* pArg,
+                          int timeoutMillis,
+                          int communicationMode,
+                          PullCallback* pullCallback,
+                          void* pArg,
                           const SessionCredentials& sessionCredentials);
 
-  void sendHearbeat(const string& addr, HeartbeatData* pHeartbeatData,
-                    const SessionCredentials& sessionCredentials);
+  void sendHearbeat(const string& addr, HeartbeatData* pHeartbeatData, const SessionCredentials& sessionCredentials);
 
-  void unregisterClient(const string& addr, const string& clientID,
+  void unregisterClient(const string& addr,
+                        const string& clientID,
                         const string& producerGroup,
                         const string& consumerGroup,
                         const SessionCredentials& sessionCredentials);
 
-  TopicRouteData* getTopicRouteInfoFromNameServer(
-      const string& topic, int timeoutMillis,
-      const SessionCredentials& sessionCredentials);
+  TopicRouteData* getTopicRouteInfoFromNameServer(const string& topic,
+                                                  int timeoutMillis,
+                                                  const SessionCredentials& sessionCredentials);
 
-  TopicList* getTopicListFromNameServer(
-      const SessionCredentials& sessionCredentials);
+  TopicList* getTopicListFromNameServer(const SessionCredentials& sessionCredentials);
 
-  int wipeWritePermOfBroker(const string& namesrvAddr, const string& brokerName,
-                            int timeoutMillis);
+  int wipeWritePermOfBroker(const string& namesrvAddr, const string& brokerName, int timeoutMillis);
 
-  void deleteTopicInBroker(const string& addr, const string& topic,
-                           int timeoutMillis);
+  void deleteTopicInBroker(const string& addr, const string& topic, int timeoutMillis);
 
-  void deleteTopicInNameServer(const string& addr, const string& topic,
-                               int timeoutMillis);
+  void deleteTopicInNameServer(const string& addr, const string& topic, int timeoutMillis);
 
-  void deleteSubscriptionGroup(const string& addr, const string& groupName,
-                               int timeoutMillis);
+  void deleteSubscriptionGroup(const string& addr, const string& groupName, int timeoutMillis);
 
-  string getKVConfigByValue(const string& projectNamespace,
-                            const string& projectGroup, int timeoutMillis);
+  string getKVConfigByValue(const string& projectNamespace, const string& projectGroup, int timeoutMillis);
 
-  KVTable getKVListByNamespace(const string& projectNamespace,
-                               int timeoutMillis);
+  KVTable getKVListByNamespace(const string& projectNamespace, int timeoutMillis);
 
-  void deleteKVConfigByValue(const string& projectNamespace,
-                             const string& projectGroup, int timeoutMillis);
+  void deleteKVConfigByValue(const string& projectNamespace, const string& projectGroup, int timeoutMillis);
 
-  SendResult processSendResponse(const string& brokerName, const MQMessage& msg,
-                                 RemotingCommand* pResponse);
+  SendResult processSendResponse(const string& brokerName, const MQMessage& msg, RemotingCommand* pResponse);
 
   PullResult* processPullResponse(RemotingCommand* pResponse);
 
-  int64 getMinOffset(const string& addr, const string& topic, int queueId,
+  int64 getMinOffset(const string& addr,
+                     const string& topic,
+                     int queueId,
                      int timeoutMillis,
                      const SessionCredentials& sessionCredentials);
 
-  int64 getMaxOffset(const string& addr, const string& topic, int queueId,
+  int64 getMaxOffset(const string& addr,
+                     const string& topic,
+                     int queueId,
                      int timeoutMillis,
                      const SessionCredentials& sessionCredentials);
 
-  int64 searchOffset(const string& addr, const string& topic, int queueId,
-                     uint64_t timestamp, int timeoutMillis,
+  int64 searchOffset(const string& addr,
+                     const string& topic,
+                     int queueId,
+                     uint64_t timestamp,
+                     int timeoutMillis,
                      const SessionCredentials& sessionCredentials);
 
-  MQMessageExt* viewMessage(const string& addr, int64 phyoffset,
+  MQMessageExt* viewMessage(const string& addr,
+                            int64 phyoffset,
                             int timeoutMillis,
                             const SessionCredentials& sessionCredentials);
 
-  int64 getEarliestMsgStoretime(const string& addr, const string& topic,
-                                int queueId, int timeoutMillis,
+  int64 getEarliestMsgStoretime(const string& addr,
+                                const string& topic,
+                                int queueId,
+                                int timeoutMillis,
                                 const SessionCredentials& sessionCredentials);
 
-  void getConsumerIdListByGroup(const string& addr, const string& consumerGroup,
-                                vector<string>& cids, int timeoutMillis,
+  void getConsumerIdListByGroup(const string& addr,
+                                const string& consumerGroup,
+                                vector<string>& cids,
+                                int timeoutMillis,
                                 const SessionCredentials& sessionCredentials);
 
   int64 queryConsumerOffset(const string& addr,
@@ -146,43 +162,54 @@
                             int timeoutMillis,
                             const SessionCredentials& sessionCredentials);
 
-  void updateConsumerOffsetOneway(
-      const string& addr, UpdateConsumerOffsetRequestHeader* pRequestHeader,
-      int timeoutMillis, const SessionCredentials& sessionCredentials);
+  void updateConsumerOffsetOneway(const string& addr,
+                                  UpdateConsumerOffsetRequestHeader* pRequestHeader,
+                                  int timeoutMillis,
+                                  const SessionCredentials& sessionCredentials);
 
-  void consumerSendMessageBack(MQMessageExt& msg, const string& consumerGroup,
-                               int delayLevel, int timeoutMillis,
+  void consumerSendMessageBack(MQMessageExt& msg,
+                               const string& consumerGroup,
+                               int delayLevel,
+                               int timeoutMillis,
                                const SessionCredentials& sessionCredentials);
 
-  void lockBatchMQ(const string& addr, LockBatchRequestBody* requestBody,
-                   vector<MQMessageQueue>& mqs, int timeoutMillis,
+  void lockBatchMQ(const string& addr,
+                   LockBatchRequestBody* requestBody,
+                   vector<MQMessageQueue>& mqs,
+                   int timeoutMillis,
                    const SessionCredentials& sessionCredentials);
 
-  void unlockBatchMQ(const string& addr, UnlockBatchRequestBody* requestBody,
+  void unlockBatchMQ(const string& addr,
+                     UnlockBatchRequestBody* requestBody,
                      int timeoutMillis,
                      const SessionCredentials& sessionCredentials);
 
-  void sendMessageAsync(const string& addr, const string& brokerName,
-                        const MQMessage& msg, RemotingCommand& request,
-                        SendCallback* pSendCallback, int64 timeoutMilliseconds,
-                        int maxRetryTimes=1,
-                        int retrySendTimes=1);
-  void deleteOpaqueForDropPullRequest(const MQMessageQueue& mq, int opaque);
+  void sendMessageAsync(const string& addr,
+                        const string& brokerName,
+                        const MQMessage& msg,
+                        RemotingCommand& request,
+                        SendCallback* pSendCallback,
+                        int64 timeoutMilliseconds,
+                        int maxRetryTimes = 1,
+                        int retrySendTimes = 1);
 
  private:
-  SendResult sendMessageSync(const string& addr, const string& brokerName,
-                             const MQMessage& msg, RemotingCommand& request,
+  SendResult sendMessageSync(const string& addr,
+                             const string& brokerName,
+                             const MQMessage& msg,
+                             RemotingCommand& request,
                              int timeoutMillis);
   /*
   void sendMessageAsync(const string& addr, const string& brokerName,
                         const MQMessage& msg, RemotingCommand& request,
                         SendCallback* pSendCallback, int64 timeoutMilliseconds);
   */
-  PullResult* pullMessageSync(const string& addr, RemotingCommand& request,
-                              int timeoutMillis);
+  PullResult* pullMessageSync(const string& addr, RemotingCommand& request, int timeoutMillis);
 
-  void pullMessageAsync(const string& addr, RemotingCommand& request,
-                        int timeoutMillis, PullCallback* pullCallback,
+  void pullMessageAsync(const string& addr,
+                        RemotingCommand& request,
+                        int timeoutMillis,
+                        PullCallback* pullCallback,
                         void* pArg);
 
  private:
@@ -192,6 +219,6 @@
   bool m_firstFetchNameSrv;
   string m_mqClientId;
 };
-}  //<!end namespace;
+}  // namespace rocketmq
 //<!***************************************************************************
 #endif
diff --git a/src/MQClientFactory.cpp b/src/MQClientFactory.cpp
index 2dd7bdb..99c4ffd 100644
--- a/src/MQClientFactory.cpp
+++ b/src/MQClientFactory.cpp
@@ -21,6 +21,7 @@
 #include "PullRequest.h"
 #include "Rebalance.h"
 #include "TopicPublishInfo.h"
+#include "TransactionMQProducer.h"
 
 #define MAX_BUFF_SIZE 8192
 #define SAFE_BUFF_SIZE 7936  // 8192 - 256 = 7936
@@ -28,7 +29,8 @@
 
 namespace rocketmq {
 //<!***************************************************************************
-MQClientFactory::MQClientFactory(const string& clientID, int pullThreadNum,
+MQClientFactory::MQClientFactory(const string& clientID,
+                                 int pullThreadNum,
                                  uint64_t tcpConnectTimeout,
                                  uint64_t tcpTransportTryLockTimeout,
                                  string unitName)
@@ -38,9 +40,8 @@
   boost::shared_ptr<TopicPublishInfo> pDefaultTopicInfo(new TopicPublishInfo());
   m_topicPublishInfoTable[DEFAULT_TOPIC] = pDefaultTopicInfo;
   m_pClientRemotingProcessor.reset(new ClientRemotingProcessor(this));
-  m_pClientAPIImpl.reset(new MQClientAPIImpl(
-      m_clientId, m_pClientRemotingProcessor.get(), pullThreadNum,
-      tcpConnectTimeout, tcpTransportTryLockTimeout, unitName));
+  m_pClientAPIImpl.reset(new MQClientAPIImpl(m_clientId, m_pClientRemotingProcessor.get(), pullThreadNum,
+                                             tcpConnectTimeout, tcpTransportTryLockTimeout, unitName));
   m_serviceState = CREATE_JUST;
   LOG_DEBUG("MQClientFactory construct");
 }
@@ -48,8 +49,7 @@
 MQClientFactory::~MQClientFactory() {
   LOG_INFO("MQClientFactory:%s destruct", m_clientId.c_str());
 
-  for (TRDMAP::iterator itp = m_topicRouteTable.begin();
-       itp != m_topicRouteTable.end(); ++itp) {
+  for (TRDMAP::iterator itp = m_topicRouteTable.begin(); itp != m_topicRouteTable.end(); ++itp) {
     delete itp->second;
   }
 
@@ -68,23 +68,21 @@
       LOG_INFO("MQClientFactory:%s start", m_clientId.c_str());
       m_serviceState = START_FAILED;
       //<!start time task;
-      m_async_service_thread.reset(new boost::thread(boost::bind(
-          &MQClientFactory::startScheduledTask, this, m_bFetchNSService)));
+      m_async_service_thread.reset(
+          new boost::thread(boost::bind(&MQClientFactory::startScheduledTask, this, m_bFetchNSService)));
       m_serviceState = RUNNING;
       break;
     case RUNNING:
     case SHUTDOWN_ALREADY:
     case START_FAILED:
-      LOG_INFO("The Factory object:%s start failed with fault state:%d",
-               m_clientId.c_str(), m_serviceState);
+      LOG_INFO("The Factory object:%s start failed with fault state:%d", m_clientId.c_str(), m_serviceState);
       break;
     default:
       break;
   }
 }
 
-void MQClientFactory::updateTopicRouteInfo(boost::system::error_code& ec,
-                                           boost::asio::deadline_timer* t) {
+void MQClientFactory::updateTopicRouteInfo(boost::system::error_code& ec, boost::asio::deadline_timer* t) {
   if ((getConsumerTableSize() == 0) && (getProducerTableSize() == 0)) {
     return;
   }
@@ -107,10 +105,8 @@
   }
 
   boost::system::error_code e;
-  t->expires_from_now(t->expires_from_now() + boost::posix_time::seconds(30),
-                      e);
-  t->async_wait(
-      boost::bind(&MQClientFactory::updateTopicRouteInfo, this, ec, t));
+  t->expires_from_now(t->expires_from_now() + boost::posix_time::seconds(30), e);
+  t->async_wait(boost::bind(&MQClientFactory::updateTopicRouteInfo, this, ec, t));
 }
 
 TopicRouteData* MQClientFactory::getTopicRouteData(const string& topic) {
@@ -121,8 +117,7 @@
   return NULL;
 }
 
-void MQClientFactory::addTopicRouteData(const string& topic,
-                                        TopicRouteData* pTopicRouteData) {
+void MQClientFactory::addTopicRouteData(const string& topic, TopicRouteData* pTopicRouteData) {
   boost::lock_guard<boost::mutex> lock(m_topicRouteTableMutex);
   if (m_topicRouteTable.find(topic) != m_topicRouteTable.end()) {
     delete m_topicRouteTable[topic];
@@ -132,12 +127,12 @@
 }
 
 boost::shared_ptr<TopicPublishInfo> MQClientFactory::tryToFindTopicPublishInfo(
-    const string& topic, const SessionCredentials& session_credentials) {
-  boost::lock_guard<boost::mutex> lock(
-      m_topicPublishInfoLock);  // add topicPublishInfoLock to avoid con-current
-                                // excuting updateTopicRouteInfoFromNameServer
-                                // when producer send msg  before topicRouteInfo
-                                // was got;
+    const string& topic,
+    const SessionCredentials& session_credentials) {
+  boost::lock_guard<boost::mutex> lock(m_topicPublishInfoLock);  // add topicPublishInfoLock to avoid con-current
+                                                                 // excuting updateTopicRouteInfoFromNameServer
+                                                                 // when producer send msg  before topicRouteInfo
+                                                                 // was got;
   if (!isTopicInfoValidInTable(topic)) {
     updateTopicRouteInfoFromNameServer(topic, session_credentials);
   }
@@ -156,29 +151,28 @@
   return getTopicPublishInfoFromTable(topic);
 }
 
-bool MQClientFactory::updateTopicRouteInfoFromNameServer(
-    const string& topic, const SessionCredentials& session_credentials,
-    bool isDefault /* = false */) {
+bool MQClientFactory::updateTopicRouteInfoFromNameServer(const string& topic,
+                                                         const SessionCredentials& session_credentials,
+                                                         bool isDefault /* = false */) {
   boost::lock_guard<boost::mutex> lock(m_factoryLock);
   unique_ptr<TopicRouteData> pTopicRouteData;
   LOG_INFO("updateTopicRouteInfoFromNameServer start:%s", topic.c_str());
 
   if (isDefault) {
-    pTopicRouteData.reset(m_pClientAPIImpl->getTopicRouteInfoFromNameServer(
-        DEFAULT_TOPIC, 1000 * 5, session_credentials));
+    pTopicRouteData.reset(
+        m_pClientAPIImpl->getTopicRouteInfoFromNameServer(DEFAULT_TOPIC, 1000 * 5, session_credentials));
     if (pTopicRouteData != NULL) {
       vector<QueueData>& queueDatas = pTopicRouteData->getQueueDatas();
       vector<QueueData>::iterator it = queueDatas.begin();
       for (; it != queueDatas.end(); ++it) {
-        // ¶Áд·ÖÇø¸öÊýÊÇÒ»Ö£¬¹ÊÖ»×öÒ»´ÎÅжÏ;
         int queueNums = std::min(4, it->readQueueNums);
         it->readQueueNums = queueNums;
         it->writeQueueNums = queueNums;
       }
     }
+    LOG_DEBUG("getTopicRouteInfoFromNameServer is null for topic :%s", topic.c_str());
   } else {
-    pTopicRouteData.reset(m_pClientAPIImpl->getTopicRouteInfoFromNameServer(
-        topic, 1000 * 5, session_credentials));
+    pTopicRouteData.reset(m_pClientAPIImpl->getTopicRouteInfoFromNameServer(topic, 1000 * 5, session_credentials));
   }
 
   if (pTopicRouteData != NULL) {
@@ -201,16 +195,13 @@
       vector<BrokerData> brokerList = pTopicRouteData->getBrokerDatas();
       vector<BrokerData>::iterator it = brokerList.begin();
       for (; it != brokerList.end(); ++it) {
-        LOG_INFO(
-            "updateTopicRouteInfoFromNameServer changed with broker name:%s",
-            (*it).brokerName.c_str());
+        LOG_INFO("updateTopicRouteInfoFromNameServer changed with broker name:%s", (*it).brokerName.c_str());
         addBrokerToAddrMap((*it).brokerName, (*it).brokerAddrs);
       }
 
       //<! update publish info;
       {
-        boost::shared_ptr<TopicPublishInfo> publishInfo(
-            topicRouteData2TopicPublishInfo(topic, pTopicRouteData.get()));
+        boost::shared_ptr<TopicPublishInfo> publishInfo(topicRouteData2TopicPublishInfo(topic, pTopicRouteData.get()));
         addTopicInfoToTable(topic, publishInfo);  // erase first, then add
       }
 
@@ -224,9 +215,8 @@
   return false;
 }
 
-boost::shared_ptr<TopicPublishInfo>
-MQClientFactory::topicRouteData2TopicPublishInfo(const string& topic,
-                                                 TopicRouteData* pRoute) {
+boost::shared_ptr<TopicPublishInfo> MQClientFactory::topicRouteData2TopicPublishInfo(const string& topic,
+                                                                                     TopicRouteData* pRoute) {
   boost::shared_ptr<TopicPublishInfo> info(new TopicPublishInfo());
   string OrderTopicConf = pRoute->getOrderTopicConf();
   //<! order msg
@@ -265,8 +255,9 @@
   return info;
 }
 
-void MQClientFactory::topicRouteData2TopicSubscribeInfo(
-    const string& topic, TopicRouteData* pRoute, vector<MQMessageQueue>& mqs) {
+void MQClientFactory::topicRouteData2TopicSubscribeInfo(const string& topic,
+                                                        TopicRouteData* pRoute,
+                                                        vector<MQMessageQueue>& mqs) {
   mqs.clear();
   vector<QueueData>& queueDatas = pRoute->getQueueDatas();
   vector<QueueData>::iterator it = queueDatas.begin();
@@ -282,13 +273,14 @@
 }
 
 void MQClientFactory::shutdown() {
-  if (getConsumerTableSize() != 0) return;
+  if (getConsumerTableSize() != 0)
+    return;
 
-  if (getProducerTableSize() != 0) return;
+  if (getProducerTableSize() != 0)
+    return;
 
   switch (m_serviceState) {
     case RUNNING: {
-      //<! stop;
       if (m_consumer_async_service_thread) {
         m_consumer_async_ioService.stop();
         m_consumer_async_service_thread->interrupt();
@@ -313,7 +305,6 @@
       break;
   }
 
-  //<!ɾ³ý×Ô¼º;
   MQClientManager::getInstance()->removeClientFactory(m_clientId);
 }
 
@@ -332,9 +323,9 @@
   //<!set nameserver;
   if (namesrvaddr.empty()) {
     string nameSrvDomain(pProducer->getNamesrvDomain());
-    if (!nameSrvDomain.empty()) m_nameSrvDomain = nameSrvDomain;
-    pProducer->setNamesrvAddr(
-        m_pClientAPIImpl->fetchNameServerAddr(m_nameSrvDomain));
+    if (!nameSrvDomain.empty())
+      m_nameSrvDomain = nameSrvDomain;
+    pProducer->setNamesrvAddr(m_pClientAPIImpl->fetchNameServerAddr(m_nameSrvDomain));
   } else {
     m_bFetchNSService = false;
     m_pClientAPIImpl->updateNameServerAddr(namesrvaddr);
@@ -364,9 +355,9 @@
   //<!set nameserver;
   if (namesrvaddr.empty()) {
     string nameSrvDomain(pConsumer->getNamesrvDomain());
-    if (!nameSrvDomain.empty()) m_nameSrvDomain = nameSrvDomain;
-    pConsumer->setNamesrvAddr(
-        m_pClientAPIImpl->fetchNameServerAddr(m_nameSrvDomain));
+    if (!nameSrvDomain.empty())
+      m_nameSrvDomain = nameSrvDomain;
+    pConsumer->setNamesrvAddr(m_pClientAPIImpl->fetchNameServerAddr(m_nameSrvDomain));
   } else {
     m_bFetchNSService = false;
     m_pClientAPIImpl->updateNameServerAddr(namesrvaddr);
@@ -391,23 +382,23 @@
   return NULL;
 }
 
-bool MQClientFactory::getSessionCredentialFromProducerTable(
-    SessionCredentials& sessionCredentials) {
+bool MQClientFactory::getSessionCredentialFromProducerTable(SessionCredentials& sessionCredentials) {
   boost::lock_guard<boost::mutex> lock(m_producerTableMutex);
-  for (MQPMAP::iterator it = m_producerTable.begin();
-       it != m_producerTable.end(); ++it) {
-    if (it->second) sessionCredentials = it->second->getSessionCredentials();
+  for (MQPMAP::iterator it = m_producerTable.begin(); it != m_producerTable.end(); ++it) {
+    if (it->second)
+      sessionCredentials = it->second->getSessionCredentials();
   }
 
-  if (sessionCredentials.isValid()) return true;
+  if (sessionCredentials.isValid())
+    return true;
 
   return false;
 }
 
-bool MQClientFactory::addProducerToTable(const string& producerName,
-                                         MQProducer* pMQProducer) {
+bool MQClientFactory::addProducerToTable(const string& producerName, MQProducer* pMQProducer) {
   boost::lock_guard<boost::mutex> lock(m_producerTableMutex);
-  if (m_producerTable.find(producerName) != m_producerTable.end()) return false;
+  if (m_producerTable.find(producerName) != m_producerTable.end())
+    return false;
   m_producerTable[producerName] = pMQProducer;
   return true;
 }
@@ -423,11 +414,9 @@
   return m_producerTable.size();
 }
 
-void MQClientFactory::insertProducerInfoToHeartBeatData(
-    HeartbeatData* pHeartbeatData) {
+void MQClientFactory::insertProducerInfoToHeartBeatData(HeartbeatData* pHeartbeatData) {
   boost::lock_guard<boost::mutex> lock(m_producerTableMutex);
-  for (MQPMAP::iterator it = m_producerTable.begin();
-       it != m_producerTable.end(); ++it) {
+  for (MQPMAP::iterator it = m_producerTable.begin(); it != m_producerTable.end(); ++it) {
     ProducerData producerData;
     producerData.groupName = it->first;
     pHeartbeatData->insertDataToProducerDataSet(producerData);
@@ -442,36 +431,36 @@
   return NULL;
 }
 
-bool MQClientFactory::getSessionCredentialFromConsumerTable(
-    SessionCredentials& sessionCredentials) {
+bool MQClientFactory::getSessionCredentialFromConsumerTable(SessionCredentials& sessionCredentials) {
   boost::lock_guard<boost::mutex> lock(m_consumerTableMutex);
-  for (MQCMAP::iterator it = m_consumerTable.begin();
-       it != m_consumerTable.end(); ++it) {
-    if (it->second) sessionCredentials = it->second->getSessionCredentials();
+  for (MQCMAP::iterator it = m_consumerTable.begin(); it != m_consumerTable.end(); ++it) {
+    if (it->second)
+      sessionCredentials = it->second->getSessionCredentials();
   }
 
-  if (sessionCredentials.isValid()) return true;
+  if (sessionCredentials.isValid())
+    return true;
 
   return false;
 }
 
-bool MQClientFactory::getSessionCredentialFromConsumer(
-    const string& consumerGroup, SessionCredentials& sessionCredentials) {
+bool MQClientFactory::getSessionCredentialFromConsumer(const string& consumerGroup,
+                                                       SessionCredentials& sessionCredentials) {
   boost::lock_guard<boost::mutex> lock(m_consumerTableMutex);
   if (m_consumerTable.find(consumerGroup) != m_consumerTable.end()) {
-    sessionCredentials =
-        m_consumerTable[consumerGroup]->getSessionCredentials();
+    sessionCredentials = m_consumerTable[consumerGroup]->getSessionCredentials();
   }
 
-  if (sessionCredentials.isValid()) return true;
+  if (sessionCredentials.isValid())
+    return true;
 
   return false;
 }
 
-bool MQClientFactory::addConsumerToTable(const string& consumerName,
-                                         MQConsumer* pMQConsumer) {
+bool MQClientFactory::addConsumerToTable(const string& consumerName, MQConsumer* pMQConsumer) {
   boost::lock_guard<boost::mutex> lock(m_consumerTableMutex);
-  if (m_consumerTable.find(consumerName) != m_consumerTable.end()) return false;
+  if (m_consumerTable.find(consumerName) != m_consumerTable.end())
+    return false;
   m_consumerTable[consumerName] = pMQConsumer;
   return true;
 }
@@ -490,11 +479,9 @@
   return m_consumerTable.size();
 }
 
-void MQClientFactory::getTopicListFromConsumerSubscription(
-    set<string>& topicList) {
+void MQClientFactory::getTopicListFromConsumerSubscription(set<string>& topicList) {
   boost::lock_guard<boost::mutex> lock(m_consumerTableMutex);
-  for (MQCMAP::iterator it = m_consumerTable.begin();
-       it != m_consumerTable.end(); ++it) {
+  for (MQCMAP::iterator it = m_consumerTable.begin(); it != m_consumerTable.end(); ++it) {
     vector<SubscriptionData> result;
     it->second->getSubscriptions(result);
 
@@ -505,20 +492,16 @@
   }
 }
 
-void MQClientFactory::updateConsumerSubscribeTopicInfo(
-    const string& topic, vector<MQMessageQueue> mqs) {
+void MQClientFactory::updateConsumerSubscribeTopicInfo(const string& topic, vector<MQMessageQueue> mqs) {
   boost::lock_guard<boost::mutex> lock(m_consumerTableMutex);
-  for (MQCMAP::iterator it = m_consumerTable.begin();
-       it != m_consumerTable.end(); ++it) {
+  for (MQCMAP::iterator it = m_consumerTable.begin(); it != m_consumerTable.end(); ++it) {
     it->second->updateTopicSubscribeInfo(topic, mqs);
   }
 }
 
-void MQClientFactory::insertConsumerInfoToHeartBeatData(
-    HeartbeatData* pHeartbeatData) {
+void MQClientFactory::insertConsumerInfoToHeartBeatData(HeartbeatData* pHeartbeatData) {
   boost::lock_guard<boost::mutex> lock(m_consumerTableMutex);
-  for (MQCMAP::iterator it = m_consumerTable.begin();
-       it != m_consumerTable.end(); ++it) {
+  for (MQCMAP::iterator it = m_consumerTable.begin(); it != m_consumerTable.end(); ++it) {
     MQConsumer* pConsumer = it->second;
     ConsumerData consumerData;
     consumerData.groupName = pConsumer->getGroupName();
@@ -535,9 +518,7 @@
   }
 }
 
-void MQClientFactory::addTopicInfoToTable(
-    const string& topic,
-    boost::shared_ptr<TopicPublishInfo> pTopicPublishInfo) {
+void MQClientFactory::addTopicInfoToTable(const string& topic, boost::shared_ptr<TopicPublishInfo> pTopicPublishInfo) {
   boost::lock_guard<boost::mutex> lock(m_topicPublishInfoTableMutex);
   if (m_topicPublishInfoTable.find(topic) != m_topicPublishInfoTable.end()) {
     m_topicPublishInfoTable.erase(topic);
@@ -555,13 +536,13 @@
 bool MQClientFactory::isTopicInfoValidInTable(const string& topic) {
   boost::lock_guard<boost::mutex> lock(m_topicPublishInfoTableMutex);
   if (m_topicPublishInfoTable.find(topic) != m_topicPublishInfoTable.end()) {
-    if (m_topicPublishInfoTable[topic]->ok()) return true;
+    if (m_topicPublishInfoTable[topic]->ok())
+      return true;
   }
   return false;
 }
 
-boost::shared_ptr<TopicPublishInfo>
-MQClientFactory::getTopicPublishInfoFromTable(const string& topic) {
+boost::shared_ptr<TopicPublishInfo> MQClientFactory::getTopicPublishInfoFromTable(const string& topic) {
   boost::lock_guard<boost::mutex> lock(m_topicPublishInfoTableMutex);
   if (m_topicPublishInfoTable.find(topic) != m_topicPublishInfoTable.end()) {
     return m_topicPublishInfoTable[topic];
@@ -572,8 +553,7 @@
 
 void MQClientFactory::getTopicListFromTopicPublishInfo(set<string>& topicList) {
   boost::lock_guard<boost::mutex> lock(m_topicPublishInfoTableMutex);
-  for (TPMap::iterator itp = m_topicPublishInfoTable.begin();
-       itp != m_topicPublishInfoTable.end(); ++itp) {
+  for (TPMap::iterator itp = m_topicPublishInfoTable.begin(); itp != m_topicPublishInfoTable.end(); ++itp) {
     topicList.insert(itp->first);
   }
 }
@@ -583,8 +563,7 @@
   m_brokerAddrTable.clear();
 }
 
-void MQClientFactory::addBrokerToAddrMap(const string& brokerName,
-                                         map<int, string>& brokerAddrs) {
+void MQClientFactory::addBrokerToAddrMap(const string& brokerName, map<int, string>& brokerAddrs) {
   boost::lock_guard<boost::mutex> lock(m_brokerAddrlock);
   if (m_brokerAddrTable.find(brokerName) != m_brokerAddrTable.end()) {
     m_brokerAddrTable.erase(brokerName);
@@ -626,47 +605,47 @@
   }
 
   brokerTable.clear();
-  if (found) return brokerAddr;
+  if (found)
+    return brokerAddr;
 
   return "";
 }
 
-FindBrokerResult *MQClientFactory::findBrokerAddressInSubscribe(const string &brokerName,
+FindBrokerResult* MQClientFactory::findBrokerAddressInSubscribe(const string& brokerName,
                                                                 int brokerId,
                                                                 bool onlyThisBroker) {
-    string brokerAddr;
-    bool slave = false;
-    bool found = false;
-    BrokerAddrMAP brokerTable(getBrokerAddrMap());
+  string brokerAddr;
+  bool slave = false;
+  bool found = false;
+  BrokerAddrMAP brokerTable(getBrokerAddrMap());
 
-    if (brokerTable.find(brokerName) != brokerTable.end()) {
-        map<int, string> brokerMap(brokerTable[brokerName]);
-        if (!brokerMap.empty()) {
-            auto iter = brokerMap.find(brokerId);
-            if (iter != brokerMap.end()) {
-                brokerAddr = iter->second;
-                slave = (brokerId != MASTER_ID);
-                found = true;
-            } else if (!onlyThisBroker) {  // not only from master
-                iter = brokerMap.begin();
-                brokerAddr = iter->second;
-                slave = iter->first != MASTER_ID;
-                found = true;
-            }
-        }
+  if (brokerTable.find(brokerName) != brokerTable.end()) {
+    map<int, string> brokerMap(brokerTable[brokerName]);
+    if (!brokerMap.empty()) {
+      auto iter = brokerMap.find(brokerId);
+      if (iter != brokerMap.end()) {
+        brokerAddr = iter->second;
+        slave = (brokerId != MASTER_ID);
+        found = true;
+      } else if (!onlyThisBroker) {  // not only from master
+        iter = brokerMap.begin();
+        brokerAddr = iter->second;
+        slave = iter->first != MASTER_ID;
+        found = true;
+      }
     }
+  }
 
-    brokerTable.clear();
+  brokerTable.clear();
 
-    if (found) {
-        return new FindBrokerResult(brokerAddr, slave);
-    }
+  if (found) {
+    return new FindBrokerResult(brokerAddr, slave);
+  }
 
-    return nullptr;
+  return nullptr;
 }
 
-FindBrokerResult* MQClientFactory::findBrokerAddressInAdmin(
-    const string& brokerName) {
+FindBrokerResult* MQClientFactory::findBrokerAddressInAdmin(const string& brokerName) {
   BrokerAddrMAP brokerTable(getBrokerAddrMap());
   bool found = false;
   bool slave = false;
@@ -683,11 +662,37 @@
   }
 
   brokerTable.clear();
-  if (found) return new FindBrokerResult(brokerAddr, slave);
+  if (found)
+    return new FindBrokerResult(brokerAddr, slave);
 
   return NULL;
 }
 
+void MQClientFactory::checkTransactionState(const std::string& addr,
+                                            const MQMessageExt& messageExt,
+                                            const CheckTransactionStateRequestHeader& checkRequestHeader) {
+  string group = messageExt.getProperty(MQMessage::PROPERTY_PRODUCER_GROUP);
+  if (!group.empty()) {
+    MQProducer* producer = selectProducer(group);
+    if (producer != nullptr) {
+      TransactionMQProducer* transProducer = dynamic_cast<TransactionMQProducer*>(producer);
+      if (transProducer != nullptr) {
+        transProducer->checkTransactionState(addr, messageExt, checkRequestHeader.m_tranStateTableOffset,
+                                             checkRequestHeader.m_commitLogOffset, checkRequestHeader.m_msgId,
+                                             checkRequestHeader.m_transactionId, checkRequestHeader.m_offsetMsgId);
+      } else {
+        LOG_ERROR("checkTransactionState, producer not TransactionMQProducer failed, msg:%s",
+                  messageExt.toString().data());
+      }
+    } else {
+      LOG_ERROR("checkTransactionState, pick producer by group[%s] failed, msg:%s", group.data(),
+                messageExt.toString().data());
+    }
+  } else {
+    LOG_ERROR("checkTransactionState, pick producer group failed, msg:%s", messageExt.toString().data());
+  }
+}
+
 MQClientAPIImpl* MQClientFactory::getMQClientAPIImpl() const {
   return m_pClientAPIImpl.get();
 }
@@ -710,17 +715,16 @@
 
   SessionCredentials session_credentials;
   getSessionCredentialsFromOneOfProducerOrConsumer(session_credentials);
-  for (BrokerAddrMAP::iterator it = brokerTable.begin();
-       it != brokerTable.end(); ++it) {
+  for (BrokerAddrMAP::iterator it = brokerTable.begin(); it != brokerTable.end(); ++it) {
     map<int, string> brokerMap(it->second);
     map<int, string>::iterator it1 = brokerMap.begin();
     for (; it1 != brokerMap.end(); ++it1) {
       string& addr = it1->second;
-      if (consumerEmpty && it1->first != MASTER_ID) continue;
+      if (consumerEmpty && it1->first != MASTER_ID)
+        continue;
 
       try {
-        m_pClientAPIImpl->sendHearbeat(addr, heartbeatData.get(),
-                                       session_credentials);
+        m_pClientAPIImpl->sendHearbeat(addr, heartbeatData.get(), session_credentials);
       } catch (MQException& e) {
         LOG_ERROR(e.what());
       }
@@ -729,13 +733,11 @@
   brokerTable.clear();
 }
 
-void MQClientFactory::persistAllConsumerOffset(boost::system::error_code& ec,
-                                               boost::asio::deadline_timer* t) {
+void MQClientFactory::persistAllConsumerOffset(boost::system::error_code& ec, boost::asio::deadline_timer* t) {
   {
     boost::lock_guard<boost::mutex> lock(m_consumerTableMutex);
     if (m_consumerTable.size() > 0) {
-      for (MQCMAP::iterator it = m_consumerTable.begin();
-           it != m_consumerTable.end(); ++it) {
+      for (MQCMAP::iterator it = m_consumerTable.begin(); it != m_consumerTable.end(); ++it) {
         LOG_DEBUG("Client factory start persistAllConsumerOffset");
         it->second->persistConsumerOffset();
       }
@@ -744,8 +746,7 @@
 
   boost::system::error_code e;
   t->expires_from_now(t->expires_from_now() + boost::posix_time::seconds(5), e);
-  t->async_wait(
-      boost::bind(&MQClientFactory::persistAllConsumerOffset, this, ec, t));
+  t->async_wait(boost::bind(&MQClientFactory::persistAllConsumerOffset, this, ec, t));
 }
 
 HeartbeatData* MQClientFactory::prepareHeartbeatData() {
@@ -762,26 +763,20 @@
   return pHeartbeatData;
 }
 
-void MQClientFactory::timerCB_sendHeartbeatToAllBroker(
-    boost::system::error_code& ec, boost::asio::deadline_timer* t) {
+void MQClientFactory::timerCB_sendHeartbeatToAllBroker(boost::system::error_code& ec, boost::asio::deadline_timer* t) {
   sendHeartbeatToAllBroker();
 
   boost::system::error_code e;
-  t->expires_from_now(t->expires_from_now() + boost::posix_time::seconds(30),
-                      e);
-  t->async_wait(boost::bind(&MQClientFactory::timerCB_sendHeartbeatToAllBroker,
-                            this, ec, t));
+  t->expires_from_now(t->expires_from_now() + boost::posix_time::seconds(30), e);
+  t->async_wait(boost::bind(&MQClientFactory::timerCB_sendHeartbeatToAllBroker, this, ec, t));
 }
 
-void MQClientFactory::fetchNameServerAddr(boost::system::error_code& ec,
-                                          boost::asio::deadline_timer* t) {
+void MQClientFactory::fetchNameServerAddr(boost::system::error_code& ec, boost::asio::deadline_timer* t) {
   m_pClientAPIImpl->fetchNameServerAddr(m_nameSrvDomain);
 
   boost::system::error_code e;
-  t->expires_from_now(
-      t->expires_from_now() + boost::posix_time::seconds(60 * 2), e);
-  t->async_wait(
-      boost::bind(&MQClientFactory::fetchNameServerAddr, this, ec, t));
+  t->expires_from_now(t->expires_from_now() + boost::posix_time::seconds(60 * 2), e);
+  t->async_wait(boost::bind(&MQClientFactory::fetchNameServerAddr, this, ec, t));
 }
 
 void MQClientFactory::startScheduledTask(bool startFetchNSService) {
@@ -791,23 +786,18 @@
                                                           // callback
 
   boost::system::error_code ec1;
-  boost::asio::deadline_timer t1(m_async_ioService,
-                                 boost::posix_time::seconds(3));
-  t1.async_wait(
-      boost::bind(&MQClientFactory::updateTopicRouteInfo, this, ec1, &t1));
+  boost::asio::deadline_timer t1(m_async_ioService, boost::posix_time::seconds(3));
+  t1.async_wait(boost::bind(&MQClientFactory::updateTopicRouteInfo, this, ec1, &t1));
 
   boost::system::error_code ec2;
-  boost::asio::deadline_timer t2(m_async_ioService,
-                                 boost::posix_time::milliseconds(10));
-  t2.async_wait(boost::bind(&MQClientFactory::timerCB_sendHeartbeatToAllBroker,
-                            this, ec2, &t2));
+  boost::asio::deadline_timer t2(m_async_ioService, boost::posix_time::milliseconds(10));
+  t2.async_wait(boost::bind(&MQClientFactory::timerCB_sendHeartbeatToAllBroker, this, ec2, &t2));
 
   if (startFetchNSService) {
     boost::system::error_code ec5;
-    boost::asio::deadline_timer* t5 = new boost::asio::deadline_timer(
-        m_async_ioService, boost::posix_time::seconds(60 * 2));
-    t5->async_wait(
-        boost::bind(&MQClientFactory::fetchNameServerAddr, this, ec5, t5));
+    boost::asio::deadline_timer* t5 =
+        new boost::asio::deadline_timer(m_async_ioService, boost::posix_time::seconds(60 * 2));
+    t5->async_wait(boost::bind(&MQClientFactory::fetchNameServerAddr, this, ec5, t5));
   }
 
   LOG_INFO("start scheduled task:%s", m_clientId.c_str());
@@ -819,54 +809,44 @@
   // m_consumer_async_service_thread will be only started once for all consumer
   if (m_consumer_async_service_thread == NULL) {
     doRebalance();
-    m_consumer_async_service_thread.reset(new boost::thread(
-        boost::bind(&MQClientFactory::consumer_timerOperation, this)));
+    m_consumer_async_service_thread.reset(
+        new boost::thread(boost::bind(&MQClientFactory::consumer_timerOperation, this)));
   }
 }
 
 void MQClientFactory::consumer_timerOperation() {
-  LOG_INFO("clientFactory:%s start consumer_timerOperation",
-           m_clientId.c_str());
-  boost::asio::io_service::work work(
-      m_consumer_async_ioService);  // avoid async io
-                                    // service stops after
-                                    // first timer timeout
-                                    // callback
+  LOG_INFO("clientFactory:%s start consumer_timerOperation", m_clientId.c_str());
+  boost::asio::io_service::work work(m_consumer_async_ioService);  // avoid async io
+                                                                   // service stops after
+                                                                   // first timer timeout
+                                                                   // callback
 
   boost::system::error_code ec1;
-  boost::asio::deadline_timer t(m_consumer_async_ioService,
-                                boost::posix_time::seconds(10));
-  t.async_wait(
-      boost::bind(&MQClientFactory::timerCB_doRebalance, this, ec1, &t));
+  boost::asio::deadline_timer t(m_consumer_async_ioService, boost::posix_time::seconds(10));
+  t.async_wait(boost::bind(&MQClientFactory::timerCB_doRebalance, this, ec1, &t));
 
   boost::system::error_code ec2;
-  boost::asio::deadline_timer t2(m_consumer_async_ioService,
-                                 boost::posix_time::seconds(5));
-  t2.async_wait(
-      boost::bind(&MQClientFactory::persistAllConsumerOffset, this, ec2, &t2));
+  boost::asio::deadline_timer t2(m_consumer_async_ioService, boost::posix_time::seconds(5));
+  t2.async_wait(boost::bind(&MQClientFactory::persistAllConsumerOffset, this, ec2, &t2));
 
   boost::system::error_code ec;
   m_consumer_async_ioService.run(ec);
   LOG_INFO("clientFactory:%s stop consumer_timerOperation", m_clientId.c_str());
 }
 
-void MQClientFactory::timerCB_doRebalance(boost::system::error_code& ec,
-                                          boost::asio::deadline_timer* t) {
+void MQClientFactory::timerCB_doRebalance(boost::system::error_code& ec, boost::asio::deadline_timer* t) {
   doRebalance();
 
   boost::system::error_code e;
-  t->expires_from_now(t->expires_from_now() + boost::posix_time::seconds(10),
-                      e);
-  t->async_wait(
-      boost::bind(&MQClientFactory::timerCB_doRebalance, this, ec, t));
+  t->expires_from_now(t->expires_from_now() + boost::posix_time::seconds(10), e);
+  t->async_wait(boost::bind(&MQClientFactory::timerCB_doRebalance, this, ec, t));
 }
 
 void MQClientFactory::doRebalance() {
   LOG_INFO("Client factory:%s start dorebalance", m_clientId.c_str());
   if (getConsumerTableSize() > 0) {
     boost::lock_guard<boost::mutex> lock(m_consumerTableMutex);
-    for (MQCMAP::iterator it = m_consumerTable.begin();
-         it != m_consumerTable.end(); ++it) {
+    for (MQCMAP::iterator it = m_consumerTable.begin(); it != m_consumerTable.end(); ++it) {
       it->second->doRebalance();
     }
   }
@@ -876,33 +856,47 @@
 void MQClientFactory::doRebalanceByConsumerGroup(const string& consumerGroup) {
   boost::lock_guard<boost::mutex> lock(m_consumerTableMutex);
   if (m_consumerTable.find(consumerGroup) != m_consumerTable.end()) {
-    LOG_INFO("Client factory:%s start dorebalance for consumer:%s",
-             m_clientId.c_str(), consumerGroup.c_str());
+    LOG_INFO("Client factory:%s start dorebalance for consumer:%s", m_clientId.c_str(), consumerGroup.c_str());
     MQConsumer* pMQConsumer = m_consumerTable[consumerGroup];
     pMQConsumer->doRebalance();
   }
 }
 
-void MQClientFactory::unregisterClient(
-    const string& producerGroup, const string& consumerGroup,
-    const SessionCredentials& sessionCredentials) {
+void MQClientFactory::endTransactionOneway(const MQMessageQueue& mq,
+                                           EndTransactionRequestHeader* requestHeader,
+                                           const SessionCredentials& sessionCredentials) {
+  string brokerAddr = findBrokerAddressInPublish(mq.getBrokerName());
+  string remark = "";
+  if (!brokerAddr.empty()) {
+    try {
+      getMQClientAPIImpl()->endTransactionOneway(brokerAddr, requestHeader, remark, sessionCredentials);
+    } catch (MQException& e) {
+      LOG_ERROR("endTransactionOneway exception:%s", e.what());
+      throw e;
+    }
+  } else {
+    THROW_MQEXCEPTION(MQClientException, "The broker[" + mq.getBrokerName() + "] not exist", -1);
+  }
+}
+
+void MQClientFactory::unregisterClient(const string& producerGroup,
+                                       const string& consumerGroup,
+                                       const SessionCredentials& sessionCredentials) {
   BrokerAddrMAP brokerTable(getBrokerAddrMap());
-  for (BrokerAddrMAP::iterator it = brokerTable.begin();
-       it != brokerTable.end(); ++it) {
+  for (BrokerAddrMAP::iterator it = brokerTable.begin(); it != brokerTable.end(); ++it) {
     map<int, string> brokerMap(it->second);
     map<int, string>::iterator it1 = brokerMap.begin();
     for (; it1 != brokerMap.end(); ++it1) {
       string& addr = it1->second;
-      m_pClientAPIImpl->unregisterClient(addr, m_clientId, producerGroup,
-                                         consumerGroup, sessionCredentials);
+      m_pClientAPIImpl->unregisterClient(addr, m_clientId, producerGroup, consumerGroup, sessionCredentials);
     }
   }
 }
 
 //<!************************************************************************
-void MQClientFactory::fetchSubscribeMessageQueues(
-    const string& topic, vector<MQMessageQueue>& mqs,
-    const SessionCredentials& sessionCredentials) {
+void MQClientFactory::fetchSubscribeMessageQueues(const string& topic,
+                                                  vector<MQMessageQueue>& mqs,
+                                                  const SessionCredentials& sessionCredentials) {
   TopicRouteData* pTopicRouteData = getTopicRouteData(topic);
   if (pTopicRouteData == NULL) {
     updateTopicRouteInfoFromNameServer(topic, sessionCredentials);
@@ -919,12 +913,12 @@
 }
 
 //<!***************************************************************************
-void MQClientFactory::createTopic(
-    const string& key, const string& newTopic, int queueNum,
-    const SessionCredentials& sessionCredentials) {}
+void MQClientFactory::createTopic(const string& key,
+                                  const string& newTopic,
+                                  int queueNum,
+                                  const SessionCredentials& sessionCredentials) {}
 
-int64 MQClientFactory::minOffset(const MQMessageQueue& mq,
-                                 const SessionCredentials& sessionCredentials) {
+int64 MQClientFactory::minOffset(const MQMessageQueue& mq, const SessionCredentials& sessionCredentials) {
   string brokerAddr = findBrokerAddressInPublish(mq.getBrokerName());
   if (brokerAddr.empty()) {
     updateTopicRouteInfoFromNameServer(mq.getTopic(), sessionCredentials);
@@ -933,9 +927,7 @@
 
   if (!brokerAddr.empty()) {
     try {
-      return m_pClientAPIImpl->getMinOffset(brokerAddr, mq.getTopic(),
-                                            mq.getQueueId(), 1000 * 3,
-                                            sessionCredentials);
+      return m_pClientAPIImpl->getMinOffset(brokerAddr, mq.getTopic(), mq.getQueueId(), 1000 * 3, sessionCredentials);
     } catch (MQException& e) {
       LOG_ERROR(e.what());
     }
@@ -943,8 +935,7 @@
   THROW_MQEXCEPTION(MQClientException, "The broker is not exist", -1);
 }
 
-int64 MQClientFactory::maxOffset(const MQMessageQueue& mq,
-                                 const SessionCredentials& sessionCredentials) {
+int64 MQClientFactory::maxOffset(const MQMessageQueue& mq, const SessionCredentials& sessionCredentials) {
   string brokerAddr = findBrokerAddressInPublish(mq.getBrokerName());
   if (brokerAddr.empty()) {
     updateTopicRouteInfoFromNameServer(mq.getTopic(), sessionCredentials);
@@ -953,8 +944,26 @@
 
   if (!brokerAddr.empty()) {
     try {
-      return m_pClientAPIImpl->getMaxOffset(brokerAddr, mq.getTopic(),
-                                            mq.getQueueId(), 1000 * 3,
+      return m_pClientAPIImpl->getMaxOffset(brokerAddr, mq.getTopic(), mq.getQueueId(), 1000 * 3, sessionCredentials);
+    } catch (MQException& e) {
+      THROW_MQEXCEPTION(MQClientException, "Invoke Broker exception", -1);
+    }
+  }
+  THROW_MQEXCEPTION(MQClientException, "The broker is not exist", -1);
+}
+
+int64 MQClientFactory::searchOffset(const MQMessageQueue& mq,
+                                    int64 timestamp,
+                                    const SessionCredentials& sessionCredentials) {
+  string brokerAddr = findBrokerAddressInPublish(mq.getBrokerName());
+  if (brokerAddr.empty()) {
+    updateTopicRouteInfoFromNameServer(mq.getTopic(), sessionCredentials);
+    brokerAddr = findBrokerAddressInPublish(mq.getBrokerName());
+  }
+
+  if (!brokerAddr.empty()) {
+    try {
+      return m_pClientAPIImpl->searchOffset(brokerAddr, mq.getTopic(), mq.getQueueId(), timestamp, 1000 * 3,
                                             sessionCredentials);
     } catch (MQException& e) {
       THROW_MQEXCEPTION(MQClientException, "Invoke Broker exception", -1);
@@ -963,29 +972,7 @@
   THROW_MQEXCEPTION(MQClientException, "The broker is not exist", -1);
 }
 
-int64 MQClientFactory::searchOffset(
-    const MQMessageQueue& mq, int64 timestamp,
-    const SessionCredentials& sessionCredentials) {
-  string brokerAddr = findBrokerAddressInPublish(mq.getBrokerName());
-  if (brokerAddr.empty()) {
-    updateTopicRouteInfoFromNameServer(mq.getTopic(), sessionCredentials);
-    brokerAddr = findBrokerAddressInPublish(mq.getBrokerName());
-  }
-
-  if (!brokerAddr.empty()) {
-    try {
-      return m_pClientAPIImpl->searchOffset(brokerAddr, mq.getTopic(),
-                                            mq.getQueueId(), timestamp,
-                                            1000 * 3, sessionCredentials);
-    } catch (MQException& e) {
-      THROW_MQEXCEPTION(MQClientException, "Invoke Broker exception", -1);
-    }
-  }
-  THROW_MQEXCEPTION(MQClientException, "The broker is not exist", -1);
-}
-
-MQMessageExt* MQClientFactory::viewMessage(
-    const string& msgId, const SessionCredentials& sessionCredentials) {
+MQMessageExt* MQClientFactory::viewMessage(const string& msgId, const SessionCredentials& sessionCredentials) {
   try {
     return NULL;
   } catch (MQException& e) {
@@ -993,8 +980,7 @@
   }
 }
 
-int64 MQClientFactory::earliestMsgStoreTime(
-    const MQMessageQueue& mq, const SessionCredentials& sessionCredentials) {
+int64 MQClientFactory::earliestMsgStoreTime(const MQMessageQueue& mq, const SessionCredentials& sessionCredentials) {
   string brokerAddr = findBrokerAddressInPublish(mq.getBrokerName());
   if (brokerAddr.empty()) {
     updateTopicRouteInfoFromNameServer(mq.getTopic(), sessionCredentials);
@@ -1003,9 +989,8 @@
 
   if (!brokerAddr.empty()) {
     try {
-      return m_pClientAPIImpl->getEarliestMsgStoretime(
-          brokerAddr, mq.getTopic(), mq.getQueueId(), 1000 * 3,
-          sessionCredentials);
+      return m_pClientAPIImpl->getEarliestMsgStoretime(brokerAddr, mq.getTopic(), mq.getQueueId(), 1000 * 3,
+                                                       sessionCredentials);
     } catch (MQException& e) {
       THROW_MQEXCEPTION(MQClientException, "Invoke Broker exception", -1);
     }
@@ -1013,15 +998,19 @@
   THROW_MQEXCEPTION(MQClientException, "The broker is not exist", -1);
 }
 
-QueryResult MQClientFactory::queryMessage(
-    const string& topic, const string& key, int maxNum, int64 begin, int64 end,
-    const SessionCredentials& sessionCredentials) {
+QueryResult MQClientFactory::queryMessage(const string& topic,
+                                          const string& key,
+                                          int maxNum,
+                                          int64 begin,
+                                          int64 end,
+                                          const SessionCredentials& sessionCredentials) {
   THROW_MQEXCEPTION(MQClientException, "queryMessage", -1);
 }
 
-void MQClientFactory::findConsumerIds(
-    const string& topic, const string& group, vector<string>& cids,
-    const SessionCredentials& sessionCredentials) {
+void MQClientFactory::findConsumerIds(const string& topic,
+                                      const string& group,
+                                      vector<string>& cids,
+                                      const SessionCredentials& sessionCredentials) {
   string brokerAddr;
   TopicRouteData* pTopicRouteData = getTopicRouteData(topic);
   if (pTopicRouteData == NULL) {
@@ -1035,28 +1024,16 @@
   if (!brokerAddr.empty()) {
     try {
       LOG_INFO("getConsumerIdList from broker:%s", brokerAddr.c_str());
-      return m_pClientAPIImpl->getConsumerIdListByGroup(
-          brokerAddr, group, cids, 5000, sessionCredentials);
+      return m_pClientAPIImpl->getConsumerIdListByGroup(brokerAddr, group, cids, 5000, sessionCredentials);
     } catch (MQException& e) {
       LOG_ERROR(e.what());
     }
   }
 }
 
-void MQClientFactory::removeDropedPullRequestOpaque(PullRequest* pullRequest) {
-  //delete the opaque record that's ignore the response of this pullrequest when drop pullrequest
-  if (!pullRequest) return;
-  MQMessageQueue mq = pullRequest->m_messageQueue;
-  int opaque = pullRequest->getLatestPullRequestOpaque();
-  if (opaque > 0) {
-      LOG_INFO("####### need delete the pullrequest for opaque:%d, mq:%s", opaque, mq.toString().data());
-      getMQClientAPIImpl()->deleteOpaqueForDropPullRequest(mq, opaque);
-  }
-}
-
-void MQClientFactory::resetOffset(
-    const string& group, const string& topic,
-    const map<MQMessageQueue, int64>& offsetTable) {
+void MQClientFactory::resetOffset(const string& group,
+                                  const string& topic,
+                                  const map<MQMessageQueue, int64>& offsetTable) {
   MQConsumer* pConsumer = selectConsumer(group);
   if (pConsumer) {
     map<MQMessageQueue, int64>::const_iterator it = offsetTable.begin();
@@ -1066,14 +1043,11 @@
       PullRequest* pullreq = pConsumer->getRebalance()->getPullRequest(mq);
       if (pullreq) {
         pullreq->setDroped(true);
-        LOG_INFO("resetOffset setDroped for opaque:%d, mq:%s", pullreq->getLatestPullRequestOpaque(), mq.toString().data());
-        //delete the opaque record that's ignore the response of this pullrequest when drop pullrequest
-        //removeDropedPullRequestOpaque(pullreq);
+        LOG_INFO("resetOffset setDroped for mq:%s", mq.toString().data());
         pullreq->clearAllMsgs();
         pullreq->updateQueueMaxOffset(it->second);
       } else {
-        LOG_ERROR("no corresponding pullRequest found for topic:%s",
-                  topic.c_str());
+        LOG_ERROR("no corresponding pullRequest found for topic:%s", topic.c_str());
       }
     }
 
@@ -1091,8 +1065,7 @@
     for (it = offsetTable.begin(); it != offsetTable.end(); ++it) {
       MQMessageQueue mq = it->first;
       if (topic == mq.getTopic()) {
-        LOG_DEBUG("resetOffset sets to:%lld for mq:%s", it->second,
-                  mq.toString().c_str());
+        LOG_DEBUG("resetOffset sets to:%lld for mq:%s", it->second, mq.toString().c_str());
         pConsumer->updateConsumeOffset(mq, it->second);
       }
     }
@@ -1113,35 +1086,28 @@
   }
 }
 
-ConsumerRunningInfo* MQClientFactory::consumerRunningInfo(
-    const string& consumerGroup) {
+ConsumerRunningInfo* MQClientFactory::consumerRunningInfo(const string& consumerGroup) {
   MQConsumer* pConsumer = selectConsumer(consumerGroup);
   if (pConsumer) {
     ConsumerRunningInfo* runningInfo = pConsumer->getConsumerRunningInfo();
     if (runningInfo) {
-      runningInfo->setProperty(ConsumerRunningInfo::PROP_NAMESERVER_ADDR,
-                               pConsumer->getNamesrvAddr());
+      runningInfo->setProperty(ConsumerRunningInfo::PROP_NAMESERVER_ADDR, pConsumer->getNamesrvAddr());
       if (pConsumer->getConsumeType() == CONSUME_PASSIVELY) {
-        runningInfo->setProperty(ConsumerRunningInfo::PROP_CONSUME_TYPE,
-                                 "CONSUME_PASSIVELY");
+        runningInfo->setProperty(ConsumerRunningInfo::PROP_CONSUME_TYPE, "CONSUME_PASSIVELY");
       } else {
-        runningInfo->setProperty(ConsumerRunningInfo::PROP_CONSUME_TYPE,
-                                 "CONSUME_ACTIVELY");
+        runningInfo->setProperty(ConsumerRunningInfo::PROP_CONSUME_TYPE, "CONSUME_ACTIVELY");
       }
-      runningInfo->setProperty(ConsumerRunningInfo::PROP_CLIENT_VERSION,
-                               "V3_1_8");  // MQVersion::s_CurrentVersion ));
+      runningInfo->setProperty(ConsumerRunningInfo::PROP_CLIENT_VERSION, "V3_1_8");  // MQVersion::s_CurrentVersion ));
 
       return runningInfo;
     }
   }
 
-  LOG_ERROR("no corresponding consumer found for group:%s",
-            consumerGroup.c_str());
+  LOG_ERROR("no corresponding consumer found for group:%s", consumerGroup.c_str());
   return NULL;
 }
 
-void MQClientFactory::getSessionCredentialsFromOneOfProducerOrConsumer(
-    SessionCredentials& session_credentials) {
+void MQClientFactory::getSessionCredentialsFromOneOfProducerOrConsumer(SessionCredentials& session_credentials) {
   // Note: on the same MQClientFactory, all producers and consumers used the
   // same
   // sessionCredentials,
@@ -1164,4 +1130,4 @@
 }
 
 //<!************************************************************************
-}  //<!end namespace;
+}  // namespace rocketmq
diff --git a/src/MQClientFactory.h b/src/MQClientFactory.h
index 7da2e21..e0d0efd 100644
--- a/src/MQClientFactory.h
+++ b/src/MQClientFactory.h
@@ -40,9 +40,11 @@
 class TopicPublishInfo;
 class MQClientFactory {
  public:
-  MQClientFactory(const string& clientID, int pullThreadNum,
+  MQClientFactory(const string& clientID,
+                  int pullThreadNum,
                   uint64_t tcpConnectTimeout,
-                  uint64_t tcpTransportTryLockTimeout, string unitName);
+                  uint64_t tcpTransportTryLockTimeout,
+                  string unitName);
   virtual ~MQClientFactory();
 
   void start();
@@ -52,68 +54,66 @@
   bool registerConsumer(MQConsumer* pConsumer);
   void unregisterConsumer(MQConsumer* pConsumer);
 
-  void createTopic(const string& key, const string& newTopic, int queueNum,
+  void createTopic(const string& key,
+                   const string& newTopic,
+                   int queueNum,
                    const SessionCredentials& session_credentials);
-  int64 minOffset(const MQMessageQueue& mq,
-                  const SessionCredentials& session_credentials);
-  int64 maxOffset(const MQMessageQueue& mq,
-                  const SessionCredentials& session_credentials);
-  int64 searchOffset(const MQMessageQueue& mq, int64 timestamp,
-                     const SessionCredentials& session_credentials);
-  int64 earliestMsgStoreTime(const MQMessageQueue& mq,
-                             const SessionCredentials& session_credentials);
-  MQMessageExt* viewMessage(const string& msgId,
-                            const SessionCredentials& session_credentials);
-  QueryResult queryMessage(const string& topic, const string& key, int maxNum,
-                           int64 begin, int64 end,
+  int64 minOffset(const MQMessageQueue& mq, const SessionCredentials& session_credentials);
+  int64 maxOffset(const MQMessageQueue& mq, const SessionCredentials& session_credentials);
+  int64 searchOffset(const MQMessageQueue& mq, int64 timestamp, const SessionCredentials& session_credentials);
+  int64 earliestMsgStoreTime(const MQMessageQueue& mq, const SessionCredentials& session_credentials);
+  MQMessageExt* viewMessage(const string& msgId, const SessionCredentials& session_credentials);
+  QueryResult queryMessage(const string& topic,
+                           const string& key,
+                           int maxNum,
+                           int64 begin,
+                           int64 end,
                            const SessionCredentials& session_credentials);
-
+  void endTransactionOneway(const MQMessageQueue& mq,
+                            EndTransactionRequestHeader* requestHeader,
+                            const SessionCredentials& sessionCredentials);
+  void checkTransactionState(const std::string& addr,
+                             const MQMessageExt& message,
+                             const CheckTransactionStateRequestHeader& checkRequestHeader);
   MQClientAPIImpl* getMQClientAPIImpl() const;
   MQProducer* selectProducer(const string& group);
   MQConsumer* selectConsumer(const string& group);
 
-  boost::shared_ptr<TopicPublishInfo> topicRouteData2TopicPublishInfo(
-      const string& topic, TopicRouteData* pRoute);
+  boost::shared_ptr<TopicPublishInfo> topicRouteData2TopicPublishInfo(const string& topic, TopicRouteData* pRoute);
 
-  void topicRouteData2TopicSubscribeInfo(const string& topic,
-                                         TopicRouteData* pRoute,
-                                         vector<MQMessageQueue>& mqs);
+  void topicRouteData2TopicSubscribeInfo(const string& topic, TopicRouteData* pRoute, vector<MQMessageQueue>& mqs);
 
-  FindBrokerResult* findBrokerAddressInSubscribe(const string& brokerName,
-                                                 int brokerId,
-                                                 bool onlyThisBroker);
+  FindBrokerResult* findBrokerAddressInSubscribe(const string& brokerName, int brokerId, bool onlyThisBroker);
 
   FindBrokerResult* findBrokerAddressInAdmin(const string& brokerName);
 
   string findBrokerAddressInPublish(const string& brokerName);
 
-  boost::shared_ptr<TopicPublishInfo> tryToFindTopicPublishInfo(
-      const string& topic, const SessionCredentials& session_credentials);
+  boost::shared_ptr<TopicPublishInfo> tryToFindTopicPublishInfo(const string& topic,
+                                                                const SessionCredentials& session_credentials);
 
-  void fetchSubscribeMessageQueues(
-      const string& topic, vector<MQMessageQueue>& mqs,
-      const SessionCredentials& session_credentials);
+  void fetchSubscribeMessageQueues(const string& topic,
+                                   vector<MQMessageQueue>& mqs,
+                                   const SessionCredentials& session_credentials);
 
-  bool updateTopicRouteInfoFromNameServer(
-      const string& topic, const SessionCredentials& session_credentials,
-      bool isDefault = false);
+  bool updateTopicRouteInfoFromNameServer(const string& topic,
+                                          const SessionCredentials& session_credentials,
+                                          bool isDefault = false);
   void rebalanceImmediately();
   void doRebalanceByConsumerGroup(const string& consumerGroup);
   void sendHeartbeatToAllBroker();
 
-  void findConsumerIds(const string& topic, const string& group,
+  void findConsumerIds(const string& topic,
+                       const string& group,
                        vector<string>& cids,
                        const SessionCredentials& session_credentials);
-  void resetOffset(const string& group, const string& topic,
-                   const map<MQMessageQueue, int64>& offsetTable);
+  void resetOffset(const string& group, const string& topic, const map<MQMessageQueue, int64>& offsetTable);
   ConsumerRunningInfo* consumerRunningInfo(const string& consumerGroup);
-  bool getSessionCredentialFromConsumer(const string& consumerGroup,
-                                        SessionCredentials& sessionCredentials);
-  void addBrokerToAddrMap(const string& brokerName,
-                          map<int, string>& brokerAddrs);
+  bool getSessionCredentialFromConsumer(const string& consumerGroup, SessionCredentials& sessionCredentials);
+  void addBrokerToAddrMap(const string& brokerName, map<int, string>& brokerAddrs);
   map<string, map<int, string>> getBrokerAddrMap();
   void clearBrokerAddrMap();
-  void removeDropedPullRequestOpaque(PullRequest* pullRequest);
+
  private:
   void unregisterClient(const string& producerGroup,
                         const string& consumerGroup,
@@ -124,50 +124,38 @@
 
   void startScheduledTask(bool startFetchNSService = true);
   //<!timer async callback
-  void fetchNameServerAddr(boost::system::error_code& ec,
-                           boost::asio::deadline_timer* t);
-  void updateTopicRouteInfo(boost::system::error_code& ec,
-                            boost::asio::deadline_timer* t);
-  void timerCB_sendHeartbeatToAllBroker(boost::system::error_code& ec,
-                                        boost::asio::deadline_timer* t);
+  void fetchNameServerAddr(boost::system::error_code& ec, boost::asio::deadline_timer* t);
+  void updateTopicRouteInfo(boost::system::error_code& ec, boost::asio::deadline_timer* t);
+  void timerCB_sendHeartbeatToAllBroker(boost::system::error_code& ec, boost::asio::deadline_timer* t);
 
   // consumer related operation
   void consumer_timerOperation();
-  void persistAllConsumerOffset(boost::system::error_code& ec,
-                                boost::asio::deadline_timer* t);
+  void persistAllConsumerOffset(boost::system::error_code& ec, boost::asio::deadline_timer* t);
   void doRebalance();
-  void timerCB_doRebalance(boost::system::error_code& ec,
-                           boost::asio::deadline_timer* t);
-  bool getSessionCredentialFromConsumerTable(
-      SessionCredentials& sessionCredentials);
+  void timerCB_doRebalance(boost::system::error_code& ec, boost::asio::deadline_timer* t);
+  bool getSessionCredentialFromConsumerTable(SessionCredentials& sessionCredentials);
   bool addConsumerToTable(const string& consumerName, MQConsumer* pMQConsumer);
   void eraseConsumerFromTable(const string& consumerName);
   int getConsumerTableSize();
   void getTopicListFromConsumerSubscription(set<string>& topicList);
-  void updateConsumerSubscribeTopicInfo(const string& topic,
-                                        vector<MQMessageQueue> mqs);
+  void updateConsumerSubscribeTopicInfo(const string& topic, vector<MQMessageQueue> mqs);
   void insertConsumerInfoToHeartBeatData(HeartbeatData* pHeartbeatData);
 
   // producer related operation
-  bool getSessionCredentialFromProducerTable(
-      SessionCredentials& sessionCredentials);
+  bool getSessionCredentialFromProducerTable(SessionCredentials& sessionCredentials);
   bool addProducerToTable(const string& producerName, MQProducer* pMQProducer);
   void eraseProducerFromTable(const string& producerName);
   int getProducerTableSize();
   void insertProducerInfoToHeartBeatData(HeartbeatData* pHeartbeatData);
 
   // topicPublishInfo related operation
-  void addTopicInfoToTable(
-      const string& topic,
-      boost::shared_ptr<TopicPublishInfo> pTopicPublishInfo);
+  void addTopicInfoToTable(const string& topic, boost::shared_ptr<TopicPublishInfo> pTopicPublishInfo);
   void eraseTopicInfoFromTable(const string& topic);
   bool isTopicInfoValidInTable(const string& topic);
-  boost::shared_ptr<TopicPublishInfo> getTopicPublishInfoFromTable(
-      const string& topic);
+  boost::shared_ptr<TopicPublishInfo> getTopicPublishInfoFromTable(const string& topic);
   void getTopicListFromTopicPublishInfo(set<string>& topicList);
 
-  void getSessionCredentialsFromOneOfProducerOrConsumer(
-      SessionCredentials& session_credentials);
+  void getSessionCredentialsFromOneOfProducerOrConsumer(SessionCredentials& session_credentials);
 
  private:
   string m_clientId;
@@ -215,6 +203,6 @@
   unique_ptr<boost::thread> m_consumer_async_service_thread;
 };
 
-}  //<!end namespace;
+}  // namespace rocketmq
 
 #endif
diff --git a/src/MQClientManager.cpp b/src/MQClientManager.cpp
old mode 100755
new mode 100644
index 79ef77e..2a658c8
--- a/src/MQClientManager.cpp
+++ b/src/MQClientManager.cpp
@@ -21,23 +21,26 @@
 //<!************************************************************************
 MQClientManager::MQClientManager() {}
 
-MQClientManager::~MQClientManager() { m_factoryTable.clear(); }
+MQClientManager::~MQClientManager() {
+  m_factoryTable.clear();
+}
 
 MQClientManager* MQClientManager::getInstance() {
   static MQClientManager instance;
   return &instance;
 }
 
-MQClientFactory* MQClientManager::getMQClientFactory(
-    const string& clientId, int pullThreadNum, uint64_t tcpConnectTimeout,
-    uint64_t tcpTransportTryLockTimeout, string unitName) {
+MQClientFactory* MQClientManager::getMQClientFactory(const string& clientId,
+                                                     int pullThreadNum,
+                                                     uint64_t tcpConnectTimeout,
+                                                     uint64_t tcpTransportTryLockTimeout,
+                                                     string unitName) {
   FTMAP::iterator it = m_factoryTable.find(clientId);
   if (it != m_factoryTable.end()) {
     return it->second;
   } else {
     MQClientFactory* factory =
-        new MQClientFactory(clientId, pullThreadNum, tcpConnectTimeout,
-                            tcpTransportTryLockTimeout, unitName);
+        new MQClientFactory(clientId, pullThreadNum, tcpConnectTimeout, tcpTransportTryLockTimeout, unitName);
     m_factoryTable[clientId] = factory;
     return factory;
   }
diff --git a/src/MQClientManager.h b/src/MQClientManager.h
old mode 100755
new mode 100644
index 7703c15..fc253d7
--- a/src/MQClientManager.h
+++ b/src/MQClientManager.h
@@ -27,7 +27,8 @@
 class MQClientManager {
  public:
   virtual ~MQClientManager();
-  MQClientFactory* getMQClientFactory(const string& clientId, int pullThreadNum,
+  MQClientFactory* getMQClientFactory(const string& clientId,
+                                      int pullThreadNum,
                                       uint64_t tcpConnectTimeout,
                                       uint64_t tcpTransportTryLockTimeout,
                                       string unitName);
diff --git a/src/common/Arg_helper.cpp b/src/common/Arg_helper.cpp
old mode 100755
new mode 100644
diff --git a/src/common/AsyncArg.h b/src/common/AsyncArg.h
old mode 100755
new mode 100644
index 4e23743..fc358cb
--- a/src/common/AsyncArg.h
+++ b/src/common/AsyncArg.h
@@ -21,7 +21,7 @@
 #include "MQMessageQueue.h"

 #include "PullAPIWrapper.h"

 #include "SubscriptionData.h"

-#include "../consumer/PullRequest.h"

+

 namespace rocketmq {

 //<!***************************************************************************

 

@@ -29,7 +29,6 @@
   MQMessageQueue mq;

   SubscriptionData subData;

   PullAPIWrapper* pPullWrapper;

-  PullRequest* pPullRequest;

 };

 

 //<!***************************************************************************

diff --git a/src/common/AsyncCallbackWrap.cpp b/src/common/AsyncCallbackWrap.cpp
index b0ffa04..cb26fda 100755
--- a/src/common/AsyncCallbackWrap.cpp
+++ b/src/common/AsyncCallbackWrap.cpp
@@ -1,197 +1,193 @@
-/*

- * Licensed to the Apache Software Foundation (ASF) under one or more

- * contributor license agreements.  See the NOTICE file distributed with

- * this work for additional information regarding copyright ownership.

- * The ASF licenses this file to You under the Apache License, Version 2.0

- * (the "License"); you may not use this file except in compliance with

- * the License.  You may obtain a copy of the License at

- *

- *     http://www.apache.org/licenses/LICENSE-2.0

- *

- * Unless required by applicable law or agreed to in writing, software

- * distributed under the License is distributed on an "AS IS" BASIS,

- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- * See the License for the specific language governing permissions and

- * limitations under the License.

- */

-

-#include "AsyncCallbackWrap.h"

-#include "Logging.h"

-#include "MQClientAPIImpl.h"

-#include "MQDecoder.h"

-#include "MQMessageQueue.h"

-#include "MQProtos.h"

-#include "PullAPIWrapper.h"

-#include "PullResultExt.h"

-#include "ResponseFuture.h"

-

-namespace rocketmq {

-//<!***************************************************************************

-AsyncCallbackWrap::AsyncCallbackWrap(AsyncCallback* pAsyncCallback,

-                                     MQClientAPIImpl* pclientAPI)

-    : m_pAsyncCallBack(pAsyncCallback), m_pClientAPI(pclientAPI) {}

-

-AsyncCallbackWrap::~AsyncCallbackWrap() {

-  m_pAsyncCallBack = NULL;

-  m_pClientAPI = NULL;

-}

-

-//<!************************************************************************

-SendCallbackWrap::SendCallbackWrap(const string& brokerName,

-                                   const MQMessage& msg,

-                                   AsyncCallback* pAsyncCallback,

-                                   MQClientAPIImpl* pclientAPI)

-    : AsyncCallbackWrap(pAsyncCallback, pclientAPI),

-      m_msg(msg),

-      m_brokerName(brokerName) {}

-

-void SendCallbackWrap::onException() {

-  if (m_pAsyncCallBack == NULL) return;

-

-  SendCallback* pCallback = static_cast<SendCallback*>(m_pAsyncCallBack);

-  if (pCallback) {

-    unique_ptr<MQException> exception(new MQException(

-        "send msg failed due to wait response timeout or network error", -1,

-        __FILE__, __LINE__));

-    pCallback->onException(*exception);

-    if (pCallback->getSendCallbackType() == autoDeleteSendCallback) {

-      deleteAndZero(pCallback);

-    }

-  }

-}

-

-void SendCallbackWrap::operationComplete(ResponseFuture* pResponseFuture,

-                                         bool bProducePullRequest) {

-  unique_ptr<RemotingCommand> pResponse(pResponseFuture->getCommand());

-

-  if (m_pAsyncCallBack == NULL) {

-    return;

-  }

-  int opaque = pResponseFuture->getOpaque();

-  SendCallback* pCallback = static_cast<SendCallback*>(m_pAsyncCallBack);

-

-  if (!pResponse) {

-    string err = "unknow reseaon";

-    if (!pResponseFuture->isSendRequestOK()) {

-      err = "send request failed";

-

-    } else if (pResponseFuture->isTimeOut()) {

-      // pResponseFuture->setAsyncResponseFlag();

-      err = "wait response timeout";

-    }

-    if (pCallback) {

-      MQException exception(err, -1, __FILE__, __LINE__);

-      pCallback->onException(exception);

-    }

-    LOG_ERROR("send failed of:%d", pResponseFuture->getOpaque());

-  } else {

-    try {

-        SendResult ret = m_pClientAPI->processSendResponse(m_brokerName, m_msg, pResponse.get());

-        if (pCallback) { 

-            LOG_DEBUG("operationComplete: processSendResponse success, opaque:%d, maxRetryTime:%d, retrySendTimes:%d", opaque, pResponseFuture->getMaxRetrySendTimes(), pResponseFuture->getRetrySendTimes());

-            pCallback->onSuccess(ret); 

-        }

-    } catch (MQException& e) {

-        LOG_ERROR("operationComplete: processSendResponse exception: %s", e.what());

-

-        //broker may return exception, need consider retry send

-        int maxRetryTimes = pResponseFuture->getMaxRetrySendTimes();

-        int retryTimes = pResponseFuture->getRetrySendTimes();

-        if (pResponseFuture->getASyncFlag() && retryTimes < maxRetryTimes && maxRetryTimes > 1) {

-

-            int64 left_timeout_ms = pResponseFuture->leftTime(); 

-            string brokerAddr = pResponseFuture->getBrokerAddr();

-            const RemotingCommand& requestCommand = pResponseFuture->getRequestCommand();

-            retryTimes += 1;

-            LOG_WARN("retry send, opaque:%d, sendTimes:%d, maxRetryTimes:%d, left_timeout:%lld, brokerAddr:%s, msg:%s", 

-                    opaque, retryTimes, maxRetryTimes, left_timeout_ms, brokerAddr.data(), m_msg.toString().data());

-

-            bool exception_flag = false;

-            try {

-                m_pClientAPI->sendMessageAsync(pResponseFuture->getBrokerAddr(), m_brokerName, m_msg, (RemotingCommand&)requestCommand, pCallback, left_timeout_ms, maxRetryTimes, retryTimes);

-            } catch (MQClientException& e) {

-                LOG_ERROR("retry send exception:%s, opaque:%d, retryTimes:%d, msg:%s, not retry send again", e.what(), opaque, retryTimes, m_msg.toString().data());

-                exception_flag = true;

-            }

-

-            if (exception_flag == false) {

-                return; //send retry again, here need return

-            }

-        }

-      

-        if (pCallback) {

-            MQException exception("process send response error", -1, __FILE__,

-                                  __LINE__);

-            pCallback->onException(exception);

-        }

-    }

-  }

-  if (pCallback && pCallback->getSendCallbackType() == autoDeleteSendCallback) {

-    deleteAndZero(pCallback);

-  }

-}

-

-//<!************************************************************************

-PullCallbackWarp::PullCallbackWarp(AsyncCallback* pAsyncCallback,

-                                   MQClientAPIImpl* pclientAPI, void* pArg)

-    : AsyncCallbackWrap(pAsyncCallback, pclientAPI) {

-  m_pArg = *static_cast<AsyncArg*>(pArg);

-}

-

-PullCallbackWarp::~PullCallbackWarp() {}

-

-void PullCallbackWarp::onException() {

-  if (m_pAsyncCallBack == NULL) return;

-

-  PullCallback* pCallback = static_cast<PullCallback*>(m_pAsyncCallBack);

-  if (pCallback) {

-    MQException exception("wait response timeout", -1, __FILE__, __LINE__);

-    pCallback->onException(exception);

-  } else {

-    LOG_ERROR("PullCallback is NULL, AsyncPull could not continue");

-  }

-}

-

-void PullCallbackWarp::operationComplete(ResponseFuture* pResponseFuture,

-                                         bool bProducePullRequest) {

-  unique_ptr<RemotingCommand> pResponse(pResponseFuture->getCommand());

-  if (m_pAsyncCallBack == NULL) {

-    LOG_ERROR("m_pAsyncCallBack is NULL, AsyncPull could not continue");

-    return;

-  }

-  PullCallback* pCallback = static_cast<PullCallback*>(m_pAsyncCallBack);

-  if (!pResponse) {

-    string err = "unknow reseaon";

-    if (!pResponseFuture->isSendRequestOK()) {

-      err = "send request failed";

-

-    } else if (pResponseFuture->isTimeOut()) {

-      // pResponseFuture->setAsyncResponseFlag();

-      err = "wait response timeout";

-    }

-    MQException exception(err, -1, __FILE__, __LINE__);

-    LOG_ERROR("Async pull exception of opaque:%d",

-              pResponseFuture->getOpaque());

-    if (pCallback && bProducePullRequest) pCallback->onException(exception);

-  } else {

-    try {

-      if (m_pArg.pPullWrapper) {

-        unique_ptr<PullResult> pullResult(

-            m_pClientAPI->processPullResponse(pResponse.get()));

-        PullResult result = m_pArg.pPullWrapper->processPullResult(

-            m_pArg.mq, pullResult.get(), &m_pArg.subData);

-        if (pCallback)

-          pCallback->onSuccess(m_pArg.mq, result, bProducePullRequest);

-      } else {

-        LOG_ERROR("pPullWrapper had been destroyed with consumer");

-      }

-    } catch (MQException& e) {

-      LOG_ERROR(e.what());

-      MQException exception("pullResult error", -1, __FILE__, __LINE__);

-      if (pCallback && bProducePullRequest) pCallback->onException(exception);

-    }

-  }

-}

-

-//<!***************************************************************************

-}  //<!end namespace;

+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "AsyncCallbackWrap.h"
+#include "Logging.h"
+#include "MQClientAPIImpl.h"
+#include "MQDecoder.h"
+#include "MQMessageQueue.h"
+#include "MQProtos.h"
+#include "PullAPIWrapper.h"
+#include "PullResultExt.h"
+#include "ResponseFuture.h"
+
+namespace rocketmq {
+//<!***************************************************************************
+AsyncCallbackWrap::AsyncCallbackWrap(AsyncCallback* pAsyncCallback, MQClientAPIImpl* pclientAPI)
+    : m_pAsyncCallBack(pAsyncCallback), m_pClientAPI(pclientAPI) {}
+
+AsyncCallbackWrap::~AsyncCallbackWrap() {
+  m_pAsyncCallBack = NULL;
+  m_pClientAPI = NULL;
+}
+
+//<!************************************************************************
+SendCallbackWrap::SendCallbackWrap(const string& brokerName,
+                                   const MQMessage& msg,
+                                   AsyncCallback* pAsyncCallback,
+                                   MQClientAPIImpl* pclientAPI)
+    : AsyncCallbackWrap(pAsyncCallback, pclientAPI), m_msg(msg), m_brokerName(brokerName) {}
+
+void SendCallbackWrap::onException() {
+  if (m_pAsyncCallBack == NULL)
+    return;
+
+  SendCallback* pCallback = static_cast<SendCallback*>(m_pAsyncCallBack);
+  if (pCallback) {
+    unique_ptr<MQException> exception(
+        new MQException("send msg failed due to wait response timeout or network error", -1, __FILE__, __LINE__));
+    pCallback->onException(*exception);
+    if (pCallback->getSendCallbackType() == autoDeleteSendCallback) {
+      deleteAndZero(pCallback);
+    }
+  }
+}
+
+void SendCallbackWrap::operationComplete(ResponseFuture* pResponseFuture, bool bProducePullRequest) {
+  unique_ptr<RemotingCommand> pResponse(pResponseFuture->getCommand());
+
+  if (m_pAsyncCallBack == NULL) {
+    return;
+  }
+  int opaque = pResponseFuture->getOpaque();
+  SendCallback* pCallback = static_cast<SendCallback*>(m_pAsyncCallBack);
+
+  if (!pResponse) {
+    string err = "unknow reseaon";
+    if (!pResponseFuture->isSendRequestOK()) {
+      err = "send request failed";
+
+    } else if (pResponseFuture->isTimeOut()) {
+      // pResponseFuture->setAsyncResponseFlag();
+      err = "wait response timeout";
+    }
+    if (pCallback) {
+      MQException exception(err, -1, __FILE__, __LINE__);
+      pCallback->onException(exception);
+    }
+    LOG_ERROR("send failed of:%d", pResponseFuture->getOpaque());
+  } else {
+    try {
+      SendResult ret = m_pClientAPI->processSendResponse(m_brokerName, m_msg, pResponse.get());
+      if (pCallback) {
+        LOG_DEBUG("operationComplete: processSendResponse success, opaque:%d, maxRetryTime:%d, retrySendTimes:%d",
+                  opaque, pResponseFuture->getMaxRetrySendTimes(), pResponseFuture->getRetrySendTimes());
+        pCallback->onSuccess(ret);
+      }
+    } catch (MQException& e) {
+      LOG_ERROR("operationComplete: processSendResponse exception: %s", e.what());
+
+      // broker may return exception, need consider retry send
+      int maxRetryTimes = pResponseFuture->getMaxRetrySendTimes();
+      int retryTimes = pResponseFuture->getRetrySendTimes();
+      if (pResponseFuture->getAsyncFlag() && retryTimes < maxRetryTimes && maxRetryTimes > 1) {
+        int64 left_timeout_ms = pResponseFuture->leftTime();
+        string brokerAddr = pResponseFuture->getBrokerAddr();
+        const RemotingCommand& requestCommand = pResponseFuture->getRequestCommand();
+        retryTimes += 1;
+        LOG_WARN("retry send, opaque:%d, sendTimes:%d, maxRetryTimes:%d, left_timeout:%lld, brokerAddr:%s, msg:%s",
+                 opaque, retryTimes, maxRetryTimes, left_timeout_ms, brokerAddr.data(), m_msg.toString().data());
+
+        bool exception_flag = false;
+        try {
+          m_pClientAPI->sendMessageAsync(pResponseFuture->getBrokerAddr(), m_brokerName, m_msg,
+                                         (RemotingCommand&)requestCommand, pCallback, left_timeout_ms, maxRetryTimes,
+                                         retryTimes);
+        } catch (MQClientException& e) {
+          LOG_ERROR("retry send exception:%s, opaque:%d, retryTimes:%d, msg:%s, not retry send again", e.what(), opaque,
+                    retryTimes, m_msg.toString().data());
+          exception_flag = true;
+        }
+
+        if (exception_flag == false) {
+          return;  // send retry again, here need return
+        }
+      }
+
+      if (pCallback) {
+        MQException exception("process send response error", -1, __FILE__, __LINE__);
+        pCallback->onException(exception);
+      }
+    }
+  }
+  if (pCallback && pCallback->getSendCallbackType() == autoDeleteSendCallback) {
+    deleteAndZero(pCallback);
+  }
+}
+
+//<!************************************************************************
+PullCallbackWarp::PullCallbackWarp(AsyncCallback* pAsyncCallback, MQClientAPIImpl* pclientAPI, void* pArg)
+    : AsyncCallbackWrap(pAsyncCallback, pclientAPI) {
+  m_pArg = *static_cast<AsyncArg*>(pArg);
+}
+
+PullCallbackWarp::~PullCallbackWarp() {}
+
+void PullCallbackWarp::onException() {
+  if (m_pAsyncCallBack == NULL)
+    return;
+
+  PullCallback* pCallback = static_cast<PullCallback*>(m_pAsyncCallBack);
+  if (pCallback) {
+    MQException exception("wait response timeout", -1, __FILE__, __LINE__);
+    pCallback->onException(exception);
+  } else {
+    LOG_ERROR("PullCallback is NULL, AsyncPull could not continue");
+  }
+}
+
+void PullCallbackWarp::operationComplete(ResponseFuture* pResponseFuture, bool bProducePullRequest) {
+  unique_ptr<RemotingCommand> pResponse(pResponseFuture->getCommand());
+  if (m_pAsyncCallBack == NULL) {
+    LOG_ERROR("m_pAsyncCallBack is NULL, AsyncPull could not continue");
+    return;
+  }
+  PullCallback* pCallback = static_cast<PullCallback*>(m_pAsyncCallBack);
+  if (!pResponse) {
+    string err = "unknow reseaon";
+    if (!pResponseFuture->isSendRequestOK()) {
+      err = "send request failed";
+
+    } else if (pResponseFuture->isTimeOut()) {
+      // pResponseFuture->setAsyncResponseFlag();
+      err = "wait response timeout";
+    }
+    MQException exception(err, -1, __FILE__, __LINE__);
+    LOG_ERROR("Async pull exception of opaque:%d", pResponseFuture->getOpaque());
+    if (pCallback && bProducePullRequest)
+      pCallback->onException(exception);
+  } else {
+    try {
+      if (m_pArg.pPullWrapper) {
+        unique_ptr<PullResult> pullResult(m_pClientAPI->processPullResponse(pResponse.get()));
+        PullResult result = m_pArg.pPullWrapper->processPullResult(m_pArg.mq, pullResult.get(), &m_pArg.subData);
+        if (pCallback)
+          pCallback->onSuccess(m_pArg.mq, result, bProducePullRequest);
+      } else {
+        LOG_ERROR("pPullWrapper had been destroyed with consumer");
+      }
+    } catch (MQException& e) {
+      LOG_ERROR(e.what());
+      MQException exception("pullResult error", -1, __FILE__, __LINE__);
+      if (pCallback && bProducePullRequest)
+        pCallback->onException(exception);
+    }
+  }
+}
+
+//<!***************************************************************************
+}  // namespace rocketmq
diff --git a/src/common/AsyncCallbackWrap.h b/src/common/AsyncCallbackWrap.h
old mode 100755
new mode 100644
index 02ae07f..9b202a8
--- a/src/common/AsyncCallbackWrap.h
+++ b/src/common/AsyncCallbackWrap.h
@@ -30,18 +30,13 @@
 class DefaultMQProducer;

 class SendMessageRequestHeader;

 //<!***************************************************************************

-enum asyncCallBackType {

-  asyncCallbackWrap = 0,

-  sendCallbackWrap = 1,

-  pullCallbackWarp = 2

-};

+enum asyncCallBackType { asyncCallbackWrap = 0, sendCallbackWrap = 1, pullCallbackWarp = 2 };

 

 struct AsyncCallbackWrap {

  public:

   AsyncCallbackWrap(AsyncCallback* pAsyncCallback, MQClientAPIImpl* pclientAPI);

   virtual ~AsyncCallbackWrap();

-  virtual void operationComplete(ResponseFuture* pResponseFuture,

-                                 bool bProducePullRequest) = 0;

+  virtual void operationComplete(ResponseFuture* pResponseFuture, bool bProducePullRequest) = 0;

   virtual void onException() = 0;

   virtual asyncCallBackType getCallbackType() = 0;

 

@@ -53,12 +48,13 @@
 //<!************************************************************************

 class SendCallbackWrap : public AsyncCallbackWrap {

  public:

-  SendCallbackWrap(const string& brokerName, const MQMessage& msg,

-                   AsyncCallback* pAsyncCallback, MQClientAPIImpl* pclientAPI);

+  SendCallbackWrap(const string& brokerName,

+                   const MQMessage& msg,

+                   AsyncCallback* pAsyncCallback,

+                   MQClientAPIImpl* pclientAPI);

 

   virtual ~SendCallbackWrap(){};

-  virtual void operationComplete(ResponseFuture* pResponseFuture,

-                                 bool bProducePullRequest);

+  virtual void operationComplete(ResponseFuture* pResponseFuture, bool bProducePullRequest);

   virtual void onException();

   virtual asyncCallBackType getCallbackType() { return sendCallbackWrap; }

 

@@ -70,11 +66,9 @@
 //<!***************************************************************************

 class PullCallbackWarp : public AsyncCallbackWrap {

  public:

-  PullCallbackWarp(AsyncCallback* pAsyncCallback, MQClientAPIImpl* pclientAPI,

-                   void* pArg);

+  PullCallbackWarp(AsyncCallback* pAsyncCallback, MQClientAPIImpl* pclientAPI, void* pArg);

   virtual ~PullCallbackWarp();

-  virtual void operationComplete(ResponseFuture* pResponseFuture,

-                                 bool bProducePullRequest);

+  virtual void operationComplete(ResponseFuture* pResponseFuture, bool bProducePullRequest);

   virtual void onException();

   virtual asyncCallBackType getCallbackType() { return pullCallbackWarp; }

 

diff --git a/src/common/ByteOrder.h b/src/common/ByteOrder.h
old mode 100755
new mode 100644
index e626b72..2ecb6ab
--- a/src/common/ByteOrder.h
+++ b/src/common/ByteOrder.h
@@ -113,14 +113,25 @@
   return (((uint64)swap((uint32)value)) << 32) | swap((uint32)(value >> 32));

 }

 

-#if __BYTE_ORDER__ == \

-    __ORDER_LITTLE_ENDIAN__  //__BYTE_ORDER__ is defined by GCC

-inline uint16 ByteOrder::swapIfBigEndian(const uint16 v) { return v; }

-inline uint32 ByteOrder::swapIfBigEndian(const uint32 v) { return v; }

-inline uint64 ByteOrder::swapIfBigEndian(const uint64 v) { return v; }

-inline uint16 ByteOrder::swapIfLittleEndian(const uint16 v) { return swap(v); }

-inline uint32 ByteOrder::swapIfLittleEndian(const uint32 v) { return swap(v); }

-inline uint64 ByteOrder::swapIfLittleEndian(const uint64 v) { return swap(v); }

+#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__  //__BYTE_ORDER__ is defined by GCC

+inline uint16 ByteOrder::swapIfBigEndian(const uint16 v) {

+  return v;

+}

+inline uint32 ByteOrder::swapIfBigEndian(const uint32 v) {

+  return v;

+}

+inline uint64 ByteOrder::swapIfBigEndian(const uint64 v) {

+  return v;

+}

+inline uint16 ByteOrder::swapIfLittleEndian(const uint16 v) {

+  return swap(v);

+}

+inline uint32 ByteOrder::swapIfLittleEndian(const uint32 v) {

+  return swap(v);

+}

+inline uint64 ByteOrder::swapIfLittleEndian(const uint64 v) {

+  return swap(v);

+}

 inline uint32 ByteOrder::littleEndianInt(const void* const bytes) {

   return *static_cast<const uint32*>(bytes);

 }

@@ -139,14 +150,28 @@
 inline uint16 ByteOrder::bigEndianShort(const void* const bytes) {

   return swap(*static_cast<const uint16*>(bytes));

 }

-inline bool ByteOrder::isBigEndian() { return false; }

+inline bool ByteOrder::isBigEndian() {

+  return false;

+}

 #else

-inline uint16 ByteOrder::swapIfBigEndian(const uint16 v) { return swap(v); }

-inline uint32 ByteOrder::swapIfBigEndian(const uint32 v) { return swap(v); }

-inline uint64 ByteOrder::swapIfBigEndian(const uint64 v) { return swap(v); }

-inline uint16 ByteOrder::swapIfLittleEndian(const uint16 v) { return v; }

-inline uint32 ByteOrder::swapIfLittleEndian(const uint32 v) { return v; }

-inline uint64 ByteOrder::swapIfLittleEndian(const uint64 v) { return v; }

+inline uint16 ByteOrder::swapIfBigEndian(const uint16 v) {

+  return swap(v);

+}

+inline uint32 ByteOrder::swapIfBigEndian(const uint32 v) {

+  return swap(v);

+}

+inline uint64 ByteOrder::swapIfBigEndian(const uint64 v) {

+  return swap(v);

+}

+inline uint16 ByteOrder::swapIfLittleEndian(const uint16 v) {

+  return v;

+}

+inline uint32 ByteOrder::swapIfLittleEndian(const uint32 v) {

+  return v;

+}

+inline uint64 ByteOrder::swapIfLittleEndian(const uint64 v) {

+  return v;

+}

 inline uint32 ByteOrder::littleEndianInt(const void* const bytes) {

   return swap(*static_cast<const uint32*>(bytes));

 }

@@ -165,27 +190,25 @@
 inline uint16 ByteOrder::bigEndianShort(const void* const bytes) {

   return *static_cast<const uint16*>(bytes);

 }

-inline bool ByteOrder::isBigEndian() { return true; }

+inline bool ByteOrder::isBigEndian() {

+  return true;

+}

 #endif

 

 inline int ByteOrder::littleEndian24Bit(const void* const bytes) {

-  return (((int)static_cast<const int8*>(bytes)[2]) << 16) |

-         (((int)static_cast<const uint8*>(bytes)[1]) << 8) |

+  return (((int)static_cast<const int8*>(bytes)[2]) << 16) | (((int)static_cast<const uint8*>(bytes)[1]) << 8) |

          ((int)static_cast<const uint8*>(bytes)[0]);

 }

 inline int ByteOrder::bigEndian24Bit(const void* const bytes) {

-  return (((int)static_cast<const int8*>(bytes)[0]) << 16) |

-         (((int)static_cast<const uint8*>(bytes)[1]) << 8) |

+  return (((int)static_cast<const int8*>(bytes)[0]) << 16) | (((int)static_cast<const uint8*>(bytes)[1]) << 8) |

          ((int)static_cast<const uint8*>(bytes)[2]);

 }

-inline void ByteOrder::littleEndian24BitToChars(const int value,

-                                                void* const destBytes) {

+inline void ByteOrder::littleEndian24BitToChars(const int value, void* const destBytes) {

   static_cast<uint8*>(destBytes)[0] = (uint8)value;

   static_cast<uint8*>(destBytes)[1] = (uint8)(value >> 8);

   static_cast<uint8*>(destBytes)[2] = (uint8)(value >> 16);

 }

-inline void ByteOrder::bigEndian24BitToChars(const int value,

-                                             void* const destBytes) {

+inline void ByteOrder::bigEndian24BitToChars(const int value, void* const destBytes) {

   static_cast<uint8*>(destBytes)[0] = (uint8)(value >> 16);

   static_cast<uint8*>(destBytes)[1] = (uint8)(value >> 8);

   static_cast<uint8*>(destBytes)[2] = (uint8)value;

diff --git a/src/common/ClientRPCHook.cpp b/src/common/ClientRPCHook.cpp
old mode 100755
new mode 100644
index 54c21dd..cd216d1
--- a/src/common/ClientRPCHook.cpp
+++ b/src/common/ClientRPCHook.cpp
@@ -31,51 +31,42 @@
 const string SessionCredentials::SignatureMethod = "SignatureMethod";
 const string SessionCredentials::ONSChannelKey = "OnsChannel";
 
-void ClientRPCHook::doBeforeRequest(const string& remoteAddr,
-                                    RemotingCommand& request) {
+void ClientRPCHook::doBeforeRequest(const string& remoteAddr, RemotingCommand& request) {
   CommandHeader* header = request.getCommandHeader();
 
   map<string, string> requestMap;
   string totalMsg;
 
-  requestMap.insert(pair<string, string>(SessionCredentials::AccessKey,
-                                         sessionCredentials.getAccessKey()));
-  requestMap.insert(pair<string, string>(SessionCredentials::ONSChannelKey,
-                                         sessionCredentials.getAuthChannel()));
+  requestMap.insert(pair<string, string>(SessionCredentials::AccessKey, sessionCredentials.getAccessKey()));
+  requestMap.insert(pair<string, string>(SessionCredentials::ONSChannelKey, sessionCredentials.getAuthChannel()));
 
-  LOG_DEBUG("before insert declared filed,MAP SIZE is:" SIZET_FMT "",
-            requestMap.size());
+  LOG_DEBUG("before insert declared filed,MAP SIZE is:" SIZET_FMT "", requestMap.size());
   if (header != NULL) {
     header->SetDeclaredFieldOfCommandHeader(requestMap);
   }
-  LOG_DEBUG("after insert declared filed, MAP SIZE is:" SIZET_FMT "",
-            requestMap.size());
+  LOG_DEBUG("after insert declared filed, MAP SIZE is:" SIZET_FMT "", requestMap.size());
 
   map<string, string>::iterator it = requestMap.begin();
   for (; it != requestMap.end(); ++it) {
     totalMsg.append(it->second);
   }
   if (request.getMsgBody().length() > 0) {
-    LOG_DEBUG("msgBody is:%s, msgBody length is:" SIZET_FMT "",
-              request.getMsgBody().c_str(), request.getMsgBody().length());
+    LOG_DEBUG("msgBody is:%s, msgBody length is:" SIZET_FMT "", request.getMsgBody().c_str(),
+              request.getMsgBody().length());
 
     totalMsg.append(request.getMsgBody());
   }
-  LOG_DEBUG("total msg info are:%s, size is:" SIZET_FMT "", totalMsg.c_str(),
-            totalMsg.size());
+  LOG_DEBUG("total msg info are:%s, size is:" SIZET_FMT "", totalMsg.c_str(), totalMsg.size());
   char* pSignature =
-      rocketmqSignature::spas_sign(totalMsg.c_str(), totalMsg.size(),
-                                sessionCredentials.getSecretKey().c_str());
+      rocketmqSignature::spas_sign(totalMsg.c_str(), totalMsg.size(), sessionCredentials.getSecretKey().c_str());
   // char *pSignature = spas_sign(totalMsg.c_str(),
   // sessionCredentials.getSecretKey().c_str());
 
   if (pSignature != NULL) {
     string signature(static_cast<const char*>(pSignature));
     request.addExtField(SessionCredentials::Signature, signature);
-    request.addExtField(SessionCredentials::AccessKey,
-                        sessionCredentials.getAccessKey());
-    request.addExtField(SessionCredentials::ONSChannelKey,
-                        sessionCredentials.getAuthChannel());
+    request.addExtField(SessionCredentials::AccessKey, sessionCredentials.getAccessKey());
+    request.addExtField(SessionCredentials::ONSChannelKey, sessionCredentials.getAuthChannel());
     rocketmqSignature::spas_mem_free(pSignature);
   } else {
     LOG_ERROR("signature for request failed");
diff --git a/src/common/ClientRPCHook.h b/src/common/ClientRPCHook.h
old mode 100755
new mode 100644
index 853917d..72e2f76
--- a/src/common/ClientRPCHook.h
+++ b/src/common/ClientRPCHook.h
@@ -25,10 +25,8 @@
  public:
   RPCHook() {}
   virtual ~RPCHook() {}
-  virtual void doBeforeRequest(const string& remoteAddr,
-                               RemotingCommand& request) = 0;
-  virtual void doAfterResponse(RemotingCommand& request,
-                               RemotingCommand& response) = 0;
+  virtual void doBeforeRequest(const string& remoteAddr, RemotingCommand& request) = 0;
+  virtual void doAfterResponse(RemotingCommand& request, RemotingCommand& response) = 0;
 };
 
 class ClientRPCHook : public RPCHook {
@@ -36,15 +34,12 @@
   SessionCredentials sessionCredentials;
 
  public:
-  ClientRPCHook(const SessionCredentials& session_credentials)
-      : sessionCredentials(session_credentials) {}
+  ClientRPCHook(const SessionCredentials& session_credentials) : sessionCredentials(session_credentials) {}
   virtual ~ClientRPCHook() {}
 
-  virtual void doBeforeRequest(const string& remoteAddr,
-                               RemotingCommand& request);
+  virtual void doBeforeRequest(const string& remoteAddr, RemotingCommand& request);
 
-  virtual void doAfterResponse(RemotingCommand& request,
-                               RemotingCommand& response) {}
+  virtual void doAfterResponse(RemotingCommand& request, RemotingCommand& response) {}
 };
 }
 #endif
diff --git a/src/common/CommunicationMode.h b/src/common/CommunicationMode.h
old mode 100755
new mode 100644
index 9d9b283..6ba947a
--- a/src/common/CommunicationMode.h
+++ b/src/common/CommunicationMode.h
@@ -14,7 +14,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
- 
+
 #ifndef __COMMUNICATIONMODE_H__
 #define __COMMUNICATIONMODE_H__
 
diff --git a/src/common/FilterAPI.h b/src/common/FilterAPI.h
old mode 100755
new mode 100644
index c95f17e..d632bc2
--- a/src/common/FilterAPI.h
+++ b/src/common/FilterAPI.h
@@ -26,8 +26,7 @@
 //<!***************************************************************************
 class FilterAPI {
  public:
-  static SubscriptionData* buildSubscriptionData(const string topic,
-                                                 const string& subString) {
+  static SubscriptionData* buildSubscriptionData(const string topic, const string& subString) {
     //<!delete in balance;
     SubscriptionData* subscriptionData = new SubscriptionData(topic, subString);
 
@@ -38,8 +37,7 @@
       UtilAll::Split(out, subString, "||");
 
       if (out.empty()) {
-        THROW_MQEXCEPTION(MQClientException, "FilterAPI subString split error",
-                          -1);
+        THROW_MQEXCEPTION(MQClientException, "FilterAPI subString split error", -1);
       }
 
       for (size_t i = 0; i < out.size(); i++) {
diff --git a/src/common/InputStream.cpp b/src/common/InputStream.cpp
old mode 100755
new mode 100644
index cc5b1ab..f807d6b
--- a/src/common/InputStream.cpp
+++ b/src/common/InputStream.cpp
@@ -1,18 +1,18 @@
-/*
-* Licensed to the Apache Software Foundation (ASF) under one or more
-* contributor license agreements.  See the NOTICE file distributed with
-* this work for additional information regarding copyright ownership.
-* The ASF licenses this file to You under the Apache License, Version 2.0
-* (the "License"); you may not use this file except in compliance with
-* the License.  You may obtain a copy of the License at
-*
-*     http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+/*

+* Licensed to the Apache Software Foundation (ASF) under one or more

+* contributor license agreements.  See the NOTICE file distributed with

+* this work for additional information regarding copyright ownership.

+* The ASF licenses this file to You under the Apache License, Version 2.0

+* (the "License"); you may not use this file except in compliance with

+* the License.  You may obtain a copy of the License at

+*

+*     http://www.apache.org/licenses/LICENSE-2.0

+*

+* Unless required by applicable law or agreed to in writing, software

+* distributed under the License is distributed on an "AS IS" BASIS,

+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

+* See the License for the specific language governing permissions and

+* limitations under the License.

 */

 #include "InputStream.h"

 #include <algorithm>

@@ -23,7 +23,8 @@
 int64 InputStream::getNumBytesRemaining() {

   int64 len = getTotalLength();

 

-  if (len >= 0) len -= getPosition();

+  if (len >= 0)

+    len -= getPosition();

 

   return len;

 }

@@ -34,7 +35,9 @@
   return temp;

 }

 

-bool InputStream::readBool() { return readByte() != 0; }

+bool InputStream::readBool() {

+  return readByte() != 0;

+}

 

 short InputStream::readShortBigEndian() {

   char temp[2];

@@ -100,8 +103,7 @@
     char* temp = static_cast<char*>(std::malloc(skipBufferSize * sizeof(char)));

 

     while (numBytesToSkip > 0 && !isExhausted())

-      numBytesToSkip -=

-          read(temp, (int)std::min(numBytesToSkip, (int64)skipBufferSize));

+      numBytesToSkip -= read(temp, (int)std::min(numBytesToSkip, (int64)skipBufferSize));

 

     std::free(temp);

   }

diff --git a/src/common/InputStream.h b/src/common/InputStream.h
old mode 100755
new mode 100644
index d3916c4..8c6ddb5
--- a/src/common/InputStream.h
+++ b/src/common/InputStream.h
@@ -156,8 +156,7 @@
                                   will be read until the stream is exhausted.

       @returns the number of bytes that were added to the memory block

   */

-  virtual size_t readIntoMemoryBlock(MemoryBlock& destBlock,

-                                     size_t maxNumBytesToRead = -1);

+  virtual size_t readIntoMemoryBlock(MemoryBlock& destBlock, size_t maxNumBytesToRead = -1);

 

   //==============================================================================

   /** Returns the offset of the next byte that will be read from the stream.

diff --git a/src/common/MQClient.cpp b/src/common/MQClient.cpp
index 1529689..42d77a5 100644
--- a/src/common/MQClient.cpp
+++ b/src/common/MQClient.cpp
@@ -21,19 +21,19 @@
 #include "MQClientManager.h"
 #include "TopicPublishInfo.h"
 #include "UtilAll.h"
+#include "NameSpaceUtil.h"
 
 namespace rocketmq {
 
 #define ROCKETMQCPP_VERSION "1.0.1"
 #define BUILD_DATE "03-14-2018"
 // display version: strings bin/librocketmq.so |grep VERSION
-const char *rocketmq_build_time =
-    "VERSION: " ROCKETMQCPP_VERSION ", BUILD DATE: " BUILD_DATE " ";
+const char* rocketmq_build_time = "VERSION: " ROCKETMQCPP_VERSION ", BUILD DATE: " BUILD_DATE " ";
 
 //<!************************************************************************
 MQClient::MQClient() {
   string NAMESRV_ADDR_ENV = "NAMESRV_ADDR";
-  if (const char *addr = getenv(NAMESRV_ADDR_ENV.c_str()))
+  if (const char* addr = getenv(NAMESRV_ADDR_ENV.c_str()))
     m_namesrvAddr = addr;
   else
     m_namesrvAddr = "";
@@ -56,102 +56,110 @@
 }
 
 //<!groupName;
-const string &MQClient::getGroupName() const { return m_GroupName; }
+const string& MQClient::getGroupName() const {
+  return m_GroupName;
+}
 
-void MQClient::setGroupName(const string &groupname) {
+void MQClient::setGroupName(const string& groupname) {
   m_GroupName = groupname;
 }
 
-const string &MQClient::getNamesrvAddr() const { return m_namesrvAddr; }
-
-void MQClient::setNamesrvAddr(const string &namesrvAddr) {
-  m_namesrvAddr = namesrvAddr;
+const string& MQClient::getNamesrvAddr() const {
+  return m_namesrvAddr;
 }
 
-const string &MQClient::getNamesrvDomain() const { return m_namesrvDomain; }
+void MQClient::setNamesrvAddr(const string& namesrvAddr) {
+  m_namesrvAddr = NameSpaceUtil::formatNameServerURL(namesrvAddr);
+}
 
-void MQClient::setNamesrvDomain(const string &namesrvDomain) {
+const string& MQClient::getNamesrvDomain() const {
+  return m_namesrvDomain;
+}
+
+void MQClient::setNamesrvDomain(const string& namesrvDomain) {
   m_namesrvDomain = namesrvDomain;
 }
 
-const string &MQClient::getInstanceName() const { return m_instanceName; }
+const string& MQClient::getInstanceName() const {
+  return m_instanceName;
+}
 
-void MQClient::setInstanceName(const string &instanceName) {
+void MQClient::setInstanceName(const string& instanceName) {
   m_instanceName = instanceName;
 }
 
-void MQClient::createTopic(const string &key, const string &newTopic,
-                           int queueNum) {
+void MQClient::createTopic(const string& key, const string& newTopic, int queueNum) {
   try {
     getFactory()->createTopic(key, newTopic, queueNum, m_SessionCredentials);
-  } catch (MQException &e) {
+  } catch (MQException& e) {
     LOG_ERROR(e.what());
   }
 }
 
-int64 MQClient::earliestMsgStoreTime(const MQMessageQueue &mq) {
+int64 MQClient::earliestMsgStoreTime(const MQMessageQueue& mq) {
   return getFactory()->earliestMsgStoreTime(mq, m_SessionCredentials);
 }
 
-QueryResult MQClient::queryMessage(const string &topic, const string &key,
-                                   int maxNum, int64 begin, int64 end) {
-  return getFactory()->queryMessage(topic, key, maxNum, begin, end,
-                                    m_SessionCredentials);
+QueryResult MQClient::queryMessage(const string& topic, const string& key, int maxNum, int64 begin, int64 end) {
+  return getFactory()->queryMessage(topic, key, maxNum, begin, end, m_SessionCredentials);
 }
 
-int64 MQClient::minOffset(const MQMessageQueue &mq) {
+int64 MQClient::minOffset(const MQMessageQueue& mq) {
   return getFactory()->minOffset(mq, m_SessionCredentials);
 }
 
-int64 MQClient::maxOffset(const MQMessageQueue &mq) {
+int64 MQClient::maxOffset(const MQMessageQueue& mq) {
   return getFactory()->maxOffset(mq, m_SessionCredentials);
 }
 
-int64 MQClient::searchOffset(const MQMessageQueue &mq, uint64_t timestamp) {
+int64 MQClient::searchOffset(const MQMessageQueue& mq, uint64_t timestamp) {
   return getFactory()->searchOffset(mq, timestamp, m_SessionCredentials);
 }
 
-MQMessageExt *MQClient::viewMessage(const string &msgId) {
+MQMessageExt* MQClient::viewMessage(const string& msgId) {
   return getFactory()->viewMessage(msgId, m_SessionCredentials);
 }
 
-vector<MQMessageQueue> MQClient::getTopicMessageQueueInfo(const string &topic) {
+vector<MQMessageQueue> MQClient::getTopicMessageQueueInfo(const string& topic) {
   boost::weak_ptr<TopicPublishInfo> weak_topicPublishInfo(
       getFactory()->tryToFindTopicPublishInfo(topic, m_SessionCredentials));
-  boost::shared_ptr<TopicPublishInfo> topicPublishInfo(
-      weak_topicPublishInfo.lock());
+  boost::shared_ptr<TopicPublishInfo> topicPublishInfo(weak_topicPublishInfo.lock());
   if (topicPublishInfo) {
     return topicPublishInfo->getMessageQueueList();
   }
-  THROW_MQEXCEPTION(
-      MQClientException,
-      "could not find MessageQueue Info of topic: [" + topic + "].", -1);
+  THROW_MQEXCEPTION(MQClientException, "could not find MessageQueue Info of topic: [" + topic + "].", -1);
 }
 
 void MQClient::start() {
   if (getFactory() == NULL) {
     m_clientFactory = MQClientManager::getInstance()->getMQClientFactory(
-        getMQClientId(), m_pullThreadNum, m_tcpConnectTimeout,
-        m_tcpTransportTryLockTimeout, m_unitName);
+        getMQClientId(), m_pullThreadNum, m_tcpConnectTimeout, m_tcpTransportTryLockTimeout, m_unitName);
   }
   LOG_INFO(
       "MQClient "
       "start,groupname:%s,clientID:%s,instanceName:%s,nameserveraddr:%s",
-      getGroupName().c_str(), getMQClientId().c_str(),
-      getInstanceName().c_str(), getNamesrvAddr().c_str());
+      getGroupName().c_str(), getMQClientId().c_str(), getInstanceName().c_str(), getNamesrvAddr().c_str());
 }
 
-void MQClient::shutdown() { m_clientFactory = NULL; }
+void MQClient::shutdown() {
+  m_clientFactory = NULL;
+}
 
-MQClientFactory *MQClient::getFactory() const { return m_clientFactory; }
+MQClientFactory* MQClient::getFactory() const {
+  return m_clientFactory;
+}
 
-bool MQClient::isServiceStateOk() { return m_serviceState == RUNNING; }
+bool MQClient::isServiceStateOk() {
+  return m_serviceState == RUNNING;
+}
 
 void MQClient::setLogLevel(elogLevel inputLevel) {
   ALOG_ADAPTER->setLogLevel(inputLevel);
 }
 
-elogLevel MQClient::getLogLevel() { return ALOG_ADAPTER->getLogLevel(); }
+elogLevel MQClient::getLogLevel() {
+  return ALOG_ADAPTER->getLogLevel();
+}
 
 void MQClient::setLogFileSizeAndNum(int fileNum, long perFileSize) {
   ALOG_ADAPTER->setLogFileNumAndSize(fileNum, perFileSize);
@@ -184,18 +192,22 @@
   return m_tcpTransportTryLockTimeout;
 }
 
-void MQClient::setUnitName(string unitName) { m_unitName = unitName; }
-const string &MQClient::getUnitName() { return m_unitName; }
+void MQClient::setUnitName(string unitName) {
+  m_unitName = unitName;
+}
+const string& MQClient::getUnitName() {
+  return m_unitName;
+}
 
-void MQClient::setSessionCredentials(const string &input_accessKey,
-                                     const string &input_secretKey,
-                                     const string &input_onsChannel) {
+void MQClient::setSessionCredentials(const string& input_accessKey,
+                                     const string& input_secretKey,
+                                     const string& input_onsChannel) {
   m_SessionCredentials.setAccessKey(input_accessKey);
   m_SessionCredentials.setSecretKey(input_secretKey);
   m_SessionCredentials.setAuthChannel(input_onsChannel);
 }
 
-const SessionCredentials &MQClient::getSessionCredentials() const {
+const SessionCredentials& MQClient::getSessionCredentials() const {
   return m_SessionCredentials;
 }
 
diff --git a/src/common/MQClientErrorContainer.cpp b/src/common/MQClientErrorContainer.cpp
new file mode 100644
index 0000000..45f4b41
--- /dev/null
+++ b/src/common/MQClientErrorContainer.cpp
@@ -0,0 +1,44 @@
+#pragma once
+/*
+* Licensed to the Apache Software Foundation (ASF) under one or more
+* contributor license agreements.  See the NOTICE file distributed with
+* this work for additional information regarding copyright ownership.
+* The ASF licenses this file to You under the Apache License, Version 2.0
+* (the "License"); you may not use this file except in compliance with
+* the License.  You may obtain a copy of the License at
+*
+*     http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+ 
+#include "MQClientErrorContainer.h"
+
+
+
+
+namespace rocketmq {
+	MQClientErrorContainer * MQClientErrorContainer::s_instance = nullptr;
+
+	MQClientErrorContainer * MQClientErrorContainer::instance() {
+		if (!s_instance)
+			s_instance = new MQClientErrorContainer();
+		return s_instance;
+	}
+
+	void MQClientErrorContainer::setErr(std::string str) {
+		boost::lock_guard<boost::mutex> lock(this->mutex);
+		this->m_err = str;
+	}
+
+	std::string MQClientErrorContainer::getErr() {
+		boost::lock_guard<boost::mutex> lock(this->mutex);
+		return this->m_err;
+	}
+}
+ 
diff --git a/src/common/MQClientErrorContainer.h b/src/common/MQClientErrorContainer.h
new file mode 100644
index 0000000..377859f
--- /dev/null
+++ b/src/common/MQClientErrorContainer.h
@@ -0,0 +1,43 @@
+#pragma once
+/*
+* Licensed to the Apache Software Foundation (ASF) under one or more
+* contributor license agreements.  See the NOTICE file distributed with
+* this work for additional information regarding copyright ownership.
+* The ASF licenses this file to You under the Apache License, Version 2.0
+* (the "License"); you may not use this file except in compliance with
+* the License.  You may obtain a copy of the License at
+*
+*     http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#ifndef MQCLIENTERRORCONTAINER_H_INCLUDE
+#define MQCLIENTERRORCONTAINER_H_INCLUDE
+#include <string>
+#include <exception>
+#include <boost/thread/mutex.hpp>
+#include <boost/thread/lock_guard.hpp>
+
+namespace rocketmq {
+	class  MQClientErrorContainer {
+
+	public:
+		static MQClientErrorContainer * instance();
+
+		void setErr(std::string str);
+
+		std::string getErr();
+
+	private:
+		std::string m_err;
+		static MQClientErrorContainer * s_instance;
+		boost::mutex mutex;
+	};
+}
+
+#endif
diff --git a/src/common/MQVersion.cpp b/src/common/MQVersion.cpp
old mode 100755
new mode 100644
diff --git a/src/common/MQVersion.h b/src/common/MQVersion.h
old mode 100755
new mode 100644
diff --git a/src/common/MemoryInputStream.cpp b/src/common/MemoryInputStream.cpp
old mode 100755
new mode 100644
index c3585bb..3d65992
--- a/src/common/MemoryInputStream.cpp
+++ b/src/common/MemoryInputStream.cpp
@@ -1,18 +1,18 @@
-/*
-* Licensed to the Apache Software Foundation (ASF) under one or more
-* contributor license agreements.  See the NOTICE file distributed with
-* this work for additional information regarding copyright ownership.
-* The ASF licenses this file to You under the Apache License, Version 2.0
-* (the "License"); you may not use this file except in compliance with
-* the License.  You may obtain a copy of the License at
-*
-*     http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+/*

+* Licensed to the Apache Software Foundation (ASF) under one or more

+* contributor license agreements.  See the NOTICE file distributed with

+* this work for additional information regarding copyright ownership.

+* The ASF licenses this file to You under the Apache License, Version 2.0

+* (the "License"); you may not use this file except in compliance with

+* the License.  You may obtain a copy of the License at

+*

+*     http://www.apache.org/licenses/LICENSE-2.0

+*

+* Unless required by applicable law or agreed to in writing, software

+* distributed under the License is distributed on an "AS IS" BASIS,

+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

+* See the License for the specific language governing permissions and

+* limitations under the License.

 */

 #include "MemoryInputStream.h"

 

@@ -20,20 +20,15 @@
 MemoryInputStream::MemoryInputStream(const void* const sourceData,

                                      const size_t sourceDataSize,

                                      const bool keepInternalCopy)

-    : data(sourceData),

-      dataSize(sourceDataSize),

-      position(0),

-      internalCopy(NULL) {

-  if (keepInternalCopy) createInternalCopy();

+    : data(sourceData), dataSize(sourceDataSize), position(0), internalCopy(NULL) {

+  if (keepInternalCopy)

+    createInternalCopy();

 }

 

-MemoryInputStream::MemoryInputStream(const MemoryBlock& sourceData,

-                                     const bool keepInternalCopy)

-    : data(sourceData.getData()),

-      dataSize(sourceData.getSize()),

-      position(0),

-      internalCopy(NULL) {

-  if (keepInternalCopy) createInternalCopy();

+MemoryInputStream::MemoryInputStream(const MemoryBlock& sourceData, const bool keepInternalCopy)

+    : data(sourceData.getData()), dataSize(sourceData.getSize()), position(0), internalCopy(NULL) {

+  if (keepInternalCopy)

+    createInternalCopy();

 }

 

 void MemoryInputStream::createInternalCopy() {

@@ -43,20 +38,27 @@
   data = internalCopy;

 }

 

-MemoryInputStream::~MemoryInputStream() { std::free(internalCopy); }

+MemoryInputStream::~MemoryInputStream() {

+  std::free(internalCopy);

+}

 

-int64 MemoryInputStream::getTotalLength() { return (int64)dataSize; }

+int64 MemoryInputStream::getTotalLength() {

+  return (int64)dataSize;

+}

 

 int MemoryInputStream::read(void* const buffer, const int howMany) {

   const int num = std::min(howMany, (int)(dataSize - position));

-  if (num <= 0) return 0;

+  if (num <= 0)

+    return 0;

 

   memcpy((char*)buffer, (char*)data + position, (size_t)num);

   position += (unsigned int)num;

   return num;

 }

 

-bool MemoryInputStream::isExhausted() { return position >= dataSize; }

+bool MemoryInputStream::isExhausted() {

+  return position >= dataSize;

+}

 

 bool MemoryInputStream::setPosition(const int64 pos) {

   if (pos < 0)

@@ -67,5 +69,7 @@
   return true;

 }

 

-int64 MemoryInputStream::getPosition() { return (int64)position; }

+int64 MemoryInputStream::getPosition() {

+  return (int64)position;

+}

 }

diff --git a/src/common/MemoryInputStream.h b/src/common/MemoryInputStream.h
old mode 100755
new mode 100644
index f76cadc..53584b9
--- a/src/common/MemoryInputStream.h
+++ b/src/common/MemoryInputStream.h
@@ -1,19 +1,19 @@
-/*
-* Licensed to the Apache Software Foundation (ASF) under one or more
-* contributor license agreements.  See the NOTICE file distributed with
-* this work for additional information regarding copyright ownership.
-* The ASF licenses this file to You under the Apache License, Version 2.0
-* (the "License"); you may not use this file except in compliance with
-* the License.  You may obtain a copy of the License at
-*
-*     http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
+/*

+* Licensed to the Apache Software Foundation (ASF) under one or more

+* contributor license agreements.  See the NOTICE file distributed with

+* this work for additional information regarding copyright ownership.

+* The ASF licenses this file to You under the Apache License, Version 2.0

+* (the "License"); you may not use this file except in compliance with

+* the License.  You may obtain a copy of the License at

+*

+*     http://www.apache.org/licenses/LICENSE-2.0

+*

+* Unless required by applicable law or agreed to in writing, software

+* distributed under the License is distributed on an "AS IS" BASIS,

+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

+* See the License for the specific language governing permissions and

+* limitations under the License.

+*/

 

 #ifndef MEMORYINPUTSTREAM_H_INCLUDED

 #define MEMORYINPUTSTREAM_H_INCLUDED

@@ -48,8 +48,7 @@
      the

                                       data and use that.

   */

-  MemoryInputStream(const void* sourceData, size_t sourceDataSize,

-                    bool keepInternalCopyOfData);

+  MemoryInputStream(const void* sourceData, size_t sourceDataSize, bool keepInternalCopyOfData);

 

   /** Creates a MemoryInputStream.

 

diff --git a/src/common/MemoryOutputStream.cpp b/src/common/MemoryOutputStream.cpp
old mode 100755
new mode 100644
index ce74d8e..9578c8a
--- a/src/common/MemoryOutputStream.cpp
+++ b/src/common/MemoryOutputStream.cpp
@@ -1,52 +1,43 @@
-/*
-* Licensed to the Apache Software Foundation (ASF) under one or more
-* contributor license agreements.  See the NOTICE file distributed with
-* this work for additional information regarding copyright ownership.
-* The ASF licenses this file to You under the Apache License, Version 2.0
-* (the "License"); you may not use this file except in compliance with
-* the License.  You may obtain a copy of the License at
-*
-*     http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+/*

+* Licensed to the Apache Software Foundation (ASF) under one or more

+* contributor license agreements.  See the NOTICE file distributed with

+* this work for additional information regarding copyright ownership.

+* The ASF licenses this file to You under the Apache License, Version 2.0

+* (the "License"); you may not use this file except in compliance with

+* the License.  You may obtain a copy of the License at

+*

+*     http://www.apache.org/licenses/LICENSE-2.0

+*

+* Unless required by applicable law or agreed to in writing, software

+* distributed under the License is distributed on an "AS IS" BASIS,

+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

+* See the License for the specific language governing permissions and

+* limitations under the License.

 */

 #include "MemoryOutputStream.h"

 

 namespace rocketmq {

 MemoryOutputStream::MemoryOutputStream(const size_t initialSize)

-    : blockToUse(&internalBlock),

-      externalData(NULL),

-      position(0),

-      size(0),

-      availableSize(0) {

+    : blockToUse(&internalBlock), externalData(NULL), position(0), size(0), availableSize(0) {

   internalBlock.setSize(initialSize, false);

 }

 

-MemoryOutputStream::MemoryOutputStream(MemoryBlock& memoryBlockToWriteTo,

-                                       const bool appendToExistingBlockContent)

-    : blockToUse(&memoryBlockToWriteTo),

-      externalData(NULL),

-      position(0),

-      size(0),

-      availableSize(0) {

+MemoryOutputStream::MemoryOutputStream(MemoryBlock& memoryBlockToWriteTo, const bool appendToExistingBlockContent)

+    : blockToUse(&memoryBlockToWriteTo), externalData(NULL), position(0), size(0), availableSize(0) {

   if (appendToExistingBlockContent)

     position = size = memoryBlockToWriteTo.getSize();

 }

 

 MemoryOutputStream::MemoryOutputStream(void* destBuffer, size_t destBufferSize)

-    : blockToUse(NULL),

-      externalData(destBuffer),

-      position(0),

-      size(0),

-      availableSize(destBufferSize) {}

+    : blockToUse(NULL), externalData(destBuffer), position(0), size(0), availableSize(destBufferSize) {}

 

-MemoryOutputStream::~MemoryOutputStream() { trimExternalBlockSize(); }

+MemoryOutputStream::~MemoryOutputStream() {

+  trimExternalBlockSize();

+}

 

-void MemoryOutputStream::flush() { trimExternalBlockSize(); }

+void MemoryOutputStream::flush() {

+  trimExternalBlockSize();

+}

 

 void MemoryOutputStream::trimExternalBlockSize() {

   if (blockToUse != &internalBlock && blockToUse != NULL)

@@ -54,7 +45,8 @@
 }

 

 void MemoryOutputStream::preallocate(const size_t bytesToPreallocate) {

-  if (blockToUse != NULL) blockToUse->ensureSize(bytesToPreallocate + 1);

+  if (blockToUse != NULL)

+    blockToUse->ensureSize(bytesToPreallocate + 1);

 }

 

 void MemoryOutputStream::reset() {

@@ -69,14 +61,12 @@
 

   if (blockToUse != NULL) {

     if (storageNeeded >= (unsigned int)(blockToUse->getSize()))

-      blockToUse->ensureSize(

-          (storageNeeded + std::min(storageNeeded / 2, (size_t)(1024 * 1024)) +

-           32) &

-          ~31u);

+      blockToUse->ensureSize((storageNeeded + std::min(storageNeeded / 2, (size_t)(1024 * 1024)) + 32) & ~31u);

 

     data = static_cast<char*>(blockToUse->getData());

   } else {

-    if (storageNeeded > availableSize) return NULL;

+    if (storageNeeded > availableSize)

+      return NULL;

 

     data = static_cast<char*>(externalData);

   }

@@ -88,7 +78,8 @@
 }

 

 bool MemoryOutputStream::write(const void* const buffer, size_t howMany) {

-  if (howMany == 0) return true;

+  if (howMany == 0)

+    return true;

 

   if (char* dest = prepareToWrite(howMany)) {

     memcpy(dest, buffer, howMany);

@@ -99,7 +90,8 @@
 }

 

 bool MemoryOutputStream::writeRepeatedByte(uint8 byte, size_t howMany) {

-  if (howMany == 0) return true;

+  if (howMany == 0)

+    return true;

 

   if (char* dest = prepareToWrite(howMany)) {

     memset(dest, byte, howMany);

@@ -114,7 +106,8 @@
 }

 

 const void* MemoryOutputStream::getData() const {

-  if (blockToUse == NULL) return externalData;

+  if (blockToUse == NULL)

+    return externalData;

 

   if ((unsigned int)blockToUse->getSize() > size)

     static_cast<char*>(blockToUse->getData())[size] = 0;

@@ -136,8 +129,7 @@
   return false;

 }

 

-int64 MemoryOutputStream::writeFromInputStream(InputStream& source,

-                                               int64 maxNumBytesToWrite) {

+int64 MemoryOutputStream::writeFromInputStream(InputStream& source, int64 maxNumBytesToWrite) {

   // before writing from an input, see if we can preallocate to make it more

   // efficient..

   int64 availableData = source.getTotalLength() - source.getPosition();

@@ -153,11 +145,11 @@
   return OutputStream::writeFromInputStream(source, maxNumBytesToWrite);

 }

 

-OutputStream& operator<<(OutputStream& stream,

-                         const MemoryOutputStream& streamToRead) {

+OutputStream& operator<<(OutputStream& stream, const MemoryOutputStream& streamToRead) {

   const size_t dataSize = streamToRead.getDataSize();

 

-  if (dataSize > 0) stream.write(streamToRead.getData(), dataSize);

+  if (dataSize > 0)

+    stream.write(streamToRead.getData(), dataSize);

 

   return stream;

 }

diff --git a/src/common/MemoryOutputStream.h b/src/common/MemoryOutputStream.h
old mode 100755
new mode 100644
index 6d9098f..4b39879
--- a/src/common/MemoryOutputStream.h
+++ b/src/common/MemoryOutputStream.h
@@ -1,19 +1,19 @@
-/*
-* Licensed to the Apache Software Foundation (ASF) under one or more
-* contributor license agreements.  See the NOTICE file distributed with
-* this work for additional information regarding copyright ownership.
-* The ASF licenses this file to You under the Apache License, Version 2.0
-* (the "License"); you may not use this file except in compliance with
-* the License.  You may obtain a copy of the License at
-*
-*     http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
+/*

+* Licensed to the Apache Software Foundation (ASF) under one or more

+* contributor license agreements.  See the NOTICE file distributed with

+* this work for additional information regarding copyright ownership.

+* The ASF licenses this file to You under the Apache License, Version 2.0

+* (the "License"); you may not use this file except in compliance with

+* the License.  You may obtain a copy of the License at

+*

+*     http://www.apache.org/licenses/LICENSE-2.0

+*

+* Unless required by applicable law or agreed to in writing, software

+* distributed under the License is distributed on an "AS IS" BASIS,

+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

+* See the License for the specific language governing permissions and

+* limitations under the License.

+*/

 

 #ifndef MEMORYOUTPUTSTREAM_H_INCLUDED

 #define MEMORYOUTPUTSTREAM_H_INCLUDED

@@ -57,8 +57,7 @@
                                               the block will be cleared before

      use

   */

-  MemoryOutputStream(MemoryBlock& memoryBlockToWriteTo,

-                     bool appendToExistingBlockContent);

+  MemoryOutputStream(MemoryBlock& memoryBlockToWriteTo, bool appendToExistingBlockContent);

 

   /** Creates a MemoryOutputStream that will write into a user-supplied,

      fixed-size

@@ -126,7 +125,6 @@
 

 /** Copies all the data that has been written to a MemoryOutputStream into

  * another stream. */

-OutputStream& operator<<(OutputStream& stream,

-                         const MemoryOutputStream& streamToRead);

+OutputStream& operator<<(OutputStream& stream, const MemoryOutputStream& streamToRead);

 }

 #endif  // MEMORYOUTPUTSTREAM_H_INCLUDED

diff --git a/src/common/MessageSysFlag.cpp b/src/common/MessageSysFlag.cpp
old mode 100755
new mode 100644
diff --git a/src/common/MessageSysFlag.h b/src/common/MessageSysFlag.h
old mode 100755
new mode 100644
diff --git a/src/common/NameSpaceUtil.cpp b/src/common/NameSpaceUtil.cpp
new file mode 100644
index 0000000..ff44a00
--- /dev/null
+++ b/src/common/NameSpaceUtil.cpp
@@ -0,0 +1,39 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "NameSpaceUtil.h"
+#include "Logging.h"
+
+namespace rocketmq {
+
+bool NameSpaceUtil::isEndPointURL(string nameServerAddr) {
+  if (nameServerAddr.length() >= ENDPOINT_PREFIX_LENGTH && nameServerAddr.find(ENDPOINT_PREFIX) != string::npos) {
+    return true;
+  }
+  return false;
+}
+
+string NameSpaceUtil::formatNameServerURL(string nameServerAddr) {
+  auto index = nameServerAddr.find(ENDPOINT_PREFIX);
+  if (index != string::npos) {
+    LOG_DEBUG("Get Name Server from endpoint [%s]",
+              nameServerAddr.substr(ENDPOINT_PREFIX_LENGTH, nameServerAddr.length() - ENDPOINT_PREFIX_LENGTH).c_str());
+    return nameServerAddr.substr(ENDPOINT_PREFIX_LENGTH, nameServerAddr.length() - ENDPOINT_PREFIX_LENGTH);
+  }
+  return nameServerAddr;
+}
+}  // namespace rocketmq
diff --git a/src/common/NameSpaceUtil.h b/src/common/NameSpaceUtil.h
new file mode 100644
index 0000000..1d4afcf
--- /dev/null
+++ b/src/common/NameSpaceUtil.h
@@ -0,0 +1,36 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __NAMESPACEUTIL_H__
+#define __NAMESPACEUTIL_H__
+
+#include <string>
+
+using namespace std;
+
+static const string ENDPOINT_PREFIX = "http://";
+static const unsigned int ENDPOINT_PREFIX_LENGTH = ENDPOINT_PREFIX.length();
+namespace rocketmq {
+class NameSpaceUtil {
+ public:
+  static bool isEndPointURL(string nameServerAddr);
+
+  static string formatNameServerURL(string nameServerAddr);
+};
+
+}  // namespace rocketmq
+#endif  //__NAMESPACEUTIL_H__
diff --git a/src/common/NamesrvConfig.h b/src/common/NamesrvConfig.h
old mode 100755
new mode 100644
index 4bf8eb1..30bbb0e
--- a/src/common/NamesrvConfig.h
+++ b/src/common/NamesrvConfig.h
@@ -24,29 +24,29 @@
 namespace rocketmq {
 //<!***************************************************************************
 class NamesrvConfig {
-   public:
-    NamesrvConfig() {
-        m_kvConfigPath = "";
+ public:
+  NamesrvConfig() {
+    m_kvConfigPath = "";
 
-        char *home = getenv(rocketmq::ROCKETMQ_HOME_ENV.c_str());
-        if (home) {
-            m_rocketmqHome = home;
-        } else {
-            m_rocketmqHome = "";
-        }
+    char* home = getenv(rocketmq::ROCKETMQ_HOME_ENV.c_str());
+    if (home) {
+      m_rocketmqHome = home;
+    } else {
+      m_rocketmqHome = "";
     }
+  }
 
-    const string &getRocketmqHome() const { return m_rocketmqHome; }
+  const string& getRocketmqHome() const { return m_rocketmqHome; }
 
-    void setRocketmqHome(const string &rocketmqHome) { m_rocketmqHome = rocketmqHome; }
+  void setRocketmqHome(const string& rocketmqHome) { m_rocketmqHome = rocketmqHome; }
 
-    const string &getKvConfigPath() const { return m_kvConfigPath; }
+  const string& getKvConfigPath() const { return m_kvConfigPath; }
 
-    void setKvConfigPath(const string &kvConfigPath) { m_kvConfigPath = kvConfigPath; }
+  void setKvConfigPath(const string& kvConfigPath) { m_kvConfigPath = kvConfigPath; }
 
-   private:
-    string m_rocketmqHome;
-    string m_kvConfigPath;
+ private:
+  string m_rocketmqHome;
+  string m_kvConfigPath;
 };
 
 //<!***************************************************************************
diff --git a/src/common/OutputStream.cpp b/src/common/OutputStream.cpp
old mode 100755
new mode 100644
index 831e57d..2a056d3
--- a/src/common/OutputStream.cpp
+++ b/src/common/OutputStream.cpp
@@ -1,18 +1,18 @@
-/*
-* Licensed to the Apache Software Foundation (ASF) under one or more
-* contributor license agreements.  See the NOTICE file distributed with
-* this work for additional information regarding copyright ownership.
-* The ASF licenses this file to You under the Apache License, Version 2.0
-* (the "License"); you may not use this file except in compliance with
-* the License.  You may obtain a copy of the License at
-*
-*     http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+/*

+* Licensed to the Apache Software Foundation (ASF) under one or more

+* contributor license agreements.  See the NOTICE file distributed with

+* this work for additional information regarding copyright ownership.

+* The ASF licenses this file to You under the Apache License, Version 2.0

+* (the "License"); you may not use this file except in compliance with

+* the License.  You may obtain a copy of the License at

+*

+*     http://www.apache.org/licenses/LICENSE-2.0

+*

+* Unless required by applicable law or agreed to in writing, software

+* distributed under the License is distributed on an "AS IS" BASIS,

+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

+* See the License for the specific language governing permissions and

+* limitations under the License.

 */

 #include "OutputStream.h"

 #include <limits>

@@ -29,11 +29,14 @@
   return writeByte(b ? (char)1 : (char)0);

 }

 

-bool OutputStream::writeByte(char byte) { return write(&byte, 1); }

+bool OutputStream::writeByte(char byte) {

+  return write(&byte, 1);

+}

 

 bool OutputStream::writeRepeatedByte(uint8 byte, size_t numTimesToRepeat) {

   for (size_t i = 0; i < numTimesToRepeat; ++i)

-    if (!writeByte((char)byte)) return false;

+    if (!writeByte((char)byte))

+      return false;

 

   return true;

 }

@@ -77,18 +80,18 @@
   return writeInt64BigEndian(n.asInt);

 }

 

-int64 OutputStream::writeFromInputStream(InputStream& source,

-                                         int64 numBytesToWrite) {

-  if (numBytesToWrite < 0) numBytesToWrite = std::numeric_limits<int64>::max();

+int64 OutputStream::writeFromInputStream(InputStream& source, int64 numBytesToWrite) {

+  if (numBytesToWrite < 0)

+    numBytesToWrite = std::numeric_limits<int64>::max();

 

   int64 numWritten = 0;

 

   while (numBytesToWrite > 0) {

     char buffer[8192];

-    const int num = source.read(

-        buffer, (int)std::min(numBytesToWrite, (int64)sizeof(buffer)));

+    const int num = source.read(buffer, (int)std::min(numBytesToWrite, (int64)sizeof(buffer)));

 

-    if (num <= 0) break;

+    if (num <= 0)

+      break;

 

     write(buffer, (size_t)num);

 

diff --git a/src/common/OutputStream.h b/src/common/OutputStream.h
old mode 100755
new mode 100644
index 30ca334..3792169
--- a/src/common/OutputStream.h
+++ b/src/common/OutputStream.h
@@ -141,8 +141,7 @@
                                   is exhausted)

       @returns the number of bytes written

   */

-  virtual int64 writeFromInputStream(InputStream& source,

-                                     int64 maxNumBytesToWrite);

+  virtual int64 writeFromInputStream(InputStream& source, int64 maxNumBytesToWrite);

 };

 }

 

diff --git a/src/common/PermName.cpp b/src/common/PermName.cpp
old mode 100755
new mode 100644
index 7f168a4..bd36bfc
--- a/src/common/PermName.cpp
+++ b/src/common/PermName.cpp
@@ -24,7 +24,9 @@
 int PermName::PERM_WRITE = 0x1 << 1;
 int PermName::PERM_INHERIT = 0x1 << 0;
 
-bool PermName::isReadable(int perm) { return (perm & PERM_READ) == PERM_READ; }
+bool PermName::isReadable(int perm) {
+  return (perm & PERM_READ) == PERM_READ;
+}
 
 bool PermName::isWriteable(int perm) {
   return (perm & PERM_WRITE) == PERM_WRITE;
diff --git a/src/common/PermName.h b/src/common/PermName.h
old mode 100755
new mode 100644
diff --git a/src/common/PullSysFlag.cpp b/src/common/PullSysFlag.cpp
old mode 100755
new mode 100644
index 6d68457..a4af97a
--- a/src/common/PullSysFlag.cpp
+++ b/src/common/PullSysFlag.cpp
@@ -23,8 +23,7 @@
 int PullSysFlag::FLAG_SUBSCRIPTION = 0x1 << 2;
 int PullSysFlag::FLAG_CLASS_FILTER = 0x1 << 3;
 
-int PullSysFlag::buildSysFlag(bool commitOffset, bool suspend,
-                              bool subscription, bool classFilter) {
+int PullSysFlag::buildSysFlag(bool commitOffset, bool suspend, bool subscription, bool classFilter) {
   int flag = 0;
 
   if (commitOffset) {
diff --git a/src/common/PullSysFlag.h b/src/common/PullSysFlag.h
old mode 100755
new mode 100644
index c809772..37fcd89
--- a/src/common/PullSysFlag.h
+++ b/src/common/PullSysFlag.h
@@ -20,8 +20,7 @@
 //<!************************************************************************
 class PullSysFlag {
  public:
-  static int buildSysFlag(bool commitOffset, bool suspend, bool subscription,
-                          bool classFilter);
+  static int buildSysFlag(bool commitOffset, bool suspend, bool subscription, bool classFilter);
 
   static int clearCommitOffsetFlag(int sysFlag);
   static bool hasCommitOffsetFlag(int sysFlag);
diff --git a/src/common/ServiceState.h b/src/common/ServiceState.h
old mode 100755
new mode 100644
diff --git a/src/common/SubscriptionGroupConfig.h b/src/common/SubscriptionGroupConfig.h
old mode 100755
new mode 100644
diff --git a/src/common/TopAddressing.cpp b/src/common/TopAddressing.cpp
index 2a031a9..41f7b72 100644
--- a/src/common/TopAddressing.cpp
+++ b/src/common/TopAddressing.cpp
@@ -26,10 +26,12 @@
 TopAddressing::~TopAddressing() {}
 
 int TopAddressing::IsIPAddr(const char* sValue) {
-  if (NULL == sValue) return -1;
+  if (NULL == sValue)
+    return -1;
 
   while (*sValue != '\0') {
-    if ((*sValue < '0' || *sValue > '9') && (*sValue != '.')) return -1;
+    if ((*sValue < '0' || *sValue > '9') && (*sValue != '.'))
+      return -1;
     sValue++;
   }
   return 0;
@@ -39,7 +41,8 @@
   boost::lock_guard<boost::mutex> lock(m_addrLock);
   vector<string> out;
   UtilAll::Split(out, adds, ";");
-  if (out.size() > 0) m_addrs.clear();
+  if (out.size() > 0)
+    m_addrs.clear();
   for (size_t i = 0; i < out.size(); i++) {
     string addr = out[i];
     UtilAll::Trim(addr);
@@ -67,9 +70,8 @@
   std::string tmp_nameservers;
   std::string nameservers;
   Url url_s(nsAddr);
-  LOG_INFO("fetchNSAddr protocol: %s, port: %s, host:%s, path:%s, ",
-           url_s.protocol_.c_str(), url_s.port_.c_str(), url_s.host_.c_str(),
-           url_s.path_.c_str());
+  LOG_INFO("fetchNSAddr protocol: %s, port: %s, host:%s, path:%s, ", url_s.protocol_.c_str(), url_s.port_.c_str(),
+           url_s.host_.c_str(), url_s.path_.c_str());
 
   bool ret = SyncfetchNsAddr(url_s, tmp_nameservers);
   if (ret) {
@@ -80,8 +82,7 @@
       updateNameServerAddressList(nameservers);
     }
   } else {
-    LOG_ERROR(
-        "fetchNSAddr with domain failed, connect failure or wrong response");
+    LOG_ERROR("fetchNSAddr with domain failed, connect failure or wrong response");
   }
 
   return nameservers;
diff --git a/src/common/TopAddressing.h b/src/common/TopAddressing.h
old mode 100755
new mode 100644
diff --git a/src/common/TopicConfig.cpp b/src/common/TopicConfig.cpp
old mode 100755
new mode 100644
index e0e1b4d..9f01199
--- a/src/common/TopicConfig.cpp
+++ b/src/common/TopicConfig.cpp
@@ -39,8 +39,7 @@
       m_perm(PermName::PERM_READ | PermName::PERM_WRITE),
       m_topicFilterType(SINGLE_TAG) {}
 
-TopicConfig::TopicConfig(const string& topicName, int readQueueNums,
-                         int writeQueueNums, int perm)
+TopicConfig::TopicConfig(const string& topicName, int readQueueNums, int writeQueueNums, int perm)
     : m_topicName(topicName),
       m_readQueueNums(readQueueNums),
       m_writeQueueNums(writeQueueNums),
@@ -51,8 +50,7 @@
 
 string TopicConfig::encode() {
   stringstream ss;
-  ss << m_topicName << SEPARATOR << m_readQueueNums << SEPARATOR
-     << m_writeQueueNums << SEPARATOR << m_perm << SEPARATOR
+  ss << m_topicName << SEPARATOR << m_readQueueNums << SEPARATOR << m_writeQueueNums << SEPARATOR << m_perm << SEPARATOR
      << m_topicFilterType;
 
   return ss.str();
@@ -73,29 +71,41 @@
   return true;
 }
 
-const string& TopicConfig::getTopicName() { return m_topicName; }
+const string& TopicConfig::getTopicName() {
+  return m_topicName;
+}
 
 void TopicConfig::setTopicName(const string& topicName) {
   m_topicName = topicName;
 }
 
-int TopicConfig::getReadQueueNums() { return m_readQueueNums; }
+int TopicConfig::getReadQueueNums() {
+  return m_readQueueNums;
+}
 
 void TopicConfig::setReadQueueNums(int readQueueNums) {
   m_readQueueNums = readQueueNums;
 }
 
-int TopicConfig::getWriteQueueNums() { return m_writeQueueNums; }
+int TopicConfig::getWriteQueueNums() {
+  return m_writeQueueNums;
+}
 
 void TopicConfig::setWriteQueueNums(int writeQueueNums) {
   m_writeQueueNums = writeQueueNums;
 }
 
-int TopicConfig::getPerm() { return m_perm; }
+int TopicConfig::getPerm() {
+  return m_perm;
+}
 
-void TopicConfig::setPerm(int perm) { m_perm = perm; }
+void TopicConfig::setPerm(int perm) {
+  m_perm = perm;
+}
 
-TopicFilterType TopicConfig::getTopicFilterType() { return m_topicFilterType; }
+TopicFilterType TopicConfig::getTopicFilterType() {
+  return m_topicFilterType;
+}
 
 void TopicConfig::setTopicFilterType(TopicFilterType topicFilterType) {
   m_topicFilterType = topicFilterType;
diff --git a/src/common/TopicConfig.h b/src/common/TopicConfig.h
old mode 100755
new mode 100644
index 0e7c17a..32178c9
--- a/src/common/TopicConfig.h
+++ b/src/common/TopicConfig.h
@@ -26,8 +26,7 @@
  public:
   TopicConfig();
   TopicConfig(const string& topicName);
-  TopicConfig(const string& topicName, int readQueueNums, int writeQueueNums,
-              int perm);
+  TopicConfig(const string& topicName, int readQueueNums, int writeQueueNums, int perm);
   ~TopicConfig();
 
   string encode();
diff --git a/src/common/TopicFilterType.h b/src/common/TopicFilterType.h
old mode 100755
new mode 100644
diff --git a/src/common/UtilAll.cpp b/src/common/UtilAll.cpp
index 9f9126b..df3ec0b 100644
--- a/src/common/UtilAll.cpp
+++ b/src/common/UtilAll.cpp
@@ -23,20 +23,20 @@
 std::string UtilAll::s_localHostName;
 std::string UtilAll::s_localIpAddress;
 
-bool UtilAll::startsWith_retry(const string &topic) {
+bool UtilAll::startsWith_retry(const string& topic) {
   return topic.find(RETRY_GROUP_TOPIC_PREFIX) == 0;
 }
 
-string UtilAll::getRetryTopic(const string &consumerGroup) {
+string UtilAll::getRetryTopic(const string& consumerGroup) {
   return RETRY_GROUP_TOPIC_PREFIX + consumerGroup;
 }
 
-void UtilAll::Trim(string &str) {
+void UtilAll::Trim(string& str) {
   str.erase(0, str.find_first_not_of(' '));  // prefixing spaces
   str.erase(str.find_last_not_of(' ') + 1);  // surfixing spaces
 }
 
-bool UtilAll::isBlank(const string &str) {
+bool UtilAll::isBlank(const string& str) {
   if (str.empty()) {
     return true;
   }
@@ -51,27 +51,19 @@
 }
 
 const int hex2int[256] = {
-    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-     0,  1,  2,  3,  4,  5,  6,  7,  8,  9, -1, -1, -1, -1, -1, -1,
-    -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-    -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
-};
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0,  1,  2,  3,  4,  5,  6,  7,  8,  9,
+    -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
 
-uint64 UtilAll::hexstr2ull(const char *str) {
+uint64 UtilAll::hexstr2ull(const char* str) {
   uint64 num = 0;
-  unsigned char *ch = (unsigned char *) str;
+  unsigned char* ch = (unsigned char*)str;
   while (*ch != '\0') {
     num = (num << 4) + hex2int[*ch];
     ch++;
@@ -79,11 +71,11 @@
   return num;
 }
 
-int64 UtilAll::str2ll(const char *str) {
+int64 UtilAll::str2ll(const char* str) {
   return boost::lexical_cast<int64>(str);
 }
 
-string UtilAll::bytes2string(const char *bytes, int len) {
+string UtilAll::bytes2string(const char* bytes, int len) {
   if (bytes == NULL || len <= 0) {
     return string();
   }
@@ -113,7 +105,7 @@
 #endif
 }
 
-bool UtilAll::SplitURL(const string &serverURL, string &addr, short &nPort) {
+bool UtilAll::SplitURL(const string& serverURL, string& addr, short& nPort) {
   size_t pos = serverURL.find(':');
   if (pos == string::npos) {
     return false;
@@ -133,8 +125,9 @@
   return true;
 }
 
-int UtilAll::Split(vector<string> &ret_, const string &strIn, const char sep) {
-  if (strIn.empty()) return 0;
+int UtilAll::Split(vector<string>& ret_, const string& strIn, const char sep) {
+  if (strIn.empty())
+    return 0;
 
   string tmp;
   string::size_type pos_begin = strIn.find_first_not_of(sep);
@@ -157,9 +150,9 @@
   }
   return ret_.size();
 }
-int UtilAll::Split(vector<string> &ret_, const string &strIn,
-                   const string &sep) {
-  if (strIn.empty()) return 0;
+int UtilAll::Split(vector<string>& ret_, const string& strIn, const string& sep) {
+  if (strIn.empty())
+    return 0;
 
   string tmp;
   string::size_type pos_begin = strIn.find_first_not_of(sep);
@@ -183,31 +176,33 @@
   return ret_.size();
 }
 
-int32_t UtilAll::StringToInt32(const std::string &str, int32_t &out) {
+int32_t UtilAll::StringToInt32(const std::string& str, int32_t& out) {
   out = 0;
   if (str.empty()) {
     return false;
   }
 
-  char *end = NULL;
+  char* end = NULL;
   errno = 0;
   long l = strtol(str.c_str(), &end, 10);
   /* Both checks are needed because INT_MAX == LONG_MAX is possible. */
-  if (l > INT_MAX || (errno == ERANGE && l == LONG_MAX)) return false;
-  if (l < INT_MIN || (errno == ERANGE && l == LONG_MIN)) return false;
-  if (*end != '\0') return false;
+  if (l > INT_MAX || (errno == ERANGE && l == LONG_MAX))
+    return false;
+  if (l < INT_MIN || (errno == ERANGE && l == LONG_MIN))
+    return false;
+  if (*end != '\0')
+    return false;
   out = l;
   return true;
 }
 
-int64_t UtilAll::StringToInt64(const std::string &str, int64_t &val) {
-  char *endptr = NULL;
+int64_t UtilAll::StringToInt64(const std::string& str, int64_t& val) {
+  char* endptr = NULL;
   errno = 0; /* To distinguish success/failure after call */
   val = strtoll(str.c_str(), &endptr, 10);
 
   /* Check for various possible errors */
-  if ((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN)) ||
-      (errno != 0 && val == 0)) {
+  if ((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN)) || (errno != 0 && val == 0)) {
     return false;
   }
   /*no digit was found Or  Further characters after number*/
@@ -229,8 +224,7 @@
 
     char name[1024];
     boost::system::error_code ec;
-    if (boost::asio::detail::socket_ops::gethostname(name, sizeof(name), ec) !=
-        0) {
+    if (boost::asio::detail::socket_ops::gethostname(name, sizeof(name), ec) != 0) {
       return std::string();
     }
     s_localHostName.append(name, strlen(name));
@@ -244,8 +238,7 @@
     boost::asio::ip::tcp::resolver resolver(io_service);
     boost::asio::ip::tcp::resolver::query query(getLocalHostName(), "");
     boost::system::error_code error;
-    boost::asio::ip::tcp::resolver::iterator iter =
-        resolver.resolve(query, error);
+    boost::asio::ip::tcp::resolver::iterator iter = resolver.resolve(query, error);
     if (error) {
       return "";
     }
@@ -261,7 +254,7 @@
 
 string UtilAll::getHomeDirectory() {
 #ifndef WIN32
-  char *homeEnv = getenv("HOME");
+  char* homeEnv = getenv("HOME");
   string homeDir;
   if (homeEnv == NULL) {
     homeDir.append(getpwuid(getuid())->pw_dir);
@@ -294,7 +287,7 @@
   else
     buf[retval] = '\0';
 
-  char *process_name = strrchr(buf, '/');
+  char* process_name = strrchr(buf, '/');
   if (process_name) {
     return std::string(process_name + 1);
   } else {
@@ -309,21 +302,18 @@
 
 uint64_t UtilAll::currentTimeMillis() {
   auto since_epoch =
-      std::chrono::duration_cast<std::chrono::milliseconds>(
-          std::chrono::system_clock::now().time_since_epoch());
+      std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch());
   return static_cast<uint64_t>(since_epoch.count());
 }
 
 uint64_t UtilAll::currentTimeSeconds() {
   auto since_epoch =
-      std::chrono::duration_cast<std::chrono::seconds>(
-          std::chrono::system_clock::now().time_since_epoch());
+      std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch());
   return static_cast<uint64_t>(since_epoch.count());
 }
 
-bool UtilAll::deflate(std::string &input, std::string &out, int level) {
-  boost::iostreams::zlib_params zlibParams(level,
-                                           boost::iostreams::zlib::deflated);
+bool UtilAll::deflate(std::string& input, std::string& out, int level) {
+  boost::iostreams::zlib_params zlibParams(level, boost::iostreams::zlib::deflated);
   boost::iostreams::filtering_ostream compressingStream;
   compressingStream.push(boost::iostreams::zlib_compressor(zlibParams));
   compressingStream.push(boost::iostreams::back_inserter(out));
@@ -333,7 +323,7 @@
   return true;
 }
 
-bool UtilAll::inflate(std::string &input, std::string &out) {
+bool UtilAll::inflate(std::string& input, std::string& out) {
   boost::iostreams::filtering_ostream decompressingStream;
   decompressingStream.push(boost::iostreams::zlib_decompressor());
   decompressingStream.push(boost::iostreams::back_inserter(out));
@@ -343,23 +333,23 @@
   return true;
 }
 
-bool UtilAll::ReplaceFile(const std::string &from_path,
-                          const std::string &to_path) {
+bool UtilAll::ReplaceFile(const std::string& from_path, const std::string& to_path) {
 #ifdef WIN32
   // Try a simple move first.  It will only succeed when |to_path| doesn't
   // already exist.
-  if (::MoveFile(from_path.c_str(), to_path.c_str())) return true;
+  if (::MoveFile(from_path.c_str(), to_path.c_str()))
+    return true;
   // Try the full-blown replace if the move fails, as ReplaceFile will only
   // succeed when |to_path| does exist. When writing to a network share, we may
   // not be able to change the ACLs. Ignore ACL errors then
   // (REPLACEFILE_IGNORE_MERGE_ERRORS).
-  if (::ReplaceFile(to_path.c_str(), from_path.c_str(), NULL,
-                    REPLACEFILE_IGNORE_MERGE_ERRORS, NULL, NULL)) {
+  if (::ReplaceFile(to_path.c_str(), from_path.c_str(), NULL, REPLACEFILE_IGNORE_MERGE_ERRORS, NULL, NULL)) {
     return true;
   }
   return false;
 #else
-  if (rename(from_path.c_str(), to_path.c_str()) == 0) return true;
+  if (rename(from_path.c_str(), to_path.c_str()) == 0)
+    return true;
   return false;
 #endif
 }
diff --git a/src/common/UtilAll.h b/src/common/UtilAll.h
index e342f5f..98fc906 100644
--- a/src/common/UtilAll.h
+++ b/src/common/UtilAll.h
@@ -76,7 +76,7 @@
 const string null = "";
 
 template <typename Type>
-inline void deleteAndZero(Type &pointer) {
+inline void deleteAndZero(Type& pointer) {
   delete pointer;
   pointer = NULL;
 }
@@ -90,31 +90,30 @@
 //<!************************************************************************
 class UtilAll {
  public:
-  static bool startsWith_retry(const string &topic);
-  static string getRetryTopic(const string &consumerGroup);
+  static bool startsWith_retry(const string& topic);
+  static string getRetryTopic(const string& consumerGroup);
 
-  static void Trim(string &str);
-  static bool isBlank(const string &str);
-  static uint64 hexstr2ull(const char *str);
-  static int64 str2ll(const char *str);
-  static string bytes2string(const char *bytes, int len);
+  static void Trim(string& str);
+  static bool isBlank(const string& str);
+  static uint64 hexstr2ull(const char* str);
+  static int64 str2ll(const char* str);
+  static string bytes2string(const char* bytes, int len);
 
   template <typename T>
-  static string to_string(const T &n) {
+  static string to_string(const T& n) {
     std::ostringstream stm;
     stm << n;
     return stm.str();
   }
 
-  static bool to_bool(std::string const &s) { return atoi(s.c_str()); }
+  static bool to_bool(std::string const& s) { return atoi(s.c_str()); }
 
-  static bool SplitURL(const string &serverURL, string &addr, short &nPort);
-  static int Split(vector<string> &ret_, const string &strIn, const char sep);
-  static int Split(vector<string> &ret_, const string &strIn,
-                   const string &sep);
+  static bool SplitURL(const string& serverURL, string& addr, short& nPort);
+  static int Split(vector<string>& ret_, const string& strIn, const char sep);
+  static int Split(vector<string>& ret_, const string& strIn, const string& sep);
 
-  static int32_t StringToInt32(const std::string &str, int32_t &out);
-  static int64_t StringToInt64(const std::string &str, int64_t &val);
+  static int32_t StringToInt32(const std::string& str, int32_t& out);
+  static int64_t StringToInt64(const std::string& str, int64_t& val);
 
   static string getLocalHostName();
   static string getLocalAddress();
@@ -125,16 +124,15 @@
   static uint64_t currentTimeMillis();
   static uint64_t currentTimeSeconds();
 
-  static bool deflate(std::string &input, std::string &out, int level);
-  static bool inflate(std::string &input, std::string &out);
+  static bool deflate(std::string& input, std::string& out, int level);
+  static bool inflate(std::string& input, std::string& out);
   // Renames file |from_path| to |to_path|. Both paths must be on the same
   // volume, or the function will fail. Destination file will be created
   // if it doesn't exist. Prefer this function over Move when dealing with
   // temporary files. On Windows it preserves attributes of the target file.
   // Returns true on success.
   // Returns false on failure..
-  static bool ReplaceFile(const std::string &from_path,
-                          const std::string &to_path);
+  static bool ReplaceFile(const std::string& from_path, const std::string& to_path);
 
  private:
   static std::string s_localHostName;
diff --git a/src/common/Validators.cpp b/src/common/Validators.cpp
old mode 100755
new mode 100644
index 7484c98..8743a20
--- a/src/common/Validators.cpp
+++ b/src/common/Validators.cpp
@@ -22,8 +22,7 @@
 const string Validators::validPatternStr = "^[a-zA-Z0-9_-]+$";
 const int Validators::CHARACTER_MAX_LENGTH = 255;
 //<!***************************************************************************
-bool Validators::regularExpressionMatcher(const string& origin,
-                                          const string& patternStr) {
+bool Validators::regularExpressionMatcher(const string& origin, const string& patternStr) {
   if (UtilAll::isBlank(origin)) {
     return false;
   }
@@ -39,8 +38,7 @@
   return true;
 }
 
-string Validators::getGroupWithRegularExpression(const string& origin,
-                                                 const string& patternStr) {
+string Validators::getGroupWithRegularExpression(const string& origin, const string& patternStr) {
   /*Pattern pattern = Pattern.compile(patternStr);
   Matcher matcher = pattern.matcher(origin);
   while (matcher.find()) {
@@ -55,21 +53,16 @@
   }
 
   if ((int)topic.length() > CHARACTER_MAX_LENGTH) {
-    THROW_MQEXCEPTION(
-        MQClientException,
-        "the specified topic is longer than topic max length 255.", -1);
+    THROW_MQEXCEPTION(MQClientException, "the specified topic is longer than topic max length 255.", -1);
   }
 
   if (topic == DEFAULT_TOPIC) {
-    THROW_MQEXCEPTION(
-        MQClientException,
-        "the topic[" + topic + "] is conflict with default topic.", -1);
+    THROW_MQEXCEPTION(MQClientException, "the topic[" + topic + "] is conflict with default topic.", -1);
   }
 
   if (!regularExpressionMatcher(topic, validPatternStr)) {
     string str;
-    str = "the specified topic[" + topic +
-          "] contains illegal characters, allowing only" + validPatternStr;
+    str = "the specified topic[" + topic + "] contains illegal characters, allowing only" + validPatternStr;
 
     THROW_MQEXCEPTION(MQClientException, str.c_str(), -1);
   }
@@ -82,15 +75,12 @@
 
   if (!regularExpressionMatcher(group, validPatternStr)) {
     string str;
-    str = "the specified group[" + group +
-          "] contains illegal characters, allowing only" + validPatternStr;
+    str = "the specified group[" + group + "] contains illegal characters, allowing only" + validPatternStr;
 
     THROW_MQEXCEPTION(MQClientException, str.c_str(), -1);
   }
   if ((int)group.length() > CHARACTER_MAX_LENGTH) {
-    THROW_MQEXCEPTION(
-        MQClientException,
-        "the specified group is longer than group max length 255.", -1);
+    THROW_MQEXCEPTION(MQClientException, "the specified group is longer than group max length 255.", -1);
   }
 }
 
@@ -105,8 +95,7 @@
 
   if ((int)body.length() > maxMessageSize) {
     char info[256];
-    sprintf(info, "the message body size over max value, MAX: %d",
-            maxMessageSize);
+    sprintf(info, "the message body size over max value, MAX: %d", maxMessageSize);
     THROW_MQEXCEPTION(MQClientException, info, -1);
   }
 }
diff --git a/src/common/Validators.h b/src/common/Validators.h
old mode 100755
new mode 100644
index 4190588..cc03fb5
--- a/src/common/Validators.h
+++ b/src/common/Validators.h
@@ -25,10 +25,8 @@
 //<!***************************************************************************
 class Validators {
  public:
-  static bool regularExpressionMatcher(const string& origin,
-                                       const string& patternStr);
-  static string getGroupWithRegularExpression(const string& origin,
-                                              const string& patternStr);
+  static bool regularExpressionMatcher(const string& origin, const string& patternStr);
+  static string getGroupWithRegularExpression(const string& origin, const string& patternStr);
   static void checkTopic(const string& topic);
   static void checkGroup(const string& group);
   static void checkMessage(const MQMessage& msg, int maxMessageSize);
diff --git a/src/common/VirtualEnvUtil.cpp b/src/common/VirtualEnvUtil.cpp
old mode 100755
new mode 100644
index 6daf731..15517e9
--- a/src/common/VirtualEnvUtil.cpp
+++ b/src/common/VirtualEnvUtil.cpp
@@ -23,8 +23,7 @@
 const char* VirtualEnvUtil::VIRTUAL_APPGROUP_PREFIX = "%%PROJECT_%s%%";
 
 //<!***************************************************************************
-string VirtualEnvUtil::buildWithProjectGroup(const string& origin,
-                                             const string& projectGroup) {
+string VirtualEnvUtil::buildWithProjectGroup(const string& origin, const string& projectGroup) {
   if (!UtilAll::isBlank(projectGroup)) {
     char prefix[1024];
     sprintf(prefix, VIRTUAL_APPGROUP_PREFIX, projectGroup.c_str());
@@ -39,8 +38,7 @@
   }
 }
 
-string VirtualEnvUtil::clearProjectGroup(const string& origin,
-                                         const string& projectGroup) {
+string VirtualEnvUtil::clearProjectGroup(const string& origin, const string& projectGroup) {
   char prefix[1024];
   sprintf(prefix, VIRTUAL_APPGROUP_PREFIX, projectGroup.c_str());
   string::size_type pos = origin.find_last_of(prefix);
diff --git a/src/common/VirtualEnvUtil.h b/src/common/VirtualEnvUtil.h
old mode 100755
new mode 100644
index 88e44f8..7edc4eb
--- a/src/common/VirtualEnvUtil.h
+++ b/src/common/VirtualEnvUtil.h
@@ -22,10 +22,8 @@
 //<!***************************************************************************
 class VirtualEnvUtil {
  public:
-  static std::string buildWithProjectGroup(const std::string& origin,
-                                      const std::string& projectGroup);
-  static std::string clearProjectGroup(const std::string& origin,
-                                  const std::string& projectGroup);
+  static std::string buildWithProjectGroup(const std::string& origin, const std::string& projectGroup);
+  static std::string clearProjectGroup(const std::string& origin, const std::string& projectGroup);
 
  public:
   static const char* VIRTUAL_APPGROUP_PREFIX;
diff --git a/src/common/big_endian.cpp b/src/common/big_endian.cpp
index 1e4819a..7976d95 100644
--- a/src/common/big_endian.cpp
+++ b/src/common/big_endian.cpp
@@ -24,17 +24,18 @@
 
 namespace rocketmq {
 
-BigEndianReader::BigEndianReader(const char* buf, size_t len)
-    : ptr_(buf), end_(ptr_ + len) {}
+BigEndianReader::BigEndianReader(const char* buf, size_t len) : ptr_(buf), end_(ptr_ + len) {}
 
 bool BigEndianReader::Skip(size_t len) {
-  if (ptr_ + len > end_) return false;
+  if (ptr_ + len > end_)
+    return false;
   ptr_ += len;
   return true;
 }
 
 bool BigEndianReader::ReadBytes(void* out, size_t len) {
-  if (ptr_ + len > end_) return false;
+  if (ptr_ + len > end_)
+    return false;
   memcpy(out, ptr_, len);
   ptr_ += len;
   return true;
@@ -42,31 +43,41 @@
 
 template <typename T>
 bool BigEndianReader::Read(T* value) {
-  if (ptr_ + sizeof(T) > end_) return false;
+  if (ptr_ + sizeof(T) > end_)
+    return false;
   ReadBigEndian<T>(ptr_, value);
   ptr_ += sizeof(T);
   return true;
 }
 
-bool BigEndianReader::ReadU8(uint8_t* value) { return Read(value); }
+bool BigEndianReader::ReadU8(uint8_t* value) {
+  return Read(value);
+}
 
-bool BigEndianReader::ReadU16(uint16_t* value) { return Read(value); }
+bool BigEndianReader::ReadU16(uint16_t* value) {
+  return Read(value);
+}
 
-bool BigEndianReader::ReadU32(uint32_t* value) { return Read(value); }
+bool BigEndianReader::ReadU32(uint32_t* value) {
+  return Read(value);
+}
 
-bool BigEndianReader::ReadU64(uint64_t* value) { return Read(value); }
+bool BigEndianReader::ReadU64(uint64_t* value) {
+  return Read(value);
+}
 
-BigEndianWriter::BigEndianWriter(char* buf, size_t len)
-    : ptr_(buf), end_(ptr_ + len) {}
+BigEndianWriter::BigEndianWriter(char* buf, size_t len) : ptr_(buf), end_(ptr_ + len) {}
 
 bool BigEndianWriter::Skip(size_t len) {
-  if (ptr_ + len > end_) return false;
+  if (ptr_ + len > end_)
+    return false;
   ptr_ += len;
   return true;
 }
 
 bool BigEndianWriter::WriteBytes(const void* buf, size_t len) {
-  if (ptr_ + len > end_) return false;
+  if (ptr_ + len > end_)
+    return false;
   memcpy(ptr_, buf, len);
   ptr_ += len;
   return true;
@@ -74,18 +85,27 @@
 
 template <typename T>
 bool BigEndianWriter::Write(T value) {
-  if (ptr_ + sizeof(T) > end_) return false;
+  if (ptr_ + sizeof(T) > end_)
+    return false;
   WriteBigEndian<T>(ptr_, value);
   ptr_ += sizeof(T);
   return true;
 }
 
-bool BigEndianWriter::WriteU8(uint8_t value) { return Write(value); }
+bool BigEndianWriter::WriteU8(uint8_t value) {
+  return Write(value);
+}
 
-bool BigEndianWriter::WriteU16(uint16_t value) { return Write(value); }
+bool BigEndianWriter::WriteU16(uint16_t value) {
+  return Write(value);
+}
 
-bool BigEndianWriter::WriteU32(uint32_t value) { return Write(value); }
+bool BigEndianWriter::WriteU32(uint32_t value) {
+  return Write(value);
+}
 
-bool BigEndianWriter::WriteU64(uint64_t value) { return Write(value); }
+bool BigEndianWriter::WriteU64(uint64_t value) {
+  return Write(value);
+}
 
 }  // namespace base
diff --git a/src/common/dataBlock.cpp b/src/common/dataBlock.cpp
old mode 100755
new mode 100644
index 4195f2b..daca4e4
--- a/src/common/dataBlock.cpp
+++ b/src/common/dataBlock.cpp
@@ -21,40 +21,41 @@
 
 MemoryBlock::MemoryBlock() : size(0), data(NULL) {}
 
-MemoryBlock::MemoryBlock(const int initialSize, const bool initialiseToZero)
-    : size(0), data(NULL) {
+MemoryBlock::MemoryBlock(const int initialSize, const bool initialiseToZero) : size(0), data(NULL) {
   if (initialSize > 0) {
     size = initialSize;
-    data = static_cast<char *>(initialiseToZero
-                               ? std::calloc(initialSize, sizeof(char))
-                               : std::malloc(initialSize * sizeof(char)));
+    data = static_cast<char*>(initialiseToZero ? std::calloc(initialSize, sizeof(char))
+                                               : std::malloc(initialSize * sizeof(char)));
   }
 }
 
-MemoryBlock::MemoryBlock(const void *const dataToInitialiseFrom, const size_t sizeInBytes)
+MemoryBlock::MemoryBlock(const void* const dataToInitialiseFrom, const size_t sizeInBytes)
     : size(sizeInBytes), data(NULL) {
   if (size > 0) {
-    data = static_cast<char *>(std::malloc(size * sizeof(char)));
+    data = static_cast<char*>(std::malloc(size * sizeof(char)));
 
-    if (dataToInitialiseFrom != NULL) memcpy(data, dataToInitialiseFrom, size);
+    if (dataToInitialiseFrom != NULL)
+      memcpy(data, dataToInitialiseFrom, size);
   }
 }
 
-MemoryBlock::MemoryBlock(const MemoryBlock &other) : size(other.size), data(NULL) {
+MemoryBlock::MemoryBlock(const MemoryBlock& other) : size(other.size), data(NULL) {
   if (size > 0) {
-    data = static_cast<char *>(std::malloc(size * sizeof(char)));
+    data = static_cast<char*>(std::malloc(size * sizeof(char)));
     memcpy(data, other.data, size);
   }
 }
 
-MemoryBlock::MemoryBlock(MemoryBlock &&other) : size(other.size), data(other.data) {
+MemoryBlock::MemoryBlock(MemoryBlock&& other) : size(other.size), data(other.data) {
   other.size = 0;
   other.data = NULL;
 }
 
-MemoryBlock::~MemoryBlock() { std::free(data); }
+MemoryBlock::~MemoryBlock() {
+  std::free(data);
+}
 
-MemoryBlock &MemoryBlock::operator=(const MemoryBlock &other) {
+MemoryBlock& MemoryBlock::operator=(const MemoryBlock& other) {
   if (this != &other) {
     setSize(other.size, false);
     memcpy(data, other.data, size);
@@ -63,7 +64,7 @@
   return *this;
 }
 
-MemoryBlock &MemoryBlock::operator=(MemoryBlock &&other) {
+MemoryBlock& MemoryBlock::operator=(MemoryBlock&& other) {
   if (this != &other) {
     std::free(data);
 
@@ -78,15 +79,15 @@
 }
 
 //==============================================================================
-bool MemoryBlock::operator==(const MemoryBlock &other) const {
+bool MemoryBlock::operator==(const MemoryBlock& other) const {
   return matches(other.data, other.size);
 }
 
-bool MemoryBlock::operator!=(const MemoryBlock &other) const {
+bool MemoryBlock::operator!=(const MemoryBlock& other) const {
   return !operator==(other);
 }
 
-bool MemoryBlock::matches(const void *dataToCompare, int dataSize) const {
+bool MemoryBlock::matches(const void* dataToCompare, int dataSize) const {
   return size == dataSize && memcmp(data, dataToCompare, size) == 0;
 }
 
@@ -98,17 +99,15 @@
       reset();
     } else {
       if (data != NULL) {
-        data = static_cast<char *>(
-            data == NULL ? std::malloc(newSize * sizeof(char))
-                         : std::realloc(data, newSize * sizeof(char)));
+        data = static_cast<char*>(data == NULL ? std::malloc(newSize * sizeof(char))
+                                               : std::realloc(data, newSize * sizeof(char)));
 
         if (initialiseToZero && (newSize > size))
           memset(data + size, 0, newSize - size);
       } else {
         std::free(data);
-        data = static_cast<char *>(initialiseToZero
-                                   ? std::calloc(newSize, sizeof(char))
-                                   : std::malloc(newSize * sizeof(char)));
+        data = static_cast<char*>(initialiseToZero ? std::calloc(newSize, sizeof(char))
+                                                   : std::malloc(newSize * sizeof(char)));
       }
 
       size = newSize;
@@ -123,15 +122,16 @@
 }
 
 void MemoryBlock::ensureSize(const int minimumSize, const bool initialiseToZero) {
-  if (size < minimumSize) setSize(minimumSize, initialiseToZero);
+  if (size < minimumSize)
+    setSize(minimumSize, initialiseToZero);
 }
 
 //==============================================================================
 void MemoryBlock::fillWith(const int value) {
-  memset(data, (int) value, size);
+  memset(data, (int)value, size);
 }
 
-void MemoryBlock::append(const void *const srcData, const int numBytes) {
+void MemoryBlock::append(const void* const srcData, const int numBytes) {
   if (numBytes > 0) {
     const int oldSize = size;
     setSize(size + numBytes);
@@ -139,22 +139,21 @@
   }
 }
 
-void MemoryBlock::replaceWith(const void *const srcData, const int numBytes) {
+void MemoryBlock::replaceWith(const void* const srcData, const int numBytes) {
   if (numBytes > 0) {
     setSize(numBytes);
     memcpy(data, srcData, numBytes);
   }
 }
 
-void MemoryBlock::insert(const void *const srcData, const int numBytes, int insertPosition) {
+void MemoryBlock::insert(const void* const srcData, const int numBytes, int insertPosition) {
   if (numBytes > 0) {
     insertPosition = std::min(insertPosition, size);
     const int trailingDataSize = size - insertPosition;
     setSize(size + numBytes, false);
 
     if (trailingDataSize > 0)
-      memmove(data + insertPosition + numBytes, data + insertPosition,
-              trailingDataSize);
+      memmove(data + insertPosition + numBytes, data + insertPosition, trailingDataSize);
 
     memcpy(data + insertPosition, srcData, numBytes);
   }
@@ -170,36 +169,39 @@
   }
 }
 
-void MemoryBlock::copyFrom(const void *const src, int offset, int num) {
-  const char *d = static_cast<const char *>(src);
+void MemoryBlock::copyFrom(const void* const src, int offset, int num) {
+  const char* d = static_cast<const char*>(src);
 
   if (offset < 0) {
     d -= offset;
-    num += (size_t) -offset;
+    num += (size_t)-offset;
     offset = 0;
   }
 
-  if ((size_t) offset + num > (unsigned int) size) num = size - (size_t) offset;
+  if ((size_t)offset + num > (unsigned int)size)
+    num = size - (size_t)offset;
 
-  if (num > 0) memcpy(data + offset, d, num);
+  if (num > 0)
+    memcpy(data + offset, d, num);
 }
 
-void MemoryBlock::copyTo(void *const dst, int offset, int num) const {
-  char *d = static_cast<char *>(dst);
+void MemoryBlock::copyTo(void* const dst, int offset, int num) const {
+  char* d = static_cast<char*>(dst);
 
   if (offset < 0) {
-    memset(d, 0, (size_t) -offset);
+    memset(d, 0, (size_t)-offset);
     d -= offset;
-    num -= (size_t) -offset;
+    num -= (size_t)-offset;
     offset = 0;
   }
 
-  if ((size_t) offset + num > (unsigned int) size) {
-    const int newNum = (size_t) size - (size_t) offset;
+  if ((size_t)offset + num > (unsigned int)size) {
+    const int newNum = (size_t)size - (size_t)offset;
     memset(d + newNum, 0, num - newNum);
     num = newNum;
   }
 
-  if (num > 0) memcpy(d, data + offset, num);
+  if (num > 0)
+    memcpy(d, data + offset, num);
 }
 }
diff --git a/src/common/dataBlock.h b/src/common/dataBlock.h
old mode 100755
new mode 100644
index 88099b7..4419af3
--- a/src/common/dataBlock.h
+++ b/src/common/dataBlock.h
@@ -46,12 +46,12 @@
       @param dataToInitialiseFrom     some data to copy into this block
       @param sizeInBytes              how much space to use
   */
-  MemoryBlock(const void *dataToInitialiseFrom, size_t sizeInBytes);
+  MemoryBlock(const void* dataToInitialiseFrom, size_t sizeInBytes);
 
   /** Creates a copy of another memory block. */
-  MemoryBlock(const MemoryBlock &);
+  MemoryBlock(const MemoryBlock&);
 
-  MemoryBlock(MemoryBlock &&);
+  MemoryBlock(MemoryBlock&&);
 
   /** Destructor. */
   ~MemoryBlock();
@@ -59,22 +59,22 @@
   /** Copies another memory block onto this one.
       This block will be resized and copied to exactly match the other one.
   */
-  MemoryBlock &operator=(const MemoryBlock &);
+  MemoryBlock& operator=(const MemoryBlock&);
 
-  MemoryBlock &operator=(MemoryBlock &&);
+  MemoryBlock& operator=(MemoryBlock&&);
 
   //==============================================================================
   /** Compares two memory blocks.
       @returns true only if the two blocks are the same size and have identical
      contents.
   */
-  bool operator==(const MemoryBlock &other) const;
+  bool operator==(const MemoryBlock& other) const;
 
   /** Compares two memory blocks.
       @returns true if the two blocks are different sizes or have different
      contents.
   */
-  bool operator!=(const MemoryBlock &other) const;
+  bool operator!=(const MemoryBlock& other) const;
 
   //==============================================================================
   /** Returns a void pointer to the data.
@@ -82,19 +82,19 @@
       Note that the pointer returned will probably become invalid when the
       block is resized.
   */
-  char *getData() const { return data; }
+  char* getData() const { return data; }
 
   /** Returns a byte from the memory block.
       This returns a reference, so you can also use it to set a byte.
   */
-  template<typename Type>
-  char &operator[](const Type offset) const {
+  template <typename Type>
+  char& operator[](const Type offset) const {
     return data[offset];
   }
 
   /** Returns true if the data in this MemoryBlock matches the raw bytes
    * passed-in. */
-  bool matches(const void *data, int dataSize) const;
+  bool matches(const void* data, int dataSize) const;
 
   //==============================================================================
   /** Returns the block's current allocated size, in bytes. */
@@ -145,13 +145,13 @@
       The data pointer must not be null. This block's size will be increased
      accordingly.
   */
-  void append(const void *data, int numBytes);
+  void append(const void* data, int numBytes);
 
   /** Resizes this block to the given size and fills its contents from the
      supplied buffer.
       The data pointer must not be null.
   */
-  void replaceWith(const void *data, int numBytes);
+  void replaceWith(const void* data, int numBytes);
 
   /** Inserts some data into the block.
       The dataToInsert pointer must not be null. This block's size will be
@@ -160,8 +160,7 @@
      be clipped to
       within the range before being used.
   */
-  void insert(const void *dataToInsert, int numBytesToInsert,
-              int insertPosition);
+  void insert(const void* dataToInsert, int numBytesToInsert, int insertPosition);
 
   /** Chops out a section  of the block.
 
@@ -186,7 +185,7 @@
                                   it will be clipped so not to do anything
      nasty)
   */
-  void copyFrom(const void *srcData, int destinationOffset, int numBytes);
+  void copyFrom(const void* srcData, int destinationOffset, int numBytes);
 
   /** Copies data from this MemoryBlock to a memory address.
 
@@ -197,12 +196,12 @@
      limits of the memory block,
                               zeros will be used for that portion of the data)
   */
-  void copyTo(void *destData, int sourceOffset, int numBytes) const;
+  void copyTo(void* destData, int sourceOffset, int numBytes) const;
 
  private:
   //==============================================================================
   int size;
-  char *data;
+  char* data;
 };
 }
 
diff --git a/src/common/noncopyable.h b/src/common/noncopyable.h
new file mode 100644
index 0000000..f52f988
--- /dev/null
+++ b/src/common/noncopyable.h
@@ -0,0 +1,33 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#ifndef __NONCOPYABLE_H__
+#define __NONCOPYABLE_H__
+
+namespace rocketmq {
+
+class noncopyable {
+ protected:
+  noncopyable() = default;
+  ~noncopyable() = default;
+
+  noncopyable(const noncopyable&) = delete;
+  noncopyable& operator=(const noncopyable&) = delete;
+};
+
+}  // namespace rocketmq
+
+#endif  //__NONCOPYABLE_H__
diff --git a/src/common/sync_http_client.cpp b/src/common/sync_http_client.cpp
old mode 100755
new mode 100644
index f07ac0d..78f0292
--- a/src/common/sync_http_client.cpp
+++ b/src/common/sync_http_client.cpp
@@ -31,8 +31,7 @@
 using boost::asio::deadline_timer;
 
 namespace {
-void check_deadline(deadline_timer* deadline, tcp::socket* socket,
-                    const boost::system::error_code& ec) {
+void check_deadline(deadline_timer* deadline, tcp::socket* socket, const boost::system::error_code& ec) {
   // Check whether the deadline has passed. We compare the deadline against
   // the current time since a new asynchronous operation may have moved the
   // deadline before this actor had a chance to run.
@@ -49,8 +48,7 @@
   }
 
   // Put the actor back to sleep.
-  deadline->async_wait(boost::bind(&check_deadline, deadline, socket,
-                                   boost::asio::placeholders::error));
+  deadline->async_wait(boost::bind(&check_deadline, deadline, socket, boost::asio::placeholders::error));
 }
 }  // namespace
 
@@ -73,8 +71,7 @@
     boost::system::error_code deadline_ec;
     check_deadline(&deadline, &socket, deadline_ec);
 
-    boost::asio::async_connect(socket, endpoint_iterator,
-                               boost::lambda::var(ec) = boost::lambda::_1);
+    boost::asio::async_connect(socket, endpoint_iterator, boost::lambda::var(ec) = boost::lambda::_1);
 
     do {
       io_service.run_one();
@@ -134,14 +131,12 @@
     if (response.size() > 0) {
       boost::asio::streambuf::const_buffers_type cbt = response.data();
       body.clear();
-      body.insert(body.begin(), boost::asio::buffers_begin(cbt),
-                  boost::asio::buffers_end(cbt));
+      body.insert(body.begin(), boost::asio::buffers_begin(cbt), boost::asio::buffers_end(cbt));
     }
 
     // Read until EOF, writing data to output as we go.
     boost::system::error_code error;
-    while (boost::asio::read(socket, response,
-                             boost::asio::transfer_at_least(1), error))
+    while (boost::asio::read(socket, response, boost::asio::transfer_at_least(1), error))
       std::cout << &response;
     if (error != boost::asio::error::eof)
       throw boost::system::system_error(error);
diff --git a/src/common/sync_http_client.h b/src/common/sync_http_client.h
old mode 100755
new mode 100644
diff --git a/src/common/url.cpp b/src/common/url.cpp
old mode 100755
new mode 100644
index 348f27a..f8d9155
--- a/src/common/url.cpp
+++ b/src/common/url.cpp
@@ -23,17 +23,19 @@
 
 namespace rocketmq {
 
-Url::Url(const std::string& url_s) { parse(url_s); }
+Url::Url(const std::string& url_s) {
+  parse(url_s);
+}
 
 void Url::parse(const std::string& url_s) {
   const std::string prot_end("://");
-  auto prot_i =
-      std::search(url_s.begin(), url_s.end(), prot_end.begin(), prot_end.end());
+  auto prot_i = std::search(url_s.begin(), url_s.end(), prot_end.begin(), prot_end.end());
   protocol_.reserve(std::distance(url_s.begin(), prot_i));
   std::transform(url_s.begin(), prot_i, std::back_inserter(protocol_),
                  std::ptr_fun<int, int>(tolower));  // protocol is icase
 
-  if (prot_i == url_s.end()) return;
+  if (prot_i == url_s.end())
+    return;
 
   std::advance(prot_i, prot_end.length());
 
@@ -51,12 +53,12 @@
   }
 
   host_.reserve(distance(prot_i, path_i));
-  std::transform(prot_i, path_i, std::back_inserter(host_),
-                 std::ptr_fun<int, int>(tolower));  // host is icase}
+  std::transform(prot_i, path_i, std::back_inserter(host_), std::ptr_fun<int, int>(tolower));  // host is icase}
 
   auto query_i = find(path_end_i, url_s.end(), '?');
   path_.assign(path_end_i, query_i);
-  if (query_i != url_s.end()) ++query_i;
+  if (query_i != url_s.end())
+    ++query_i;
   query_.assign(query_i, url_s.end());
 }
 
diff --git a/src/common/url.h b/src/common/url.h
old mode 100755
new mode 100644
diff --git a/src/consumer/AllocateMQStrategy.h b/src/consumer/AllocateMQStrategy.h
old mode 100755
new mode 100644
index fbe501a..4613040
--- a/src/consumer/AllocateMQStrategy.h
+++ b/src/consumer/AllocateMQStrategy.h
@@ -70,12 +70,9 @@
 
     int mqAllSize = mqAll.size();
     int mod = mqAllSize % cidAllSize;
-    int averageSize = mqAllSize <= cidAllSize
-                          ? 1
-                          : (mod > 0 && index < mod ? mqAllSize / cidAllSize + 1
-                                                    : mqAllSize / cidAllSize);
-    int startIndex = (mod > 0 && index < mod) ? index * averageSize
-                                              : index * averageSize + mod;
+    int averageSize =
+        mqAllSize <= cidAllSize ? 1 : (mod > 0 && index < mod ? mqAllSize / cidAllSize + 1 : mqAllSize / cidAllSize);
+    int startIndex = (mod > 0 && index < mod) ? index * averageSize : index * averageSize + mod;
     int range = (std::min)(averageSize, mqAllSize - startIndex);
     LOG_INFO(
         "range is:%d, index is:%d, mqAllSize is:%d, averageSize is:%d, "
diff --git a/src/consumer/ConsumeMessageConcurrentlyService.cpp b/src/consumer/ConsumeMessageConcurrentlyService.cpp
old mode 100755
new mode 100644
index 9d4e1a4..9069350
--- a/src/consumer/ConsumeMessageConcurrentlyService.cpp
+++ b/src/consumer/ConsumeMessageConcurrentlyService.cpp
@@ -24,18 +24,16 @@
 namespace rocketmq {

 

 //<!************************************************************************

-ConsumeMessageConcurrentlyService::ConsumeMessageConcurrentlyService(

-    MQConsumer* consumer, int threadCount, MQMessageListener* msgListener)

-    : m_pConsumer(consumer),

-      m_pMessageListener(msgListener),

-      m_ioServiceWork(m_ioService) {

+ConsumeMessageConcurrentlyService::ConsumeMessageConcurrentlyService(MQConsumer* consumer,

+                                                                     int threadCount,

+                                                                     MQMessageListener* msgListener)

+    : m_pConsumer(consumer), m_pMessageListener(msgListener), m_ioServiceWork(m_ioService) {

 #if !defined(WIN32) && !defined(__APPLE__)

   string taskName = UtilAll::getProcessName();

   prctl(PR_SET_NAME, "ConsumeTP", 0, 0, 0);

 #endif

   for (int i = 0; i != threadCount; ++i) {

-    m_threadpool.create_thread(

-        boost::bind(&boost::asio::io_service::run, &m_ioService));

+    m_threadpool.create_thread(boost::bind(&boost::asio::io_service::run, &m_ioService));

   }

 #if !defined(WIN32) && !defined(__APPLE__)

   prctl(PR_SET_NAME, taskName.c_str(), 0, 0, 0);

@@ -49,26 +47,24 @@
 

 void ConsumeMessageConcurrentlyService::start() {}

 

-void ConsumeMessageConcurrentlyService::shutdown() { stopThreadPool(); }

+void ConsumeMessageConcurrentlyService::shutdown() {

+  stopThreadPool();

+}

 

 void ConsumeMessageConcurrentlyService::stopThreadPool() {

   m_ioService.stop();

   m_threadpool.join_all();

 }

 

-MessageListenerType

-ConsumeMessageConcurrentlyService::getConsumeMsgSerivceListenerType() {

+MessageListenerType ConsumeMessageConcurrentlyService::getConsumeMsgSerivceListenerType() {

   return m_pMessageListener->getMessageListenerType();

 }

 

-void ConsumeMessageConcurrentlyService::submitConsumeRequest(

-    PullRequest* request, vector<MQMessageExt>& msgs) {

-  m_ioService.post(boost::bind(

-      &ConsumeMessageConcurrentlyService::ConsumeRequest, this, request, msgs));

+void ConsumeMessageConcurrentlyService::submitConsumeRequest(PullRequest* request, vector<MQMessageExt>& msgs) {

+  m_ioService.post(boost::bind(&ConsumeMessageConcurrentlyService::ConsumeRequest, this, request, msgs));

 }

 

-void ConsumeMessageConcurrentlyService::ConsumeRequest(

-    PullRequest* request, vector<MQMessageExt>& msgs) {

+void ConsumeMessageConcurrentlyService::ConsumeRequest(PullRequest* request, vector<MQMessageExt>& msgs) {

   if (!request || request->isDroped()) {

     LOG_WARN("the pull result is NULL or Had been dropped");

     request->clearAllMsgs();  // add clear operation to avoid bad state when

@@ -78,8 +74,7 @@
 

   //<!¶ÁÈ¡Êý¾Ý;

   if (msgs.empty()) {

-    LOG_WARN("the msg of pull result is NULL,its mq:%s",

-             (request->m_messageQueue).toString().c_str());

+    LOG_WARN("the msg of pull result is NULL,its mq:%s", (request->m_messageQueue).toString().c_str());

     return;

   }

 

@@ -109,8 +104,7 @@
       // Note: broadcasting reconsume should do by application, as it has big

       // affect to broker cluster

       if (ackIndex != (int)msgs.size())

-        LOG_WARN("BROADCASTING, the message consume failed, drop it:%s",

-                 (request->m_messageQueue).toString().c_str());

+        LOG_WARN("BROADCASTING, the message consume failed, drop it:%s", (request->m_messageQueue).toString().c_str());

       break;

     case CLUSTERING:

       // send back msg to broker;

@@ -118,8 +112,8 @@
         LOG_WARN("consume fail, MQ is:%s, its msgId is:%s, index is:" SIZET_FMT

                  ", reconsume "

                  "times is:%d",

-                 (request->m_messageQueue).toString().c_str(),

-                 msgs[i].getMsgId().c_str(), i, msgs[i].getReconsumeTimes());

+                 (request->m_messageQueue).toString().c_str(), msgs[i].getMsgId().c_str(), i,

+                 msgs[i].getReconsumeTimes());

         m_pConsumer->sendMessageBack(msgs[i], 0);

       }

       break;

@@ -134,13 +128,11 @@
   if (offset >= 0) {

     m_pConsumer->updateConsumeOffset(request->m_messageQueue, offset);

   } else {

-    LOG_WARN("Note: accumulation consume occurs on mq:%s",

-             (request->m_messageQueue).toString().c_str());

+    LOG_WARN("Note: accumulation consume occurs on mq:%s", (request->m_messageQueue).toString().c_str());

   }

 }

 

-void ConsumeMessageConcurrentlyService::resetRetryTopic(

-    vector<MQMessageExt>& msgs) {

+void ConsumeMessageConcurrentlyService::resetRetryTopic(vector<MQMessageExt>& msgs) {

   string groupTopic = UtilAll::getRetryTopic(m_pConsumer->getGroupName());

   for (size_t i = 0; i < msgs.size(); i++) {

     MQMessageExt& msg = msgs[i];

diff --git a/src/consumer/ConsumeMessageOrderlyService.cpp b/src/consumer/ConsumeMessageOrderlyService.cpp
old mode 100755
new mode 100644
index e66c0cb..800bb4d
--- a/src/consumer/ConsumeMessageOrderlyService.cpp
+++ b/src/consumer/ConsumeMessageOrderlyService.cpp
@@ -26,8 +26,9 @@
 namespace rocketmq {

 

 //<!***************************************************************************

-ConsumeMessageOrderlyService::ConsumeMessageOrderlyService(

-    MQConsumer* consumer, int threadCount, MQMessageListener* msgListener)

+ConsumeMessageOrderlyService::ConsumeMessageOrderlyService(MQConsumer* consumer,

+                                                           int threadCount,

+                                                           MQMessageListener* msgListener)

     : m_pConsumer(consumer),

       m_shutdownInprogress(false),

       m_pMessageListener(msgListener),

@@ -39,8 +40,7 @@
   prctl(PR_SET_NAME, "oderlyConsumeTP", 0, 0, 0);

 #endif

   for (int i = 0; i != threadCount; ++i) {

-    m_threadpool.create_thread(

-        boost::bind(&boost::asio::io_service::run, &m_ioService));

+    m_threadpool.create_thread(boost::bind(&boost::asio::io_service::run, &m_ioService));

   }

 #if !defined(WIN32) && !defined(__APPLE__)

   prctl(PR_SET_NAME, taskName.c_str(), 0, 0, 0);

@@ -54,11 +54,8 @@
                                                           // first timer timeout

                                                           // callback

   boost::system::error_code ec;

-  boost::asio::deadline_timer t(

-      m_async_ioService,

-      boost::posix_time::milliseconds(PullRequest::RebalanceLockInterval));

-  t.async_wait(boost::bind(&ConsumeMessageOrderlyService::lockMQPeriodically,

-                           this, ec, &t));

+  boost::asio::deadline_timer t(m_async_ioService, boost::posix_time::milliseconds(PullRequest::RebalanceLockInterval));

+  t.async_wait(boost::bind(&ConsumeMessageOrderlyService::lockMQPeriodically, this, ec, &t));

 

   m_async_ioService.run();

 }

@@ -69,8 +66,7 @@
 }

 

 void ConsumeMessageOrderlyService::start() {

-  m_async_service_thread.reset(new boost::thread(

-      boost::bind(&ConsumeMessageOrderlyService::boost_asio_work, this)));

+  m_async_service_thread.reset(new boost::thread(boost::bind(&ConsumeMessageOrderlyService::boost_asio_work, this)));

 }

 

 void ConsumeMessageOrderlyService::shutdown() {

@@ -78,16 +74,12 @@
   unlockAllMQ();

 }

 

-void ConsumeMessageOrderlyService::lockMQPeriodically(

-    boost::system::error_code& ec, boost::asio::deadline_timer* t) {

+void ConsumeMessageOrderlyService::lockMQPeriodically(boost::system::error_code& ec, boost::asio::deadline_timer* t) {

   m_pConsumer->getRebalance()->lockAll();

 

   boost::system::error_code e;

-  t->expires_at(t->expires_at() + boost::posix_time::milliseconds(

-                                      PullRequest::RebalanceLockInterval),

-                e);

-  t->async_wait(boost::bind(&ConsumeMessageOrderlyService::lockMQPeriodically,

-                            this, ec, t));

+  t->expires_at(t->expires_at() + boost::posix_time::milliseconds(PullRequest::RebalanceLockInterval), e);

+  t->async_wait(boost::bind(&ConsumeMessageOrderlyService::lockMQPeriodically, this, ec, t));

 }

 

 void ConsumeMessageOrderlyService::unlockAllMQ() {

@@ -107,41 +99,35 @@
   m_threadpool.join_all();

 }

 

-MessageListenerType

-ConsumeMessageOrderlyService::getConsumeMsgSerivceListenerType() {

+MessageListenerType ConsumeMessageOrderlyService::getConsumeMsgSerivceListenerType() {

   return m_pMessageListener->getMessageListenerType();

 }

 

-void ConsumeMessageOrderlyService::submitConsumeRequest(

-    PullRequest* request, vector<MQMessageExt>& msgs) {

-  m_ioService.post(boost::bind(&ConsumeMessageOrderlyService::ConsumeRequest,

-                               this, request));

+void ConsumeMessageOrderlyService::submitConsumeRequest(PullRequest* request, vector<MQMessageExt>& msgs) {

+  m_ioService.post(boost::bind(&ConsumeMessageOrderlyService::ConsumeRequest, this, request));

 }

 

-void ConsumeMessageOrderlyService::static_submitConsumeRequestLater(

-    void* context, PullRequest* request, bool tryLockMQ,

-    boost::asio::deadline_timer* t) {

-  LOG_INFO("submit consumeRequest later for mq:%s",

-           request->m_messageQueue.toString().c_str());

+void ConsumeMessageOrderlyService::static_submitConsumeRequestLater(void* context,

+                                                                    PullRequest* request,

+                                                                    bool tryLockMQ,

+                                                                    boost::asio::deadline_timer* t) {

+  LOG_INFO("submit consumeRequest later for mq:%s", request->m_messageQueue.toString().c_str());

   vector<MQMessageExt> msgs;

-  ConsumeMessageOrderlyService* orderlyService =

-      (ConsumeMessageOrderlyService*)context;

+  ConsumeMessageOrderlyService* orderlyService = (ConsumeMessageOrderlyService*)context;

   orderlyService->submitConsumeRequest(request, msgs);

   if (tryLockMQ) {

     orderlyService->lockOneMQ(request->m_messageQueue);

   }

-  if (t) deleteAndZero(t);

+  if (t)

+    deleteAndZero(t);

 }

 

 void ConsumeMessageOrderlyService::ConsumeRequest(PullRequest* request) {

   bool bGetMutex = false;

-  boost::unique_lock<boost::timed_mutex> lock(

-      request->getPullRequestCriticalSection(), boost::try_to_lock);

+  boost::unique_lock<boost::timed_mutex> lock(request->getPullRequestCriticalSection(), boost::try_to_lock);

   if (!lock.owns_lock()) {

-    if (!lock.timed_lock(boost::get_system_time() +

-                         boost::posix_time::seconds(1))) {

-      LOG_ERROR("ConsumeRequest of:%s get timed_mutex timeout",

-                request->m_messageQueue.toString().c_str());

+    if (!lock.timed_lock(boost::get_system_time() + boost::posix_time::seconds(1))) {

+      LOG_ERROR("ConsumeRequest of:%s get timed_mutex timeout", request->m_messageQueue.toString().c_str());

       return;

     } else {

       bGetMutex = true;

@@ -162,14 +148,12 @@
   }

 

   if (m_pMessageListener) {

-    if ((request->isLocked() && !request->isLockExpired()) ||

-        m_pConsumer->getMessageModel() == BROADCASTING) {

+    if ((request->isLocked() && !request->isLockExpired()) || m_pConsumer->getMessageModel() == BROADCASTING) {

       DefaultMQPushConsumer* pConsumer = (DefaultMQPushConsumer*)m_pConsumer;

       uint64_t beginTime = UtilAll::currentTimeMillis();

       bool continueConsume = true;

       while (continueConsume) {

-        if ((UtilAll::currentTimeMillis() - beginTime) >

-            m_MaxTimeConsumeContinuously) {

+        if ((UtilAll::currentTimeMillis() - beginTime) > m_MaxTimeConsumeContinuously) {

           LOG_INFO(

               "continuely consume message queue:%s more than 60s, consume it "

               "later",

@@ -181,15 +165,13 @@
         request->takeMessages(msgs, pConsumer->getConsumeMessageBatchMaxSize());

         if (!msgs.empty()) {

           request->setLastConsumeTimestamp(UtilAll::currentTimeMillis());

-          ConsumeStatus consumeStatus =

-              m_pMessageListener->consumeMessage(msgs);

+          ConsumeStatus consumeStatus = m_pMessageListener->consumeMessage(msgs);

           if (consumeStatus == RECONSUME_LATER) {

             request->makeMessageToCosumeAgain(msgs);

             continueConsume = false;

             tryLockLaterAndReconsume(request, false);

           } else {

-            m_pConsumer->updateConsumeOffset(request->m_messageQueue,

-                                             request->commit());

+            m_pConsumer->updateConsumeOffset(request->m_messageQueue, request->commit());

           }

         } else {

           continueConsume = false;

@@ -200,22 +182,18 @@
           return;

         }

       }

-      LOG_DEBUG("consume once exit of mq:%s",

-                request->m_messageQueue.toString().c_str());

+      LOG_DEBUG("consume once exit of mq:%s", request->m_messageQueue.toString().c_str());

     } else {

-      LOG_ERROR("message queue:%s was not locked",

-                request->m_messageQueue.toString().c_str());

+      LOG_ERROR("message queue:%s was not locked", request->m_messageQueue.toString().c_str());

       tryLockLaterAndReconsume(request, true);

     }

   }

 }

-void ConsumeMessageOrderlyService::tryLockLaterAndReconsume(

-    PullRequest* request, bool tryLockMQ) {

+void ConsumeMessageOrderlyService::tryLockLaterAndReconsume(PullRequest* request, bool tryLockMQ) {

   int retryTimer = tryLockMQ ? 500 : 100;

-  boost::asio::deadline_timer* t = new boost::asio::deadline_timer(

-      m_async_ioService, boost::posix_time::milliseconds(retryTimer));

-  t->async_wait(boost::bind(

-      &(ConsumeMessageOrderlyService::static_submitConsumeRequestLater), this,

-      request, tryLockMQ, t));

+  boost::asio::deadline_timer* t =

+      new boost::asio::deadline_timer(m_async_ioService, boost::posix_time::milliseconds(retryTimer));

+  t->async_wait(

+      boost::bind(&(ConsumeMessageOrderlyService::static_submitConsumeRequestLater), this, request, tryLockMQ, t));

 }

 }

diff --git a/src/consumer/ConsumeMsgService.h b/src/consumer/ConsumeMsgService.h
old mode 100755
new mode 100644
index 5878cb4..2bb7979
--- a/src/consumer/ConsumeMsgService.h
+++ b/src/consumer/ConsumeMsgService.h
@@ -14,7 +14,7 @@
  * See the License for the specific language governing permissions and

  * limitations under the License.

  */

- 

+

 #ifndef _CONSUMEMESSAGESERVICE_H_

 #define _CONSUMEMESSAGESERVICE_H_

 

@@ -38,22 +38,17 @@
   virtual void start() {}

   virtual void shutdown() {}

   virtual void stopThreadPool() {}

-  virtual void submitConsumeRequest(PullRequest* request,

-                                    vector<MQMessageExt>& msgs) {}

-  virtual MessageListenerType getConsumeMsgSerivceListenerType() {

-    return messageListenerDefaultly;

-  }

+  virtual void submitConsumeRequest(PullRequest* request, vector<MQMessageExt>& msgs) {}

+  virtual MessageListenerType getConsumeMsgSerivceListenerType() { return messageListenerDefaultly; }

 };

 

 class ConsumeMessageConcurrentlyService : public ConsumeMsgService {

  public:

-  ConsumeMessageConcurrentlyService(MQConsumer*, int threadCount,

-                                    MQMessageListener* msgListener);

+  ConsumeMessageConcurrentlyService(MQConsumer*, int threadCount, MQMessageListener* msgListener);

   virtual ~ConsumeMessageConcurrentlyService();

   virtual void start();

   virtual void shutdown();

-  virtual void submitConsumeRequest(PullRequest* request,

-                                    vector<MQMessageExt>& msgs);

+  virtual void submitConsumeRequest(PullRequest* request, vector<MQMessageExt>& msgs);

   virtual MessageListenerType getConsumeMsgSerivceListenerType();

   virtual void stopThreadPool();

 

@@ -72,13 +67,11 @@
 

 class ConsumeMessageOrderlyService : public ConsumeMsgService {

  public:

-  ConsumeMessageOrderlyService(MQConsumer*, int threadCount,

-                               MQMessageListener* msgListener);

+  ConsumeMessageOrderlyService(MQConsumer*, int threadCount, MQMessageListener* msgListener);

   virtual ~ConsumeMessageOrderlyService();

   virtual void start();

   virtual void shutdown();

-  virtual void submitConsumeRequest(PullRequest* request,

-                                    vector<MQMessageExt>& msgs);

+  virtual void submitConsumeRequest(PullRequest* request, vector<MQMessageExt>& msgs);

   virtual void stopThreadPool();

   virtual MessageListenerType getConsumeMsgSerivceListenerType();

 

@@ -89,8 +82,7 @@
                                                bool tryLockMQ,

                                                boost::asio::deadline_timer* t);

   void ConsumeRequest(PullRequest* request);

-  void lockMQPeriodically(boost::system::error_code& ec,

-                          boost::asio::deadline_timer* t);

+  void lockMQPeriodically(boost::system::error_code& ec, boost::asio::deadline_timer* t);

   void unlockAllMQ();

   bool lockOneMQ(const MQMessageQueue& mq);

 

diff --git a/src/consumer/DefaultMQPullConsumer.cpp b/src/consumer/DefaultMQPullConsumer.cpp
old mode 100755
new mode 100644
index bfc4e9d..2175feb
--- a/src/consumer/DefaultMQPullConsumer.cpp
+++ b/src/consumer/DefaultMQPullConsumer.cpp
@@ -59,7 +59,7 @@
 #ifndef WIN32
   /* Ignore the SIGPIPE */
   struct sigaction sa;
-  memset(&sa,0, sizeof(struct sigaction));
+  memset(&sa, 0, sizeof(struct sigaction));
   sa.sa_handler = SIG_IGN;
   sa.sa_flags = 0;
   sigaction(SIGPIPE, &sa, 0);
@@ -86,9 +86,7 @@
         m_serviceState = CREATE_JUST;
         THROW_MQEXCEPTION(
             MQClientException,
-            "The cousumer group[" + getGroupName() +
-                "] has been created before, specify another name please.",
-            -1);
+            "The cousumer group[" + getGroupName() + "] has been created before, specify another name please.", -1);
       }
 
       //<!msg model;
@@ -144,26 +142,20 @@
   }
 }
 
-void DefaultMQPullConsumer::sendMessageBack(MQMessageExt& msg, int delayLevel) {
+void DefaultMQPullConsumer::sendMessageBack(MQMessageExt& msg, int delayLevel) {}
 
-}
-
-void DefaultMQPullConsumer::fetchSubscribeMessageQueues(
-    const string& topic, vector<MQMessageQueue>& mqs) {
+void DefaultMQPullConsumer::fetchSubscribeMessageQueues(const string& topic, vector<MQMessageQueue>& mqs) {
   mqs.clear();
   try {
-    getFactory()->fetchSubscribeMessageQueues(topic, mqs,
-                                              getSessionCredentials());
+    getFactory()->fetchSubscribeMessageQueues(topic, mqs, getSessionCredentials());
   } catch (MQException& e) {
     LOG_ERROR(e.what());
   }
 }
 
-void DefaultMQPullConsumer::updateTopicSubscribeInfo(
-    const string& topic, vector<MQMessageQueue>& info) {}
+void DefaultMQPullConsumer::updateTopicSubscribeInfo(const string& topic, vector<MQMessageQueue>& info) {}
 
-void DefaultMQPullConsumer::registerMessageQueueListener(
-    const string& topic, MQueueListener* pListener) {
+void DefaultMQPullConsumer::registerMessageQueueListener(const string& topic, MQueueListener* pListener) {
   m_registerTopics.insert(topic);
   if (pListener) {
     m_pMessageQueueListener = pListener;
@@ -172,36 +164,44 @@
 
 PullResult DefaultMQPullConsumer::pull(const MQMessageQueue& mq,
                                        const string& subExpression,
-                                       int64 offset, int maxNums) {
+                                       int64 offset,
+                                       int maxNums) {
   return pullSyncImpl(mq, subExpression, offset, maxNums, false);
 }
 
 void DefaultMQPullConsumer::pull(const MQMessageQueue& mq,
-                                 const string& subExpression, int64 offset,
-                                 int maxNums, PullCallback* pPullCallback) {
+                                 const string& subExpression,
+                                 int64 offset,
+                                 int maxNums,
+                                 PullCallback* pPullCallback) {
   pullAsyncImpl(mq, subExpression, offset, maxNums, false, pPullCallback);
 }
 
-PullResult DefaultMQPullConsumer::pullBlockIfNotFound(
-    const MQMessageQueue& mq, const string& subExpression, int64 offset,
-    int maxNums) {
+PullResult DefaultMQPullConsumer::pullBlockIfNotFound(const MQMessageQueue& mq,
+                                                      const string& subExpression,
+                                                      int64 offset,
+                                                      int maxNums) {
   return pullSyncImpl(mq, subExpression, offset, maxNums, true);
 }
 
 void DefaultMQPullConsumer::pullBlockIfNotFound(const MQMessageQueue& mq,
                                                 const string& subExpression,
-                                                int64 offset, int maxNums,
+                                                int64 offset,
+                                                int maxNums,
                                                 PullCallback* pPullCallback) {
   pullAsyncImpl(mq, subExpression, offset, maxNums, true, pPullCallback);
 }
 
 PullResult DefaultMQPullConsumer::pullSyncImpl(const MQMessageQueue& mq,
                                                const string& subExpression,
-                                               int64 offset, int maxNums,
+                                               int64 offset,
+                                               int maxNums,
                                                bool block) {
-  if (offset < 0) THROW_MQEXCEPTION(MQClientException, "offset < 0", -1);
+  if (offset < 0)
+    THROW_MQEXCEPTION(MQClientException, "offset < 0", -1);
 
-  if (maxNums <= 0) THROW_MQEXCEPTION(MQClientException, "maxNums <= 0", -1);
+  if (maxNums <= 0)
+    THROW_MQEXCEPTION(MQClientException, "maxNums <= 0", -1);
 
   //<!auto subscript,all sub;
   subscriptionAutomatically(mq.getTopic());
@@ -209,27 +209,24 @@
   int sysFlag = PullSysFlag::buildSysFlag(false, block, true, false);
 
   //<!this sub;
-  unique_ptr<SubscriptionData> pSData(
-      FilterAPI::buildSubscriptionData(mq.getTopic(), subExpression));
+  unique_ptr<SubscriptionData> pSData(FilterAPI::buildSubscriptionData(mq.getTopic(), subExpression));
 
   int timeoutMillis = block ? 1000 * 30 : 1000 * 10;
 
   try {
-    unique_ptr<PullResult> pullResult(
-        m_pPullAPIWrapper->pullKernelImpl(mq,                      // 1
-                                          pSData->getSubString(),  // 2
-                                          0L,                      // 3
-                                          offset,                  // 4
-                                          maxNums,                 // 5
-                                          sysFlag,                 // 6
-                                          0,                       // 7
-                                          1000 * 20,               // 8
-                                          timeoutMillis,           // 9
-                                          ComMode_SYNC,            // 10
-                                          NULL,                    //<!callback;
-                                          getSessionCredentials(), NULL));
-    return m_pPullAPIWrapper->processPullResult(mq, pullResult.get(),
-                                                pSData.get());
+    unique_ptr<PullResult> pullResult(m_pPullAPIWrapper->pullKernelImpl(mq,                      // 1
+                                                                        pSData->getSubString(),  // 2
+                                                                        0L,                      // 3
+                                                                        offset,                  // 4
+                                                                        maxNums,                 // 5
+                                                                        sysFlag,                 // 6
+                                                                        0,                       // 7
+                                                                        1000 * 20,               // 8
+                                                                        timeoutMillis,           // 9
+                                                                        ComMode_SYNC,            // 10
+                                                                        NULL,                    //<!callback;
+                                                                        getSessionCredentials(), NULL));
+    return m_pPullAPIWrapper->processPullResult(mq, pullResult.get(), pSData.get());
   } catch (MQException& e) {
     LOG_ERROR(e.what());
   }
@@ -238,11 +235,15 @@
 
 void DefaultMQPullConsumer::pullAsyncImpl(const MQMessageQueue& mq,
                                           const string& subExpression,
-                                          int64 offset, int maxNums, bool block,
+                                          int64 offset,
+                                          int maxNums,
+                                          bool block,
                                           PullCallback* pPullCallback) {
-  if (offset < 0) THROW_MQEXCEPTION(MQClientException, "offset < 0", -1);
+  if (offset < 0)
+    THROW_MQEXCEPTION(MQClientException, "offset < 0", -1);
 
-  if (maxNums <= 0) THROW_MQEXCEPTION(MQClientException, "maxNums <= 0", -1);
+  if (maxNums <= 0)
+    THROW_MQEXCEPTION(MQClientException, "maxNums <= 0", -1);
 
   if (!pPullCallback)
     THROW_MQEXCEPTION(MQClientException, "pPullCallback is null", -1);
@@ -253,8 +254,7 @@
   int sysFlag = PullSysFlag::buildSysFlag(false, block, true, false);
 
   //<!this sub;
-  unique_ptr<SubscriptionData> pSData(
-      FilterAPI::buildSubscriptionData(mq.getTopic(), subExpression));
+  unique_ptr<SubscriptionData> pSData(FilterAPI::buildSubscriptionData(mq.getTopic(), subExpression));
 
   int timeoutMillis = block ? 1000 * 30 : 1000 * 10;
 
@@ -263,21 +263,19 @@
   arg.mq = mq;
   arg.subData = *pSData;
   arg.pPullWrapper = m_pPullAPIWrapper;
-  arg.pPullRequest = NULL;
 
   try {
-    unique_ptr<PullResult> pullResult(m_pPullAPIWrapper->pullKernelImpl(
-        mq,                      // 1
-        pSData->getSubString(),  // 2
-        0L,                      // 3
-        offset,                  // 4
-        maxNums,                 // 5
-        sysFlag,                 // 6
-        0,                       // 7
-        1000 * 20,               // 8
-        timeoutMillis,           // 9
-        ComMode_ASYNC,           // 10
-        pPullCallback, getSessionCredentials(), &arg));
+    unique_ptr<PullResult> pullResult(m_pPullAPIWrapper->pullKernelImpl(mq,                      // 1
+                                                                        pSData->getSubString(),  // 2
+                                                                        0L,                      // 3
+                                                                        offset,                  // 4
+                                                                        maxNums,                 // 5
+                                                                        sysFlag,                 // 6
+                                                                        0,                       // 7
+                                                                        1000 * 20,               // 8
+                                                                        timeoutMillis,           // 9
+                                                                        ComMode_ASYNC,           // 10
+                                                                        pPullCallback, getSessionCredentials(), &arg));
   } catch (MQException& e) {
     LOG_ERROR(e.what());
   }
@@ -286,14 +284,12 @@
 void DefaultMQPullConsumer::subscriptionAutomatically(const string& topic) {
   SubscriptionData* pSdata = m_pRebalance->getSubscriptionData(topic);
   if (pSdata == NULL) {
-    unique_ptr<SubscriptionData> subscriptionData(
-        FilterAPI::buildSubscriptionData(topic, SUB_ALL));
+    unique_ptr<SubscriptionData> subscriptionData(FilterAPI::buildSubscriptionData(topic, SUB_ALL));
     m_pRebalance->setSubscriptionData(topic, subscriptionData.release());
   }
 }
 
-void DefaultMQPullConsumer::updateConsumeOffset(const MQMessageQueue& mq,
-                                                int64 offset) {
+void DefaultMQPullConsumer::updateConsumeOffset(const MQMessageQueue& mq, int64 offset) {
   m_pOffsetStore->updateOffset(mq, offset);
 }
 
@@ -301,11 +297,8 @@
   m_pOffsetStore->removeOffset(mq);
 }
 
-int64 DefaultMQPullConsumer::fetchConsumeOffset(const MQMessageQueue& mq,
-                                                bool fromStore) {
-  return m_pOffsetStore->readOffset(
-      mq, fromStore ? READ_FROM_STORE : MEMORY_FIRST_THEN_STORE,
-      getSessionCredentials());
+int64 DefaultMQPullConsumer::fetchConsumeOffset(const MQMessageQueue& mq, bool fromStore) {
+  return m_pOffsetStore->readOffset(mq, fromStore ? READ_FROM_STORE : MEMORY_FIRST_THEN_STORE, getSessionCredentials());
 }
 
 void DefaultMQPullConsumer::persistConsumerOffset() {
@@ -327,15 +320,13 @@
 
 void DefaultMQPullConsumer::persistConsumerOffsetByResetOffset() {}
 
-void DefaultMQPullConsumer::persistConsumerOffset4PullConsumer(
-    const MQMessageQueue& mq) {
+void DefaultMQPullConsumer::persistConsumerOffset4PullConsumer(const MQMessageQueue& mq) {
   if (isServiceStateOk()) {
     m_pOffsetStore->persist(mq, getSessionCredentials());
   }
 }
 
-void DefaultMQPullConsumer::fetchMessageQueuesInBalance(
-    const string& topic, vector<MQMessageQueue> mqs) {}
+void DefaultMQPullConsumer::fetchMessageQueuesInBalance(const string& topic, vector<MQMessageQueue> mqs) {}
 
 void DefaultMQPullConsumer::checkConfig() {
   string groupname = getGroupName();
@@ -344,8 +335,7 @@
 
   // consumerGroup
   if (!groupname.compare(DEFAULT_CONSUMER_GROUP)) {
-    THROW_MQEXCEPTION(MQClientException,
-                      "consumerGroup can not equal DEFAULT_CONSUMER", -1);
+    THROW_MQEXCEPTION(MQClientException, "consumerGroup can not equal DEFAULT_CONSUMER", -1);
   }
 
   if (getMessageModel() != BROADCASTING && getMessageModel() != CLUSTERING) {
@@ -358,13 +348,14 @@
 void DefaultMQPullConsumer::copySubscription() {
   set<string>::iterator it = m_registerTopics.begin();
   for (; it != m_registerTopics.end(); ++it) {
-    unique_ptr<SubscriptionData> subscriptionData(
-        FilterAPI::buildSubscriptionData((*it), SUB_ALL));
+    unique_ptr<SubscriptionData> subscriptionData(FilterAPI::buildSubscriptionData((*it), SUB_ALL));
     m_pRebalance->setSubscriptionData((*it), subscriptionData.release());
   }
 }
 
-ConsumeType DefaultMQPullConsumer::getConsumeType() { return CONSUME_ACTIVELY; }
+ConsumeType DefaultMQPullConsumer::getConsumeType() {
+  return CONSUME_ACTIVELY;
+}
 
 ConsumeFromWhere DefaultMQPullConsumer::getConsumeFromWhere() {
   return CONSUME_FROM_LAST_OFFSET;
@@ -380,7 +371,9 @@
 
 void DefaultMQPullConsumer::producePullMsgTask(PullRequest*) {}
 
-Rebalance* DefaultMQPullConsumer::getRebalance() const { return NULL; }
+Rebalance* DefaultMQPullConsumer::getRebalance() const {
+  return NULL;
+}
 
 //<!************************************************************************
 }  //<!end namespace;
diff --git a/src/consumer/DefaultMQPushConsumer.cpp b/src/consumer/DefaultMQPushConsumer.cpp
index 11e16ed..0f51ea1 100644
--- a/src/consumer/DefaultMQPushConsumer.cpp
+++ b/src/consumer/DefaultMQPushConsumer.cpp
@@ -35,932 +35,865 @@
 
 namespace rocketmq {
 
-    class AsyncPullCallback : public PullCallback {
-    public:
-        AsyncPullCallback(DefaultMQPushConsumer *pushConsumer, PullRequest *request)
-                : m_callbackOwner(pushConsumer),
-                  m_pullRequest(request),
-                  m_bShutdown(false) {}
+class AsyncPullCallback : public PullCallback {
+ public:
+  AsyncPullCallback(DefaultMQPushConsumer* pushConsumer, PullRequest* request)
+      : m_callbackOwner(pushConsumer), m_pullRequest(request), m_bShutdown(false) {}
 
-        virtual ~AsyncPullCallback() {
-            m_callbackOwner = NULL;
-            m_pullRequest = NULL;
-        }
+  virtual ~AsyncPullCallback() {
+    m_callbackOwner = NULL;
+    m_pullRequest = NULL;
+  }
 
-        virtual void onSuccess(MQMessageQueue &mq, PullResult &result,
-                               bool bProducePullRequest) {
-            if (m_bShutdown == true) {
-                LOG_INFO("pullrequest for:%s in shutdown, return",
-                         (m_pullRequest->m_messageQueue).toString().c_str());
-                m_pullRequest->removePullMsgEvent();
-                return;
-            }
+  virtual void onSuccess(MQMessageQueue& mq, PullResult& result, bool bProducePullRequest) {
+    if (m_bShutdown == true) {
+      LOG_INFO("pullrequest for:%s in shutdown, return", (m_pullRequest->m_messageQueue).toString().c_str());
+      m_pullRequest->removePullMsgEvent();
+      return;
+    }
 
-            switch (result.pullStatus) {
-                case FOUND: {
-                    if (!m_pullRequest->isDroped())  // if request is setted to dropped,
-                        // don't add msgFoundList to
-                        // m_msgTreeMap and don't call
-                        // producePullMsgTask
-                    {  // avoid issue: pullMsg is sent out, rebalance is doing concurrently
-                        // and this request is dropped, and then received pulled msgs.
-                        m_pullRequest->setNextOffset(result.nextBeginOffset);
-                        m_pullRequest->putMessage(result.msgFoundList);
+    switch (result.pullStatus) {
+      case FOUND: {
+        if (!m_pullRequest->isDroped())  // if request is setted to dropped,
+                                         // don't add msgFoundList to
+                                         // m_msgTreeMap and don't call
+                                         // producePullMsgTask
+        {                                // avoid issue: pullMsg is sent out, rebalance is doing concurrently
+          // and this request is dropped, and then received pulled msgs.
+          m_pullRequest->setNextOffset(result.nextBeginOffset);
+          m_pullRequest->putMessage(result.msgFoundList);
 
-                        m_callbackOwner->getConsumerMsgService()->submitConsumeRequest(
-                                m_pullRequest, result.msgFoundList);
+          m_callbackOwner->getConsumerMsgService()->submitConsumeRequest(m_pullRequest, result.msgFoundList);
 
-                        if (bProducePullRequest)
-                            m_callbackOwner->producePullMsgTask(m_pullRequest);
-                        else
-                            m_pullRequest->removePullMsgEvent();
-
-                        LOG_DEBUG("FOUND:%s with size:"
-                                          SIZET_FMT
-                                          ", nextBeginOffset:%lld",
-                                  (m_pullRequest->m_messageQueue).toString().c_str(),
-                                  result.msgFoundList.size(), result.nextBeginOffset);
-                    } else {
-                        LOG_INFO("remove pullmsg event of mq:%s",
-                                 (m_pullRequest->m_messageQueue).toString().c_str());
-                        m_pullRequest->removePullMsgEvent();
-                    }
-                    break;
-                }
-                case NO_NEW_MSG: {
-                    m_pullRequest->setNextOffset(result.nextBeginOffset);
-
-                    vector<MQMessageExt> msgs;
-                    m_pullRequest->getMessage(msgs);
-                    if ((msgs.size() == 0) && (result.nextBeginOffset > 0)) {
-                        /*if broker losted/cleared msgs of one msgQueue, but the brokerOffset
-                        is kept, then consumer will enter following situation:
-                        1>. get pull offset with 0 when do rebalance, and set
-                        m_offsetTable[mq] to 0;
-                        2>. NO_NEW_MSG or NO_MATCHED_MSG got when pullMessage, and nextBegin
-                        offset increase by 800
-                        3>. request->getMessage(msgs) always NULL
-                        4>. we need update consumerOffset to nextBeginOffset indicated by
-                        broker
-                        but if really no new msg could be pulled, also go to this CASE
-
-                        LOG_INFO("maybe misMatch between broker and client happens, update
-                        consumerOffset to nextBeginOffset indicated by broker");*/
-                        m_callbackOwner->updateConsumeOffset(m_pullRequest->m_messageQueue,
-                                                             result.nextBeginOffset);
-                    }
-                    if (bProducePullRequest)
-                        m_callbackOwner->producePullMsgTask(m_pullRequest);
-                    else
-                        m_pullRequest->removePullMsgEvent();
-
-                    /*LOG_INFO("NO_NEW_MSG:%s,nextBeginOffset:%lld",
-                             (m_pullRequest->m_messageQueue).toString().c_str(),
-                             result.nextBeginOffset);*/
-                    break;
-                }
-                case NO_MATCHED_MSG: {
-                    m_pullRequest->setNextOffset(result.nextBeginOffset);
-
-                    vector<MQMessageExt> msgs;
-                    m_pullRequest->getMessage(msgs);
-                    if ((msgs.size() == 0) && (result.nextBeginOffset > 0)) {
-                        /*if broker losted/cleared msgs of one msgQueue, but the brokerOffset
-                        is kept, then consumer will enter following situation:
-                        1>. get pull offset with 0 when do rebalance, and set
-                        m_offsetTable[mq] to 0;
-                        2>. NO_NEW_MSG or NO_MATCHED_MSG got when pullMessage, and nextBegin
-                        offset increase by 800
-                        3>. request->getMessage(msgs) always NULL
-                        4>. we need update consumerOffset to nextBeginOffset indicated by
-                        broker
-                        but if really no new msg could be pulled, also go to this CASE
-
-                        LOG_INFO("maybe misMatch between broker and client happens, update
-                        consumerOffset to nextBeginOffset indicated by broker");*/
-                        m_callbackOwner->updateConsumeOffset(m_pullRequest->m_messageQueue,
-                                                             result.nextBeginOffset);
-                    }
-                    if (bProducePullRequest)
-                        m_callbackOwner->producePullMsgTask(m_pullRequest);
-                    else
-                        m_pullRequest->removePullMsgEvent();
-                    /*LOG_INFO("NO_MATCHED_MSG:%s,nextBeginOffset:%lld",
-                             (m_pullRequest->m_messageQueue).toString().c_str(),
-                             result.nextBeginOffset);*/
-                    break;
-                }
-                case OFFSET_ILLEGAL: {
-                    m_pullRequest->setNextOffset(result.nextBeginOffset);
-                    if (bProducePullRequest)
-                        m_callbackOwner->producePullMsgTask(m_pullRequest);
-                    else
-                        m_pullRequest->removePullMsgEvent();
-
-                    /*LOG_INFO("OFFSET_ILLEGAL:%s,nextBeginOffset:%lld",
-                             (m_pullRequest->m_messageQueue).toString().c_str(),
-                             result.nextBeginOffset);*/
-                    break;
-                }
-                case BROKER_TIMEOUT: {  // as BROKER_TIMEOUT is defined by client, broker
-                    // will not returns this status, so this case
-                    // could not be entered.
-                    LOG_ERROR("impossible BROKER_TIMEOUT Occurs");
-                    m_pullRequest->setNextOffset(result.nextBeginOffset);
-                    if (bProducePullRequest)
-                        m_callbackOwner->producePullMsgTask(m_pullRequest);
-                    else
-                        m_pullRequest->removePullMsgEvent();
-                    break;
-                }
-            }
-        }
-
-        virtual void onException(MQException &e) {
-            if (m_bShutdown == true) {
-                LOG_INFO("pullrequest for:%s in shutdown, return",
-                         (m_pullRequest->m_messageQueue).toString().c_str());
-                m_pullRequest->removePullMsgEvent();
-                return;
-            }
-            LOG_WARN("pullrequest for:%s occurs exception, reproduce it",
-                     (m_pullRequest->m_messageQueue).toString().c_str());
+          if (bProducePullRequest)
             m_callbackOwner->producePullMsgTask(m_pullRequest);
+          else
+            m_pullRequest->removePullMsgEvent();
+
+          LOG_DEBUG("FOUND:%s with size:" SIZET_FMT ", nextBeginOffset:%lld",
+                    (m_pullRequest->m_messageQueue).toString().c_str(), result.msgFoundList.size(),
+                    result.nextBeginOffset);
+        } else {
+          LOG_INFO("remove pullmsg event of mq:%s", (m_pullRequest->m_messageQueue).toString().c_str());
+          m_pullRequest->removePullMsgEvent();
         }
+        break;
+      }
+      case NO_NEW_MSG: {
+        m_pullRequest->setNextOffset(result.nextBeginOffset);
 
-        void setShutdownStatus() { m_bShutdown = true; }
+        vector<MQMessageExt> msgs;
+        m_pullRequest->getMessage(msgs);
+        if ((msgs.size() == 0) && (result.nextBeginOffset > 0)) {
+          /*if broker losted/cleared msgs of one msgQueue, but the brokerOffset
+          is kept, then consumer will enter following situation:
+          1>. get pull offset with 0 when do rebalance, and set
+          m_offsetTable[mq] to 0;
+          2>. NO_NEW_MSG or NO_MATCHED_MSG got when pullMessage, and nextBegin
+          offset increase by 800
+          3>. request->getMessage(msgs) always NULL
+          4>. we need update consumerOffset to nextBeginOffset indicated by
+          broker
+          but if really no new msg could be pulled, also go to this CASE
 
-    private:
-        DefaultMQPushConsumer *m_callbackOwner;
-        PullRequest *m_pullRequest;
-        bool m_bShutdown;
-    };
+          LOG_INFO("maybe misMatch between broker and client happens, update
+          consumerOffset to nextBeginOffset indicated by broker");*/
+          m_callbackOwner->updateConsumeOffset(m_pullRequest->m_messageQueue, result.nextBeginOffset);
+        }
+        if (bProducePullRequest)
+          m_callbackOwner->producePullMsgTask(m_pullRequest);
+        else
+          m_pullRequest->removePullMsgEvent();
+
+        /*LOG_INFO("NO_NEW_MSG:%s,nextBeginOffset:%lld",
+                 (m_pullRequest->m_messageQueue).toString().c_str(),
+                 result.nextBeginOffset);*/
+        break;
+      }
+      case NO_MATCHED_MSG: {
+        m_pullRequest->setNextOffset(result.nextBeginOffset);
+
+        vector<MQMessageExt> msgs;
+        m_pullRequest->getMessage(msgs);
+        if ((msgs.size() == 0) && (result.nextBeginOffset > 0)) {
+          /*if broker losted/cleared msgs of one msgQueue, but the brokerOffset
+          is kept, then consumer will enter following situation:
+          1>. get pull offset with 0 when do rebalance, and set
+          m_offsetTable[mq] to 0;
+          2>. NO_NEW_MSG or NO_MATCHED_MSG got when pullMessage, and nextBegin
+          offset increase by 800
+          3>. request->getMessage(msgs) always NULL
+          4>. we need update consumerOffset to nextBeginOffset indicated by
+          broker
+          but if really no new msg could be pulled, also go to this CASE
+
+          LOG_INFO("maybe misMatch between broker and client happens, update
+          consumerOffset to nextBeginOffset indicated by broker");*/
+          m_callbackOwner->updateConsumeOffset(m_pullRequest->m_messageQueue, result.nextBeginOffset);
+        }
+        if (bProducePullRequest)
+          m_callbackOwner->producePullMsgTask(m_pullRequest);
+        else
+          m_pullRequest->removePullMsgEvent();
+        /*LOG_INFO("NO_MATCHED_MSG:%s,nextBeginOffset:%lld",
+                 (m_pullRequest->m_messageQueue).toString().c_str(),
+                 result.nextBeginOffset);*/
+        break;
+      }
+      case OFFSET_ILLEGAL: {
+        m_pullRequest->setNextOffset(result.nextBeginOffset);
+        if (bProducePullRequest)
+          m_callbackOwner->producePullMsgTask(m_pullRequest);
+        else
+          m_pullRequest->removePullMsgEvent();
+
+        /*LOG_INFO("OFFSET_ILLEGAL:%s,nextBeginOffset:%lld",
+                 (m_pullRequest->m_messageQueue).toString().c_str(),
+                 result.nextBeginOffset);*/
+        break;
+      }
+      case BROKER_TIMEOUT: {  // as BROKER_TIMEOUT is defined by client, broker
+        // will not returns this status, so this case
+        // could not be entered.
+        LOG_ERROR("impossible BROKER_TIMEOUT Occurs");
+        m_pullRequest->setNextOffset(result.nextBeginOffset);
+        if (bProducePullRequest)
+          m_callbackOwner->producePullMsgTask(m_pullRequest);
+        else
+          m_pullRequest->removePullMsgEvent();
+        break;
+      }
+    }
+  }
+
+  virtual void onException(MQException& e) {
+    if (m_bShutdown == true) {
+      LOG_INFO("pullrequest for:%s in shutdown, return", (m_pullRequest->m_messageQueue).toString().c_str());
+      m_pullRequest->removePullMsgEvent();
+      return;
+    }
+    LOG_WARN("pullrequest for:%s occurs exception, reproduce it", (m_pullRequest->m_messageQueue).toString().c_str());
+    m_callbackOwner->producePullMsgTask(m_pullRequest);
+  }
+
+  void setShutdownStatus() { m_bShutdown = true; }
+
+ private:
+  DefaultMQPushConsumer* m_callbackOwner;
+  PullRequest* m_pullRequest;
+  bool m_bShutdown;
+};
 
 //<!***************************************************************************
-    static boost::mutex m_asyncCallbackLock;
+static boost::mutex m_asyncCallbackLock;
 
-    DefaultMQPushConsumer::DefaultMQPushConsumer(const string &groupname)
-            : m_consumeFromWhere(CONSUME_FROM_LAST_OFFSET),
-              m_pOffsetStore(NULL),
-              m_pRebalance(NULL),
-              m_pPullAPIWrapper(NULL),
-              m_consumerService(NULL),
-              m_pMessageListener(NULL),
-              m_consumeMessageBatchMaxSize(1),
-              m_maxMsgCacheSize(1000),
-              m_pullmsgQueue(NULL) {
-        //<!set default group name;
-        string gname = groupname.empty() ? DEFAULT_CONSUMER_GROUP : groupname;
-        setGroupName(gname);
-        m_asyncPull = true;
-        m_asyncPullTimeout = 30 * 1000;
-        setMessageModel(CLUSTERING);
+DefaultMQPushConsumer::DefaultMQPushConsumer(const string& groupname)
+    : m_consumeFromWhere(CONSUME_FROM_LAST_OFFSET),
+      m_pOffsetStore(NULL),
+      m_pRebalance(NULL),
+      m_pPullAPIWrapper(NULL),
+      m_consumerService(NULL),
+      m_pMessageListener(NULL),
+      m_consumeMessageBatchMaxSize(1),
+      m_maxMsgCacheSize(1000),
+      m_pullmsgQueue(NULL) {
+  //<!set default group name;
+  string gname = groupname.empty() ? DEFAULT_CONSUMER_GROUP : groupname;
+  setGroupName(gname);
+  m_asyncPull = true;
+  m_asyncPullTimeout = 30 * 1000;
+  setMessageModel(CLUSTERING);
 
-        m_startTime = UtilAll::currentTimeMillis();
-        m_consumeThreadCount = boost::thread::hardware_concurrency();
-        m_pullMsgThreadPoolNum = boost::thread::hardware_concurrency();
-        m_async_service_thread.reset(new boost::thread(
-                boost::bind(&DefaultMQPushConsumer::boost_asio_work, this)));
+  m_startTime = UtilAll::currentTimeMillis();
+  m_consumeThreadCount = boost::thread::hardware_concurrency();
+  m_pullMsgThreadPoolNum = boost::thread::hardware_concurrency();
+  m_async_service_thread.reset(new boost::thread(boost::bind(&DefaultMQPushConsumer::boost_asio_work, this)));
+}
+
+void DefaultMQPushConsumer::boost_asio_work() {
+  LOG_INFO("DefaultMQPushConsumer::boost asio async service runing");
+  boost::asio::io_service::work work(m_async_ioService);  // avoid async io
+  // service stops after
+  // first timer timeout
+  // callback
+  m_async_ioService.run();
+}
+
+DefaultMQPushConsumer::~DefaultMQPushConsumer() {
+  m_pMessageListener = NULL;
+  if (m_pullmsgQueue != NULL) {
+    deleteAndZero(m_pullmsgQueue);
+  }
+  if (m_pRebalance != NULL) {
+    deleteAndZero(m_pRebalance);
+  }
+  if (m_pOffsetStore != NULL) {
+    deleteAndZero(m_pOffsetStore);
+  }
+  if (m_pPullAPIWrapper != NULL) {
+    deleteAndZero(m_pPullAPIWrapper);
+  }
+  if (m_consumerService != NULL) {
+    deleteAndZero(m_consumerService);
+  }
+  PullMAP::iterator it = m_PullCallback.begin();
+  for (; it != m_PullCallback.end(); ++it) {
+    deleteAndZero(it->second);
+  }
+  m_PullCallback.clear();
+  m_subTopics.clear();
+}
+
+void DefaultMQPushConsumer::sendMessageBack(MQMessageExt& msg, int delayLevel) {
+  try {
+    getFactory()->getMQClientAPIImpl()->consumerSendMessageBack(msg, getGroupName(), delayLevel, 3000,
+                                                                getSessionCredentials());
+  } catch (MQException& e) {
+    LOG_ERROR(e.what());
+  }
+}
+
+void DefaultMQPushConsumer::fetchSubscribeMessageQueues(const string& topic, vector<MQMessageQueue>& mqs) {
+  mqs.clear();
+  try {
+    getFactory()->fetchSubscribeMessageQueues(topic, mqs, getSessionCredentials());
+  } catch (MQException& e) {
+    LOG_ERROR(e.what());
+  }
+}
+
+void DefaultMQPushConsumer::doRebalance() {
+  if (isServiceStateOk()) {
+    try {
+      m_pRebalance->doRebalance();
+    } catch (MQException& e) {
+      LOG_ERROR(e.what());
     }
+  }
+}
 
-    void DefaultMQPushConsumer::boost_asio_work() {
-        LOG_INFO("DefaultMQPushConsumer::boost asio async service runing");
-        boost::asio::io_service::work work(m_async_ioService);  // avoid async io
-        // service stops after
-        // first timer timeout
-        // callback
-        m_async_ioService.run();
-    }
+void DefaultMQPushConsumer::persistConsumerOffset() {
+  if (isServiceStateOk()) {
+    m_pRebalance->persistConsumerOffset();
+  }
+}
 
-    DefaultMQPushConsumer::~DefaultMQPushConsumer() {
-        m_pMessageListener = NULL;
-        if (m_pullmsgQueue != NULL) {
-            deleteAndZero(m_pullmsgQueue);
-        }
-        if (m_pRebalance != NULL) {
-            deleteAndZero(m_pRebalance);
-        }
-        if (m_pOffsetStore != NULL) {
-            deleteAndZero(m_pOffsetStore);
-        }
-        if (m_pPullAPIWrapper != NULL) {
-            deleteAndZero(m_pPullAPIWrapper);
-        }
-        if (m_consumerService != NULL) {
-            deleteAndZero(m_consumerService);
-        }
-        PullMAP::iterator it = m_PullCallback.begin();
-        for (; it != m_PullCallback.end(); ++it) {
-            deleteAndZero(it->second);
-        }
-        m_PullCallback.clear();
-        m_subTopics.clear();
-    }
+void DefaultMQPushConsumer::persistConsumerOffsetByResetOffset() {
+  if (isServiceStateOk()) {
+    m_pRebalance->persistConsumerOffsetByResetOffset();
+  }
+}
 
-    void DefaultMQPushConsumer::sendMessageBack(MQMessageExt &msg, int delayLevel) {
-        try {
-            getFactory()->getMQClientAPIImpl()->consumerSendMessageBack(
-                    msg, getGroupName(), delayLevel, 3000, getSessionCredentials());
-        } catch (MQException &e) {
-            LOG_ERROR(e.what());
-        }
-    }
-
-    void DefaultMQPushConsumer::fetchSubscribeMessageQueues(
-            const string &topic, vector<MQMessageQueue> &mqs) {
-        mqs.clear();
-        try {
-            getFactory()->fetchSubscribeMessageQueues(topic, mqs,
-                                                      getSessionCredentials());
-        } catch (MQException &e) {
-            LOG_ERROR(e.what());
-        }
-    }
-
-    void DefaultMQPushConsumer::doRebalance() {
-        if (isServiceStateOk()) {
-            try {
-                m_pRebalance->doRebalance();
-            } catch (MQException &e) {
-                LOG_ERROR(e.what());
-            }
-        }
-    }
-
-    void DefaultMQPushConsumer::persistConsumerOffset() {
-        if (isServiceStateOk()) {
-            m_pRebalance->persistConsumerOffset();
-        }
-    }
-
-    void DefaultMQPushConsumer::persistConsumerOffsetByResetOffset() {
-        if (isServiceStateOk()) {
-            m_pRebalance->persistConsumerOffsetByResetOffset();
-        }
-    }
-
-    void DefaultMQPushConsumer::start() {
+void DefaultMQPushConsumer::start() {
 #ifndef WIN32
-        /* Ignore the SIGPIPE */
-        struct sigaction sa;
-        memset(&sa,0, sizeof(struct sigaction));
-        sa.sa_handler = SIG_IGN;
-        sa.sa_flags = 0;
-        sigaction(SIGPIPE, &sa, 0);
+  /* Ignore the SIGPIPE */
+  struct sigaction sa;
+  memset(&sa, 0, sizeof(struct sigaction));
+  sa.sa_handler = SIG_IGN;
+  sa.sa_flags = 0;
+  sigaction(SIGPIPE, &sa, 0);
 #endif
-        switch (m_serviceState) {
-            case CREATE_JUST: {
-                m_serviceState = START_FAILED;
-                MQClient::start();
-                LOG_INFO("DefaultMQPushConsumer:%s start", m_GroupName.c_str());
+  switch (m_serviceState) {
+    case CREATE_JUST: {
+      m_serviceState = START_FAILED;
+      MQClient::start();
+      LOG_INFO("DefaultMQPushConsumer:%s start", m_GroupName.c_str());
 
-                //<!data;
-                checkConfig();
+      //<!data;
+      checkConfig();
 
-                //<!create rebalance;
-                m_pRebalance = new RebalancePush(this, getFactory());
+      //<!create rebalance;
+      m_pRebalance = new RebalancePush(this, getFactory());
 
-                string groupname = getGroupName();
-                m_pPullAPIWrapper = new PullAPIWrapper(getFactory(), groupname);
+      string groupname = getGroupName();
+      m_pPullAPIWrapper = new PullAPIWrapper(getFactory(), groupname);
 
-                if (m_pMessageListener) {
-                    if (m_pMessageListener->getMessageListenerType() ==
-                        messageListenerOrderly) {
-                        LOG_INFO("start orderly consume service:%s", getGroupName().c_str());
-                        m_consumerService = new ConsumeMessageOrderlyService(
-                                this, m_consumeThreadCount, m_pMessageListener);
-                    } else  // for backward compatible, defaultly and concurrently listeners
-                        // are allocating ConsumeMessageConcurrentlyService
-                    {
-                        LOG_INFO("start concurrently consume service:%s",
-                                 getGroupName().c_str());
-                        m_consumerService = new ConsumeMessageConcurrentlyService(
-                                this, m_consumeThreadCount, m_pMessageListener);
-                    }
-                }
-
-                m_pullmsgQueue = new TaskQueue(m_pullMsgThreadPoolNum);
-                m_pullmsgThread.reset(new boost::thread(boost::bind(
-                        &DefaultMQPushConsumer::runPullMsgQueue, this, m_pullmsgQueue)));
-
-                copySubscription();
-
-                //<! registe;
-                bool registerOK = getFactory()->registerConsumer(this);
-                if (!registerOK) {
-                    m_serviceState = CREATE_JUST;
-                    THROW_MQEXCEPTION(
-                            MQClientException,
-                            "The cousumer group[" + getGroupName() +
-                            "] has been created before, specify another name please.",
-                            -1);
-                }
-
-                //<!msg model;
-                switch (getMessageModel()) {
-                    case BROADCASTING:
-                        m_pOffsetStore = new LocalFileOffsetStore(groupname, getFactory());
-                        break;
-                    case CLUSTERING:
-                        m_pOffsetStore = new RemoteBrokerOffsetStore(groupname, getFactory());
-                        break;
-                }
-                bool bStartFailed = false;
-                string errorMsg;
-                try {
-                    m_pOffsetStore->load();
-                } catch (MQClientException &e) {
-                    bStartFailed = true;
-                    errorMsg = std::string(e.what());
-                }
-                m_consumerService->start();
-
-                getFactory()->start();
-
-                updateTopicSubscribeInfoWhenSubscriptionChanged();
-                getFactory()->sendHeartbeatToAllBroker();
-
-                m_serviceState = RUNNING;
-                if (bStartFailed) {
-                    shutdown();
-                    THROW_MQEXCEPTION(MQClientException, errorMsg, -1);
-                }
-                break;
-            }
-            case RUNNING:
-            case START_FAILED:
-            case SHUTDOWN_ALREADY:
-                break;
-            default:
-                break;
+      if (m_pMessageListener) {
+        if (m_pMessageListener->getMessageListenerType() == messageListenerOrderly) {
+          LOG_INFO("start orderly consume service:%s", getGroupName().c_str());
+          m_consumerService = new ConsumeMessageOrderlyService(this, m_consumeThreadCount, m_pMessageListener);
+        } else  // for backward compatible, defaultly and concurrently listeners
+                // are allocating ConsumeMessageConcurrentlyService
+        {
+          LOG_INFO("start concurrently consume service:%s", getGroupName().c_str());
+          m_consumerService = new ConsumeMessageConcurrentlyService(this, m_consumeThreadCount, m_pMessageListener);
         }
+      }
 
-        getFactory()->rebalanceImmediately();
+      m_pullmsgQueue = new TaskQueue(m_pullMsgThreadPoolNum);
+      m_pullmsgThread.reset(
+          new boost::thread(boost::bind(&DefaultMQPushConsumer::runPullMsgQueue, this, m_pullmsgQueue)));
+
+      copySubscription();
+
+      //<! registe;
+      bool registerOK = getFactory()->registerConsumer(this);
+      if (!registerOK) {
+        m_serviceState = CREATE_JUST;
+        THROW_MQEXCEPTION(
+            MQClientException,
+            "The cousumer group[" + getGroupName() + "] has been created before, specify another name please.", -1);
+      }
+
+      //<!msg model;
+      switch (getMessageModel()) {
+        case BROADCASTING:
+          m_pOffsetStore = new LocalFileOffsetStore(groupname, getFactory());
+          break;
+        case CLUSTERING:
+          m_pOffsetStore = new RemoteBrokerOffsetStore(groupname, getFactory());
+          break;
+      }
+      bool bStartFailed = false;
+      string errorMsg;
+      try {
+        m_pOffsetStore->load();
+      } catch (MQClientException& e) {
+        bStartFailed = true;
+        errorMsg = std::string(e.what());
+      }
+      m_consumerService->start();
+
+      getFactory()->start();
+
+      updateTopicSubscribeInfoWhenSubscriptionChanged();
+      getFactory()->sendHeartbeatToAllBroker();
+
+      m_serviceState = RUNNING;
+      if (bStartFailed) {
+        shutdown();
+        THROW_MQEXCEPTION(MQClientException, errorMsg, -1);
+      }
+      break;
     }
+    case RUNNING:
+    case START_FAILED:
+    case SHUTDOWN_ALREADY:
+      break;
+    default:
+      break;
+  }
 
-    void DefaultMQPushConsumer::shutdown() {
-        switch (m_serviceState) {
-            case RUNNING: {
-                LOG_INFO("DefaultMQPushConsumer shutdown");
-                m_async_ioService.stop();
-                m_async_service_thread->interrupt();
-                m_async_service_thread->join();
-                m_pullmsgQueue->close();
-                m_pullmsgThread->interrupt();
-                m_pullmsgThread->join();
-                m_consumerService->shutdown();
-                persistConsumerOffset();
-                shutdownAsyncPullCallBack();  // delete aync pullMsg resources
-                getFactory()->unregisterConsumer(this);
-                getFactory()->shutdown();
-                m_serviceState = SHUTDOWN_ALREADY;
-                break;
-            }
-            case CREATE_JUST:
-            case SHUTDOWN_ALREADY:
-                break;
-            default:
-                break;
-        }
+  getFactory()->rebalanceImmediately();
+}
+
+void DefaultMQPushConsumer::shutdown() {
+  switch (m_serviceState) {
+    case RUNNING: {
+      LOG_INFO("DefaultMQPushConsumer shutdown");
+      m_async_ioService.stop();
+      m_async_service_thread->interrupt();
+      m_async_service_thread->join();
+      m_pullmsgQueue->close();
+      m_pullmsgThread->interrupt();
+      m_pullmsgThread->join();
+      m_consumerService->shutdown();
+      persistConsumerOffset();
+      shutdownAsyncPullCallBack();  // delete aync pullMsg resources
+      getFactory()->unregisterConsumer(this);
+      getFactory()->shutdown();
+      m_serviceState = SHUTDOWN_ALREADY;
+      break;
     }
+    case CREATE_JUST:
+    case SHUTDOWN_ALREADY:
+      break;
+    default:
+      break;
+  }
+}
 
-    void DefaultMQPushConsumer::registerMessageListener(
-            MQMessageListener *pMessageListener) {
-        if (NULL != pMessageListener) {
-            m_pMessageListener = pMessageListener;
-        }
+void DefaultMQPushConsumer::registerMessageListener(MQMessageListener* pMessageListener) {
+  if (NULL != pMessageListener) {
+    m_pMessageListener = pMessageListener;
+  }
+}
+
+MessageListenerType DefaultMQPushConsumer::getMessageListenerType() {
+  if (NULL != m_pMessageListener) {
+    return m_pMessageListener->getMessageListenerType();
+  }
+  return messageListenerDefaultly;
+}
+
+ConsumeMsgService* DefaultMQPushConsumer::getConsumerMsgService() const {
+  return m_consumerService;
+}
+
+OffsetStore* DefaultMQPushConsumer::getOffsetStore() const {
+  return m_pOffsetStore;
+}
+
+Rebalance* DefaultMQPushConsumer::getRebalance() const {
+  return m_pRebalance;
+}
+
+void DefaultMQPushConsumer::subscribe(const string& topic, const string& subExpression) {
+  m_subTopics[topic] = subExpression;
+}
+
+void DefaultMQPushConsumer::checkConfig() {
+  string groupname = getGroupName();
+  // check consumerGroup
+  Validators::checkGroup(groupname);
+
+  // consumerGroup
+  if (!groupname.compare(DEFAULT_CONSUMER_GROUP)) {
+    THROW_MQEXCEPTION(MQClientException, "consumerGroup can not equal DEFAULT_CONSUMER", -1);
+  }
+
+  if (getMessageModel() != BROADCASTING && getMessageModel() != CLUSTERING) {
+    THROW_MQEXCEPTION(MQClientException, "messageModel is valid ", -1);
+  }
+
+  if (m_pMessageListener == NULL) {
+    THROW_MQEXCEPTION(MQClientException, "messageListener is null ", -1);
+  }
+}
+
+void DefaultMQPushConsumer::copySubscription() {
+  map<string, string>::iterator it = m_subTopics.begin();
+  for (; it != m_subTopics.end(); ++it) {
+    LOG_INFO("buildSubscriptionData,:%s,%s", it->first.c_str(), it->second.c_str());
+    unique_ptr<SubscriptionData> pSData(FilterAPI::buildSubscriptionData(it->first, it->second));
+
+    m_pRebalance->setSubscriptionData(it->first, pSData.release());
+  }
+
+  switch (getMessageModel()) {
+    case BROADCASTING:
+      break;
+    case CLUSTERING: {
+      string retryTopic = UtilAll::getRetryTopic(getGroupName());
+
+      //<!this sub;
+      unique_ptr<SubscriptionData> pSData(FilterAPI::buildSubscriptionData(retryTopic, SUB_ALL));
+
+      m_pRebalance->setSubscriptionData(retryTopic, pSData.release());
+      break;
     }
+    default:
+      break;
+  }
+}
 
-    MessageListenerType DefaultMQPushConsumer::getMessageListenerType() {
-        if (NULL != m_pMessageListener) {
-            return m_pMessageListener->getMessageListenerType();
-        }
-        return messageListenerDefaultly;
+void DefaultMQPushConsumer::updateTopicSubscribeInfo(const string& topic, vector<MQMessageQueue>& info) {
+  m_pRebalance->setTopicSubscribeInfo(topic, info);
+}
+
+void DefaultMQPushConsumer::updateTopicSubscribeInfoWhenSubscriptionChanged() {
+  map<string, SubscriptionData*>& subTable = m_pRebalance->getSubscriptionInner();
+  map<string, SubscriptionData*>::iterator it = subTable.begin();
+  for (; it != subTable.end(); ++it) {
+    bool btopic = getFactory()->updateTopicRouteInfoFromNameServer(it->first, getSessionCredentials());
+    if (btopic == false) {
+      LOG_WARN("The topic:[%s] not exist", it->first.c_str());
     }
+  }
+}
 
-    ConsumeMsgService *DefaultMQPushConsumer::getConsumerMsgService() const {
-        return m_consumerService;
+ConsumeType DefaultMQPushConsumer::getConsumeType() {
+  return CONSUME_PASSIVELY;
+}
+
+ConsumeFromWhere DefaultMQPushConsumer::getConsumeFromWhere() {
+  return m_consumeFromWhere;
+}
+
+void DefaultMQPushConsumer::setConsumeFromWhere(ConsumeFromWhere consumeFromWhere) {
+  m_consumeFromWhere = consumeFromWhere;
+}
+
+void DefaultMQPushConsumer::getSubscriptions(vector<SubscriptionData>& result) {
+  map<string, SubscriptionData*>& subTable = m_pRebalance->getSubscriptionInner();
+  map<string, SubscriptionData*>::iterator it = subTable.begin();
+  for (; it != subTable.end(); ++it) {
+    result.push_back(*(it->second));
+  }
+}
+
+void DefaultMQPushConsumer::updateConsumeOffset(const MQMessageQueue& mq, int64 offset) {
+  if (offset >= 0) {
+    m_pOffsetStore->updateOffset(mq, offset);
+  } else {
+    LOG_ERROR("updateConsumeOffset of mq:%s error", mq.toString().c_str());
+  }
+}
+
+void DefaultMQPushConsumer::removeConsumeOffset(const MQMessageQueue& mq) {
+  m_pOffsetStore->removeOffset(mq);
+}
+
+void DefaultMQPushConsumer::triggerNextPullRequest(boost::asio::deadline_timer* t, PullRequest* request) {
+  // LOG_INFO("trigger pullrequest for:%s",
+  // (request->m_messageQueue).toString().c_str());
+  producePullMsgTask(request);
+  deleteAndZero(t);
+}
+
+void DefaultMQPushConsumer::producePullMsgTask(PullRequest* request) {
+  if (m_pullmsgQueue->bTaskQueueStatusOK() && isServiceStateOk()) {
+    request->addPullMsgEvent();
+    if (m_asyncPull) {
+      m_pullmsgQueue->produce(TaskBinder::gen(&DefaultMQPushConsumer::pullMessageAsync, this, request));
+    } else {
+      m_pullmsgQueue->produce(TaskBinder::gen(&DefaultMQPushConsumer::pullMessage, this, request));
     }
+  } else {
+    LOG_WARN("produce pullmsg of mq:%s failed", request->m_messageQueue.toString().c_str());
+  }
+}
 
-    OffsetStore *DefaultMQPushConsumer::getOffsetStore() const {
-        return m_pOffsetStore;
-    }
+void DefaultMQPushConsumer::runPullMsgQueue(TaskQueue* pTaskQueue) {
+  pTaskQueue->run();
+}
 
-    Rebalance *DefaultMQPushConsumer::getRebalance() const { return m_pRebalance; }
+void DefaultMQPushConsumer::pullMessage(PullRequest* request) {
+  if (request == NULL) {
+    LOG_ERROR("Pull request is NULL, return");
+    return;
+  }
+  if (request->isDroped()) {
+    LOG_WARN("Pull request is set drop with mq:%s, return", (request->m_messageQueue).toString().c_str());
+    request->removePullMsgEvent();
+    return;
+  }
 
-    void DefaultMQPushConsumer::subscribe(const string &topic,
-                                          const string &subExpression) {
-        m_subTopics[topic] = subExpression;
-    }
-
-    void DefaultMQPushConsumer::checkConfig() {
-        string groupname = getGroupName();
-        // check consumerGroup
-        Validators::checkGroup(groupname);
-
-        // consumerGroup
-        if (!groupname.compare(DEFAULT_CONSUMER_GROUP)) {
-            THROW_MQEXCEPTION(MQClientException,
-                              "consumerGroup can not equal DEFAULT_CONSUMER", -1);
-        }
-
-        if (getMessageModel() != BROADCASTING && getMessageModel() != CLUSTERING) {
-            THROW_MQEXCEPTION(MQClientException, "messageModel is valid ", -1);
-        }
-
-        if (m_pMessageListener == NULL) {
-            THROW_MQEXCEPTION(MQClientException, "messageListener is null ", -1);
-        }
-    }
-
-    void DefaultMQPushConsumer::copySubscription() {
-        map<string, string>::iterator it = m_subTopics.begin();
-        for (; it != m_subTopics.end(); ++it) {
-            LOG_INFO("buildSubscriptionData,:%s,%s", it->first.c_str(),
-                     it->second.c_str());
-            unique_ptr<SubscriptionData> pSData(
-                    FilterAPI::buildSubscriptionData(it->first, it->second));
-
-            m_pRebalance->setSubscriptionData(it->first, pSData.release());
-        }
-
-        switch (getMessageModel()) {
-            case BROADCASTING:
-                break;
-            case CLUSTERING: {
-                string retryTopic = UtilAll::getRetryTopic(getGroupName());
-
-                //<!this sub;
-                unique_ptr<SubscriptionData> pSData(
-                        FilterAPI::buildSubscriptionData(retryTopic, SUB_ALL));
-
-                m_pRebalance->setSubscriptionData(retryTopic, pSData.release());
-                break;
-            }
-            default:
-                break;
-        }
-    }
-
-    void DefaultMQPushConsumer::updateTopicSubscribeInfo(
-            const string &topic, vector<MQMessageQueue> &info) {
-        m_pRebalance->setTopicSubscribeInfo(topic, info);
-    }
-
-    void DefaultMQPushConsumer::updateTopicSubscribeInfoWhenSubscriptionChanged() {
-        map<string, SubscriptionData *> &subTable =
-                m_pRebalance->getSubscriptionInner();
-        map<string, SubscriptionData *>::iterator it = subTable.begin();
-        for (; it != subTable.end(); ++it) {
-            bool btopic = getFactory()->updateTopicRouteInfoFromNameServer(
-                    it->first, getSessionCredentials());
-            if (btopic == false) {
-                LOG_WARN("The topic:[%s] not exist", it->first.c_str());
-            }
-        }
-    }
-
-    ConsumeType DefaultMQPushConsumer::getConsumeType() {
-        return CONSUME_PASSIVELY;
-    }
-
-    ConsumeFromWhere DefaultMQPushConsumer::getConsumeFromWhere() {
-        return m_consumeFromWhere;
-    }
-
-    void DefaultMQPushConsumer::setConsumeFromWhere(
-            ConsumeFromWhere consumeFromWhere) {
-        m_consumeFromWhere = consumeFromWhere;
-    }
-
-    void DefaultMQPushConsumer::getSubscriptions(vector<SubscriptionData> &result) {
-        map<string, SubscriptionData *> &subTable =
-                m_pRebalance->getSubscriptionInner();
-        map<string, SubscriptionData *>::iterator it = subTable.begin();
-        for (; it != subTable.end(); ++it) {
-            result.push_back(*(it->second));
-        }
-    }
-
-    void DefaultMQPushConsumer::updateConsumeOffset(const MQMessageQueue &mq,
-                                                    int64 offset) {
-        if (offset >= 0) {
-            m_pOffsetStore->updateOffset(mq, offset);
-        } else {
-            LOG_ERROR("updateConsumeOffset of mq:%s error", mq.toString().c_str());
-        }
-    }
-
-    void DefaultMQPushConsumer::removeConsumeOffset(const MQMessageQueue &mq) {
-        m_pOffsetStore->removeOffset(mq);
-    }
-
-    void DefaultMQPushConsumer::triggerNextPullRequest(
-            boost::asio::deadline_timer *t, PullRequest *request) {
-        // LOG_INFO("trigger pullrequest for:%s",
-        // (request->m_messageQueue).toString().c_str());
+  MQMessageQueue& messageQueue = request->m_messageQueue;
+  if (m_consumerService->getConsumeMsgSerivceListenerType() == messageListenerOrderly) {
+    if (!request->isLocked() || request->isLockExpired()) {
+      if (!m_pRebalance->lock(messageQueue)) {
         producePullMsgTask(request);
-        deleteAndZero(t);
+        return;
+      }
     }
+  }
 
-    void DefaultMQPushConsumer::producePullMsgTask(PullRequest *request) {
-        if (m_pullmsgQueue->bTaskQueueStatusOK() && isServiceStateOk()) {
-            request->addPullMsgEvent();
-            if (m_asyncPull) {
-                m_pullmsgQueue->produce(TaskBinder::gen(
-                        &DefaultMQPushConsumer::pullMessageAsync, this, request));
-            } else {
-                m_pullmsgQueue->produce(
-                        TaskBinder::gen(&DefaultMQPushConsumer::pullMessage, this, request));
-            }
-        } else {
-            LOG_WARN("produce pullmsg of mq:%s failed",
-                     request->m_messageQueue.toString().c_str());
-        }
+  if (request->getCacheMsgCount() > m_maxMsgCacheSize) {
+    // LOG_INFO("retry pullrequest for:%s after 1s, as cachMsgSize:%d is larger
+    // than:%d",  (request->m_messageQueue).toString().c_str(),
+    // request->getCacheMsgCount(), m_maxMsgCacheSize);
+    boost::asio::deadline_timer* t =
+        new boost::asio::deadline_timer(m_async_ioService, boost::posix_time::milliseconds(1 * 1000));
+    t->async_wait(boost::bind(&DefaultMQPushConsumer::triggerNextPullRequest, this, t, request));
+    return;
+  }
+
+  bool commitOffsetEnable = false;
+  int64 commitOffsetValue = 0;
+  if (CLUSTERING == getMessageModel()) {
+    commitOffsetValue = m_pOffsetStore->readOffset(messageQueue, READ_FROM_MEMORY, getSessionCredentials());
+    if (commitOffsetValue > 0) {
+      commitOffsetEnable = true;
     }
+  }
 
-    void DefaultMQPushConsumer::runPullMsgQueue(TaskQueue *pTaskQueue) {
-        pTaskQueue->run();
-    }
+  string subExpression;
+  SubscriptionData* pSdata = m_pRebalance->getSubscriptionData(messageQueue.getTopic());
+  if (pSdata == NULL) {
+    producePullMsgTask(request);
+    return;
+  }
+  subExpression = pSdata->getSubString();
 
-    void DefaultMQPushConsumer::pullMessage(PullRequest *request) {
-        if (request == NULL) {
-            LOG_ERROR("Pull request is NULL, return");
-            return;
-        }
-        if (request->isDroped()) {
-            LOG_WARN("Pull request is set drop with mq:%s, return",
-                     (request->m_messageQueue).toString().c_str());
-            request->removePullMsgEvent();
-            return;
-        }
-
-        MQMessageQueue &messageQueue = request->m_messageQueue;
-        if (m_consumerService->getConsumeMsgSerivceListenerType() ==
-            messageListenerOrderly) {
-            if (!request->isLocked() || request->isLockExpired()) {
-                if (!m_pRebalance->lock(messageQueue)) {
-                    producePullMsgTask(request);
-                    return;
-                }
-            }
-        }
-
-        if (request->getCacheMsgCount() > m_maxMsgCacheSize) {
-            // LOG_INFO("retry pullrequest for:%s after 1s, as cachMsgSize:%d is larger
-            // than:%d",  (request->m_messageQueue).toString().c_str(),
-            // request->getCacheMsgCount(), m_maxMsgCacheSize);
-            boost::asio::deadline_timer *t = new boost::asio::deadline_timer(
-                    m_async_ioService, boost::posix_time::milliseconds(1 * 1000));
-            t->async_wait(boost::bind(&DefaultMQPushConsumer::triggerNextPullRequest,
-                                      this, t, request));
-            return;
-        }
-
-        bool commitOffsetEnable = false;
-        int64 commitOffsetValue = 0;
-        if (CLUSTERING == getMessageModel()) {
-            commitOffsetValue = m_pOffsetStore->readOffset(
-                    messageQueue, READ_FROM_MEMORY, getSessionCredentials());
-            if (commitOffsetValue > 0) {
-                commitOffsetEnable = true;
-            }
-        }
-
-        string subExpression;
-        SubscriptionData *pSdata =
-                m_pRebalance->getSubscriptionData(messageQueue.getTopic());
-        if (pSdata == NULL) {
-            producePullMsgTask(request);
-            return;
-        }
-        subExpression = pSdata->getSubString();
-
-        int sysFlag =
-                PullSysFlag::buildSysFlag(commitOffsetEnable,      // commitOffset
+  int sysFlag = PullSysFlag::buildSysFlag(commitOffsetEnable,      // commitOffset
                                           false,                   // suspend
                                           !subExpression.empty(),  // subscription
                                           false);                  // class filter
 
-        try {
-            request->setLastPullTimestamp(UtilAll::currentTimeMillis());
-            unique_ptr<PullResult> result(
-                    m_pPullAPIWrapper->pullKernelImpl(messageQueue,              // 1
-                                                      subExpression,             // 2
-                                                      pSdata->getSubVersion(),   // 3
-                                                      request->getNextOffset(),  // 4
-                                                      32,                        // 5
-                                                      sysFlag,                   // 6
-                                                      commitOffsetValue,         // 7
-                                                      1000 * 15,                 // 8
-                                                      1000 * 30,                 // 9
-                                                      ComMode_SYNC,              // 10
-                                                      NULL, getSessionCredentials()));
+  try {
+    request->setLastPullTimestamp(UtilAll::currentTimeMillis());
+    unique_ptr<PullResult> result(m_pPullAPIWrapper->pullKernelImpl(messageQueue,              // 1
+                                                                    subExpression,             // 2
+                                                                    pSdata->getSubVersion(),   // 3
+                                                                    request->getNextOffset(),  // 4
+                                                                    32,                        // 5
+                                                                    sysFlag,                   // 6
+                                                                    commitOffsetValue,         // 7
+                                                                    1000 * 15,                 // 8
+                                                                    1000 * 30,                 // 9
+                                                                    ComMode_SYNC,              // 10
+                                                                    NULL, getSessionCredentials()));
 
-            PullResult pullResult = m_pPullAPIWrapper->processPullResult(
-                    messageQueue, result.get(), pSdata);
+    PullResult pullResult = m_pPullAPIWrapper->processPullResult(messageQueue, result.get(), pSdata);
 
-            switch (pullResult.pullStatus) {
-                case FOUND: {
-                    if (!request->isDroped())  // if request is setted to dropped, don't add
-                        // msgFoundList to m_msgTreeMap and don't
-                        // call producePullMsgTask
-                    {  // avoid issue: pullMsg is sent out, rebalance is doing concurrently
-                        // and this request is dropped, and then received pulled msgs.
-                        request->setNextOffset(pullResult.nextBeginOffset);
-                        request->putMessage(pullResult.msgFoundList);
+    switch (pullResult.pullStatus) {
+      case FOUND: {
+        if (!request->isDroped())  // if request is setted to dropped, don't add
+                                   // msgFoundList to m_msgTreeMap and don't
+                                   // call producePullMsgTask
+        {                          // avoid issue: pullMsg is sent out, rebalance is doing concurrently
+          // and this request is dropped, and then received pulled msgs.
+          request->setNextOffset(pullResult.nextBeginOffset);
+          request->putMessage(pullResult.msgFoundList);
 
-                        m_consumerService->submitConsumeRequest(request,
-                                                                pullResult.msgFoundList);
-                        producePullMsgTask(request);
+          m_consumerService->submitConsumeRequest(request, pullResult.msgFoundList);
+          producePullMsgTask(request);
 
-                        LOG_DEBUG("FOUND:%s with size:"
-                                          SIZET_FMT
-                                          ",nextBeginOffset:%lld",
-                                  messageQueue.toString().c_str(),
-                                  pullResult.msgFoundList.size(), pullResult.nextBeginOffset);
-                    } else {
-                        request->removePullMsgEvent();
-                    }
-                    break;
-                }
-                case NO_NEW_MSG: {
-                    request->setNextOffset(pullResult.nextBeginOffset);
-                    vector<MQMessageExt> msgs;
-                    request->getMessage(msgs);
-                    if ((msgs.size() == 0) && (pullResult.nextBeginOffset > 0)) {
-                        /*if broker losted/cleared msgs of one msgQueue, but the brokerOffset
-                        is kept, then consumer will enter following situation:
-                        1>. get pull offset with 0 when do rebalance, and set
-                        m_offsetTable[mq] to 0;
-                        2>. NO_NEW_MSG or NO_MATCHED_MSG got when pullMessage, and nextBegin
-                        offset increase by 800
-                        3>. request->getMessage(msgs) always NULL
-                        4>. we need update consumerOffset to nextBeginOffset indicated by
-                        broker
-                        but if really no new msg could be pulled, also go to this CASE
-                     */
-                        // LOG_DEBUG("maybe misMatch between broker and client happens, update
-                        // consumerOffset to nextBeginOffset indicated by broker");
-                        updateConsumeOffset(messageQueue, pullResult.nextBeginOffset);
-                    }
-                    producePullMsgTask(request);
-                    LOG_DEBUG("NO_NEW_MSG:%s,nextBeginOffset:%lld",
-                              messageQueue.toString().c_str(), pullResult.nextBeginOffset);
-                    break;
-                }
-                case NO_MATCHED_MSG: {
-                    request->setNextOffset(pullResult.nextBeginOffset);
-                    vector<MQMessageExt> msgs;
-                    request->getMessage(msgs);
-                    if ((msgs.size() == 0) && (pullResult.nextBeginOffset > 0)) {
-                        // LOG_DEBUG("maybe misMatch between broker and client happens, update
-                        // consumerOffset to nextBeginOffset indicated by broker");
-                        updateConsumeOffset(messageQueue, pullResult.nextBeginOffset);
-                    }
-                    producePullMsgTask(request);
-
-                    LOG_DEBUG("NO_MATCHED_MSG:%s,nextBeginOffset:%lld",
-                              messageQueue.toString().c_str(), pullResult.nextBeginOffset);
-                    break;
-                }
-                case OFFSET_ILLEGAL: {
-                    request->setNextOffset(pullResult.nextBeginOffset);
-                    producePullMsgTask(request);
-
-                    LOG_DEBUG("OFFSET_ILLEGAL:%s,nextBeginOffset:%lld",
-                              messageQueue.toString().c_str(), pullResult.nextBeginOffset);
-                    break;
-                }
-                case BROKER_TIMEOUT: {  // as BROKER_TIMEOUT is defined by client, broker
-                    // will not returns this status, so this case
-                    // could not be entered.
-                    LOG_ERROR("impossible BROKER_TIMEOUT Occurs");
-                    request->setNextOffset(pullResult.nextBeginOffset);
-                    producePullMsgTask(request);
-                    break;
-                }
-            }
-        } catch (MQException &e) {
-            LOG_ERROR(e.what());
-            producePullMsgTask(request);
+          LOG_DEBUG("FOUND:%s with size:" SIZET_FMT ",nextBeginOffset:%lld", messageQueue.toString().c_str(),
+                    pullResult.msgFoundList.size(), pullResult.nextBeginOffset);
+        } else {
+          request->removePullMsgEvent();
         }
+        break;
+      }
+      case NO_NEW_MSG: {
+        request->setNextOffset(pullResult.nextBeginOffset);
+        vector<MQMessageExt> msgs;
+        request->getMessage(msgs);
+        if ((msgs.size() == 0) && (pullResult.nextBeginOffset > 0)) {
+          /*if broker losted/cleared msgs of one msgQueue, but the brokerOffset
+          is kept, then consumer will enter following situation:
+          1>. get pull offset with 0 when do rebalance, and set
+          m_offsetTable[mq] to 0;
+          2>. NO_NEW_MSG or NO_MATCHED_MSG got when pullMessage, and nextBegin
+          offset increase by 800
+          3>. request->getMessage(msgs) always NULL
+          4>. we need update consumerOffset to nextBeginOffset indicated by
+          broker
+          but if really no new msg could be pulled, also go to this CASE
+       */
+          // LOG_DEBUG("maybe misMatch between broker and client happens, update
+          // consumerOffset to nextBeginOffset indicated by broker");
+          updateConsumeOffset(messageQueue, pullResult.nextBeginOffset);
+        }
+        producePullMsgTask(request);
+        LOG_DEBUG("NO_NEW_MSG:%s,nextBeginOffset:%lld", messageQueue.toString().c_str(), pullResult.nextBeginOffset);
+        break;
+      }
+      case NO_MATCHED_MSG: {
+        request->setNextOffset(pullResult.nextBeginOffset);
+        vector<MQMessageExt> msgs;
+        request->getMessage(msgs);
+        if ((msgs.size() == 0) && (pullResult.nextBeginOffset > 0)) {
+          // LOG_DEBUG("maybe misMatch between broker and client happens, update
+          // consumerOffset to nextBeginOffset indicated by broker");
+          updateConsumeOffset(messageQueue, pullResult.nextBeginOffset);
+        }
+        producePullMsgTask(request);
+
+        LOG_DEBUG("NO_MATCHED_MSG:%s,nextBeginOffset:%lld", messageQueue.toString().c_str(),
+                  pullResult.nextBeginOffset);
+        break;
+      }
+      case OFFSET_ILLEGAL: {
+        request->setNextOffset(pullResult.nextBeginOffset);
+        producePullMsgTask(request);
+
+        LOG_DEBUG("OFFSET_ILLEGAL:%s,nextBeginOffset:%lld", messageQueue.toString().c_str(),
+                  pullResult.nextBeginOffset);
+        break;
+      }
+      case BROKER_TIMEOUT: {  // as BROKER_TIMEOUT is defined by client, broker
+        // will not returns this status, so this case
+        // could not be entered.
+        LOG_ERROR("impossible BROKER_TIMEOUT Occurs");
+        request->setNextOffset(pullResult.nextBeginOffset);
+        producePullMsgTask(request);
+        break;
+      }
     }
+  } catch (MQException& e) {
+    LOG_ERROR(e.what());
+    producePullMsgTask(request);
+  }
+}
 
-    AsyncPullCallback *DefaultMQPushConsumer::getAsyncPullCallBack(
-            PullRequest *request, MQMessageQueue msgQueue) {
-        boost::lock_guard<boost::mutex> lock(m_asyncCallbackLock);
-        if (m_asyncPull && request) {
-            PullMAP::iterator it = m_PullCallback.find(msgQueue);
-            if (it == m_PullCallback.end()) {
-                LOG_INFO("new pull callback for mq:%s", msgQueue.toString().c_str());
-                m_PullCallback[msgQueue] = new AsyncPullCallback(this, request);
-            }
-            return m_PullCallback[msgQueue];
-        }
-
-        return NULL;
+AsyncPullCallback* DefaultMQPushConsumer::getAsyncPullCallBack(PullRequest* request, MQMessageQueue msgQueue) {
+  boost::lock_guard<boost::mutex> lock(m_asyncCallbackLock);
+  if (m_asyncPull && request) {
+    PullMAP::iterator it = m_PullCallback.find(msgQueue);
+    if (it == m_PullCallback.end()) {
+      LOG_INFO("new pull callback for mq:%s", msgQueue.toString().c_str());
+      m_PullCallback[msgQueue] = new AsyncPullCallback(this, request);
     }
+    return m_PullCallback[msgQueue];
+  }
 
-    void DefaultMQPushConsumer::shutdownAsyncPullCallBack() {
-        boost::lock_guard<boost::mutex> lock(m_asyncCallbackLock);
-        if (m_asyncPull) {
-            PullMAP::iterator it = m_PullCallback.begin();
-            for (; it != m_PullCallback.end(); ++it) {
-                if (it->second) {
-                    it->second->setShutdownStatus();
-                } else {
-                    LOG_ERROR("could not find asyncPullCallback for:%s",
-                              it->first.toString().c_str());
-                }
-            }
-        }
+  return NULL;
+}
+
+void DefaultMQPushConsumer::shutdownAsyncPullCallBack() {
+  boost::lock_guard<boost::mutex> lock(m_asyncCallbackLock);
+  if (m_asyncPull) {
+    PullMAP::iterator it = m_PullCallback.begin();
+    for (; it != m_PullCallback.end(); ++it) {
+      if (it->second) {
+        it->second->setShutdownStatus();
+      } else {
+        LOG_ERROR("could not find asyncPullCallback for:%s", it->first.toString().c_str());
+      }
     }
+  }
+}
 
-    void DefaultMQPushConsumer::pullMessageAsync(PullRequest *request) {
-        if (request == NULL) {
-            LOG_ERROR("Pull request is NULL, return");
-            return;
-        }
-        if (request->isDroped()) {
-            LOG_WARN("Pull request is set drop with mq:%s, return",
-                     (request->m_messageQueue).toString().c_str());
-            request->removePullMsgEvent();
-            return;
-        }
+void DefaultMQPushConsumer::pullMessageAsync(PullRequest* request) {
+  if (request == NULL) {
+    LOG_ERROR("Pull request is NULL, return");
+    return;
+  }
+  if (request->isDroped()) {
+    LOG_WARN("Pull request is set drop with mq:%s, return", (request->m_messageQueue).toString().c_str());
+    request->removePullMsgEvent();
+    return;
+  }
 
-        MQMessageQueue &messageQueue = request->m_messageQueue;
-        if (m_consumerService->getConsumeMsgSerivceListenerType() ==
-            messageListenerOrderly) {
-            if (!request->isLocked() || request->isLockExpired()) {
-                if (!m_pRebalance->lock(messageQueue)) {
-                    producePullMsgTask(request);
-                    return;
-                }
-            }
-        }
+  MQMessageQueue& messageQueue = request->m_messageQueue;
+  if (m_consumerService->getConsumeMsgSerivceListenerType() == messageListenerOrderly) {
+    if (!request->isLocked() || request->isLockExpired()) {
+      if (!m_pRebalance->lock(messageQueue)) {
+        producePullMsgTask(request);
+        return;
+      }
+    }
+  }
 
-        if (request->getCacheMsgCount() > m_maxMsgCacheSize) {
-            // LOG_INFO("retry pullrequest for:%s after 1s, as cachMsgSize:%d is larger
-            // than:%d",  (request->m_messageQueue).toString().c_str(),
-            // request->getCacheMsgCount(), m_maxMsgCacheSize);
-            boost::asio::deadline_timer *t = new boost::asio::deadline_timer(
-                    m_async_ioService, boost::posix_time::milliseconds(1 * 1000));
-            t->async_wait(boost::bind(&DefaultMQPushConsumer::triggerNextPullRequest,
-                                      this, t, request));
-            return;
-        }
+  if (request->getCacheMsgCount() > m_maxMsgCacheSize) {
+    // LOG_INFO("retry pullrequest for:%s after 1s, as cachMsgSize:%d is larger
+    // than:%d",  (request->m_messageQueue).toString().c_str(),
+    // request->getCacheMsgCount(), m_maxMsgCacheSize);
+    boost::asio::deadline_timer* t =
+        new boost::asio::deadline_timer(m_async_ioService, boost::posix_time::milliseconds(1 * 1000));
+    t->async_wait(boost::bind(&DefaultMQPushConsumer::triggerNextPullRequest, this, t, request));
+    return;
+  }
 
-        bool commitOffsetEnable = false;
-        int64 commitOffsetValue = 0;
-        if (CLUSTERING == getMessageModel()) {
-            commitOffsetValue = m_pOffsetStore->readOffset(
-                    messageQueue, READ_FROM_MEMORY, getSessionCredentials());
-            if (commitOffsetValue > 0) {
-                commitOffsetEnable = true;
-            }
-        }
+  bool commitOffsetEnable = false;
+  int64 commitOffsetValue = 0;
+  if (CLUSTERING == getMessageModel()) {
+    commitOffsetValue = m_pOffsetStore->readOffset(messageQueue, READ_FROM_MEMORY, getSessionCredentials());
+    if (commitOffsetValue > 0) {
+      commitOffsetEnable = true;
+    }
+  }
 
-        string subExpression;
-        SubscriptionData *pSdata =
-                (m_pRebalance->getSubscriptionData(messageQueue.getTopic()));
-        if (pSdata == NULL) {
-            producePullMsgTask(request);
-            return;
-        }
-        subExpression = pSdata->getSubString();
+  string subExpression;
+  SubscriptionData* pSdata = (m_pRebalance->getSubscriptionData(messageQueue.getTopic()));
+  if (pSdata == NULL) {
+    producePullMsgTask(request);
+    return;
+  }
+  subExpression = pSdata->getSubString();
 
-        int sysFlag =
-                PullSysFlag::buildSysFlag(commitOffsetEnable,      // commitOffset
+  int sysFlag = PullSysFlag::buildSysFlag(commitOffsetEnable,      // commitOffset
                                           true,                    // suspend
                                           !subExpression.empty(),  // subscription
                                           false);                  // class filter
 
-        AsyncArg arg;
-        arg.mq = messageQueue;
-        arg.subData = *pSdata;
-        arg.pPullWrapper = m_pPullAPIWrapper;
-        arg.pPullRequest = request;
-        try {
-            request->setLastPullTimestamp(UtilAll::currentTimeMillis());
-            m_pPullAPIWrapper->pullKernelImpl(
-                    messageQueue,                                 // 1
-                    subExpression,                                // 2
-                    pSdata->getSubVersion(),                      // 3
-                    request->getNextOffset(),                     // 4
-                    32,                                           // 5
-                    sysFlag,                                      // 6
-                    commitOffsetValue,                            // 7
-                    1000 * 15,                                    // 8
-                    m_asyncPullTimeout,                           // 9
-                    ComMode_ASYNC,                                // 10
-                    getAsyncPullCallBack(request, messageQueue),  // 11
-                    getSessionCredentials(),                      // 12
-                    &arg);                                        // 13
-        } catch (MQException &e) {
-            LOG_ERROR(e.what());
-            producePullMsgTask(request);
-        }
+  AsyncArg arg;
+  arg.mq = messageQueue;
+  arg.subData = *pSdata;
+  arg.pPullWrapper = m_pPullAPIWrapper;
+  try {
+    request->setLastPullTimestamp(UtilAll::currentTimeMillis());
+    m_pPullAPIWrapper->pullKernelImpl(messageQueue,                                 // 1
+                                      subExpression,                                // 2
+                                      pSdata->getSubVersion(),                      // 3
+                                      request->getNextOffset(),                     // 4
+                                      32,                                           // 5
+                                      sysFlag,                                      // 6
+                                      commitOffsetValue,                            // 7
+                                      1000 * 15,                                    // 8
+                                      m_asyncPullTimeout,                           // 9
+                                      ComMode_ASYNC,                                // 10
+                                      getAsyncPullCallBack(request, messageQueue),  // 11
+                                      getSessionCredentials(),                      // 12
+                                      &arg);                                        // 13
+  } catch (MQException& e) {
+    LOG_ERROR(e.what());
+    producePullMsgTask(request);
+  }
+}
+
+void DefaultMQPushConsumer::setAsyncPull(bool asyncFlag) {
+  if (asyncFlag) {
+    LOG_INFO("set pushConsumer:%s to async default pull mode", getGroupName().c_str());
+  } else {
+    LOG_INFO("set pushConsumer:%s to sync pull mode", getGroupName().c_str());
+  }
+  m_asyncPull = asyncFlag;
+}
+
+void DefaultMQPushConsumer::setConsumeThreadCount(int threadCount) {
+  if (threadCount > 0) {
+    m_consumeThreadCount = threadCount;
+  } else {
+    LOG_ERROR("setConsumeThreadCount with invalid value");
+  }
+}
+
+int DefaultMQPushConsumer::getConsumeThreadCount() const {
+  return m_consumeThreadCount;
+}
+
+void DefaultMQPushConsumer::setPullMsgThreadPoolCount(int threadCount) {
+  m_pullMsgThreadPoolNum = threadCount;
+}
+
+int DefaultMQPushConsumer::getPullMsgThreadPoolCount() const {
+  return m_pullMsgThreadPoolNum;
+}
+
+int DefaultMQPushConsumer::getConsumeMessageBatchMaxSize() const {
+  return m_consumeMessageBatchMaxSize;
+}
+
+void DefaultMQPushConsumer::setConsumeMessageBatchMaxSize(int consumeMessageBatchMaxSize) {
+  if (consumeMessageBatchMaxSize >= 1)
+    m_consumeMessageBatchMaxSize = consumeMessageBatchMaxSize;
+}
+
+void DefaultMQPushConsumer::setMaxCacheMsgSizePerQueue(int maxCacheSize) {
+  if (maxCacheSize > 0 && maxCacheSize < 65535) {
+    LOG_INFO("set maxCacheSize to:%d for consumer:%s", maxCacheSize, getGroupName().c_str());
+    m_maxMsgCacheSize = maxCacheSize;
+  }
+}
+
+int DefaultMQPushConsumer::getMaxCacheMsgSizePerQueue() const {
+  return m_maxMsgCacheSize;
+}
+
+ConsumerRunningInfo* DefaultMQPushConsumer::getConsumerRunningInfo() {
+  ConsumerRunningInfo* info = new ConsumerRunningInfo();
+  if (info) {
+    if (m_consumerService->getConsumeMsgSerivceListenerType() == messageListenerOrderly)
+      info->setProperty(ConsumerRunningInfo::PROP_CONSUME_ORDERLY, "true");
+    else
+      info->setProperty(ConsumerRunningInfo::PROP_CONSUME_ORDERLY, "flase");
+    info->setProperty(ConsumerRunningInfo::PROP_THREADPOOL_CORE_SIZE, UtilAll::to_string(m_consumeThreadCount));
+    info->setProperty(ConsumerRunningInfo::PROP_CONSUMER_START_TIMESTAMP, UtilAll::to_string(m_startTime));
+
+    vector<SubscriptionData> result;
+    getSubscriptions(result);
+    info->setSubscriptionSet(result);
+
+    map<MQMessageQueue, PullRequest*> requestTable = m_pRebalance->getPullRequestTable();
+    map<MQMessageQueue, PullRequest*>::iterator it = requestTable.begin();
+
+    for (; it != requestTable.end(); ++it) {
+      if (!it->second->isDroped()) {
+        map<MessageQueue, ProcessQueueInfo> queueTable;
+        MessageQueue queue((it->first).getTopic(), (it->first).getBrokerName(), (it->first).getQueueId());
+        ProcessQueueInfo processQueue;
+        processQueue.cachedMsgMinOffset = it->second->getCacheMinOffset();
+        processQueue.cachedMsgMaxOffset = it->second->getCacheMaxOffset();
+        processQueue.cachedMsgCount = it->second->getCacheMsgCount();
+        processQueue.setCommitOffset(
+            m_pOffsetStore->readOffset(it->first, MEMORY_FIRST_THEN_STORE, getSessionCredentials()));
+        processQueue.setDroped(it->second->isDroped());
+        processQueue.setLocked(it->second->isLocked());
+        processQueue.lastLockTimestamp = it->second->getLastLockTimestamp();
+        processQueue.lastPullTimestamp = it->second->getLastPullTimestamp();
+        processQueue.lastConsumeTimestamp = it->second->getLastConsumeTimestamp();
+        info->setMqTable(queue, processQueue);
+      }
     }
 
-    void DefaultMQPushConsumer::setAsyncPull(bool asyncFlag) {
-        if (asyncFlag) {
-            LOG_INFO("set pushConsumer:%s to async default pull mode",
-                     getGroupName().c_str());
-        } else {
-            LOG_INFO("set pushConsumer:%s to sync pull mode", getGroupName().c_str());
-        }
-        m_asyncPull = asyncFlag;
-    }
-
-    void DefaultMQPushConsumer::setConsumeThreadCount(int threadCount) {
-        if (threadCount > 0) {
-            m_consumeThreadCount = threadCount;
-        } else {
-            LOG_ERROR("setConsumeThreadCount with invalid value");
-        }
-    }
-
-    int DefaultMQPushConsumer::getConsumeThreadCount() const {
-        return m_consumeThreadCount;
-    }
-
-    void DefaultMQPushConsumer::setPullMsgThreadPoolCount(int threadCount) {
-        m_pullMsgThreadPoolNum = threadCount;
-    }
-
-    int DefaultMQPushConsumer::getPullMsgThreadPoolCount() const {
-        return m_pullMsgThreadPoolNum;
-    }
-
-    int DefaultMQPushConsumer::getConsumeMessageBatchMaxSize() const {
-        return m_consumeMessageBatchMaxSize;
-    }
-
-    void DefaultMQPushConsumer::setConsumeMessageBatchMaxSize(
-            int consumeMessageBatchMaxSize) {
-        if (consumeMessageBatchMaxSize >= 1)
-            m_consumeMessageBatchMaxSize = consumeMessageBatchMaxSize;
-    }
-
-    void DefaultMQPushConsumer::setMaxCacheMsgSizePerQueue(int maxCacheSize) {
-        if (maxCacheSize > 0 && maxCacheSize < 65535) {
-            LOG_INFO("set maxCacheSize to:%d for consumer:%s", maxCacheSize,
-                     getGroupName().c_str());
-            m_maxMsgCacheSize = maxCacheSize;
-        }
-    }
-
-    int DefaultMQPushConsumer::getMaxCacheMsgSizePerQueue() const {
-        return m_maxMsgCacheSize;
-    }
-
-    ConsumerRunningInfo *DefaultMQPushConsumer::getConsumerRunningInfo() {
-        ConsumerRunningInfo *info = new ConsumerRunningInfo();
-        if (info) {
-            if (m_consumerService->getConsumeMsgSerivceListenerType() ==
-                messageListenerOrderly)
-                info->setProperty(ConsumerRunningInfo::PROP_CONSUME_ORDERLY, "true");
-            else
-                info->setProperty(ConsumerRunningInfo::PROP_CONSUME_ORDERLY, "flase");
-            info->setProperty(ConsumerRunningInfo::PROP_THREADPOOL_CORE_SIZE,
-                              UtilAll::to_string(m_consumeThreadCount));
-            info->setProperty(ConsumerRunningInfo::PROP_CONSUMER_START_TIMESTAMP,
-                              UtilAll::to_string(m_startTime));
-
-            vector<SubscriptionData> result;
-            getSubscriptions(result);
-            info->setSubscriptionSet(result);
-
-            map<MQMessageQueue, PullRequest *> requestTable =
-                    m_pRebalance->getPullRequestTable();
-            map<MQMessageQueue, PullRequest *>::iterator it = requestTable.begin();
-
-            for (; it != requestTable.end(); ++it) {
-                if (!it->second->isDroped()) {
-                    map<MessageQueue, ProcessQueueInfo> queueTable;
-                    MessageQueue queue((it->first).getTopic(), (it->first).getBrokerName(),
-                                       (it->first).getQueueId());
-                    ProcessQueueInfo processQueue;
-                    processQueue.cachedMsgMinOffset = it->second->getCacheMinOffset();
-                    processQueue.cachedMsgMaxOffset = it->second->getCacheMaxOffset();
-                    processQueue.cachedMsgCount = it->second->getCacheMsgCount();
-                    processQueue.setCommitOffset(m_pOffsetStore->readOffset(
-                            it->first, MEMORY_FIRST_THEN_STORE, getSessionCredentials()));
-                    processQueue.setDroped(it->second->isDroped());
-                    processQueue.setLocked(it->second->isLocked());
-                    processQueue.lastLockTimestamp = it->second->getLastLockTimestamp();
-                    processQueue.lastPullTimestamp = it->second->getLastPullTimestamp();
-                    processQueue.lastConsumeTimestamp =
-                            it->second->getLastConsumeTimestamp();
-                    info->setMqTable(queue, processQueue);
-                }
-            }
-
-            return info;
-        }
-        return NULL;
-    }
+    return info;
+  }
+  return NULL;
+}
 
 //<!************************************************************************
 }  //<!end namespace;
diff --git a/src/consumer/FindBrokerResult.h b/src/consumer/FindBrokerResult.h
old mode 100755
new mode 100644
index a224b14..789dc91
--- a/src/consumer/FindBrokerResult.h
+++ b/src/consumer/FindBrokerResult.h
@@ -21,8 +21,7 @@
 namespace rocketmq {
 //<!************************************************************************
 struct FindBrokerResult {
-  FindBrokerResult(const std::string& sbrokerAddr, bool bslave)
-      : brokerAddr(sbrokerAddr), slave(bslave) {}
+  FindBrokerResult(const std::string& sbrokerAddr, bool bslave) : brokerAddr(sbrokerAddr), slave(bslave) {}
 
  public:
   std::string brokerAddr;
diff --git a/src/consumer/OffsetStore.cpp b/src/consumer/OffsetStore.cpp
index 25d1b32..fc2a5a0 100644
--- a/src/consumer/OffsetStore.cpp
+++ b/src/consumer/OffsetStore.cpp
@@ -40,14 +40,12 @@
 }
 
 //<!***************************************************************************
-LocalFileOffsetStore::LocalFileOffsetStore(const string& groupName,
-                                           MQClientFactory* pfactory)
+LocalFileOffsetStore::LocalFileOffsetStore(const string& groupName, MQClientFactory* pfactory)
     : OffsetStore(groupName, pfactory) {
   MQConsumer* pConsumer = pfactory->selectConsumer(groupName);
   if (pConsumer) {
     LOG_INFO("new LocalFileOffsetStore");
-    string directoryName =
-        UtilAll::getLocalAddress() + "@" + pConsumer->getInstanceName();
+    string directoryName = UtilAll::getLocalAddress() + "@" + pConsumer->getInstanceName();
     m_storePath = ".rocketmq_offsets/" + directoryName + "/" + groupName;
     string homeDir(UtilAll::getHomeDirectory());
     m_storeFile = homeDir + "/" + m_storePath + "/offsets.Json";
@@ -96,16 +94,13 @@
         }
         ifs.close();
 
-        for (map<string, int64>::iterator it = m_offsetTable_tmp.begin();
-             it != m_offsetTable_tmp.end(); ++it) {
+        for (map<string, int64>::iterator it = m_offsetTable_tmp.begin(); it != m_offsetTable_tmp.end(); ++it) {
           // LOG_INFO("it->first:%s, it->second:%lld", it->first.c_str(),
           // it->second);
           Json::Reader reader;
           Json::Value object;
           reader.parse(it->first.c_str(), object);
-          MQMessageQueue mq(object["topic"].asString(),
-                            object["brokerName"].asString(),
-                            object["queueId"].asInt());
+          MQMessageQueue mq(object["topic"].asString(), object["brokerName"].asString(), object["queueId"].asInt());
           updateOffset(mq, it->second);
         }
         m_offsetTable_tmp.clear();
@@ -140,15 +135,14 @@
   }
 }
 
-void LocalFileOffsetStore::updateOffset(const MQMessageQueue& mq,
-                                        int64 offset) {
+void LocalFileOffsetStore::updateOffset(const MQMessageQueue& mq, int64 offset) {
   boost::lock_guard<boost::mutex> lock(m_lock);
   m_offsetTable[mq] = offset;
 }
 
-int64 LocalFileOffsetStore::readOffset(
-    const MQMessageQueue& mq, ReadOffsetType type,
-    const SessionCredentials& session_credentials) {
+int64 LocalFileOffsetStore::readOffset(const MQMessageQueue& mq,
+                                       ReadOffsetType type,
+                                       const SessionCredentials& session_credentials) {
   switch (type) {
     case MEMORY_FIRST_THEN_STORE:
     case READ_FROM_MEMORY: {
@@ -176,13 +170,11 @@
     default:
       break;
   }
-  LOG_ERROR(
-      "can not readOffset from offsetStore.json, maybe first time consumation");
+  LOG_ERROR("can not readOffset from offsetStore.json, maybe first time consumation");
   return -1;
 }
 
-void LocalFileOffsetStore::persist(
-    const MQMessageQueue& mq, const SessionCredentials& session_credentials) {}
+void LocalFileOffsetStore::persist(const MQMessageQueue& mq, const SessionCredentials& session_credentials) {}
 
 void LocalFileOffsetStore::persistAll(const std::vector<MQMessageQueue>& mqs) {
   boost::lock_guard<boost::mutex> lock(m_lock);
@@ -190,8 +182,7 @@
   map<string, int64> m_offsetTable_tmp;
   vector<MQMessageQueue>::const_iterator it = mqs.begin();
   for (; it != mqs.end(); ++it) {
-    MessageQueue mq_tmp((*it).getTopic(), (*it).getBrokerName(),
-                        (*it).getQueueId());
+    MessageQueue mq_tmp((*it).getTopic(), (*it).getBrokerName(), (*it).getQueueId());
     string mqKey = mq_tmp.toJson().toStyledString();
     m_offsetTable_tmp[mqKey] = m_offsetTable[*it];
   }
@@ -210,8 +201,7 @@
     } catch (...) {
       LOG_ERROR("persist offset store file:%s failed", m_storeFile.c_str());
       s.close();
-      THROW_MQEXCEPTION(MQClientException,
-                        "persistAll:open offset store file failed", -1);
+      THROW_MQEXCEPTION(MQClientException, "persistAll:open offset store file failed", -1);
     }
     s.close();
     if (!UtilAll::ReplaceFile(storefile_bak, m_storeFile))
@@ -220,31 +210,28 @@
   } else {
     LOG_ERROR("open offset store file:%s failed", m_storeFile.c_str());
     m_offsetTable_tmp.clear();
-    THROW_MQEXCEPTION(MQClientException,
-                      "persistAll:open offset store file failed", -1);
+    THROW_MQEXCEPTION(MQClientException, "persistAll:open offset store file failed", -1);
   }
 }
 
 void LocalFileOffsetStore::removeOffset(const MQMessageQueue& mq) {}
 
 //<!***************************************************************************
-RemoteBrokerOffsetStore::RemoteBrokerOffsetStore(const string& groupName,
-                                                 MQClientFactory* pfactory)
+RemoteBrokerOffsetStore::RemoteBrokerOffsetStore(const string& groupName, MQClientFactory* pfactory)
     : OffsetStore(groupName, pfactory) {}
 
 RemoteBrokerOffsetStore::~RemoteBrokerOffsetStore() {}
 
 void RemoteBrokerOffsetStore::load() {}
 
-void RemoteBrokerOffsetStore::updateOffset(const MQMessageQueue& mq,
-                                           int64 offset) {
+void RemoteBrokerOffsetStore::updateOffset(const MQMessageQueue& mq, int64 offset) {
   boost::lock_guard<boost::mutex> lock(m_lock);
   m_offsetTable[mq] = offset;
 }
 
-int64 RemoteBrokerOffsetStore::readOffset(
-    const MQMessageQueue& mq, ReadOffsetType type,
-    const SessionCredentials& session_credentials) {
+int64 RemoteBrokerOffsetStore::readOffset(const MQMessageQueue& mq,
+                                          ReadOffsetType type,
+                                          const SessionCredentials& session_credentials) {
   switch (type) {
     case MEMORY_FIRST_THEN_STORE:
     case READ_FROM_MEMORY: {
@@ -259,8 +246,7 @@
     }
     case READ_FROM_STORE: {
       try {
-        int64 brokerOffset =
-            fetchConsumeOffsetFromBroker(mq, session_credentials);
+        int64 brokerOffset = fetchConsumeOffsetFromBroker(mq, session_credentials);
         //<!update;
         updateOffset(mq, brokerOffset);
         return brokerOffset;
@@ -278,8 +264,7 @@
   return -1;
 }
 
-void RemoteBrokerOffsetStore::persist(
-    const MQMessageQueue& mq, const SessionCredentials& session_credentials) {
+void RemoteBrokerOffsetStore::persist(const MQMessageQueue& mq, const SessionCredentials& session_credentials) {
   MQ2OFFSET offsetTable;
   {
     boost::lock_guard<boost::mutex> lock(m_lock);
@@ -296,42 +281,35 @@
   }
 }
 
-void RemoteBrokerOffsetStore::persistAll(
-    const std::vector<MQMessageQueue>& mq) {}
+void RemoteBrokerOffsetStore::persistAll(const std::vector<MQMessageQueue>& mq) {}
 
 void RemoteBrokerOffsetStore::removeOffset(const MQMessageQueue& mq) {
   boost::lock_guard<boost::mutex> lock(m_lock);
-  if (m_offsetTable.find(mq) != m_offsetTable.end()) m_offsetTable.erase(mq);
+  if (m_offsetTable.find(mq) != m_offsetTable.end())
+    m_offsetTable.erase(mq);
 }
 
-void RemoteBrokerOffsetStore::updateConsumeOffsetToBroker(
-    const MQMessageQueue& mq, int64 offset,
-    const SessionCredentials& session_credentials) {
-  unique_ptr<FindBrokerResult> pFindBrokerResult(
-      m_pClientFactory->findBrokerAddressInAdmin(mq.getBrokerName()));
+void RemoteBrokerOffsetStore::updateConsumeOffsetToBroker(const MQMessageQueue& mq,
+                                                          int64 offset,
+                                                          const SessionCredentials& session_credentials) {
+  unique_ptr<FindBrokerResult> pFindBrokerResult(m_pClientFactory->findBrokerAddressInAdmin(mq.getBrokerName()));
 
   if (pFindBrokerResult == NULL) {
-    m_pClientFactory->updateTopicRouteInfoFromNameServer(mq.getTopic(),
-                                                         session_credentials);
-    pFindBrokerResult.reset(
-        m_pClientFactory->findBrokerAddressInAdmin(mq.getBrokerName()));
+    m_pClientFactory->updateTopicRouteInfoFromNameServer(mq.getTopic(), session_credentials);
+    pFindBrokerResult.reset(m_pClientFactory->findBrokerAddressInAdmin(mq.getBrokerName()));
   }
 
   if (pFindBrokerResult != NULL) {
-    UpdateConsumerOffsetRequestHeader* pRequestHeader =
-        new UpdateConsumerOffsetRequestHeader();
+    UpdateConsumerOffsetRequestHeader* pRequestHeader = new UpdateConsumerOffsetRequestHeader();
     pRequestHeader->topic = mq.getTopic();
     pRequestHeader->consumerGroup = m_groupName;
     pRequestHeader->queueId = mq.getQueueId();
     pRequestHeader->commitOffset = offset;
 
     try {
-      LOG_INFO(
-          "oneway updateConsumeOffsetToBroker of mq:%s, its offset is:%lld",
-          mq.toString().c_str(), offset);
+      LOG_INFO("oneway updateConsumeOffsetToBroker of mq:%s, its offset is:%lld", mq.toString().c_str(), offset);
       return m_pClientFactory->getMQClientAPIImpl()->updateConsumerOffsetOneway(
-          pFindBrokerResult->brokerAddr, pRequestHeader, 1000 * 5,
-          session_credentials);
+          pFindBrokerResult->brokerAddr, pRequestHeader, 1000 * 5, session_credentials);
     } catch (MQException& e) {
       LOG_ERROR(e.what());
     }
@@ -339,28 +317,23 @@
   LOG_WARN("The broker not exist");
 }
 
-int64 RemoteBrokerOffsetStore::fetchConsumeOffsetFromBroker(
-    const MQMessageQueue& mq, const SessionCredentials& session_credentials) {
-  unique_ptr<FindBrokerResult> pFindBrokerResult(
-      m_pClientFactory->findBrokerAddressInAdmin(mq.getBrokerName()));
+int64 RemoteBrokerOffsetStore::fetchConsumeOffsetFromBroker(const MQMessageQueue& mq,
+                                                            const SessionCredentials& session_credentials) {
+  unique_ptr<FindBrokerResult> pFindBrokerResult(m_pClientFactory->findBrokerAddressInAdmin(mq.getBrokerName()));
 
   if (pFindBrokerResult == NULL) {
-    m_pClientFactory->updateTopicRouteInfoFromNameServer(mq.getTopic(),
-                                                         session_credentials);
-    pFindBrokerResult.reset(
-        m_pClientFactory->findBrokerAddressInAdmin(mq.getBrokerName()));
+    m_pClientFactory->updateTopicRouteInfoFromNameServer(mq.getTopic(), session_credentials);
+    pFindBrokerResult.reset(m_pClientFactory->findBrokerAddressInAdmin(mq.getBrokerName()));
   }
 
   if (pFindBrokerResult != NULL) {
-    QueryConsumerOffsetRequestHeader* pRequestHeader =
-        new QueryConsumerOffsetRequestHeader();
+    QueryConsumerOffsetRequestHeader* pRequestHeader = new QueryConsumerOffsetRequestHeader();
     pRequestHeader->topic = mq.getTopic();
     pRequestHeader->consumerGroup = m_groupName;
     pRequestHeader->queueId = mq.getQueueId();
 
-    return m_pClientFactory->getMQClientAPIImpl()->queryConsumerOffset(
-        pFindBrokerResult->brokerAddr, pRequestHeader, 1000 * 5,
-        session_credentials);
+    return m_pClientFactory->getMQClientAPIImpl()->queryConsumerOffset(pFindBrokerResult->brokerAddr, pRequestHeader,
+                                                                       1000 * 5, session_credentials);
   } else {
     LOG_ERROR("The broker not exist when fetchConsumeOffsetFromBroker");
     THROW_MQEXCEPTION(MQClientException, "The broker not exist", -1);
diff --git a/src/consumer/OffsetStore.h b/src/consumer/OffsetStore.h
old mode 100755
new mode 100644
index 7e8d8c3..d10f233
--- a/src/consumer/OffsetStore.h
+++ b/src/consumer/OffsetStore.h
@@ -28,11 +28,11 @@
 class MQClientFactory;
 //<!***************************************************************************
 enum ReadOffsetType {
-  //read offset from memory
+  // read offset from memory
   READ_FROM_MEMORY,
-  //read offset from remoting
+  // read offset from remoting
   READ_FROM_STORE,
-  //read offset from memory firstly, then from remoting
+  // read offset from memory firstly, then from remoting
   MEMORY_FIRST_THEN_STORE,
 };
 
@@ -44,10 +44,10 @@
 
   virtual void load() = 0;
   virtual void updateOffset(const MQMessageQueue& mq, int64 offset) = 0;
-  virtual int64 readOffset(const MQMessageQueue& mq, ReadOffsetType type,
+  virtual int64 readOffset(const MQMessageQueue& mq,
+                           ReadOffsetType type,
                            const SessionCredentials& session_credentials) = 0;
-  virtual void persist(const MQMessageQueue& mq,
-                       const SessionCredentials& session_credentials) = 0;
+  virtual void persist(const MQMessageQueue& mq, const SessionCredentials& session_credentials) = 0;
   virtual void persistAll(const std::vector<MQMessageQueue>& mq) = 0;
   virtual void removeOffset(const MQMessageQueue& mq) = 0;
 
@@ -67,10 +67,10 @@
 
   virtual void load();
   virtual void updateOffset(const MQMessageQueue& mq, int64 offset);
-  virtual int64 readOffset(const MQMessageQueue& mq, ReadOffsetType type,
+  virtual int64 readOffset(const MQMessageQueue& mq,
+                           ReadOffsetType type,
                            const SessionCredentials& session_credentials);
-  virtual void persist(const MQMessageQueue& mq,
-                       const SessionCredentials& session_credentials);
+  virtual void persist(const MQMessageQueue& mq, const SessionCredentials& session_credentials);
   virtual void persistAll(const std::vector<MQMessageQueue>& mq);
   virtual void removeOffset(const MQMessageQueue& mq);
 
@@ -87,19 +87,18 @@
 
   virtual void load();
   virtual void updateOffset(const MQMessageQueue& mq, int64 offset);
-  virtual int64 readOffset(const MQMessageQueue& mq, ReadOffsetType type,
+  virtual int64 readOffset(const MQMessageQueue& mq,
+                           ReadOffsetType type,
                            const SessionCredentials& session_credentials);
-  virtual void persist(const MQMessageQueue& mq,
-                       const SessionCredentials& session_credentials);
+  virtual void persist(const MQMessageQueue& mq, const SessionCredentials& session_credentials);
   virtual void persistAll(const std::vector<MQMessageQueue>& mq);
   virtual void removeOffset(const MQMessageQueue& mq);
 
  private:
-  void updateConsumeOffsetToBroker(
-      const MQMessageQueue& mq, int64 offset,
-      const SessionCredentials& session_credentials);
-  int64 fetchConsumeOffsetFromBroker(
-      const MQMessageQueue& mq, const SessionCredentials& session_credentials);
+  void updateConsumeOffsetToBroker(const MQMessageQueue& mq,
+                                   int64 offset,
+                                   const SessionCredentials& session_credentials);
+  int64 fetchConsumeOffsetFromBroker(const MQMessageQueue& mq, const SessionCredentials& session_credentials);
 };
 //<!***************************************************************************
 }  //<!end namespace;
diff --git a/src/consumer/PullAPIWrapper.cpp b/src/consumer/PullAPIWrapper.cpp
old mode 100755
new mode 100644
index 6a4b507..46832dd
--- a/src/consumer/PullAPIWrapper.cpp
+++ b/src/consumer/PullAPIWrapper.cpp
@@ -21,8 +21,7 @@
 #include "PullSysFlag.h"

 namespace rocketmq {

 //<!************************************************************************

-PullAPIWrapper::PullAPIWrapper(MQClientFactory* mQClientFactory,

-                               const string& consumerGroup) {

+PullAPIWrapper::PullAPIWrapper(MQClientFactory* mQClientFactory, const string& consumerGroup) {

   m_MQClientFactory = mQClientFactory;

   m_consumerGroup = consumerGroup;

 }

@@ -32,8 +31,7 @@
   m_pullFromWhichNodeTable.clear();

 }

 

-void PullAPIWrapper::updatePullFromWhichNode(const MQMessageQueue& mq,

-                                             int brokerId) {

+void PullAPIWrapper::updatePullFromWhichNode(const MQMessageQueue& mq, int brokerId) {

   boost::lock_guard<boost::mutex> lock(m_lock);

   m_pullFromWhichNodeTable[mq] = brokerId;

 }

@@ -46,9 +44,9 @@
   return MASTER_ID;

 }

 

-PullResult PullAPIWrapper::processPullResult(

-    const MQMessageQueue& mq, PullResult* pullResult,

-    SubscriptionData* subscriptionData) {

+PullResult PullAPIWrapper::processPullResult(const MQMessageQueue& mq,

+                                             PullResult* pullResult,

+                                             SubscriptionData* subscriptionData) {

   PullResultExt* pResultExt = static_cast<PullResultExt*>(pullResult);

   if (pResultExt == NULL) {

     string errMsg("The pullResult NULL of");

@@ -75,39 +73,35 @@
           msgFilterList.push_back(*it);

         }

       }

-    } else

-    {

+    } else {

       msgFilterList.swap(msgAllList);

     }

   }

 

-  return PullResult(pResultExt->pullStatus, pResultExt->nextBeginOffset,

-                    pResultExt->minOffset, pResultExt->maxOffset,

+  return PullResult(pResultExt->pullStatus, pResultExt->nextBeginOffset, pResultExt->minOffset, pResultExt->maxOffset,

                     msgFilterList);

 }

 

-PullResult* PullAPIWrapper::pullKernelImpl(

-    const MQMessageQueue& mq,        // 1

-    string subExpression,            // 2

-    int64 subVersion,                // 3

-    int64 offset,                    // 4

-    int maxNums,                     // 5

-    int sysFlag,                     // 6

-    int64 commitOffset,              // 7

-    int brokerSuspendMaxTimeMillis,  // 8

-    int timeoutMillis,               // 9

-    int communicationMode,           // 10

-    PullCallback* pullCallback, const SessionCredentials& session_credentials,

-    void* pArg /*= NULL*/) {

+PullResult* PullAPIWrapper::pullKernelImpl(const MQMessageQueue& mq,        // 1

+                                           string subExpression,            // 2

+                                           int64 subVersion,                // 3

+                                           int64 offset,                    // 4

+                                           int maxNums,                     // 5

+                                           int sysFlag,                     // 6

+                                           int64 commitOffset,              // 7

+                                           int brokerSuspendMaxTimeMillis,  // 8

+                                           int timeoutMillis,               // 9

+                                           int communicationMode,           // 10

+                                           PullCallback* pullCallback,

+                                           const SessionCredentials& session_credentials,

+                                           void* pArg /*= NULL*/) {

   unique_ptr<FindBrokerResult> pFindBrokerResult(

-      m_MQClientFactory->findBrokerAddressInSubscribe(

-          mq.getBrokerName(), recalculatePullFromWhichNode(mq), false));

+      m_MQClientFactory->findBrokerAddressInSubscribe(mq.getBrokerName(), recalculatePullFromWhichNode(mq), false));

   //<!goto nameserver;

   if (pFindBrokerResult == NULL) {

-    m_MQClientFactory->updateTopicRouteInfoFromNameServer(mq.getTopic(),

-                                                          session_credentials);

-    pFindBrokerResult.reset(m_MQClientFactory->findBrokerAddressInSubscribe(

-        mq.getBrokerName(), recalculatePullFromWhichNode(mq), false));

+    m_MQClientFactory->updateTopicRouteInfoFromNameServer(mq.getTopic(), session_credentials);

+    pFindBrokerResult.reset(

+        m_MQClientFactory->findBrokerAddressInSubscribe(mq.getBrokerName(), recalculatePullFromWhichNode(mq), false));

   }

 

   if (pFindBrokerResult != NULL) {

@@ -129,9 +123,9 @@
     pRequestHeader->subscription = subExpression;

     pRequestHeader->subVersion = subVersion;

 

-    return m_MQClientFactory->getMQClientAPIImpl()->pullMessage(

-        pFindBrokerResult->brokerAddr, pRequestHeader, timeoutMillis,

-        communicationMode, pullCallback, pArg, session_credentials);

+    return m_MQClientFactory->getMQClientAPIImpl()->pullMessage(pFindBrokerResult->brokerAddr, pRequestHeader,

+                                                                timeoutMillis, communicationMode, pullCallback, pArg,

+                                                                session_credentials);

   }

   THROW_MQEXCEPTION(MQClientException, "The broker not exist", -1);

 }

diff --git a/src/consumer/PullAPIWrapper.h b/src/consumer/PullAPIWrapper.h
old mode 100755
new mode 100644
index e3d0a1e..57c6f0d
--- a/src/consumer/PullAPIWrapper.h
+++ b/src/consumer/PullAPIWrapper.h
@@ -32,8 +32,7 @@
   PullAPIWrapper(MQClientFactory* mQClientFactory, const string& consumerGroup);

   ~PullAPIWrapper();

 

-  PullResult processPullResult(const MQMessageQueue& mq, PullResult* pullResult,

-                               SubscriptionData* subscriptionData);

+  PullResult processPullResult(const MQMessageQueue& mq, PullResult* pullResult, SubscriptionData* subscriptionData);

 

   PullResult* pullKernelImpl(const MQMessageQueue& mq,        // 1

                              string subExpression,            // 2

diff --git a/src/consumer/PullRequest.cpp b/src/consumer/PullRequest.cpp
index b261d82..162be2a 100644
--- a/src/consumer/PullRequest.cpp
+++ b/src/consumer/PullRequest.cpp
@@ -28,7 +28,6 @@
       m_queueOffsetMax(0),

       m_bDroped(false),

       m_bLocked(false),

-      m_latestPullRequestOpaque(0),

       m_bPullMsgEventInprogress(false) {}

 

 PullRequest::~PullRequest() {

@@ -46,7 +45,6 @@
     m_messageQueue = other.m_messageQueue;

     m_msgTreeMap = other.m_msgTreeMap;

     m_msgTreeMapTemp = other.m_msgTreeMapTemp;

-    m_latestPullRequestOpaque = other.m_latestPullRequestOpaque;

   }

   return *this;

 }

@@ -82,16 +80,16 @@
   }

 }

 

-int64 PullRequest::getCacheMaxOffset() { return m_queueOffsetMax; }

+int64 PullRequest::getCacheMaxOffset() {

+  return m_queueOffsetMax;

+}

 

 int PullRequest::getCacheMsgCount() {

   boost::lock_guard<boost::mutex> lock(m_pullRequestLock);

   return m_msgTreeMap.size();

 }

 

-void PullRequest::getMessageByQueueOffset(vector<MQMessageExt>& msgs,

-                                          int64 minQueueOffset,

-                                          int64 maxQueueOffset) {

+void PullRequest::getMessageByQueueOffset(vector<MQMessageExt>& msgs, int64 minQueueOffset, int64 maxQueueOffset) {

   boost::lock_guard<boost::mutex> lock(m_pullRequestLock);

 

   int64 it = minQueueOffset;

@@ -107,23 +105,19 @@
   LOG_DEBUG("m_queueOffsetMax is:%lld", m_queueOffsetMax);

   if (!m_msgTreeMap.empty()) {

     result = m_queueOffsetMax + 1;

-    LOG_DEBUG(

-        " offset result is:%lld, m_queueOffsetMax is:%lld, msgs size:" SIZET_FMT

-        "",

-        result, m_queueOffsetMax, msgs.size());

+    LOG_DEBUG(" offset result is:%lld, m_queueOffsetMax is:%lld, msgs size:" SIZET_FMT "", result, m_queueOffsetMax,

+              msgs.size());

     vector<MQMessageExt>::iterator it = msgs.begin();

     for (; it != msgs.end(); it++) {

-      LOG_DEBUG("remove these msg from m_msgTreeMap, its offset:%lld",

-                it->getQueueOffset());

+      LOG_DEBUG("remove these msg from m_msgTreeMap, its offset:%lld", it->getQueueOffset());

       m_msgTreeMap.erase(it->getQueueOffset());

     }

 

     if (!m_msgTreeMap.empty()) {

       map<int64, MQMessageExt>::iterator it = m_msgTreeMap.begin();

       result = it->first;

-      LOG_INFO("cache msg size:" SIZET_FMT

-               " of pullRequest:%s, return offset result is:%lld",

-               m_msgTreeMap.size(), m_messageQueue.toString().c_str(), result);

+      LOG_INFO("cache msg size:" SIZET_FMT " of pullRequest:%s, return offset result is:%lld", m_msgTreeMap.size(),

+               m_messageQueue.toString().c_str(), result);

     }

   }

 

@@ -166,7 +160,9 @@
   */

 }

 

-bool PullRequest::isDroped() const { return m_bDroped.load() == 1; }

+bool PullRequest::isDroped() const {

+  return m_bDroped.load() == 1;

+}

 

 int64 PullRequest::getNextOffset() {

   boost::lock_guard<boost::mutex> lock(m_pullRequestLock);

@@ -177,24 +173,29 @@
   int temp = (Locked == true ? 1 : 0);

   m_bLocked.store(temp);

 }

-bool PullRequest::isLocked() const { return m_bLocked.load() == 1; }

+bool PullRequest::isLocked() const {

+  return m_bLocked.load() == 1;

+}

 

 bool PullRequest::isLockExpired() const {

-  return (UtilAll::currentTimeMillis() - m_lastLockTimestamp) >

-         RebalanceLockMaxLiveTime;

+  return (UtilAll::currentTimeMillis() - m_lastLockTimestamp) > RebalanceLockMaxLiveTime;

 }

 

 void PullRequest::setLastLockTimestamp(int64 time) {

   m_lastLockTimestamp = time;

 }

 

-int64 PullRequest::getLastLockTimestamp() const { return m_lastLockTimestamp; }

+int64 PullRequest::getLastLockTimestamp() const {

+  return m_lastLockTimestamp;

+}

 

 void PullRequest::setLastPullTimestamp(uint64 time) {

   m_lastPullTimestamp = time;

 }

 

-uint64 PullRequest::getLastPullTimestamp() const { return m_lastPullTimestamp; }

+uint64 PullRequest::getLastPullTimestamp() const {

+  return m_lastPullTimestamp;

+}

 

 void PullRequest::setLastConsumeTimestamp(uint64 time) {

   m_lastConsumeTimestamp = time;

@@ -204,16 +205,22 @@
   return m_lastConsumeTimestamp;

 }

 

-void PullRequest::setTryUnlockTimes(int time) { m_lastLockTimestamp = time; }

+void PullRequest::setTryUnlockTimes(int time) {

+  m_lastLockTimestamp = time;

+}

 

-int PullRequest::getTryUnlockTimes() const { return m_lastLockTimestamp; }

+int PullRequest::getTryUnlockTimes() const {

+  return m_lastLockTimestamp;

+}

 

 void PullRequest::setNextOffset(int64 nextoffset) {

   boost::lock_guard<boost::mutex> lock(m_pullRequestLock);

   m_nextOffset = nextoffset;

 }

 

-string PullRequest::getGroupName() const { return m_groupname; }

+string PullRequest::getGroupName() const {

+  return m_groupname;

+}

 

 boost::timed_mutex& PullRequest::getPullRequestCriticalSection() {

   return m_consumeLock;

@@ -250,27 +257,18 @@
   }

 }

 

-void PullRequest::removePullMsgEvent() { m_bPullMsgEventInprogress = false; }

+void PullRequest::removePullMsgEvent() {

+  m_bPullMsgEventInprogress = false;

+}

 

 bool PullRequest::addPullMsgEvent() {

   if (m_bPullMsgEventInprogress == false) {

     m_bPullMsgEventInprogress = true;

-    LOG_INFO("pullRequest with mq :%s set pullMsgEvent",

-             m_messageQueue.toString().c_str());

+    LOG_INFO("pullRequest with mq :%s set pullMsgEvent", m_messageQueue.toString().c_str());

     return true;

   }

   return false;

 }

 

-int PullRequest::getLatestPullRequestOpaque() {

-    boost::lock_guard<boost::mutex> lock(m_pullRequestLock);

-    return m_latestPullRequestOpaque;

-}

-

-void PullRequest::setLatestPullRequestOpaque(int opaque) {

-    boost::lock_guard<boost::mutex> lock(m_pullRequestLock);

-    m_latestPullRequestOpaque = opaque;

-}

-

 //<!***************************************************************************

 }  //<!end namespace;

diff --git a/src/consumer/PullRequest.h b/src/consumer/PullRequest.h
index 57ab70b..83b39b8 100644
--- a/src/consumer/PullRequest.h
+++ b/src/consumer/PullRequest.h
@@ -35,8 +35,7 @@
   int64 getCacheMinOffset();
   int64 getCacheMaxOffset();
   int getCacheMsgCount();
-  void getMessageByQueueOffset(vector<MQMessageExt>& msgs, int64 minQueueOffset,
-                               int64 maxQueueOffset);
+  void getMessageByQueueOffset(vector<MQMessageExt>& msgs, int64 minQueueOffset, int64 maxQueueOffset);
   int64 removeMessage(vector<MQMessageExt>& msgs);
   void clearAllMsgs();
 
@@ -69,8 +68,6 @@
   boost::timed_mutex& getPullRequestCriticalSection();
   void removePullMsgEvent();
   bool addPullMsgEvent();
-  int getLatestPullRequestOpaque();
-  void setLatestPullRequestOpaque(int opaque);
 
  public:
   MQMessageQueue m_messageQueue;
@@ -87,10 +84,9 @@
   map<int64, MQMessageExt> m_msgTreeMapTemp;
   boost::mutex m_pullRequestLock;
   uint64 m_lastLockTimestamp;  // ms
-  //uint64 m_tryUnlockTimes;
+  // uint64 m_tryUnlockTimes;
   uint64 m_lastPullTimestamp;
   uint64 m_lastConsumeTimestamp;
-  int    m_latestPullRequestOpaque;
   boost::timed_mutex m_consumeLock;
   boost::atomic<bool> m_bPullMsgEventInprogress;
 };
diff --git a/src/consumer/PullResult.cpp b/src/consumer/PullResult.cpp
old mode 100755
new mode 100644
index 8648abe..5fc2f67
--- a/src/consumer/PullResult.cpp
+++ b/src/consumer/PullResult.cpp
@@ -19,36 +19,28 @@
 

 namespace rocketmq {

 //<!************************************************************************

-PullResult::PullResult()

-    : pullStatus(NO_MATCHED_MSG),

-      nextBeginOffset(0),

-      minOffset(0),

-      maxOffset(0) {}

+PullResult::PullResult() : pullStatus(NO_MATCHED_MSG), nextBeginOffset(0), minOffset(0), maxOffset(0) {}

 

-PullResult::PullResult(PullStatus status)

-    : pullStatus(status), nextBeginOffset(0), minOffset(0), maxOffset(0) {}

+PullResult::PullResult(PullStatus status) : pullStatus(status), nextBeginOffset(0), minOffset(0), maxOffset(0) {}

 

-PullResult::PullResult(PullStatus pullStatus, int64 nextBeginOffset,

-                       int64 minOffset, int64 maxOffset)

-    : pullStatus(pullStatus),

-      nextBeginOffset(nextBeginOffset),

-      minOffset(minOffset),

-      maxOffset(maxOffset) {}

+PullResult::PullResult(PullStatus pullStatus, int64 nextBeginOffset, int64 minOffset, int64 maxOffset)

+    : pullStatus(pullStatus), nextBeginOffset(nextBeginOffset), minOffset(minOffset), maxOffset(maxOffset) {}

 

-PullResult::PullResult(PullStatus pullStatus, int64 nextBeginOffset,

-                       int64 minOffset, int64 maxOffset,

+PullResult::PullResult(PullStatus pullStatus,

+                       int64 nextBeginOffset,

+                       int64 minOffset,

+                       int64 maxOffset,

                        const vector<MQMessageExt>& src)

-    : pullStatus(pullStatus),

-      nextBeginOffset(nextBeginOffset),

-      minOffset(minOffset),

-      maxOffset(maxOffset) {

+    : pullStatus(pullStatus), nextBeginOffset(nextBeginOffset), minOffset(minOffset), maxOffset(maxOffset) {

   msgFoundList.reserve(src.size());

   for (size_t i = 0; i < src.size(); i++) {

     msgFoundList.push_back(src[i]);

   }

 }

 

-PullResult::~PullResult() { msgFoundList.clear(); }

+PullResult::~PullResult() {

+  msgFoundList.clear();

+}

 

 //<!***************************************************************************

 }  //<!end namespace;

diff --git a/src/consumer/PullResultExt.h b/src/consumer/PullResultExt.h
old mode 100755
new mode 100644
index 07a8c94..c5141e2
--- a/src/consumer/PullResultExt.h
+++ b/src/consumer/PullResultExt.h
@@ -25,22 +25,32 @@
 //<!***************************************************************************
 class PullResultExt : public PullResult {
  public:
-  PullResultExt(PullStatus pullStatus, int64 nextBeginOffset, int64 minOffset,
-                int64 maxOffset, int suggestWhichBrokerId, const MemoryBlock &messageBinary)
+  PullResultExt(PullStatus pullStatus,
+                int64 nextBeginOffset,
+                int64 minOffset,
+                int64 maxOffset,
+                int suggestWhichBrokerId,
+                const MemoryBlock& messageBinary)
       : PullResult(pullStatus, nextBeginOffset, minOffset, maxOffset),
         suggestWhichBrokerId(suggestWhichBrokerId),
         msgMemBlock(messageBinary) {}
 
-  PullResultExt(PullStatus pullStatus, int64 nextBeginOffset, int64 minOffset,
-                int64 maxOffset, int suggestWhichBrokerId, MemoryBlock &&messageBinary)
+  PullResultExt(PullStatus pullStatus,
+                int64 nextBeginOffset,
+                int64 minOffset,
+                int64 maxOffset,
+                int suggestWhichBrokerId,
+                MemoryBlock&& messageBinary)
       : PullResult(pullStatus, nextBeginOffset, minOffset, maxOffset),
         suggestWhichBrokerId(suggestWhichBrokerId),
         msgMemBlock(std::forward<MemoryBlock>(messageBinary)) {}
 
-  PullResultExt(PullStatus pullStatus, int64 nextBeginOffset, int64 minOffset,
-                int64 maxOffset, int suggestWhichBrokerId)
-      : PullResult(pullStatus, nextBeginOffset, minOffset, maxOffset),
-        suggestWhichBrokerId(suggestWhichBrokerId) {}
+  PullResultExt(PullStatus pullStatus,
+                int64 nextBeginOffset,
+                int64 minOffset,
+                int64 maxOffset,
+                int suggestWhichBrokerId)
+      : PullResult(pullStatus, nextBeginOffset, minOffset, maxOffset), suggestWhichBrokerId(suggestWhichBrokerId) {}
 
   virtual ~PullResultExt() {}
 
diff --git a/src/consumer/Rebalance.cpp b/src/consumer/Rebalance.cpp
index b4e6360..549e412 100644
--- a/src/consumer/Rebalance.cpp
+++ b/src/consumer/Rebalance.cpp
@@ -32,7 +32,8 @@
 Rebalance::~Rebalance() {
   {
     map<string, SubscriptionData*>::iterator it = m_subscriptionData.begin();
-    for (; it != m_subscriptionData.end(); ++it) deleteAndZero(it->second);
+    for (; it != m_subscriptionData.end(); ++it)
+      deleteAndZero(it->second);
     m_subscriptionData.clear();
   }
   {
@@ -63,8 +64,7 @@
       }
       if (mqAll.empty()) {
         if (!UtilAll::startsWith_retry(topic))
-          THROW_MQEXCEPTION(MQClientException, "doRebalance the topic is empty",
-                            -1);
+          THROW_MQEXCEPTION(MQClientException, "doRebalance the topic is empty", -1);
       }
 
       //<!msg model;
@@ -78,9 +78,8 @@
         }
         case CLUSTERING: {
           vector<string> cidAll;
-          m_pClientFactory->findConsumerIds(
-              topic, m_pConsumer->getGroupName(), cidAll,
-              m_pConsumer->getSessionCredentials());
+          m_pClientFactory->findConsumerIds(topic, m_pConsumer->getGroupName(), cidAll,
+                                            m_pConsumer->getSessionCredentials());
 
           if (cidAll.empty()) {
             /*remove the droping pullRequest changes for recovery consume fastly
@@ -102,13 +101,11 @@
                     }
             }*/
 
-            THROW_MQEXCEPTION(MQClientException,
-                              "doRebalance the cidAll is empty", -1);
+            THROW_MQEXCEPTION(MQClientException, "doRebalance the cidAll is empty", -1);
           }
           // log
           for (int i = 0; i < (int)cidAll.size(); ++i) {
-            LOG_INFO("client id:%s of topic:%s", cidAll[i].c_str(),
-                     topic.c_str());
+            LOG_INFO("client id:%s of topic:%s", cidAll[i].c_str(), topic.c_str());
           }
           //<! sort;
           sort(mqAll.begin(), mqAll.end());
@@ -117,8 +114,7 @@
           //<! allocate;
           vector<MQMessageQueue> allocateResult;
           try {
-            m_pAllocateMQStrategy->allocate(m_pConsumer->getMQClientId(), mqAll,
-                                            cidAll, allocateResult);
+            m_pAllocateMQStrategy->allocate(m_pConsumer->getMQClientId(), mqAll, cidAll, allocateResult);
           } catch (MQException& e) {
             THROW_MQEXCEPTION(MQClientException, "allocate error", -1);
           }
@@ -145,8 +141,7 @@
 }
 
 void Rebalance::persistConsumerOffset() {
-  DefaultMQPushConsumer* pConsumer =
-      static_cast<DefaultMQPushConsumer*>(m_pConsumer);
+  DefaultMQPushConsumer* pConsumer = static_cast<DefaultMQPushConsumer*>(m_pConsumer);
   OffsetStore* pOffsetStore = pConsumer->getOffsetStore();
   vector<MQMessageQueue> mqs;
   {
@@ -170,8 +165,7 @@
 }
 
 void Rebalance::persistConsumerOffsetByResetOffset() {
-  DefaultMQPushConsumer* pConsumer =
-      static_cast<DefaultMQPushConsumer*>(m_pConsumer);
+  DefaultMQPushConsumer* pConsumer = static_cast<DefaultMQPushConsumer*>(m_pConsumer);
   OffsetStore* pOffsetStore = pConsumer->getOffsetStore();
   vector<MQMessageQueue> mqs;
   {
@@ -201,20 +195,16 @@
   return m_subscriptionData;
 }
 
-void Rebalance::setSubscriptionData(const string& topic,
-                                    SubscriptionData* pdata) {
-  if (pdata != NULL &&
-      m_subscriptionData.find(topic) == m_subscriptionData.end())
+void Rebalance::setSubscriptionData(const string& topic, SubscriptionData* pdata) {
+  if (pdata != NULL && m_subscriptionData.find(topic) == m_subscriptionData.end())
     m_subscriptionData[topic] = pdata;
 }
 
-void Rebalance::setTopicSubscribeInfo(const string& topic,
-                                      vector<MQMessageQueue>& mqs) {
+void Rebalance::setTopicSubscribeInfo(const string& topic, vector<MQMessageQueue>& mqs) {
   if (m_subscriptionData.find(topic) != m_subscriptionData.end()) {
     {
       boost::lock_guard<boost::mutex> lock(m_topicSubscribeInfoTableMutex);
-      if (m_topicSubscribeInfoTable.find(topic) !=
-          m_topicSubscribeInfoTable.end())
+      if (m_topicSubscribeInfoTable.find(topic) != m_topicSubscribeInfoTable.end())
         m_topicSubscribeInfoTable.erase(topic);
       m_topicSubscribeInfoTable[topic] = mqs;
     }
@@ -226,11 +216,9 @@
   }
 }
 
-bool Rebalance::getTopicSubscribeInfo(const string& topic,
-                                      vector<MQMessageQueue>& mqs) {
+bool Rebalance::getTopicSubscribeInfo(const string& topic, vector<MQMessageQueue>& mqs) {
   boost::lock_guard<boost::mutex> lock(m_topicSubscribeInfoTableMutex);
-  if (m_topicSubscribeInfoTable.find(topic) !=
-      m_topicSubscribeInfoTable.end()) {
+  if (m_topicSubscribeInfoTable.find(topic) != m_topicSubscribeInfoTable.end()) {
     mqs = m_topicSubscribeInfoTable[topic];
     return true;
   }
@@ -258,8 +246,7 @@
 void Rebalance::unlockAll(bool oneway) {
   map<string, vector<MQMessageQueue>*> brokerMqs;
   MQ2PULLREQ requestQueueTable = getPullRequestTable();
-  for (MQ2PULLREQ::iterator it = requestQueueTable.begin();
-       it != requestQueueTable.end(); ++it) {
+  for (MQ2PULLREQ::iterator it = requestQueueTable.begin(); it != requestQueueTable.end(); ++it) {
     if (!(it->second->isDroped())) {
       if (brokerMqs.find(it->first.getBrokerName()) == brokerMqs.end()) {
         vector<MQMessageQueue>* mqs = new vector<MQMessageQueue>;
@@ -270,26 +257,22 @@
     }
   }
   LOG_INFO("unLockAll " SIZET_FMT " broker mqs", brokerMqs.size());
-  for (map<string, vector<MQMessageQueue>*>::iterator itb = brokerMqs.begin();
-       itb != brokerMqs.end(); ++itb) {
+  for (map<string, vector<MQMessageQueue>*>::iterator itb = brokerMqs.begin(); itb != brokerMqs.end(); ++itb) {
     unique_ptr<FindBrokerResult> pFindBrokerResult(
-        m_pClientFactory->findBrokerAddressInSubscribe(itb->first, MASTER_ID,
-                                                       true));
+        m_pClientFactory->findBrokerAddressInSubscribe(itb->first, MASTER_ID, true));
     if (!pFindBrokerResult) {
       LOG_ERROR("unlockAll findBrokerAddressInSubscribe ret null for broker:%s", itb->first.data());
       continue;
     }
-    unique_ptr<UnlockBatchRequestBody> unlockBatchRequest(
-        new UnlockBatchRequestBody());
+    unique_ptr<UnlockBatchRequestBody> unlockBatchRequest(new UnlockBatchRequestBody());
     vector<MQMessageQueue> mqs(*(itb->second));
     unlockBatchRequest->setClientId(m_pConsumer->getMQClientId());
     unlockBatchRequest->setConsumerGroup(m_pConsumer->getGroupName());
     unlockBatchRequest->setMqSet(mqs);
 
     try {
-      m_pClientFactory->getMQClientAPIImpl()->unlockBatchMQ(
-          pFindBrokerResult->brokerAddr, unlockBatchRequest.get(), 1000,
-          m_pConsumer->getSessionCredentials());
+      m_pClientFactory->getMQClientAPIImpl()->unlockBatchMQ(pFindBrokerResult->brokerAddr, unlockBatchRequest.get(),
+                                                            1000, m_pConsumer->getSessionCredentials());
       for (unsigned int i = 0; i != mqs.size(); ++i) {
         PullRequest* pullreq = getPullRequest(mqs[i]);
         if (pullreq) {
@@ -309,14 +292,12 @@
 
 void Rebalance::unlock(MQMessageQueue mq) {
   unique_ptr<FindBrokerResult> pFindBrokerResult(
-      m_pClientFactory->findBrokerAddressInSubscribe(mq.getBrokerName(),
-                                                     MASTER_ID, true));
+      m_pClientFactory->findBrokerAddressInSubscribe(mq.getBrokerName(), MASTER_ID, true));
   if (!pFindBrokerResult) {
     LOG_ERROR("unlock findBrokerAddressInSubscribe ret null for broker:%s", mq.getBrokerName().data());
     return;
   }
-  unique_ptr<UnlockBatchRequestBody> unlockBatchRequest(
-      new UnlockBatchRequestBody());
+  unique_ptr<UnlockBatchRequestBody> unlockBatchRequest(new UnlockBatchRequestBody());
   vector<MQMessageQueue> mqs;
   mqs.push_back(mq);
   unlockBatchRequest->setClientId(m_pConsumer->getMQClientId());
@@ -324,9 +305,8 @@
   unlockBatchRequest->setMqSet(mqs);
 
   try {
-    m_pClientFactory->getMQClientAPIImpl()->unlockBatchMQ(
-        pFindBrokerResult->brokerAddr, unlockBatchRequest.get(), 1000,
-        m_pConsumer->getSessionCredentials());
+    m_pClientFactory->getMQClientAPIImpl()->unlockBatchMQ(pFindBrokerResult->brokerAddr, unlockBatchRequest.get(), 1000,
+                                                          m_pConsumer->getSessionCredentials());
     for (unsigned int i = 0; i != mqs.size(); ++i) {
       PullRequest* pullreq = getPullRequest(mqs[i]);
       if (pullreq) {
@@ -344,8 +324,7 @@
 void Rebalance::lockAll() {
   map<string, vector<MQMessageQueue>*> brokerMqs;
   MQ2PULLREQ requestQueueTable = getPullRequestTable();
-  for (MQ2PULLREQ::iterator it = requestQueueTable.begin();
-       it != requestQueueTable.end(); ++it) {
+  for (MQ2PULLREQ::iterator it = requestQueueTable.begin(); it != requestQueueTable.end(); ++it) {
     if (!(it->second->isDroped())) {
       string brokerKey = it->first.getBrokerName() + it->first.getTopic();
       if (brokerMqs.find(brokerKey) == brokerMqs.end()) {
@@ -358,38 +337,31 @@
     }
   }
   LOG_INFO("LockAll " SIZET_FMT " broker mqs", brokerMqs.size());
-  for (map<string, vector<MQMessageQueue>*>::iterator itb = brokerMqs.begin();
-       itb != brokerMqs.end(); ++itb) {
+  for (map<string, vector<MQMessageQueue>*>::iterator itb = brokerMqs.begin(); itb != brokerMqs.end(); ++itb) {
     string brokerName = (*(itb->second))[0].getBrokerName();
     unique_ptr<FindBrokerResult> pFindBrokerResult(
-        m_pClientFactory->findBrokerAddressInSubscribe(
-                brokerName, MASTER_ID, true));
+        m_pClientFactory->findBrokerAddressInSubscribe(brokerName, MASTER_ID, true));
     if (!pFindBrokerResult) {
       LOG_ERROR("lockAll findBrokerAddressInSubscribe ret null for broker:%s", brokerName.data());
       continue;
     }
-    unique_ptr<LockBatchRequestBody> lockBatchRequest(
-        new LockBatchRequestBody());
+    unique_ptr<LockBatchRequestBody> lockBatchRequest(new LockBatchRequestBody());
     lockBatchRequest->setClientId(m_pConsumer->getMQClientId());
     lockBatchRequest->setConsumerGroup(m_pConsumer->getGroupName());
     lockBatchRequest->setMqSet(*(itb->second));
-    LOG_INFO("try to lock:" SIZET_FMT " mqs of broker:%s", itb->second->size(),
-             itb->first.c_str());
+    LOG_INFO("try to lock:" SIZET_FMT " mqs of broker:%s", itb->second->size(), itb->first.c_str());
     try {
       vector<MQMessageQueue> messageQueues;
-      m_pClientFactory->getMQClientAPIImpl()->lockBatchMQ(
-          pFindBrokerResult->brokerAddr, lockBatchRequest.get(), messageQueues,
-          1000, m_pConsumer->getSessionCredentials());
+      m_pClientFactory->getMQClientAPIImpl()->lockBatchMQ(pFindBrokerResult->brokerAddr, lockBatchRequest.get(),
+                                                          messageQueues, 1000, m_pConsumer->getSessionCredentials());
       for (unsigned int i = 0; i != messageQueues.size(); ++i) {
         PullRequest* pullreq = getPullRequest(messageQueues[i]);
         if (pullreq) {
-          LOG_INFO("lockBatchMQ success of mq:%s",
-                   messageQueues[i].toString().c_str());
+          LOG_INFO("lockBatchMQ success of mq:%s", messageQueues[i].toString().c_str());
           pullreq->setLocked(true);
           pullreq->setLastLockTimestamp(UtilAll::currentTimeMillis());
         } else {
-          LOG_ERROR("lockBatchMQ fails of mq:%s",
-                    messageQueues[i].toString().c_str());
+          LOG_ERROR("lockBatchMQ fails of mq:%s", messageQueues[i].toString().c_str());
         }
       }
       messageQueues.clear();
@@ -402,8 +374,7 @@
 }
 bool Rebalance::lock(MQMessageQueue mq) {
   unique_ptr<FindBrokerResult> pFindBrokerResult(
-      m_pClientFactory->findBrokerAddressInSubscribe(mq.getBrokerName(),
-                                                     MASTER_ID, true));
+      m_pClientFactory->findBrokerAddressInSubscribe(mq.getBrokerName(), MASTER_ID, true));
   if (!pFindBrokerResult) {
     LOG_ERROR("lock findBrokerAddressInSubscribe ret null for broker:%s", mq.getBrokerName().data());
     return false;
@@ -419,12 +390,10 @@
   try {
     vector<MQMessageQueue> messageQueues;
     LOG_DEBUG("try to lock mq:%s", mq.toString().c_str());
-    m_pClientFactory->getMQClientAPIImpl()->lockBatchMQ(
-        pFindBrokerResult->brokerAddr, lockBatchRequest.get(), messageQueues,
-        1000, m_pConsumer->getSessionCredentials());
+    m_pClientFactory->getMQClientAPIImpl()->lockBatchMQ(pFindBrokerResult->brokerAddr, lockBatchRequest.get(),
+                                                        messageQueues, 1000, m_pConsumer->getSessionCredentials());
     if (messageQueues.size() == 0) {
-      LOG_ERROR("lock mq on broker:%s failed",
-                pFindBrokerResult->brokerAddr.c_str());
+      LOG_ERROR("lock mq on broker:%s failed", pFindBrokerResult->brokerAddr.c_str());
       return false;
     }
     for (unsigned int i = 0; i != messageQueues.size(); ++i) {
@@ -447,11 +416,9 @@
 }
 
 //<!************************************************************************
-RebalancePull::RebalancePull(MQConsumer* consumer, MQClientFactory* pfactory)
-    : Rebalance(consumer, pfactory) {}
+RebalancePull::RebalancePull(MQConsumer* consumer, MQClientFactory* pfactory) : Rebalance(consumer, pfactory) {}
 
-bool RebalancePull::updateRequestTableInRebalance(
-    const string& topic, vector<MQMessageQueue>& mqsSelf) {
+bool RebalancePull::updateRequestTableInRebalance(const string& topic, vector<MQMessageQueue>& mqsSelf) {
   return false;
 }
 
@@ -466,11 +433,9 @@
 void RebalancePull::removeUnnecessaryMessageQueue(const MQMessageQueue& mq) {}
 
 //<!***************************************************************************
-RebalancePush::RebalancePush(MQConsumer* consumer, MQClientFactory* pfactory)
-    : Rebalance(consumer, pfactory) {}
+RebalancePush::RebalancePush(MQConsumer* consumer, MQClientFactory* pfactory) : Rebalance(consumer, pfactory) {}
 
-bool RebalancePush::updateRequestTableInRebalance(
-    const string& topic, vector<MQMessageQueue>& mqsSelf) {
+bool RebalancePush::updateRequestTableInRebalance(const string& topic, vector<MQMessageQueue>& mqsSelf) {
   LOG_DEBUG("updateRequestTableInRebalance Enter");
   if (mqsSelf.empty()) {
     LOG_WARN("allocated queue is empty for topic:%s", topic.c_str());
@@ -484,17 +449,16 @@
   for (; it != requestQueueTable.end(); ++it) {
     MQMessageQueue mqtemp = it->first;
     if (mqtemp.getTopic().compare(topic) == 0) {
-      if (mqsSelf.empty() ||
-          (find(mqsSelf.begin(), mqsSelf.end(), mqtemp) == mqsSelf.end())) {
+      if (mqsSelf.empty() || (find(mqsSelf.begin(), mqsSelf.end(), mqtemp) == mqsSelf.end())) {
         if (!(it->second->isDroped())) {
           it->second->setDroped(true);
-          //delete the lastest pull request for this mq, which hasn't been response
-          //m_pClientFactory->removeDropedPullRequestOpaque(it->second);
+          // delete the lastest pull request for this mq, which hasn't been response
+          // m_pClientFactory->removeDropedPullRequestOpaque(it->second);
           removeUnnecessaryMessageQueue(mqtemp);
           it->second->clearAllMsgs();  // add clear operation to avoid bad state
                                        // when dropped pullRequest returns
                                        // normal
-          LOG_INFO("drop mq:%s, delete opaque:%d", mqtemp.toString().c_str(), it->second->getLatestPullRequestOpaque());
+          LOG_INFO("drop mq:%s", mqtemp.toString().c_str());
         }
         changed = true;
       }
@@ -503,8 +467,7 @@
 
   //<!add
   vector<PullRequest*> pullrequestAdd;
-  DefaultMQPushConsumer* pConsumer =
-      static_cast<DefaultMQPushConsumer*>(m_pConsumer);
+  DefaultMQPushConsumer* pConsumer = static_cast<DefaultMQPushConsumer*>(m_pConsumer);
   vector<MQMessageQueue>::iterator it2 = mqsSelf.begin();
   for (; it2 != mqsSelf.end(); ++it2) {
     PullRequest* pPullRequest(getPullRequest(*it2));
@@ -513,10 +476,9 @@
           "before resume the pull handle of this pullRequest, its mq is:%s, "
           "its offset is:%lld",
           (it2->toString()).c_str(), pPullRequest->getNextOffset());
-      pConsumer->getOffsetStore()->removeOffset(
-          *it2);  // remove dirty offset which maybe update to
-                  // OffsetStore::m_offsetTable by consuming After last
-                  // drop
+      pConsumer->getOffsetStore()->removeOffset(*it2);  // remove dirty offset which maybe update to
+                                                        // OffsetStore::m_offsetTable by consuming After last
+                                                        // drop
       int64 nextOffset = computePullFromWhere(*it2);
       if (nextOffset >= 0) {
         /*
@@ -530,8 +492,7 @@
         bool bPullMsgEvent = pPullRequest->addPullMsgEvent();
         while (!bPullMsgEvent) {
           boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
-          LOG_INFO("pullRequest with mq :%s has unfinished pullMsgEvent",
-                   (it2->toString()).c_str());
+          LOG_INFO("pullRequest with mq :%s has unfinished pullMsgEvent", (it2->toString()).c_str());
           bPullMsgEvent = pPullRequest->addPullMsgEvent();
         }
         pPullRequest->setDroped(false);
@@ -546,9 +507,7 @@
         changed = true;
         pConsumer->producePullMsgTask(pPullRequest);
       } else {
-        LOG_ERROR(
-            "get fatel error QueryOffset of mq:%s, do not reconsume this queue",
-            (it2->toString()).c_str());
+        LOG_ERROR("get fatel error QueryOffset of mq:%s, do not reconsume this queue", (it2->toString()).c_str());
       }
     }
 
@@ -566,8 +525,7 @@
         //<! mq-> pq;
         addPullRequest(*it2, pullRequest);
         pullrequestAdd.push_back(pullRequest);
-        LOG_INFO("add mq:%s, request initiall offset:%lld",
-                 (*it2).toString().c_str(), nextOffset);
+        LOG_INFO("add mq:%s, request initiall offset:%lld", (*it2).toString().c_str(), nextOffset);
       }
     }
   }
@@ -584,94 +542,72 @@
 
 int64 RebalancePush::computePullFromWhere(const MQMessageQueue& mq) {
   int64 result = -1;
-  DefaultMQPushConsumer* pConsumer =
-      static_cast<DefaultMQPushConsumer*>(m_pConsumer);
+  DefaultMQPushConsumer* pConsumer = static_cast<DefaultMQPushConsumer*>(m_pConsumer);
   ConsumeFromWhere consumeFromWhere = pConsumer->getConsumeFromWhere();
   OffsetStore* pOffsetStore = pConsumer->getOffsetStore();
   switch (consumeFromWhere) {
     case CONSUME_FROM_LAST_OFFSET: {
-      int64 lastOffset = pOffsetStore->readOffset(
-          mq, READ_FROM_STORE, m_pConsumer->getSessionCredentials());
+      int64 lastOffset = pOffsetStore->readOffset(mq, READ_FROM_STORE, m_pConsumer->getSessionCredentials());
       if (lastOffset >= 0) {
-        LOG_INFO("CONSUME_FROM_LAST_OFFSET, lastOffset of mq:%s is:%lld",
-                 mq.toString().c_str(), lastOffset);
+        LOG_INFO("CONSUME_FROM_LAST_OFFSET, lastOffset of mq:%s is:%lld", mq.toString().c_str(), lastOffset);
         result = lastOffset;
       } else if (-1 == lastOffset) {
-        LOG_WARN("CONSUME_FROM_LAST_OFFSET, lastOffset of mq:%s is -1",
-                 mq.toString().c_str());
+        LOG_WARN("CONSUME_FROM_LAST_OFFSET, lastOffset of mq:%s is -1", mq.toString().c_str());
         if (UtilAll::startsWith_retry(mq.getTopic())) {
-          LOG_INFO("CONSUME_FROM_LAST_OFFSET, lastOffset of mq:%s is 0",
-                   mq.toString().c_str());
+          LOG_INFO("CONSUME_FROM_LAST_OFFSET, lastOffset of mq:%s is 0", mq.toString().c_str());
           result = 0;
         } else {
           try {
             result = pConsumer->maxOffset(mq);
-            LOG_INFO("CONSUME_FROM_LAST_OFFSET, maxOffset of mq:%s is:%lld",
-                     mq.toString().c_str(), result);
+            LOG_INFO("CONSUME_FROM_LAST_OFFSET, maxOffset of mq:%s is:%lld", mq.toString().c_str(), result);
           } catch (MQException& e) {
-            LOG_ERROR(
-                "CONSUME_FROM_LAST_OFFSET error, lastOffset  of mq:%s is -1",
-                mq.toString().c_str());
+            LOG_ERROR("CONSUME_FROM_LAST_OFFSET error, lastOffset  of mq:%s is -1", mq.toString().c_str());
             result = -1;
           }
         }
       } else {
-        LOG_ERROR("CONSUME_FROM_LAST_OFFSET error, lastOffset  of mq:%s is -1",
-                  mq.toString().c_str());
+        LOG_ERROR("CONSUME_FROM_LAST_OFFSET error, lastOffset  of mq:%s is -1", mq.toString().c_str());
         result = -1;
       }
       break;
     }
     case CONSUME_FROM_FIRST_OFFSET: {
-      int64 lastOffset = pOffsetStore->readOffset(
-          mq, READ_FROM_STORE, m_pConsumer->getSessionCredentials());
+      int64 lastOffset = pOffsetStore->readOffset(mq, READ_FROM_STORE, m_pConsumer->getSessionCredentials());
       if (lastOffset >= 0) {
-        LOG_INFO("CONSUME_FROM_FIRST_OFFSET, lastOffset of mq:%s is:%lld",
-                 mq.toString().c_str(), lastOffset);
+        LOG_INFO("CONSUME_FROM_FIRST_OFFSET, lastOffset of mq:%s is:%lld", mq.toString().c_str(), lastOffset);
         result = lastOffset;
       } else if (-1 == lastOffset) {
-        LOG_INFO("CONSUME_FROM_FIRST_OFFSET, lastOffset of mq:%s, return 0",
-                 mq.toString().c_str());
+        LOG_INFO("CONSUME_FROM_FIRST_OFFSET, lastOffset of mq:%s, return 0", mq.toString().c_str());
         result = 0;
       } else {
-        LOG_ERROR("CONSUME_FROM_FIRST_OFFSET, lastOffset of mq:%s, return -1",
-                  mq.toString().c_str());
+        LOG_ERROR("CONSUME_FROM_FIRST_OFFSET, lastOffset of mq:%s, return -1", mq.toString().c_str());
         result = -1;
       }
       break;
     }
     case CONSUME_FROM_TIMESTAMP: {
-      int64 lastOffset = pOffsetStore->readOffset(
-          mq, READ_FROM_STORE, m_pConsumer->getSessionCredentials());
+      int64 lastOffset = pOffsetStore->readOffset(mq, READ_FROM_STORE, m_pConsumer->getSessionCredentials());
       if (lastOffset >= 0) {
-        LOG_INFO("CONSUME_FROM_TIMESTAMP, lastOffset of mq:%s is:%lld",
-                 mq.toString().c_str(), lastOffset);
+        LOG_INFO("CONSUME_FROM_TIMESTAMP, lastOffset of mq:%s is:%lld", mq.toString().c_str(), lastOffset);
         result = lastOffset;
       } else if (-1 == lastOffset) {
         if (UtilAll::startsWith_retry(mq.getTopic())) {
           try {
             result = pConsumer->maxOffset(mq);
-            LOG_INFO("CONSUME_FROM_TIMESTAMP, maxOffset  of mq:%s is:%lld",
-                     mq.toString().c_str(), result);
+            LOG_INFO("CONSUME_FROM_TIMESTAMP, maxOffset  of mq:%s is:%lld", mq.toString().c_str(), result);
           } catch (MQException& e) {
-            LOG_ERROR(
-                "CONSUME_FROM_TIMESTAMP error, lastOffset  of mq:%s is -1",
-                mq.toString().c_str());
+            LOG_ERROR("CONSUME_FROM_TIMESTAMP error, lastOffset  of mq:%s is -1", mq.toString().c_str());
             result = -1;
           }
         } else {
           try {
           } catch (MQException& e) {
-            LOG_ERROR(
-                "CONSUME_FROM_TIMESTAMP error, lastOffset  of mq:%s, return 0",
-                mq.toString().c_str());
+            LOG_ERROR("CONSUME_FROM_TIMESTAMP error, lastOffset  of mq:%s, return 0", mq.toString().c_str());
             result = -1;
           }
         }
       } else {
-        LOG_ERROR(
-            "CONSUME_FROM_TIMESTAMP error, lastOffset  of mq:%s, return -1",
-            mq.toString().c_str());
+        LOG_ERROR("CONSUME_FROM_TIMESTAMP error, lastOffset  of mq:%s, return -1", mq.toString().c_str());
         result = -1;
       }
       break;
@@ -687,8 +623,7 @@
                                         vector<MQMessageQueue>& mqDivided) {}
 
 void RebalancePush::removeUnnecessaryMessageQueue(const MQMessageQueue& mq) {
-  DefaultMQPushConsumer* pConsumer =
-      static_cast<DefaultMQPushConsumer*>(m_pConsumer);
+  DefaultMQPushConsumer* pConsumer = static_cast<DefaultMQPushConsumer*>(m_pConsumer);
   OffsetStore* pOffsetStore = pConsumer->getOffsetStore();
 
   pOffsetStore->persist(mq, m_pConsumer->getSessionCredentials());
@@ -699,4 +634,4 @@
 }
 
 //<!************************************************************************
-}  //<!end namespace;
+}  // namespace rocketmq
diff --git a/src/consumer/Rebalance.h b/src/consumer/Rebalance.h
old mode 100755
new mode 100644
index 42f8667..8d8a9ae
--- a/src/consumer/Rebalance.h
+++ b/src/consumer/Rebalance.h
@@ -42,8 +42,7 @@
 

   virtual int64 computePullFromWhere(const MQMessageQueue& mq) = 0;

 

-  virtual bool updateRequestTableInRebalance(

-      const string& topic, vector<MQMessageQueue>& mqsSelf) = 0;

+  virtual bool updateRequestTableInRebalance(const string& topic, vector<MQMessageQueue>& mqsSelf) = 0;

 

  public:

   void doRebalance();

@@ -95,8 +94,7 @@
 

   virtual int64 computePullFromWhere(const MQMessageQueue& mq);

 

-  virtual bool updateRequestTableInRebalance(const string& topic,

-                                             vector<MQMessageQueue>& mqsSelf);

+  virtual bool updateRequestTableInRebalance(const string& topic, vector<MQMessageQueue>& mqsSelf);

 };

 

 //<!***************************************************************************

@@ -113,8 +111,7 @@
 

   virtual int64 computePullFromWhere(const MQMessageQueue& mq);

 

-  virtual bool updateRequestTableInRebalance(const string& topic,

-                                             vector<MQMessageQueue>& mqsSelf);

+  virtual bool updateRequestTableInRebalance(const string& topic, vector<MQMessageQueue>& mqsSelf);

 };

 

 //<!************************************************************************

diff --git a/src/consumer/SubscriptionData.cpp b/src/consumer/SubscriptionData.cpp
old mode 100755
new mode 100644
index 9b20642..e771b52
--- a/src/consumer/SubscriptionData.cpp
+++ b/src/consumer/SubscriptionData.cpp
@@ -39,13 +39,21 @@
   m_codeSet = other.m_codeSet;
 }
 
-const string& SubscriptionData::getTopic() const { return m_topic; }
+const string& SubscriptionData::getTopic() const {
+  return m_topic;
+}
 
-const string& SubscriptionData::getSubString() const { return m_subString; }
+const string& SubscriptionData::getSubString() const {
+  return m_subString;
+}
 
-void SubscriptionData::setSubString(const string& sub) { m_subString = sub; }
+void SubscriptionData::setSubString(const string& sub) {
+  m_subString = sub;
+}
 
-int64 SubscriptionData::getSubVersion() const { return m_subVersion; }
+int64 SubscriptionData::getSubVersion() const {
+  return m_subVersion;
+}
 
 void SubscriptionData::putTagsSet(const string& tag) {
   m_tagSet.push_back(tag);
@@ -55,7 +63,9 @@
   return std::find(m_tagSet.begin(), m_tagSet.end(), tag) != m_tagSet.end();
 }
 
-vector<string>& SubscriptionData::getTagsSet() { return m_tagSet; }
+vector<string>& SubscriptionData::getTagsSet() {
+  return m_tagSet;
+}
 
 bool SubscriptionData::operator==(const SubscriptionData& other) const {
   if (!m_subString.compare(other.m_subString)) {
diff --git a/src/consumer/SubscriptionData.h b/src/consumer/SubscriptionData.h
old mode 100755
new mode 100644
diff --git a/src/dllmain.cpp b/src/dllmain.cpp
old mode 100755
new mode 100644
index 72f61fd..a9be1e0
--- a/src/dllmain.cpp
+++ b/src/dllmain.cpp
@@ -18,8 +18,7 @@
 #include <stdio.h>
 #include "windows.h"
 
-BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call,
-                      LPVOID lpReserved) {
+BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) {
   switch (ul_reason_for_call) {
     case DLL_PROCESS_ATTACH:
       break;
diff --git a/src/extern/CBatchMessage.cpp b/src/extern/CBatchMessage.cpp
new file mode 100644
index 0000000..3fb2a97
--- /dev/null
+++ b/src/extern/CBatchMessage.cpp
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <vector>
+
+#include "CBatchMessage.h"
+#include "CCommon.h"
+#include "CMessage.h"
+#include "MQMessage.h"
+
+using std::vector;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+using namespace rocketmq;
+
+CBatchMessage* CreateBatchMessage() {
+  vector<MQMessage>* msgs = new vector<MQMessage>();
+  return (CBatchMessage*)msgs;
+}
+
+int AddMessage(CBatchMessage* batchMsg, CMessage* msg) {
+  if (msg == NULL) {
+    return NULL_POINTER;
+  }
+  if (batchMsg == NULL) {
+    return NULL_POINTER;
+  }
+  MQMessage* message = (MQMessage*)msg;
+  ((vector<MQMessage>*)batchMsg)->push_back(*message);
+  return OK;
+}
+int DestroyBatchMessage(CBatchMessage* batchMsg) {
+  if (batchMsg == NULL) {
+    return NULL_POINTER;
+  }
+  delete (vector<MQMessage>*)batchMsg;
+  return OK;
+}
+
+#ifdef __cplusplus
+};
+#endif
diff --git a/src/extern/CErrorMessage.cpp b/src/extern/CErrorMessage.cpp
new file mode 100644
index 0000000..95cd852
--- /dev/null
+++ b/src/extern/CErrorMessage.cpp
@@ -0,0 +1,33 @@
+/*
+* Licensed to the Apache Software Foundation (ASF) under one or more
+* contributor license agreements.  See the NOTICE file distributed with
+* this work for additional information regarding copyright ownership.
+* The ASF licenses this file to You under the Apache License, Version 2.0
+* (the "License"); you may not use this file except in compliance with
+* the License.  You may obtain a copy of the License at
+*
+*     http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#include "CErrorMessage.h"
+#include "CCommon.h"
+#include "MQClientErrorContainer.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+	using namespace rocketmq;
+
+	const char *GetLatestErrorMessage() {
+		return MQClientErrorContainer::instance()->getErr().c_str();
+	}
+
+#ifdef __cplusplus
+};
+#endif
\ No newline at end of file
diff --git a/src/extern/CMessage.cpp b/src/extern/CMessage.cpp
index 4106c27..1008f00 100644
--- a/src/extern/CMessage.cpp
+++ b/src/extern/CMessage.cpp
@@ -25,69 +25,68 @@
 
 using namespace rocketmq;
 
-CMessage *CreateMessage(const char *topic) {
-
-    MQMessage *mqMessage = new MQMessage();
-    if (topic != NULL) {
-        mqMessage->setTopic(topic);
-    }
-    return (CMessage *) mqMessage;
+CMessage* CreateMessage(const char* topic) {
+  MQMessage* mqMessage = new MQMessage();
+  if (topic != NULL) {
+    mqMessage->setTopic(topic);
+  }
+  return (CMessage*)mqMessage;
 }
-int DestroyMessage(CMessage *msg) {
-    if (msg == NULL) {
-        return NULL_POINTER;
-    }
-    delete (MQMessage *)msg;
-    return OK;
+int DestroyMessage(CMessage* msg) {
+  if (msg == NULL) {
+    return NULL_POINTER;
+  }
+  delete (MQMessage*)msg;
+  return OK;
 }
-int SetMessageTopic(CMessage *msg, const char *topic) {
-    if (msg == NULL) {
-        return NULL_POINTER;
-    }
-    ((MQMessage *)msg)->setTopic(topic);
-    return OK;
+int SetMessageTopic(CMessage* msg, const char* topic) {
+  if (msg == NULL) {
+    return NULL_POINTER;
+  }
+  ((MQMessage*)msg)->setTopic(topic);
+  return OK;
 }
-int SetMessageTags(CMessage *msg, const char *tags) {
-    if (msg == NULL) {
-        return NULL_POINTER;
-    }
-    ((MQMessage *)msg)->setTags(tags);
-    return OK;
+int SetMessageTags(CMessage* msg, const char* tags) {
+  if (msg == NULL) {
+    return NULL_POINTER;
+  }
+  ((MQMessage*)msg)->setTags(tags);
+  return OK;
 }
-int SetMessageKeys(CMessage *msg, const char *keys) {
-    if (msg == NULL) {
-        return NULL_POINTER;
-    }
-    ((MQMessage *)msg)->setKeys(keys);
-    return OK;
+int SetMessageKeys(CMessage* msg, const char* keys) {
+  if (msg == NULL) {
+    return NULL_POINTER;
+  }
+  ((MQMessage*)msg)->setKeys(keys);
+  return OK;
 }
-int SetMessageBody(CMessage *msg, const char *body) {
-    if (msg == NULL) {
-        return NULL_POINTER;
-    }
-    ((MQMessage *)msg)->setBody(body);
-    return OK;
+int SetMessageBody(CMessage* msg, const char* body) {
+  if (msg == NULL) {
+    return NULL_POINTER;
+  }
+  ((MQMessage*)msg)->setBody(body);
+  return OK;
 }
-int SetByteMessageBody(CMessage *msg, const char *body, int len) {
-    if (msg == NULL) {
-        return NULL_POINTER;
-    }
-    ((MQMessage *)msg)->setBody(body,len);
-    return OK;
+int SetByteMessageBody(CMessage* msg, const char* body, int len) {
+  if (msg == NULL) {
+    return NULL_POINTER;
+  }
+  ((MQMessage*)msg)->setBody(body, len);
+  return OK;
 }
-int SetMessageProperty(CMessage *msg, const char *key, const char *value) {
-    if (msg == NULL) {
-        return NULL_POINTER;
-    }
-    ((MQMessage *)msg)->setProperty(key,value);
-    return OK;
+int SetMessageProperty(CMessage* msg, const char* key, const char* value) {
+  if (msg == NULL) {
+    return NULL_POINTER;
+  }
+  ((MQMessage*)msg)->setProperty(key, value);
+  return OK;
 }
-int SetDelayTimeLevel(CMessage *msg, int level){
-    if (msg == NULL) {
-        return NULL_POINTER;
-    }
-    ((MQMessage *)msg)->setDelayTimeLevel(level);
-    return OK;
+int SetDelayTimeLevel(CMessage* msg, int level) {
+  if (msg == NULL) {
+    return NULL_POINTER;
+  }
+  ((MQMessage*)msg)->setDelayTimeLevel(level);
+  return OK;
 }
 
 #ifdef __cplusplus
diff --git a/src/extern/CMessageExt.cpp b/src/extern/CMessageExt.cpp
index 5d612d8..03a5e2d 100644
--- a/src/extern/CMessageExt.cpp
+++ b/src/extern/CMessageExt.cpp
@@ -23,104 +23,104 @@
 extern "C" {
 #endif
 using namespace rocketmq;
-const char *GetMessageTopic(CMessageExt *msg) {
-    if (msg == NULL) {
-        return NULL;
-    }
-    return ((MQMessageExt *) msg)->getTopic().c_str();
+const char* GetMessageTopic(CMessageExt* msg) {
+  if (msg == NULL) {
+    return NULL;
+  }
+  return ((MQMessageExt*)msg)->getTopic().c_str();
 }
-const char *GetMessageTags(CMessageExt *msg) {
-    if (msg == NULL) {
-        return NULL;
-    }
-    return ((MQMessageExt *) msg)->getTags().c_str();
+const char* GetMessageTags(CMessageExt* msg) {
+  if (msg == NULL) {
+    return NULL;
+  }
+  return ((MQMessageExt*)msg)->getTags().c_str();
 }
-const char *GetMessageKeys(CMessageExt *msg) {
-    if (msg == NULL) {
-        return NULL;
-    }
-    return ((MQMessageExt *) msg)->getKeys().c_str();
+const char* GetMessageKeys(CMessageExt* msg) {
+  if (msg == NULL) {
+    return NULL;
+  }
+  return ((MQMessageExt*)msg)->getKeys().c_str();
 }
-const char *GetMessageBody(CMessageExt *msg) {
-    if (msg == NULL) {
-        return NULL;
-    }
-    return ((MQMessageExt *) msg)->getBody().c_str();
+const char* GetMessageBody(CMessageExt* msg) {
+  if (msg == NULL) {
+    return NULL;
+  }
+  return ((MQMessageExt*)msg)->getBody().c_str();
 }
-const char *GetMessageProperty(CMessageExt *msg, const char *key) {
-    if (msg == NULL) {
-        return NULL;
-    }
-    return ((MQMessageExt *) msg)->getProperty(key).c_str();
+const char* GetMessageProperty(CMessageExt* msg, const char* key) {
+  if (msg == NULL) {
+    return NULL;
+  }
+  return ((MQMessageExt*)msg)->getProperty(key).c_str();
 }
-const char *GetMessageId(CMessageExt *msg) {
-    if (msg == NULL) {
-        return NULL;
-    }
-    return ((MQMessageExt *) msg)->getMsgId().c_str();
+const char* GetMessageId(CMessageExt* msg) {
+  if (msg == NULL) {
+    return NULL;
+  }
+  return ((MQMessageExt*)msg)->getMsgId().c_str();
 }
 
-int GetMessageDelayTimeLevel(CMessageExt *msg){
-    if (msg == NULL) {
-        return NULL_POINTER;
-    }
-    return ((MQMessageExt *) msg)->getDelayTimeLevel();
+int GetMessageDelayTimeLevel(CMessageExt* msg) {
+  if (msg == NULL) {
+    return NULL_POINTER;
+  }
+  return ((MQMessageExt*)msg)->getDelayTimeLevel();
 }
 
-int GetMessageQueueId(CMessageExt *msg){
-    if (msg == NULL) {
-        return NULL_POINTER;
-    }
-    return ((MQMessageExt *) msg)->getQueueId();
+int GetMessageQueueId(CMessageExt* msg) {
+  if (msg == NULL) {
+    return NULL_POINTER;
+  }
+  return ((MQMessageExt*)msg)->getQueueId();
 }
 
-int GetMessageReconsumeTimes(CMessageExt *msg){
-    if (msg == NULL) {
-        return NULL_POINTER;
-    }
-    return ((MQMessageExt *) msg)->getReconsumeTimes();
+int GetMessageReconsumeTimes(CMessageExt* msg) {
+  if (msg == NULL) {
+    return NULL_POINTER;
+  }
+  return ((MQMessageExt*)msg)->getReconsumeTimes();
 }
 
-int GetMessageStoreSize(CMessageExt *msg){
-    if (msg == NULL) {
-        return NULL_POINTER;
-    }
-    return ((MQMessageExt *) msg)->getStoreSize();
+int GetMessageStoreSize(CMessageExt* msg) {
+  if (msg == NULL) {
+    return NULL_POINTER;
+  }
+  return ((MQMessageExt*)msg)->getStoreSize();
 }
 
-long long GetMessageBornTimestamp(CMessageExt *msg) {
-    if (msg == NULL) {
-        return NULL_POINTER;
-    }
-    return ((MQMessageExt *) msg)->getBornTimestamp();
+long long GetMessageBornTimestamp(CMessageExt* msg) {
+  if (msg == NULL) {
+    return NULL_POINTER;
+  }
+  return ((MQMessageExt*)msg)->getBornTimestamp();
 }
 
-long long GetMessageStoreTimestamp(CMessageExt *msg){
-    if (msg == NULL) {
-        return NULL_POINTER;
-    }
-    return ((MQMessageExt *) msg)->getStoreTimestamp();
+long long GetMessageStoreTimestamp(CMessageExt* msg) {
+  if (msg == NULL) {
+    return NULL_POINTER;
+  }
+  return ((MQMessageExt*)msg)->getStoreTimestamp();
 }
 
-long long GetMessageQueueOffset(CMessageExt *msg){
-    if (msg == NULL) {
-        return NULL_POINTER;
-    }
-    return ((MQMessageExt *) msg)->getQueueOffset();
+long long GetMessageQueueOffset(CMessageExt* msg) {
+  if (msg == NULL) {
+    return NULL_POINTER;
+  }
+  return ((MQMessageExt*)msg)->getQueueOffset();
 }
 
-long long GetMessageCommitLogOffset(CMessageExt *msg){
-    if (msg == NULL) {
-        return NULL_POINTER;
-    }
-    return ((MQMessageExt *) msg)->getCommitLogOffset();
+long long GetMessageCommitLogOffset(CMessageExt* msg) {
+  if (msg == NULL) {
+    return NULL_POINTER;
+  }
+  return ((MQMessageExt*)msg)->getCommitLogOffset();
 }
 
-long long GetMessagePreparedTransactionOffset(CMessageExt *msg){
-    if (msg == NULL) {
-        return NULL_POINTER;
-    }
-    return ((MQMessageExt *) msg)->getPreparedTransactionOffset();
+long long GetMessagePreparedTransactionOffset(CMessageExt* msg) {
+  if (msg == NULL) {
+    return NULL_POINTER;
+  }
+  return ((MQMessageExt*)msg)->getPreparedTransactionOffset();
 }
 #ifdef __cplusplus
 };
diff --git a/src/extern/CProducer.cpp b/src/extern/CProducer.cpp
index 58542a6..35fdcad 100644
--- a/src/extern/CProducer.cpp
+++ b/src/extern/CProducer.cpp
@@ -15,15 +15,21 @@
  * limitations under the License.
  */
 
-#include "DefaultMQProducer.h"
-#include "AsyncCallback.h"
 #include "CProducer.h"
+
+#include <string.h>
+#include <typeindex>
+
+#include "AsyncCallback.h"
+#include "CBatchMessage.h"
 #include "CCommon.h"
-#include "CSendResult.h"
-#include "CMessage.h"
 #include "CMQException.h"
 #include <string.h>
 #include <typeinfo>
+#include "MQClientErrorContainer.h"
+#include "CMessage.h"
+#include "CSendResult.h"
+#include "DefaultMQProducer.h"
 
 #ifdef __cplusplus
 extern "C" {
@@ -32,315 +38,358 @@
 using namespace std;
 
 class SelectMessageQueue : public MessageQueueSelector {
-public:
-    SelectMessageQueue(QueueSelectorCallback callback) {
-        m_pCallback = callback;
-    }
+ public:
+  SelectMessageQueue(QueueSelectorCallback callback) { m_pCallback = callback; }
 
-    MQMessageQueue select(const std::vector<MQMessageQueue> &mqs,
-                          const MQMessage &msg, void *arg) {
-        CMessage *message = (CMessage *) &msg;
-        //Get the index of sending MQMessageQueue through callback function.
-        int index = m_pCallback(mqs.size(), message, arg);
-        return mqs[index];
-    }
+  MQMessageQueue select(const std::vector<MQMessageQueue>& mqs, const MQMessage& msg, void* arg) {
+    CMessage* message = (CMessage*)&msg;
+    // Get the index of sending MQMessageQueue through callback function.
+    int index = m_pCallback(mqs.size(), message, arg);
+    return mqs[index];
+  }
 
-private:
-    QueueSelectorCallback m_pCallback;
+ private:
+  QueueSelectorCallback m_pCallback;
 };
 
-class CSendCallback : public AutoDeleteSendCallBack{
-public:
-    CSendCallback(CSendSuccessCallback cSendSuccessCallback,CSendExceptionCallback cSendExceptionCallback){
-        m_cSendSuccessCallback = cSendSuccessCallback;
-        m_cSendExceptionCallback = cSendExceptionCallback;
-    }
-    virtual ~CSendCallback(){}
-    virtual void onSuccess(SendResult& sendResult) {
-        CSendResult result;
-        result.sendStatus = CSendStatus((int) sendResult.getSendStatus());
-        result.offset = sendResult.getQueueOffset();
-        strncpy(result.msgId, sendResult.getMsgId().c_str(), MAX_MESSAGE_ID_LENGTH - 1);
-        result.msgId[MAX_MESSAGE_ID_LENGTH - 1] = 0;
-        m_cSendSuccessCallback(result);
-    }
-    virtual void onException(MQException& e) {
-        CMQException exception;
-        exception.error = e.GetError();
-        exception.line  = e.GetLine();
-        strncpy(exception.msg, e.what(), MAX_EXEPTION_MSG_LENGTH - 1);
-        strncpy(exception.file, e.GetFile(), MAX_EXEPTION_FILE_LENGTH - 1);
-        m_cSendExceptionCallback( exception );
-    }
-private:
-    CSendSuccessCallback m_cSendSuccessCallback;
-    CSendExceptionCallback m_cSendExceptionCallback;
+class CSendCallback : public AutoDeleteSendCallBack {
+ public:
+  CSendCallback(CSendSuccessCallback cSendSuccessCallback, CSendExceptionCallback cSendExceptionCallback) {
+    m_cSendSuccessCallback = cSendSuccessCallback;
+    m_cSendExceptionCallback = cSendExceptionCallback;
+  }
+  virtual ~CSendCallback() {}
+  virtual void onSuccess(SendResult& sendResult) {
+    CSendResult result;
+    result.sendStatus = CSendStatus((int)sendResult.getSendStatus());
+    result.offset = sendResult.getQueueOffset();
+    strncpy(result.msgId, sendResult.getMsgId().c_str(), MAX_MESSAGE_ID_LENGTH - 1);
+    result.msgId[MAX_MESSAGE_ID_LENGTH - 1] = 0;
+    m_cSendSuccessCallback(result);
+  }
+  virtual void onException(MQException& e) {
+    CMQException exception;
+    exception.error = e.GetError();
+    exception.line = e.GetLine();
+    strncpy(exception.msg, e.what(), MAX_EXEPTION_MSG_LENGTH - 1);
+    strncpy(exception.file, e.GetFile(), MAX_EXEPTION_FILE_LENGTH - 1);
+    m_cSendExceptionCallback(exception);
+  }
+
+ private:
+  CSendSuccessCallback m_cSendSuccessCallback;
+  CSendExceptionCallback m_cSendExceptionCallback;
 };
 
-CProducer *CreateProducer(const char *groupId) {
-    if (groupId == NULL) {
-        return NULL;
-    }
-    DefaultMQProducer *defaultMQProducer = new DefaultMQProducer(groupId);
-    return (CProducer *) defaultMQProducer;
+CProducer* CreateProducer(const char* groupId) {
+  if (groupId == NULL) {
+    return NULL;
+  }
+  DefaultMQProducer* defaultMQProducer = new DefaultMQProducer(groupId);
+  return (CProducer*)defaultMQProducer;
 }
-int DestroyProducer(CProducer *pProducer) {
-    if (pProducer == NULL) {
-        return NULL_POINTER;
-    }
-    delete reinterpret_cast<DefaultMQProducer * >(pProducer);
-    return OK;
+int DestroyProducer(CProducer* pProducer) {
+  if (pProducer == NULL) {
+    return NULL_POINTER;
+  }
+  delete reinterpret_cast<DefaultMQProducer*>(pProducer);
+  return OK;
 }
-int StartProducer(CProducer *producer) {
-    if (producer == NULL) {
-        return NULL_POINTER;
-    }
-    try {
-        ((DefaultMQProducer *) producer)->start();
-    } catch (exception &e) {
-        return PRODUCER_START_FAILED;
-    }
-    return OK;
+int StartProducer(CProducer* producer) {
+  if (producer == NULL) {
+    return NULL_POINTER;
+  }
+  try {
+    ((DefaultMQProducer*)producer)->start();
+  } catch (exception& e) {
+	MQClientErrorContainer::instance()->setErr(string(e.what()));
+    return PRODUCER_START_FAILED;
+  }
+  return OK;
 }
-int ShutdownProducer(CProducer *producer) {
-    if (producer == NULL) {
-        return NULL_POINTER;
-    }
-    ((DefaultMQProducer *) producer)->shutdown();
-    return OK;
+int ShutdownProducer(CProducer* producer) {
+  if (producer == NULL) {
+    return NULL_POINTER;
+  }
+  ((DefaultMQProducer*)producer)->shutdown();
+  return OK;
 }
-int SetProducerNameServerAddress(CProducer *producer, const char *namesrv) {
-    if (producer == NULL) {
-        return NULL_POINTER;
-    }
-    ((DefaultMQProducer *) producer)->setNamesrvAddr(namesrv);
-    return OK;
+int SetProducerNameServerAddress(CProducer* producer, const char* namesrv) {
+  if (producer == NULL) {
+    return NULL_POINTER;
+  }
+  ((DefaultMQProducer*)producer)->setNamesrvAddr(namesrv);
+  return OK;
 }
-int SetProducerNameServerDomain(CProducer *producer, const char *domain) {
-    if (producer == NULL) {
-        return NULL_POINTER;
-    }
-    ((DefaultMQProducer *) producer)->setNamesrvDomain(domain);
-    return OK;
+int SetProducerNameServerDomain(CProducer* producer, const char* domain) {
+  if (producer == NULL) {
+    return NULL_POINTER;
+  }
+  ((DefaultMQProducer*)producer)->setNamesrvDomain(domain);
+  return OK;
 }
-int SendMessageSync(CProducer *producer, CMessage *msg, CSendResult *result) {
-    //CSendResult sendResult;
-    if (producer == NULL || msg == NULL || result == NULL) {
-        return NULL_POINTER;
+int SendMessageSync(CProducer* producer, CMessage* msg, CSendResult* result) {
+  // CSendResult sendResult;
+  if (producer == NULL || msg == NULL || result == NULL) {
+    return NULL_POINTER;
+  }
+  try {
+    DefaultMQProducer* defaultMQProducer = (DefaultMQProducer*)producer;
+    MQMessage* message = (MQMessage*)msg;
+    SendResult sendResult = defaultMQProducer->send(*message);
+    switch (sendResult.getSendStatus()) {
+      case SEND_OK:
+        result->sendStatus = E_SEND_OK;
+        break;
+      case SEND_FLUSH_DISK_TIMEOUT:
+        result->sendStatus = E_SEND_FLUSH_DISK_TIMEOUT;
+        break;
+      case SEND_FLUSH_SLAVE_TIMEOUT:
+        result->sendStatus = E_SEND_FLUSH_SLAVE_TIMEOUT;
+        break;
+      case SEND_SLAVE_NOT_AVAILABLE:
+        result->sendStatus = E_SEND_SLAVE_NOT_AVAILABLE;
+        break;
+      default:
+        result->sendStatus = E_SEND_OK;
+        break;
     }
-    try {
-        DefaultMQProducer *defaultMQProducer = (DefaultMQProducer *) producer;
-        MQMessage *message = (MQMessage *) msg;
-        SendResult sendResult = defaultMQProducer->send(*message);
-        switch (sendResult.getSendStatus()) {
-            case SEND_OK:
-                result->sendStatus = E_SEND_OK;
-                break;
-            case SEND_FLUSH_DISK_TIMEOUT:
-                result->sendStatus = E_SEND_FLUSH_DISK_TIMEOUT;
-                break;
-            case SEND_FLUSH_SLAVE_TIMEOUT:
-                result->sendStatus = E_SEND_FLUSH_SLAVE_TIMEOUT;
-                break;
-            case SEND_SLAVE_NOT_AVAILABLE:
-                result->sendStatus = E_SEND_SLAVE_NOT_AVAILABLE;
-                break;
-            default:
-                result->sendStatus = E_SEND_OK;
-                break;
-        }
-        result->offset = sendResult.getQueueOffset();
-        strncpy(result->msgId, sendResult.getMsgId().c_str(), MAX_MESSAGE_ID_LENGTH - 1);
-        result->msgId[MAX_MESSAGE_ID_LENGTH - 1] = 0;
-    } catch (exception &e) {
-        return PRODUCER_SEND_SYNC_FAILED;
-    }
-    return OK;
+    result->offset = sendResult.getQueueOffset();
+    strncpy(result->msgId, sendResult.getMsgId().c_str(), MAX_MESSAGE_ID_LENGTH - 1);
+    result->msgId[MAX_MESSAGE_ID_LENGTH - 1] = 0;
+  } catch (exception& e) {
+	MQClientErrorContainer::instance()->setErr(string(e.what()));
+    return PRODUCER_SEND_SYNC_FAILED;
+  }
+  return OK;
 }
 
-int SendMessageAsync(CProducer *producer, CMessage *msg, CSendSuccessCallback cSendSuccessCallback, CSendExceptionCallback cSendExceptionCallback){
-    if (producer == NULL || msg == NULL || cSendSuccessCallback == NULL || cSendExceptionCallback == NULL) {
-        return NULL_POINTER;
+int SendBatchMessage(CProducer* producer, CBatchMessage* batcMsg, CSendResult* result) {
+  // CSendResult sendResult;
+  if (producer == NULL || batcMsg == NULL || result == NULL) {
+    return NULL_POINTER;
+  }
+  try {
+    DefaultMQProducer* defaultMQProducer = (DefaultMQProducer*)producer;
+    vector<MQMessage>* message = (vector<MQMessage>*)batcMsg;
+    SendResult sendResult = defaultMQProducer->send(*message);
+    switch (sendResult.getSendStatus()) {
+      case SEND_OK:
+        result->sendStatus = E_SEND_OK;
+        break;
+      case SEND_FLUSH_DISK_TIMEOUT:
+        result->sendStatus = E_SEND_FLUSH_DISK_TIMEOUT;
+        break;
+      case SEND_FLUSH_SLAVE_TIMEOUT:
+        result->sendStatus = E_SEND_FLUSH_SLAVE_TIMEOUT;
+        break;
+      case SEND_SLAVE_NOT_AVAILABLE:
+        result->sendStatus = E_SEND_SLAVE_NOT_AVAILABLE;
+        break;
+      default:
+        result->sendStatus = E_SEND_OK;
+        break;
     }
-    DefaultMQProducer *defaultMQProducer = (DefaultMQProducer *) producer;
-    MQMessage *message = (MQMessage *) msg;
-    CSendCallback* cSendCallback = new CSendCallback(cSendSuccessCallback , cSendExceptionCallback);
-
-    try {
-        defaultMQProducer->send(*message ,cSendCallback);
-    } catch (exception &e) {
-        if(cSendCallback != NULL){
-            if(typeid(e) == typeid( MQException )){
-                MQException &mqe = (MQException &)e;
-                cSendCallback->onException( mqe );
-            }
-            delete cSendCallback;
-            cSendCallback = NULL;
-        }
-        return PRODUCER_SEND_ASYNC_FAILED;
-    }
-    return OK;
+    result->offset = sendResult.getQueueOffset();
+    strncpy(result->msgId, sendResult.getMsgId().c_str(), MAX_MESSAGE_ID_LENGTH - 1);
+    result->msgId[MAX_MESSAGE_ID_LENGTH - 1] = 0;
+  } catch (exception& e) {
+    return PRODUCER_SEND_SYNC_FAILED;
+  }
+  return OK;
 }
 
-int SendMessageOneway(CProducer *producer, CMessage *msg) {
-    if (producer == NULL || msg == NULL) {
-        return NULL_POINTER;
+int SendMessageAsync(CProducer* producer,
+                     CMessage* msg,
+                     CSendSuccessCallback cSendSuccessCallback,
+                     CSendExceptionCallback cSendExceptionCallback) {
+  if (producer == NULL || msg == NULL || cSendSuccessCallback == NULL || cSendExceptionCallback == NULL) {
+    return NULL_POINTER;
+  }
+  DefaultMQProducer* defaultMQProducer = (DefaultMQProducer*)producer;
+  MQMessage* message = (MQMessage*)msg;
+  CSendCallback* cSendCallback = new CSendCallback(cSendSuccessCallback, cSendExceptionCallback);
+
+  try {
+    defaultMQProducer->send(*message, cSendCallback);
+  } catch (exception& e) {
+    if (cSendCallback != NULL) {
+      if (std::type_index(typeid(e)) == std::type_index(typeid(MQException))) {
+        MQException& mqe = (MQException&)e;
+        cSendCallback->onException(mqe);
+      }
+      delete cSendCallback;
+      cSendCallback = NULL;
     }
-    DefaultMQProducer *defaultMQProducer = (DefaultMQProducer *) producer;
-    MQMessage *message = (MQMessage *) msg;
-    try {
-        defaultMQProducer->sendOneway(*message);
-    } catch (exception &e) {
-        return PRODUCER_SEND_ONEWAY_FAILED;
-    }
-    return OK;
+	MQClientErrorContainer::instance()->setErr(string(e.what()));
+    return PRODUCER_SEND_ASYNC_FAILED;
+  }
+  return OK;
 }
 
-int SendMessageOnewayOrderly(CProducer *producer, CMessage *msg, QueueSelectorCallback selector, void* arg) {
-    if (producer == NULL || msg == NULL) {
-        return NULL_POINTER;
-    }
-    DefaultMQProducer *defaultMQProducer = (DefaultMQProducer *) producer;
-    MQMessage *message = (MQMessage *) msg;
-    try {
-        SelectMessageQueue selectMessageQueue(selector);
-        defaultMQProducer->sendOneway(*message, &selectMessageQueue, arg);
-    } catch (exception &e) {
-        return PRODUCER_SEND_ONEWAY_FAILED;
-    }
-    return OK;
+int SendMessageOneway(CProducer* producer, CMessage* msg) {
+  if (producer == NULL || msg == NULL) {
+    return NULL_POINTER;
+  }
+  DefaultMQProducer* defaultMQProducer = (DefaultMQProducer*)producer;
+  MQMessage* message = (MQMessage*)msg;
+  try {
+    defaultMQProducer->sendOneway(*message);
+  } catch (exception& e) {
+    return PRODUCER_SEND_ONEWAY_FAILED;
+  }
+  return OK;
 }
 
-int
-SendMessageOrderlyAsync(CProducer *producer,
-            CMessage *msg,
-            QueueSelectorCallback callback,
-            void *arg,
-            CSendSuccessCallback cSendSuccessCallback,
-            CSendExceptionCallback cSendExceptionCallback                    
-                    ) {
-    if (producer == NULL || msg == NULL || callback == NULL || cSendSuccessCallback == NULL || cSendExceptionCallback == NULL) {
-        return NULL_POINTER;
-    }
-    DefaultMQProducer *defaultMQProducer = (DefaultMQProducer *) producer;
-    MQMessage *message = (MQMessage *) msg;
-        CSendCallback* cSendCallback = new CSendCallback(cSendSuccessCallback , cSendExceptionCallback);
-
-    try {
-        //Constructing SelectMessageQueue objects through function pointer callback
-        SelectMessageQueue selectMessageQueue(callback);
-        defaultMQProducer->send(*message,
-         &selectMessageQueue, arg,cSendCallback);
-    } catch (exception &e) {
-        printf("%s\n",e.what());
-        //std::count<<e.what( )<<std::endl;
-        return PRODUCER_SEND_ORDERLYASYNC_FAILED;
-    }
-    return OK;
+int SendMessageOnewayOrderly(CProducer* producer, CMessage* msg, QueueSelectorCallback selector, void* arg) {
+  if (producer == NULL || msg == NULL) {
+    return NULL_POINTER;
+  }
+  DefaultMQProducer* defaultMQProducer = (DefaultMQProducer*)producer;
+  MQMessage* message = (MQMessage*)msg;
+  try {
+    SelectMessageQueue selectMessageQueue(selector);
+    defaultMQProducer->sendOneway(*message, &selectMessageQueue, arg);
+  } catch (exception& e) {
+	MQClientErrorContainer::instance()->setErr(string(e.what()));
+    return PRODUCER_SEND_ONEWAY_FAILED;
+  }
+  return OK;
 }
 
+int SendMessageOrderlyAsync(CProducer* producer,
+                            CMessage* msg,
+                            QueueSelectorCallback callback,
+                            void* arg,
+                            CSendSuccessCallback cSendSuccessCallback,
+                            CSendExceptionCallback cSendExceptionCallback) {
+  if (producer == NULL || msg == NULL || callback == NULL || cSendSuccessCallback == NULL ||
+      cSendExceptionCallback == NULL) {
+    return NULL_POINTER;
+  }
+  DefaultMQProducer* defaultMQProducer = (DefaultMQProducer*)producer;
+  MQMessage* message = (MQMessage*)msg;
+  CSendCallback* cSendCallback = new CSendCallback(cSendSuccessCallback, cSendExceptionCallback);
 
-
-int
-SendMessageOrderly(CProducer *producer, CMessage *msg, QueueSelectorCallback callback, void *arg, int autoRetryTimes,
-                   CSendResult *result) {
-    if (producer == NULL || msg == NULL || callback == NULL || arg == NULL || result == NULL) {
-        return NULL_POINTER;
-    }
-    DefaultMQProducer *defaultMQProducer = (DefaultMQProducer *) producer;
-    MQMessage *message = (MQMessage *) msg;
-    try {
-        //Constructing SelectMessageQueue objects through function pointer callback
-        SelectMessageQueue selectMessageQueue(callback);
-        SendResult sendResult = defaultMQProducer->send(*message, &selectMessageQueue, arg, autoRetryTimes);
-        //Convert SendStatus to CSendStatus
-        result->sendStatus = CSendStatus((int) sendResult.getSendStatus());
-        result->offset = sendResult.getQueueOffset();
-        strncpy(result->msgId, sendResult.getMsgId().c_str(), MAX_MESSAGE_ID_LENGTH - 1);
-        result->msgId[MAX_MESSAGE_ID_LENGTH - 1] = 0;
-    } catch (exception &e) {
-        return PRODUCER_SEND_ORDERLY_FAILED;
-    }
-    return OK;
+  try {
+    // Constructing SelectMessageQueue objects through function pointer callback
+    SelectMessageQueue selectMessageQueue(callback);
+    defaultMQProducer->send(*message, &selectMessageQueue, arg, cSendCallback);
+  } catch (exception& e) {
+    printf("%s\n", e.what());
+    // std::count<<e.what( )<<std::endl;
+	MQClientErrorContainer::instance()->setErr(string(e.what()));
+    return PRODUCER_SEND_ORDERLYASYNC_FAILED;
+  }
+  return OK;
 }
 
-int SetProducerGroupName(CProducer *producer, const char *groupName) {
-    if (producer == NULL) {
-        return NULL_POINTER;
-    }
-    ((DefaultMQProducer *) producer)->setGroupName(groupName);
-    return OK;
-}
-int SetProducerInstanceName(CProducer *producer, const char *instanceName) {
-    if (producer == NULL) {
-        return NULL_POINTER;
-    }
-    ((DefaultMQProducer *) producer)->setInstanceName(instanceName);
-    return OK;
-}
-int SetProducerSessionCredentials(CProducer *producer, const char *accessKey, const char *secretKey,
-                                  const char *onsChannel) {
-    if (producer == NULL) {
-        return NULL_POINTER;
-    }
-    ((DefaultMQProducer *) producer)->setSessionCredentials(accessKey, secretKey, onsChannel);
-    return OK;
-}
-int SetProducerLogPath(CProducer *producer, const char *logPath) {
-    if (producer == NULL) {
-        return NULL_POINTER;
-    }
-    //Todo, This api should be implemented by core api.
-    //((DefaultMQProducer *) producer)->setLogFileSizeAndNum(3, 102400000);
-    return OK;
+int SendMessageOrderly(CProducer* producer,
+                       CMessage* msg,
+                       QueueSelectorCallback callback,
+                       void* arg,
+                       int autoRetryTimes,
+                       CSendResult* result) {
+  if (producer == NULL || msg == NULL || callback == NULL || arg == NULL || result == NULL) {
+    return NULL_POINTER;
+  }
+  DefaultMQProducer* defaultMQProducer = (DefaultMQProducer*)producer;
+  MQMessage* message = (MQMessage*)msg;
+  try {
+    // Constructing SelectMessageQueue objects through function pointer callback
+    SelectMessageQueue selectMessageQueue(callback);
+    SendResult sendResult = defaultMQProducer->send(*message, &selectMessageQueue, arg, autoRetryTimes);
+    // Convert SendStatus to CSendStatus
+    result->sendStatus = CSendStatus((int)sendResult.getSendStatus());
+    result->offset = sendResult.getQueueOffset();
+    strncpy(result->msgId, sendResult.getMsgId().c_str(), MAX_MESSAGE_ID_LENGTH - 1);
+    result->msgId[MAX_MESSAGE_ID_LENGTH - 1] = 0;
+  } catch (exception& e) {
+	MQClientErrorContainer::instance()->setErr(string(e.what()));
+    return PRODUCER_SEND_ORDERLY_FAILED;
+  }
+  return OK;
 }
 
-int SetProducerLogFileNumAndSize(CProducer *producer, int fileNum, long fileSize) {
-    if (producer == NULL) {
-        return NULL_POINTER;
-    }
-    ((DefaultMQProducer *) producer)->setLogFileSizeAndNum(fileNum, fileSize);
-    return OK;
+int SetProducerGroupName(CProducer* producer, const char* groupName) {
+  if (producer == NULL) {
+    return NULL_POINTER;
+  }
+  ((DefaultMQProducer*)producer)->setGroupName(groupName);
+  return OK;
+}
+int SetProducerInstanceName(CProducer* producer, const char* instanceName) {
+  if (producer == NULL) {
+    return NULL_POINTER;
+  }
+  ((DefaultMQProducer*)producer)->setInstanceName(instanceName);
+  return OK;
+}
+int SetProducerSessionCredentials(CProducer* producer,
+                                  const char* accessKey,
+                                  const char* secretKey,
+                                  const char* onsChannel) {
+  if (producer == NULL) {
+    return NULL_POINTER;
+  }
+  ((DefaultMQProducer*)producer)->setSessionCredentials(accessKey, secretKey, onsChannel);
+  return OK;
+}
+int SetProducerLogPath(CProducer* producer, const char* logPath) {
+  if (producer == NULL) {
+    return NULL_POINTER;
+  }
+  // Todo, This api should be implemented by core api.
+  //((DefaultMQProducer *) producer)->setLogFileSizeAndNum(3, 102400000);
+  return OK;
 }
 
-int SetProducerLogLevel(CProducer *producer, CLogLevel level) {
-    if (producer == NULL) {
-        return NULL_POINTER;
-    }
-    ((DefaultMQProducer *) producer)->setLogLevel((elogLevel) level);
-    return OK;
+int SetProducerLogFileNumAndSize(CProducer* producer, int fileNum, long fileSize) {
+  if (producer == NULL) {
+    return NULL_POINTER;
+  }
+  ((DefaultMQProducer*)producer)->setLogFileSizeAndNum(fileNum, fileSize);
+  return OK;
 }
 
-int SetProducerSendMsgTimeout(CProducer *producer, int timeout) {
-    if (producer == NULL) {
-        return NULL_POINTER;
-    }
-    ((DefaultMQProducer *) producer)->setSendMsgTimeout(timeout);
-    return OK;
+int SetProducerLogLevel(CProducer* producer, CLogLevel level) {
+  if (producer == NULL) {
+    return NULL_POINTER;
+  }
+  ((DefaultMQProducer*)producer)->setLogLevel((elogLevel)level);
+  return OK;
 }
 
-int SetProducerCompressMsgBodyOverHowmuch(CProducer *producer, int howmuch) {
-    if (producer == NULL) {
-        return NULL_POINTER;
-    }
-    ((DefaultMQProducer *) producer)->setCompressMsgBodyOverHowmuch(howmuch);
-    return OK;
+int SetProducerSendMsgTimeout(CProducer* producer, int timeout) {
+  if (producer == NULL) {
+    return NULL_POINTER;
+  }
+  ((DefaultMQProducer*)producer)->setSendMsgTimeout(timeout);
+  return OK;
 }
 
-int SetProducerCompressLevel(CProducer *producer, int level) {
-    if (producer == NULL) {
-        return NULL_POINTER;
-    }
-    ((DefaultMQProducer *) producer)->setCompressLevel(level);
-    return OK;
+int SetProducerCompressMsgBodyOverHowmuch(CProducer* producer, int howmuch) {
+  if (producer == NULL) {
+    return NULL_POINTER;
+  }
+  ((DefaultMQProducer*)producer)->setCompressMsgBodyOverHowmuch(howmuch);
+  return OK;
 }
 
-int SetProducerMaxMessageSize(CProducer *producer, int size) {
-    if (producer == NULL) {
-        return NULL_POINTER;
-    }
-    ((DefaultMQProducer *) producer)->setMaxMessageSize(size);
-    return OK;
+int SetProducerCompressLevel(CProducer* producer, int level) {
+  if (producer == NULL) {
+    return NULL_POINTER;
+  }
+  ((DefaultMQProducer*)producer)->setCompressLevel(level);
+  return OK;
+}
+
+int SetProducerMaxMessageSize(CProducer* producer, int size) {
+  if (producer == NULL) {
+    return NULL_POINTER;
+  }
+  ((DefaultMQProducer*)producer)->setMaxMessageSize(size);
+  return OK;
 }
 #ifdef __cplusplus
 };
diff --git a/src/extern/CPullConsumer.cpp b/src/extern/CPullConsumer.cpp
index cf7c01f..567c37b 100644
--- a/src/extern/CPullConsumer.cpp
+++ b/src/extern/CPullConsumer.cpp
@@ -19,6 +19,7 @@
 #include "CMessageExt.h"
 #include "CPullConsumer.h"
 #include "CCommon.h"
+#include "MQClientErrorContainer.h"
 
 using namespace rocketmq;
 using namespace std;
@@ -27,210 +28,217 @@
 extern "C" {
 #endif
 
-
-CPullConsumer *CreatePullConsumer(const char *groupId) {
-    if (groupId == NULL) {
-        return NULL;
-    }
-    DefaultMQPullConsumer *defaultMQPullConsumer = new DefaultMQPullConsumer(groupId);
-    return (CPullConsumer *) defaultMQPullConsumer;
+CPullConsumer* CreatePullConsumer(const char* groupId) {
+  if (groupId == NULL) {
+    return NULL;
+  }
+  DefaultMQPullConsumer* defaultMQPullConsumer = new DefaultMQPullConsumer(groupId);
+  return (CPullConsumer*)defaultMQPullConsumer;
 }
-int DestroyPullConsumer(CPullConsumer *consumer) {
-    if (consumer == NULL) {
-        return NULL_POINTER;
-    }
-    delete reinterpret_cast<DefaultMQPullConsumer * >(consumer);
-    return OK;
+int DestroyPullConsumer(CPullConsumer* consumer) {
+  if (consumer == NULL) {
+    return NULL_POINTER;
+  }
+  delete reinterpret_cast<DefaultMQPullConsumer*>(consumer);
+  return OK;
 }
-int StartPullConsumer(CPullConsumer *consumer) {
-    if (consumer == NULL) {
-        return NULL_POINTER;
-    }
-    try {
-        ((DefaultMQPullConsumer *) consumer)->start();
-    } catch (exception &e) {
-        return PULLCONSUMER_START_FAILED;
-    }
-    return OK;
+int StartPullConsumer(CPullConsumer* consumer) {
+  if (consumer == NULL) {
+    return NULL_POINTER;
+  }
+  try {
+    ((DefaultMQPullConsumer*)consumer)->start();
+  } catch (exception& e) {
+	MQClientErrorContainer::instance()->setErr(string(e.what()));
+    return PULLCONSUMER_START_FAILED;
+  }
+  return OK;
 }
-int ShutdownPullConsumer(CPullConsumer *consumer) {
-    if (consumer == NULL) {
-        return NULL_POINTER;
-    }
-    ((DefaultMQPullConsumer *) consumer)->shutdown();
-    return OK;
+int ShutdownPullConsumer(CPullConsumer* consumer) {
+  if (consumer == NULL) {
+    return NULL_POINTER;
+  }
+  ((DefaultMQPullConsumer*)consumer)->shutdown();
+  return OK;
 }
-int SetPullConsumerGroupID(CPullConsumer *consumer, const char *groupId) {
-    if (consumer == NULL || groupId == NULL) {
-        return NULL_POINTER;
-    }
-    ((DefaultMQPullConsumer *) consumer)->setGroupName(groupId);
-    return OK;
+int SetPullConsumerGroupID(CPullConsumer* consumer, const char* groupId) {
+  if (consumer == NULL || groupId == NULL) {
+    return NULL_POINTER;
+  }
+  ((DefaultMQPullConsumer*)consumer)->setGroupName(groupId);
+  return OK;
 }
-const char *GetPullConsumerGroupID(CPullConsumer *consumer) {
-    if (consumer == NULL) {
-        return NULL;
-    }
-    return ((DefaultMQPullConsumer *) consumer)->getGroupName().c_str();
+const char* GetPullConsumerGroupID(CPullConsumer* consumer) {
+  if (consumer == NULL) {
+    return NULL;
+  }
+  return ((DefaultMQPullConsumer*)consumer)->getGroupName().c_str();
 }
-int SetPullConsumerNameServerAddress(CPullConsumer *consumer, const char *namesrv) {
-    if (consumer == NULL) {
-        return NULL_POINTER;
-    }
-    ((DefaultMQPullConsumer *) consumer)->setNamesrvAddr(namesrv);
-    return OK;
+int SetPullConsumerNameServerAddress(CPullConsumer* consumer, const char* namesrv) {
+  if (consumer == NULL) {
+    return NULL_POINTER;
+  }
+  ((DefaultMQPullConsumer*)consumer)->setNamesrvAddr(namesrv);
+  return OK;
 }
-int SetPullConsumerNameServerDomain(CPullConsumer *consumer, const char *domain) {
-    if (consumer == NULL) {
-        return NULL_POINTER;
-    }
-    ((DefaultMQPullConsumer *) consumer)->setNamesrvDomain(domain);
-    return OK;
+int SetPullConsumerNameServerDomain(CPullConsumer* consumer, const char* domain) {
+  if (consumer == NULL) {
+    return NULL_POINTER;
+  }
+  ((DefaultMQPullConsumer*)consumer)->setNamesrvDomain(domain);
+  return OK;
 }
-int SetPullConsumerSessionCredentials(CPullConsumer *consumer, const char *accessKey, const char *secretKey,
-                                      const char *channel) {
-    if (consumer == NULL) {
-        return NULL_POINTER;
-    }
-    ((DefaultMQPullConsumer *) consumer)->setSessionCredentials(accessKey, secretKey, channel);
-    return OK;
+int SetPullConsumerSessionCredentials(CPullConsumer* consumer,
+                                      const char* accessKey,
+                                      const char* secretKey,
+                                      const char* channel) {
+  if (consumer == NULL) {
+    return NULL_POINTER;
+  }
+  ((DefaultMQPullConsumer*)consumer)->setSessionCredentials(accessKey, secretKey, channel);
+  return OK;
 }
 
-int SetPullConsumerLogPath(CPullConsumer *consumer, const char *logPath) {
-    if (consumer == NULL) {
-        return NULL_POINTER;
-    }
-    //Todo, This api should be implemented by core api.
-    //((DefaultMQPullConsumer *) consumer)->setInstanceName(instanceName);
-    return OK;
+int SetPullConsumerLogPath(CPullConsumer* consumer, const char* logPath) {
+  if (consumer == NULL) {
+    return NULL_POINTER;
+  }
+  // Todo, This api should be implemented by core api.
+  //((DefaultMQPullConsumer *) consumer)->setInstanceName(instanceName);
+  return OK;
 }
 
-int SetPullConsumerLogFileNumAndSize(CPullConsumer *consumer, int fileNum, long fileSize) {
-    if (consumer == NULL) {
-        return NULL_POINTER;
-    }
-    ((DefaultMQPullConsumer *) consumer)->setLogFileSizeAndNum(fileNum, fileSize);
-    return OK;
+int SetPullConsumerLogFileNumAndSize(CPullConsumer* consumer, int fileNum, long fileSize) {
+  if (consumer == NULL) {
+    return NULL_POINTER;
+  }
+  ((DefaultMQPullConsumer*)consumer)->setLogFileSizeAndNum(fileNum, fileSize);
+  return OK;
 }
 
-int SetPullConsumerLogLevel(CPullConsumer *consumer, CLogLevel level) {
-    if (consumer == NULL) {
-        return NULL_POINTER;
-    }
-    ((DefaultMQPullConsumer *) consumer)->setLogLevel((elogLevel) level);
-    return OK;
+int SetPullConsumerLogLevel(CPullConsumer* consumer, CLogLevel level) {
+  if (consumer == NULL) {
+    return NULL_POINTER;
+  }
+  ((DefaultMQPullConsumer*)consumer)->setLogLevel((elogLevel)level);
+  return OK;
 }
 
-int FetchSubscriptionMessageQueues(CPullConsumer *consumer, const char *topic, CMessageQueue **mqs, int *size) {
-    if (consumer == NULL) {
-        return NULL_POINTER;
+int FetchSubscriptionMessageQueues(CPullConsumer* consumer, const char* topic, CMessageQueue** mqs, int* size) {
+  if (consumer == NULL) {
+    return NULL_POINTER;
+  }
+  unsigned int index = 0;
+  CMessageQueue* temMQ = NULL;
+  std::vector<MQMessageQueue> fullMQ;
+  try {
+    ((DefaultMQPullConsumer*)consumer)->fetchSubscribeMessageQueues(topic, fullMQ);
+    *size = fullMQ.size();
+    // Alloc memory to save the pointer to CPP MessageQueue, and the MessageQueues may be changed.
+    // Thus, this memory should be released by users using @ReleaseSubscribeMessageQueue every time.
+    temMQ = (CMessageQueue*)malloc(*size * sizeof(CMessageQueue));
+    if (temMQ == NULL) {
+      *size = 0;
+      *mqs = NULL;
+      return MALLOC_FAILED;
     }
-    unsigned int index = 0;
-    CMessageQueue *temMQ = NULL;
-    std::vector<MQMessageQueue> fullMQ;
-    try {
-        ((DefaultMQPullConsumer *) consumer)->fetchSubscribeMessageQueues(topic, fullMQ);
-        *size = fullMQ.size();
-        //Alloc memory to save the pointer to CPP MessageQueue, and the MessageQueues may be changed.
-        //Thus, this memory should be released by users using @ReleaseSubscribeMessageQueue every time.
-        temMQ = (CMessageQueue *) malloc(*size * sizeof(CMessageQueue));
-        if (temMQ == NULL) {
-            *size = 0;
-            *mqs = NULL;
-            return MALLOC_FAILED;
-        }
-        auto iter = fullMQ.begin();
-        for (index = 0; iter != fullMQ.end() && index <= fullMQ.size(); ++iter, index++) {
-            strncpy(temMQ[index].topic, iter->getTopic().c_str(), MAX_TOPIC_LENGTH - 1);
-            strncpy(temMQ[index].brokerName, iter->getBrokerName().c_str(), MAX_BROKER_NAME_ID_LENGTH - 1);
-            temMQ[index].queueId = iter->getQueueId();
-        }
-        *mqs = temMQ;
-    } catch (MQException &e) {
-        *size = 0;
-        *mqs = NULL;
-        return PULLCONSUMER_FETCH_MQ_FAILED;
+    auto iter = fullMQ.begin();
+    for (index = 0; iter != fullMQ.end() && index <= fullMQ.size(); ++iter, index++) {
+      strncpy(temMQ[index].topic, iter->getTopic().c_str(), MAX_TOPIC_LENGTH - 1);
+      strncpy(temMQ[index].brokerName, iter->getBrokerName().c_str(), MAX_BROKER_NAME_ID_LENGTH - 1);
+      temMQ[index].queueId = iter->getQueueId();
     }
-    return OK;
+    *mqs = temMQ;
+  } catch (MQException& e) {
+    *size = 0;
+    *mqs = NULL;
+	MQClientErrorContainer::instance()->setErr(string(e.what()));
+    return PULLCONSUMER_FETCH_MQ_FAILED;
+  }
+  return OK;
 }
-int ReleaseSubscriptionMessageQueue(CMessageQueue *mqs) {
-    if (mqs == NULL) {
-        return NULL_POINTER;
-    }
-    free((void *) mqs);
-    mqs = NULL;
-    return OK;
+int ReleaseSubscriptionMessageQueue(CMessageQueue* mqs) {
+  if (mqs == NULL) {
+    return NULL_POINTER;
+  }
+  free((void*)mqs);
+  mqs = NULL;
+  return OK;
 }
-CPullResult
-Pull(CPullConsumer *consumer, const CMessageQueue *mq, const char *subExpression, long long offset, int maxNums) {
-    CPullResult pullResult;
-    memset(&pullResult, 0, sizeof(CPullResult));
-    MQMessageQueue messageQueue(mq->topic, mq->brokerName, mq->queueId);
-    PullResult cppPullResult;
-    try {
-        cppPullResult = ((DefaultMQPullConsumer *) consumer)->pull(messageQueue, subExpression, offset, maxNums);
-    } catch (exception &e) {
-        cppPullResult.pullStatus = BROKER_TIMEOUT;
-    }
+CPullResult Pull(CPullConsumer* consumer,
+                 const CMessageQueue* mq,
+                 const char* subExpression,
+                 long long offset,
+                 int maxNums) {
+  CPullResult pullResult;
+  memset(&pullResult, 0, sizeof(CPullResult));
+  MQMessageQueue messageQueue(mq->topic, mq->brokerName, mq->queueId);
+  PullResult cppPullResult;
+  try {
+    cppPullResult = ((DefaultMQPullConsumer*)consumer)->pull(messageQueue, subExpression, offset, maxNums);
+  } catch (exception& e) {
+	MQClientErrorContainer::instance()->setErr(string(e.what()));
+    cppPullResult.pullStatus = BROKER_TIMEOUT;
+  }
 
-    if(cppPullResult.pullStatus != BROKER_TIMEOUT){
-        pullResult.maxOffset = cppPullResult.maxOffset;
-        pullResult.minOffset = cppPullResult.minOffset;
-        pullResult.nextBeginOffset = cppPullResult.nextBeginOffset;
-    }
+  if (cppPullResult.pullStatus != BROKER_TIMEOUT) {
+    pullResult.maxOffset = cppPullResult.maxOffset;
+    pullResult.minOffset = cppPullResult.minOffset;
+    pullResult.nextBeginOffset = cppPullResult.nextBeginOffset;
+  }
 
-    switch (cppPullResult.pullStatus) {
-        case FOUND: {
-            pullResult.pullStatus = E_FOUND;
-            pullResult.size = cppPullResult.msgFoundList.size();
-            PullResult *tmpPullResult = new PullResult(cppPullResult);
-            pullResult.pData = tmpPullResult;
-            //Alloc memory to save the pointer to CPP MQMessageExt, which will be release by the CPP SDK core.
-            //Thus, this memory should be released by users using @ReleasePullResult
-            pullResult.msgFoundList = (CMessageExt **) malloc(pullResult.size * sizeof(CMessageExt *));
-            for (size_t i = 0; i < cppPullResult.msgFoundList.size(); i++) {
-                MQMessageExt *msg = const_cast<MQMessageExt *>(&tmpPullResult->msgFoundList[i]);
-                pullResult.msgFoundList[i] = (CMessageExt *) (msg);
-            }
-            break;
-        }
-        case NO_NEW_MSG: {
-            pullResult.pullStatus = E_NO_NEW_MSG;
-            break;
-        }
-        case NO_MATCHED_MSG: {
-            pullResult.pullStatus = E_NO_MATCHED_MSG;
-            break;
-        }
-        case OFFSET_ILLEGAL: {
-            pullResult.pullStatus = E_OFFSET_ILLEGAL;
-            break;
-        }
-        case BROKER_TIMEOUT: {
-            pullResult.pullStatus = E_BROKER_TIMEOUT;
-            break;
-        }
-        default:
-            pullResult.pullStatus = E_NO_NEW_MSG;
-            break;
-
+  switch (cppPullResult.pullStatus) {
+    case FOUND: {
+      pullResult.pullStatus = E_FOUND;
+      pullResult.size = cppPullResult.msgFoundList.size();
+      PullResult* tmpPullResult = new PullResult(cppPullResult);
+      pullResult.pData = tmpPullResult;
+      // Alloc memory to save the pointer to CPP MQMessageExt, which will be release by the CPP SDK core.
+      // Thus, this memory should be released by users using @ReleasePullResult
+      pullResult.msgFoundList = (CMessageExt**)malloc(pullResult.size * sizeof(CMessageExt*));
+      for (size_t i = 0; i < cppPullResult.msgFoundList.size(); i++) {
+        MQMessageExt* msg = const_cast<MQMessageExt*>(&tmpPullResult->msgFoundList[i]);
+        pullResult.msgFoundList[i] = (CMessageExt*)(msg);
+      }
+      break;
     }
-    return pullResult;
+    case NO_NEW_MSG: {
+      pullResult.pullStatus = E_NO_NEW_MSG;
+      break;
+    }
+    case NO_MATCHED_MSG: {
+      pullResult.pullStatus = E_NO_MATCHED_MSG;
+      break;
+    }
+    case OFFSET_ILLEGAL: {
+      pullResult.pullStatus = E_OFFSET_ILLEGAL;
+      break;
+    }
+    case BROKER_TIMEOUT: {
+      pullResult.pullStatus = E_BROKER_TIMEOUT;
+      break;
+    }
+    default:
+      pullResult.pullStatus = E_NO_NEW_MSG;
+      break;
+  }
+  return pullResult;
 }
 int ReleasePullResult(CPullResult pullResult) {
-    if (pullResult.size == 0 || pullResult.msgFoundList == NULL || pullResult.pData == NULL) {
-        return NULL_POINTER;
+  if (pullResult.size == 0 || pullResult.msgFoundList == NULL || pullResult.pData == NULL) {
+    return NULL_POINTER;
+  }
+  if (pullResult.pData != NULL) {
+    try {
+      delete ((PullResult*)pullResult.pData);
+    } catch (exception& e) {
+	  MQClientErrorContainer::instance()->setErr(string(e.what()));
+      return NULL_POINTER;
     }
-    if (pullResult.pData != NULL) {
-        try {
-            delete ((PullResult *) pullResult.pData);
-        } catch (exception &e) {
-            return NULL_POINTER;
-        }
-    }
-    free((void *) pullResult.msgFoundList);
-    pullResult.msgFoundList = NULL;
-    return OK;
+  }
+  free((void*)pullResult.msgFoundList);
+  pullResult.msgFoundList = NULL;
+  return OK;
 }
 
 #ifdef __cplusplus
diff --git a/src/extern/CPushConsumer.cpp b/src/extern/CPushConsumer.cpp
index 2c35c74..4a81dae 100644
--- a/src/extern/CPushConsumer.cpp
+++ b/src/extern/CPushConsumer.cpp
@@ -20,256 +20,258 @@
 #include "CPushConsumer.h"
 #include "CCommon.h"
 #include <map>
+#include "MQClientErrorContainer.h"
 
 using namespace rocketmq;
 using namespace std;
 
 class MessageListenerInner : public MessageListenerConcurrently {
-public:
-    MessageListenerInner() {}
+ public:
+  MessageListenerInner() {}
 
-    MessageListenerInner(CPushConsumer *consumer, MessageCallBack pCallback) {
-        m_pconsumer = consumer;
-        m_pMsgReceiveCallback = pCallback;
+  MessageListenerInner(CPushConsumer* consumer, MessageCallBack pCallback) {
+    m_pconsumer = consumer;
+    m_pMsgReceiveCallback = pCallback;
+  }
+
+  ~MessageListenerInner() {}
+
+  ConsumeStatus consumeMessage(const std::vector<MQMessageExt>& msgs) {
+    // to do user call back
+    if (m_pMsgReceiveCallback == NULL) {
+      return RECONSUME_LATER;
     }
-
-    ~MessageListenerInner() {}
-
-    ConsumeStatus consumeMessage(const std::vector<MQMessageExt> &msgs) {
-        //to do user call back
-        if (m_pMsgReceiveCallback == NULL) {
-            return RECONSUME_LATER;
-        }
-        for (size_t i = 0; i < msgs.size(); ++i) {
-            MQMessageExt *msg = const_cast<MQMessageExt *>(&msgs[i]);
-            CMessageExt *message = (CMessageExt *) (msg);
-            if (m_pMsgReceiveCallback(m_pconsumer, message) != E_CONSUME_SUCCESS)
-                return RECONSUME_LATER;
-        }
-        return CONSUME_SUCCESS;
+    for (size_t i = 0; i < msgs.size(); ++i) {
+      MQMessageExt* msg = const_cast<MQMessageExt*>(&msgs[i]);
+      CMessageExt* message = (CMessageExt*)(msg);
+      if (m_pMsgReceiveCallback(m_pconsumer, message) != E_CONSUME_SUCCESS)
+        return RECONSUME_LATER;
     }
+    return CONSUME_SUCCESS;
+  }
 
-private:
-    MessageCallBack m_pMsgReceiveCallback;
-    CPushConsumer *m_pconsumer;
+ private:
+  MessageCallBack m_pMsgReceiveCallback;
+  CPushConsumer* m_pconsumer;
 };
 
 class MessageListenerOrderlyInner : public MessageListenerOrderly {
-public:
-    MessageListenerOrderlyInner(CPushConsumer *consumer, MessageCallBack pCallback) {
-        m_pconsumer = consumer;
-        m_pMsgReceiveCallback = pCallback;
-    }
+ public:
+  MessageListenerOrderlyInner(CPushConsumer* consumer, MessageCallBack pCallback) {
+    m_pconsumer = consumer;
+    m_pMsgReceiveCallback = pCallback;
+  }
 
-    ConsumeStatus consumeMessage(const std::vector<MQMessageExt> &msgs) {
-        if (m_pMsgReceiveCallback == NULL) {
-            return RECONSUME_LATER;
-        }
-        for (size_t i = 0; i < msgs.size(); ++i) {
-            MQMessageExt *msg = const_cast<MQMessageExt *>(&msgs[i]);
-            CMessageExt *message = (CMessageExt *) (msg);
-            if (m_pMsgReceiveCallback(m_pconsumer, message) != E_CONSUME_SUCCESS)
-                return RECONSUME_LATER;
-        }
-        return CONSUME_SUCCESS;
+  ConsumeStatus consumeMessage(const std::vector<MQMessageExt>& msgs) {
+    if (m_pMsgReceiveCallback == NULL) {
+      return RECONSUME_LATER;
     }
+    for (size_t i = 0; i < msgs.size(); ++i) {
+      MQMessageExt* msg = const_cast<MQMessageExt*>(&msgs[i]);
+      CMessageExt* message = (CMessageExt*)(msg);
+      if (m_pMsgReceiveCallback(m_pconsumer, message) != E_CONSUME_SUCCESS)
+        return RECONSUME_LATER;
+    }
+    return CONSUME_SUCCESS;
+  }
 
-private:
-    MessageCallBack m_pMsgReceiveCallback;
-    CPushConsumer *m_pconsumer;
+ private:
+  MessageCallBack m_pMsgReceiveCallback;
+  CPushConsumer* m_pconsumer;
 };
 
-map<CPushConsumer *, MessageListenerInner *> g_ListenerMap;
-map<CPushConsumer *, MessageListenerOrderlyInner *> g_OrderListenerMap;
+map<CPushConsumer*, MessageListenerInner*> g_ListenerMap;
+map<CPushConsumer*, MessageListenerOrderlyInner*> g_OrderListenerMap;
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-
-CPushConsumer *CreatePushConsumer(const char *groupId) {
-    if (groupId == NULL) {
-        return NULL;
-    }
-    DefaultMQPushConsumer *defaultMQPushConsumer = new DefaultMQPushConsumer(groupId);
-    defaultMQPushConsumer->setConsumeFromWhere(CONSUME_FROM_LAST_OFFSET);
-    return (CPushConsumer *) defaultMQPushConsumer;
+CPushConsumer* CreatePushConsumer(const char* groupId) {
+  if (groupId == NULL) {
+    return NULL;
+  }
+  DefaultMQPushConsumer* defaultMQPushConsumer = new DefaultMQPushConsumer(groupId);
+  defaultMQPushConsumer->setConsumeFromWhere(CONSUME_FROM_LAST_OFFSET);
+  return (CPushConsumer*)defaultMQPushConsumer;
 }
-int DestroyPushConsumer(CPushConsumer *consumer) {
-    if (consumer == NULL) {
-        return NULL_POINTER;
-    }
-    delete reinterpret_cast<DefaultMQPushConsumer * >(consumer);
-    return OK;
+int DestroyPushConsumer(CPushConsumer* consumer) {
+  if (consumer == NULL) {
+    return NULL_POINTER;
+  }
+  delete reinterpret_cast<DefaultMQPushConsumer*>(consumer);
+  return OK;
 }
-int StartPushConsumer(CPushConsumer *consumer) {
-    if (consumer == NULL) {
-        return NULL_POINTER;
-    }
-    try {
-        ((DefaultMQPushConsumer *) consumer)->start();
-    } catch (exception &e) {
-        return PUSHCONSUMER_START_FAILED;
-    }
-    return OK;
+int StartPushConsumer(CPushConsumer* consumer) {
+  if (consumer == NULL) {
+    return NULL_POINTER;
+  }
+  try {
+    ((DefaultMQPushConsumer*)consumer)->start();
+  } catch (exception& e) {
+	MQClientErrorContainer::instance()->setErr(string(e.what()));
+    return PUSHCONSUMER_START_FAILED;
+  }
+  return OK;
 }
-int ShutdownPushConsumer(CPushConsumer *consumer) {
-    if (consumer == NULL) {
-        return NULL_POINTER;
-    }
-    ((DefaultMQPushConsumer *) consumer)->shutdown();
-    return OK;
+int ShutdownPushConsumer(CPushConsumer* consumer) {
+  if (consumer == NULL) {
+    return NULL_POINTER;
+  }
+  ((DefaultMQPushConsumer*)consumer)->shutdown();
+  return OK;
 }
-int SetPushConsumerGroupID(CPushConsumer *consumer, const char *groupId) {
-    if (consumer == NULL || groupId == NULL) {
-        return NULL_POINTER;
-    }
-    ((DefaultMQPushConsumer *) consumer)->setGroupName(groupId);
-    return OK;
+int SetPushConsumerGroupID(CPushConsumer* consumer, const char* groupId) {
+  if (consumer == NULL || groupId == NULL) {
+    return NULL_POINTER;
+  }
+  ((DefaultMQPushConsumer*)consumer)->setGroupName(groupId);
+  return OK;
 }
-const char *GetPushConsumerGroupID(CPushConsumer *consumer) {
-    if (consumer == NULL) {
-        return NULL;
-    }
-    return ((DefaultMQPushConsumer *) consumer)->getGroupName().c_str();
+const char* GetPushConsumerGroupID(CPushConsumer* consumer) {
+  if (consumer == NULL) {
+    return NULL;
+  }
+  return ((DefaultMQPushConsumer*)consumer)->getGroupName().c_str();
 }
-int SetPushConsumerNameServerAddress(CPushConsumer *consumer, const char *namesrv) {
-    if (consumer == NULL) {
-        return NULL_POINTER;
-    }
-    ((DefaultMQPushConsumer *) consumer)->setNamesrvAddr(namesrv);
-    return OK;
+int SetPushConsumerNameServerAddress(CPushConsumer* consumer, const char* namesrv) {
+  if (consumer == NULL) {
+    return NULL_POINTER;
+  }
+  ((DefaultMQPushConsumer*)consumer)->setNamesrvAddr(namesrv);
+  return OK;
 }
-int SetPushConsumerNameServerDomain(CPushConsumer *consumer, const char *domain) {
-    if (consumer == NULL) {
-        return NULL_POINTER;
-    }
-    ((DefaultMQPushConsumer *) consumer)->setNamesrvDomain(domain);
-    return OK;
+int SetPushConsumerNameServerDomain(CPushConsumer* consumer, const char* domain) {
+  if (consumer == NULL) {
+    return NULL_POINTER;
+  }
+  ((DefaultMQPushConsumer*)consumer)->setNamesrvDomain(domain);
+  return OK;
 }
-int Subscribe(CPushConsumer *consumer, const char *topic, const char *expression) {
-    if (consumer == NULL) {
-        return NULL_POINTER;
-    }
-    ((DefaultMQPushConsumer *) consumer)->subscribe(topic, expression);
-    return OK;
+int Subscribe(CPushConsumer* consumer, const char* topic, const char* expression) {
+  if (consumer == NULL) {
+    return NULL_POINTER;
+  }
+  ((DefaultMQPushConsumer*)consumer)->subscribe(topic, expression);
+  return OK;
 }
 
-int RegisterMessageCallback(CPushConsumer *consumer, MessageCallBack pCallback) {
-    if (consumer == NULL || pCallback == NULL) {
-        return NULL_POINTER;
-    }
-    MessageListenerInner *listenerInner = new MessageListenerInner(consumer, pCallback);
-    ((DefaultMQPushConsumer *) consumer)->registerMessageListener(listenerInner);
-    g_ListenerMap[consumer] = listenerInner;
-    return OK;
+int RegisterMessageCallback(CPushConsumer* consumer, MessageCallBack pCallback) {
+  if (consumer == NULL || pCallback == NULL) {
+    return NULL_POINTER;
+  }
+  MessageListenerInner* listenerInner = new MessageListenerInner(consumer, pCallback);
+  ((DefaultMQPushConsumer*)consumer)->registerMessageListener(listenerInner);
+  g_ListenerMap[consumer] = listenerInner;
+  return OK;
 }
 
-int RegisterMessageCallbackOrderly(CPushConsumer *consumer, MessageCallBack pCallback) {
-    if (consumer == NULL || pCallback == NULL) {
-        return NULL_POINTER;
-    }
-    MessageListenerOrderlyInner *messageListenerOrderlyInner = new MessageListenerOrderlyInner(consumer, pCallback);
-    ((DefaultMQPushConsumer *) consumer)->registerMessageListener(messageListenerOrderlyInner);
-    g_OrderListenerMap[consumer] = messageListenerOrderlyInner;
-    return OK;
+int RegisterMessageCallbackOrderly(CPushConsumer* consumer, MessageCallBack pCallback) {
+  if (consumer == NULL || pCallback == NULL) {
+    return NULL_POINTER;
+  }
+  MessageListenerOrderlyInner* messageListenerOrderlyInner = new MessageListenerOrderlyInner(consumer, pCallback);
+  ((DefaultMQPushConsumer*)consumer)->registerMessageListener(messageListenerOrderlyInner);
+  g_OrderListenerMap[consumer] = messageListenerOrderlyInner;
+  return OK;
 }
 
-
-int UnregisterMessageCallbackOrderly(CPushConsumer *consumer) {
-    if (consumer == NULL) {
-        return NULL_POINTER;
+int UnregisterMessageCallbackOrderly(CPushConsumer* consumer) {
+  if (consumer == NULL) {
+    return NULL_POINTER;
+  }
+  map<CPushConsumer*, MessageListenerOrderlyInner*>::iterator iter;
+  iter = g_OrderListenerMap.find(consumer);
+  if (iter != g_OrderListenerMap.end()) {
+    MessageListenerOrderlyInner* listenerInner = iter->second;
+    if (listenerInner != NULL) {
+      delete listenerInner;
     }
-    map<CPushConsumer *, MessageListenerOrderlyInner *>::iterator iter;
-    iter = g_OrderListenerMap.find(consumer);
-    if (iter != g_OrderListenerMap.end()) {
-        MessageListenerOrderlyInner *listenerInner = iter->second;
-        if (listenerInner != NULL) {
-            delete listenerInner;
-        }
-        g_OrderListenerMap.erase(iter);
-    }
-    return OK;
+    g_OrderListenerMap.erase(iter);
+  }
+  return OK;
 }
 
-int UnregisterMessageCallback(CPushConsumer *consumer) {
-    if (consumer == NULL) {
-        return NULL_POINTER;
-    }
-    map<CPushConsumer *, MessageListenerInner *>::iterator iter;
-    iter = g_ListenerMap.find(consumer);
+int UnregisterMessageCallback(CPushConsumer* consumer) {
+  if (consumer == NULL) {
+    return NULL_POINTER;
+  }
+  map<CPushConsumer*, MessageListenerInner*>::iterator iter;
+  iter = g_ListenerMap.find(consumer);
 
-    if (iter != g_ListenerMap.end()) {
-        MessageListenerInner *listenerInner = iter->second;
-        if (listenerInner != NULL) {
-            delete listenerInner;
-        }
-        g_ListenerMap.erase(iter);
+  if (iter != g_ListenerMap.end()) {
+    MessageListenerInner* listenerInner = iter->second;
+    if (listenerInner != NULL) {
+      delete listenerInner;
     }
-    return OK;
+    g_ListenerMap.erase(iter);
+  }
+  return OK;
 }
 
-int SetPushConsumerMessageModel(CPushConsumer *consumer, CMessageModel messageModel) {
-    if (consumer == NULL) {
-        return NULL_POINTER;
-    }
-    ((DefaultMQPushConsumer *) consumer)->setMessageModel(MessageModel((int) messageModel));
-    return OK;
+int SetPushConsumerMessageModel(CPushConsumer* consumer, CMessageModel messageModel) {
+  if (consumer == NULL) {
+    return NULL_POINTER;
+  }
+  ((DefaultMQPushConsumer*)consumer)->setMessageModel(MessageModel((int)messageModel));
+  return OK;
 }
-int SetPushConsumerThreadCount(CPushConsumer *consumer, int threadCount) {
-    if (consumer == NULL || threadCount == 0) {
-        return NULL_POINTER;
-    }
-    ((DefaultMQPushConsumer *) consumer)->setConsumeThreadCount(threadCount);
-    return OK;
+int SetPushConsumerThreadCount(CPushConsumer* consumer, int threadCount) {
+  if (consumer == NULL || threadCount == 0) {
+    return NULL_POINTER;
+  }
+  ((DefaultMQPushConsumer*)consumer)->setConsumeThreadCount(threadCount);
+  return OK;
 }
-int SetPushConsumerMessageBatchMaxSize(CPushConsumer *consumer, int batchSize) {
-    if (consumer == NULL || batchSize == 0) {
-        return NULL_POINTER;
-    }
-    ((DefaultMQPushConsumer *) consumer)->setConsumeMessageBatchMaxSize(batchSize);
-    return OK;
+int SetPushConsumerMessageBatchMaxSize(CPushConsumer* consumer, int batchSize) {
+  if (consumer == NULL || batchSize == 0) {
+    return NULL_POINTER;
+  }
+  ((DefaultMQPushConsumer*)consumer)->setConsumeMessageBatchMaxSize(batchSize);
+  return OK;
 }
 
-int SetPushConsumerInstanceName(CPushConsumer *consumer, const char *instanceName) {
-    if (consumer == NULL) {
-        return NULL_POINTER;
-    }
-    ((DefaultMQPushConsumer *) consumer)->setInstanceName(instanceName);
-    return OK;
+int SetPushConsumerInstanceName(CPushConsumer* consumer, const char* instanceName) {
+  if (consumer == NULL) {
+    return NULL_POINTER;
+  }
+  ((DefaultMQPushConsumer*)consumer)->setInstanceName(instanceName);
+  return OK;
 }
 
-int SetPushConsumerSessionCredentials(CPushConsumer *consumer, const char *accessKey, const char *secretKey,
-                                      const char *channel) {
-    if (consumer == NULL) {
-        return NULL_POINTER;
-    }
-    ((DefaultMQPushConsumer *) consumer)->setSessionCredentials(accessKey, secretKey, channel);
-    return OK;
+int SetPushConsumerSessionCredentials(CPushConsumer* consumer,
+                                      const char* accessKey,
+                                      const char* secretKey,
+                                      const char* channel) {
+  if (consumer == NULL) {
+    return NULL_POINTER;
+  }
+  ((DefaultMQPushConsumer*)consumer)->setSessionCredentials(accessKey, secretKey, channel);
+  return OK;
 }
 
-int SetPushConsumerLogPath(CPushConsumer *consumer, const char *logPath) {
-    if (consumer == NULL) {
-        return NULL_POINTER;
-    }
-    //Todo, This api should be implemented by core api.
-    //((DefaultMQPushConsumer *) consumer)->setInstanceName(instanceName);
-    return OK;
+int SetPushConsumerLogPath(CPushConsumer* consumer, const char* logPath) {
+  if (consumer == NULL) {
+    return NULL_POINTER;
+  }
+  // Todo, This api should be implemented by core api.
+  //((DefaultMQPushConsumer *) consumer)->setInstanceName(instanceName);
+  return OK;
 }
 
-int SetPushConsumerLogFileNumAndSize(CPushConsumer *consumer, int fileNum, long fileSize) {
-    if (consumer == NULL) {
-        return NULL_POINTER;
-    }
-    ((DefaultMQPushConsumer *) consumer)->setLogFileSizeAndNum(fileNum, fileSize);
-    return OK;
+int SetPushConsumerLogFileNumAndSize(CPushConsumer* consumer, int fileNum, long fileSize) {
+  if (consumer == NULL) {
+    return NULL_POINTER;
+  }
+  ((DefaultMQPushConsumer*)consumer)->setLogFileSizeAndNum(fileNum, fileSize);
+  return OK;
 }
 
-int SetPushConsumerLogLevel(CPushConsumer *consumer, CLogLevel level) {
-    if (consumer == NULL) {
-        return NULL_POINTER;
-    }
-    ((DefaultMQPushConsumer *) consumer)->setLogLevel((elogLevel) level);
-    return OK;
+int SetPushConsumerLogLevel(CPushConsumer* consumer, CLogLevel level) {
+  if (consumer == NULL) {
+    return NULL_POINTER;
+  }
+  ((DefaultMQPushConsumer*)consumer)->setLogLevel((elogLevel)level);
+  return OK;
 }
 
 #ifdef __cplusplus
diff --git a/src/extern/CSendResult.cpp b/src/extern/CSendResult.cpp
index d4cae85..8d4dc2b 100644
--- a/src/extern/CSendResult.cpp
+++ b/src/extern/CSendResult.cpp
@@ -21,7 +21,6 @@
 extern "C" {
 #endif
 
-
 #ifdef __cplusplus
 };
 #endif
diff --git a/src/log/Logging.cpp b/src/log/Logging.cpp
old mode 100755
new mode 100644
index 0b94416..9ecd1d8
--- a/src/log/Logging.cpp
+++ b/src/log/Logging.cpp
@@ -1,19 +1,19 @@
 /*
-* Licensed to the Apache Software Foundation (ASF) under one or more
-* contributor license agreements.  See the NOTICE file distributed with
-* this work for additional information regarding copyright ownership.
-* The ASF licenses this file to You under the Apache License, Version 2.0
-* (the "License"); you may not use this file except in compliance with
-* the License.  You may obtain a copy of the License at
-*
-*     http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
 #include "Logging.h"
 #include <boost/date_time/gregorian/gregorian.hpp>
 #include "UtilAll.h"
@@ -23,7 +23,9 @@
 logAdapter* logAdapter::alogInstance;
 boost::mutex logAdapter::m_imtx;
 
-logAdapter::~logAdapter() { logging::core::get()->remove_all_sinks(); }
+logAdapter::~logAdapter() {
+  logging::core::get()->remove_all_sinks();
+}
 
 logAdapter* logAdapter::getLogInstance() {
   if (alogInstance == NULL) {
@@ -39,76 +41,68 @@
   string homeDir(UtilAll::getHomeDirectory());
   homeDir.append("/logs/rocketmq-cpp/");
   m_logFile += homeDir;
-  std::string fileName =
-      UtilAll::to_string(getpid()) + "_" + "rocketmq-cpp.log.%N";
+  std::string fileName = UtilAll::to_string(getpid()) + "_" + "rocketmq-cpp.log.%N";
   m_logFile += fileName;
 
   // boost::log::expressions::attr<
   // boost::log::attributes::current_thread_id::value_type>("ThreadID");
-  boost::log::register_simple_formatter_factory<
-      boost::log::trivial::severity_level, char>("Severity");
-  m_logSink = logging::add_file_log(
-      keywords::file_name = m_logFile,
-      keywords::rotation_size = 100 * 1024 * 1024,
-      keywords::time_based_rotation =
-          sinks::file::rotation_at_time_point(0, 0, 0),
-      keywords::format = "[%TimeStamp%](%Severity%):%Message%",
-      keywords::min_free_space = 300 * 1024 * 1024, keywords::target = homeDir,
-      keywords::max_size = 200 * 1024 * 1024,  // max keep 3 log file defaultly
-      keywords::auto_flush = true);
-  logging::core::get()->set_filter(logging::trivial::severity >=
-                                   logging::trivial::info);
+  boost::log::register_simple_formatter_factory<boost::log::trivial::severity_level, char>("Severity");
+  m_logSink = logging::add_file_log(keywords::file_name = m_logFile, keywords::rotation_size = 100 * 1024 * 1024,
+                                    keywords::time_based_rotation = sinks::file::rotation_at_time_point(0, 0, 0),
+                                    keywords::format = "[%TimeStamp%](%Severity%):%Message%",
+                                    keywords::min_free_space = 300 * 1024 * 1024, keywords::target = homeDir,
+                                    keywords::max_size = 200 * 1024 * 1024,  // max keep 3 log file defaultly
+                                    keywords::auto_flush = true);
+  // logging::core::get()->set_filter(logging::trivial::severity >= logging::trivial::info);
+  setLogLevelInner(m_logLevel);
 
   logging::add_common_attributes();
 }
 
-void logAdapter::setLogLevel(elogLevel logLevel) {
-  m_logLevel = logLevel;
+void logAdapter::setLogLevelInner(elogLevel logLevel) {
   switch (logLevel) {
     case eLOG_LEVEL_FATAL:
-      logging::core::get()->set_filter(logging::trivial::severity >=
-                                       logging::trivial::fatal);
+      logging::core::get()->set_filter(logging::trivial::severity >= logging::trivial::fatal);
       break;
     case eLOG_LEVEL_ERROR:
-      logging::core::get()->set_filter(logging::trivial::severity >=
-                                       logging::trivial::error);
+      logging::core::get()->set_filter(logging::trivial::severity >= logging::trivial::error);
 
       break;
     case eLOG_LEVEL_WARN:
-      logging::core::get()->set_filter(logging::trivial::severity >=
-                                       logging::trivial::warning);
+      logging::core::get()->set_filter(logging::trivial::severity >= logging::trivial::warning);
 
       break;
     case eLOG_LEVEL_INFO:
-      logging::core::get()->set_filter(logging::trivial::severity >=
-                                       logging::trivial::info);
+      logging::core::get()->set_filter(logging::trivial::severity >= logging::trivial::info);
 
       break;
     case eLOG_LEVEL_DEBUG:
-      logging::core::get()->set_filter(logging::trivial::severity >=
-                                       logging::trivial::debug);
+      logging::core::get()->set_filter(logging::trivial::severity >= logging::trivial::debug);
 
       break;
     case eLOG_LEVEL_TRACE:
-      logging::core::get()->set_filter(logging::trivial::severity >=
-                                       logging::trivial::trace);
+      logging::core::get()->set_filter(logging::trivial::severity >= logging::trivial::trace);
 
       break;
     default:
-      logging::core::get()->set_filter(logging::trivial::severity >=
-                                       logging::trivial::info);
+      logging::core::get()->set_filter(logging::trivial::severity >= logging::trivial::info);
 
       break;
   }
 }
+void logAdapter::setLogLevel(elogLevel logLevel) {
+  m_logLevel = logLevel;
+  setLogLevelInner(logLevel);
+}
 
-elogLevel logAdapter::getLogLevel() { return m_logLevel; }
+elogLevel logAdapter::getLogLevel() {
+  return m_logLevel;
+}
 
 void logAdapter::setLogFileNumAndSize(int logNum, int sizeOfPerFile) {
   string homeDir(UtilAll::getHomeDirectory());
   homeDir.append("/logs/rocketmq-cpp/");
   m_logSink->locked_backend()->set_file_collector(sinks::file::make_collector(
-      keywords::target = homeDir,
-      keywords::max_size = logNum * sizeOfPerFile * 1024 * 1024));
+      keywords::target = homeDir, keywords::max_size = logNum * sizeOfPerFile * 1024 * 1024));
 }
-}
+}  // namespace rocketmq
diff --git a/src/log/Logging.h b/src/log/Logging.h
old mode 100755
new mode 100644
index ee9f185..dfede34
--- a/src/log/Logging.h
+++ b/src/log/Logging.h
@@ -1,23 +1,24 @@
 /*
-* Licensed to the Apache Software Foundation (ASF) under one or more
-* contributor license agreements.  See the NOTICE file distributed with
-* this work for additional information regarding copyright ownership.
-* The ASF licenses this file to You under the Apache License, Version 2.0
-* (the "License"); you may not use this file except in compliance with
-* the License.  You may obtain a copy of the License at
-*
-*     http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
 
 #ifndef _ALOG_ADAPTER_H_
 #define _ALOG_ADAPTER_H_
 
+#include <string.h>
 #include <boost/date_time/posix_time/posix_time_types.hpp>
 #include <boost/log/core.hpp>
 #include <boost/log/expressions.hpp>
@@ -47,13 +48,11 @@
   void setLogLevel(elogLevel logLevel);
   elogLevel getLogLevel();
   void setLogFileNumAndSize(int logNum, int sizeOfPerFile);
-  src::severity_logger<boost::log::trivial::severity_level>&
-  getSeverityLogger() {
-    return m_severityLogger;
-  }
+  src::severity_logger<boost::log::trivial::severity_level>& getSeverityLogger() { return m_severityLogger; }
 
  private:
   logAdapter();
+  void setLogLevelInner(elogLevel logLevel);
   elogLevel m_logLevel;
   std::string m_logFile;
   src::severity_logger<boost::log::trivial::severity_level> m_severityLogger;
@@ -69,8 +68,7 @@
 
 class LogUtil {
  public:
-  static void LogMessage(boost::log::trivial::severity_level level, int line,
-                         const char* format, ...) {
+  static void LogMessage(boost::log::trivial::severity_level level, int line, const char* format, ...) {
     va_list arg_ptr;
     va_start(arg_ptr, format);
     boost::scoped_array<char> formattedString(new char[1024]);
@@ -78,17 +76,31 @@
     BOOST_LOG_SEV(AGENT_LOGGER, level) << formattedString.get();
     va_end(arg_ptr);
   }
+  static void LogMessageFull(boost::log::trivial::severity_level level,
+                             const char* file,
+                             const char* func,
+                             int line,
+                             const char* format,
+                             ...) {
+    va_list arg_ptr;
+    va_start(arg_ptr, format);
+    boost::scoped_array<char> formattedString(new char[1024]);
+    vsnprintf(formattedString.get(), 1024, format, arg_ptr);
+    // BOOST_LOG_SEV(AGENT_LOGGER, level) << formattedString.get() << "[" << file << ":" << func << ":"<< line << "]";
+    BOOST_LOG_SEV(AGENT_LOGGER, level) << formattedString.get() << "[" << func << ":" << line << "]";
+    va_end(arg_ptr);
+  }
 };
 
 #define LOG_FATAL(...) \
-  LogUtil::LogMessage(boost::log::trivial::fatal, __LINE__, __VA_ARGS__)
+  LogUtil::LogMessageFull(boost::log::trivial::fatal, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__)
 #define LOG_ERROR(...) \
-  LogUtil::LogMessage(boost::log::trivial::error, __LINE__, __VA_ARGS__)
+  LogUtil::LogMessageFull(boost::log::trivial::error, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__)
 #define LOG_WARN(...) \
-  LogUtil::LogMessage(boost::log::trivial::warning, __LINE__, __VA_ARGS__)
-#define LOG_INFO(...) \
-  LogUtil::LogMessage(boost::log::trivial::info, __LINE__, __VA_ARGS__)
+  LogUtil::LogMessageFull(boost::log::trivial::warning, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__)
+//#define LOG_INFO(...) LogUtil::LogMessage(boost::log::trivial::info, __LINE__, __VA_ARGS__)
+#define LOG_INFO(...) LogUtil::LogMessageFull(boost::log::trivial::info, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__)
 #define LOG_DEBUG(...) \
-  LogUtil::LogMessage(boost::log::trivial::debug, __LINE__, __VA_ARGS__)
-}
+  LogUtil::LogMessageFull(boost::log::trivial::debug, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__)
+}  // namespace rocketmq
 #endif
diff --git a/src/message/BatchMessage.cpp b/src/message/BatchMessage.cpp
index c2b9ec2..ea8849f 100644
--- a/src/message/BatchMessage.cpp
+++ b/src/message/BatchMessage.cpp
@@ -5,41 +5,41 @@
 using namespace std;
 namespace rocketmq {
 
-    std::string BatchMessage::encode(std::vector<MQMessage> &msgs) {
-        string encodedBody;
-        for (auto message : msgs) {
-            string unique_id = StringIdMaker::get_mutable_instance().get_unique_id();
-            message.setProperty(MQMessage::PROPERTY_UNIQ_CLIENT_MESSAGE_ID_KEYIDX, unique_id);
-            encodedBody.append(encode(message));
-        }
-        return encodedBody;
-    }
+std::string BatchMessage::encode(std::vector<MQMessage>& msgs) {
+  string encodedBody;
+  for (auto message : msgs) {
+    string unique_id = StringIdMaker::get_mutable_instance().get_unique_id();
+    message.setProperty(MQMessage::PROPERTY_UNIQ_CLIENT_MESSAGE_ID_KEYIDX, unique_id);
+    encodedBody.append(encode(message));
+  }
+  return encodedBody;
+}
 
-    std::string BatchMessage::encode(MQMessage &message) {
-        string encodeMsg;
-        const string &body = message.getBody();
-        int bodyLen = body.length();
-        string properties = MQDecoder::messageProperties2String(message.getProperties());
-        short propertiesLength = (short) properties.length();
-        int storeSize = 20 + bodyLen + 2 + propertiesLength;
-        //TOTALSIZE|MAGICCOD|BODYCRC|FLAG|BODYLen|Body|propertiesLength|properties
-        int magicCode = 0;
-        int bodyCrc = 0;
-        int flag = message.getFlag();
-        int storeSize_net = htonl(storeSize);
-        int magicCode_net = htonl(magicCode);
-        int bodyCrc_net = htonl(bodyCrc);
-        int flag_net = htonl(flag);
-        int bodyLen_net = htonl(bodyLen);
-        int propertiesLength_net = htons(propertiesLength);
-        encodeMsg.append((char*)&storeSize_net, sizeof(int));
-        encodeMsg.append((char*)&magicCode_net, sizeof(int));
-        encodeMsg.append((char*)&bodyCrc_net, sizeof(int));
-        encodeMsg.append((char*)&flag_net, sizeof(int));
-        encodeMsg.append((char*)&bodyLen_net, sizeof(int));
-        encodeMsg.append(body.c_str(), body.length());
-        encodeMsg.append((char*)&propertiesLength_net, sizeof(short));
-        encodeMsg.append(properties.c_str(), propertiesLength);
-        return encodeMsg;
-    }
+std::string BatchMessage::encode(MQMessage& message) {
+  string encodeMsg;
+  const string& body = message.getBody();
+  int bodyLen = body.length();
+  string properties = MQDecoder::messageProperties2String(message.getProperties());
+  short propertiesLength = (short)properties.length();
+  int storeSize = 20 + bodyLen + 2 + propertiesLength;
+  // TOTALSIZE|MAGICCOD|BODYCRC|FLAG|BODYLen|Body|propertiesLength|properties
+  int magicCode = 0;
+  int bodyCrc = 0;
+  int flag = message.getFlag();
+  int storeSize_net = htonl(storeSize);
+  int magicCode_net = htonl(magicCode);
+  int bodyCrc_net = htonl(bodyCrc);
+  int flag_net = htonl(flag);
+  int bodyLen_net = htonl(bodyLen);
+  int propertiesLength_net = htons(propertiesLength);
+  encodeMsg.append((char*)&storeSize_net, sizeof(int));
+  encodeMsg.append((char*)&magicCode_net, sizeof(int));
+  encodeMsg.append((char*)&bodyCrc_net, sizeof(int));
+  encodeMsg.append((char*)&flag_net, sizeof(int));
+  encodeMsg.append((char*)&bodyLen_net, sizeof(int));
+  encodeMsg.append(body.c_str(), body.length());
+  encodeMsg.append((char*)&propertiesLength_net, sizeof(short));
+  encodeMsg.append(properties.c_str(), propertiesLength);
+  return encodeMsg;
+}
 }
diff --git a/src/message/MQDecoder.cpp b/src/message/MQDecoder.cpp
old mode 100755
new mode 100644
index b64ff17..9e60c4d
--- a/src/message/MQDecoder.cpp
+++ b/src/message/MQDecoder.cpp
@@ -39,7 +39,7 @@
 

 //<!***************************************************************************

 string MQDecoder::createMessageId(sockaddr addr, int64 offset) {

-  struct sockaddr_in *sa = (struct sockaddr_in *) &addr;

+  struct sockaddr_in* sa = (struct sockaddr_in*)&addr;

 

   MemoryOutputStream outputmen(MSG_ID_LENGTH);

   outputmen.writeIntBigEndian(sa->sin_addr.s_addr);

@@ -47,19 +47,18 @@
   outputmen.write(&(sa->sin_port), 2);

   outputmen.writeInt64BigEndian(offset);

 

-  const char *bytes = static_cast<const char *>(outputmen.getData());

+  const char* bytes = static_cast<const char*>(outputmen.getData());

   int len = outputmen.getDataSize();

 

   return UtilAll::bytes2string(bytes, len);

 }

 

-MQMessageId MQDecoder::decodeMessageId(const string &msgId) {

-

+MQMessageId MQDecoder::decodeMessageId(const string& msgId) {

   string ipStr = msgId.substr(0, 8);

   string portStr = msgId.substr(8, 8);

   string offsetStr = msgId.substr(16);

 

-  char *end;

+  char* end;

   int ipInt = strtoul(ipStr.c_str(), &end, 16);

   int portInt = strtoul(portStr.c_str(), &end, 16);

 

@@ -70,16 +69,16 @@
   sa.sin_port = htons(portInt);

   sa.sin_addr.s_addr = htonl(ipInt);

 

-  MQMessageId id(*((sockaddr*) &sa), offset);

+  MQMessageId id(*((sockaddr*)&sa), offset);

   return id;

 }

 

-MQMessageExt *MQDecoder::decode(MemoryInputStream &byteBuffer) {

+MQMessageExt* MQDecoder::decode(MemoryInputStream& byteBuffer) {

   return decode(byteBuffer, true);

 }

 

-MQMessageExt *MQDecoder::decode(MemoryInputStream &byteBuffer, bool readBody) {

-  MQMessageExt *msgExt = new MQMessageExt();

+MQMessageExt* MQDecoder::decode(MemoryInputStream& byteBuffer, bool readBody) {

+  MQMessageExt* msgExt = new MQMessageExt();

 

   // 1 TOTALSIZE

   int storeSize = byteBuffer.readIntBigEndian();

@@ -147,7 +146,7 @@
       MemoryBlock block;

       byteBuffer.readIntoMemoryBlock(block, bodyLen);

 

-      const char *const pBody = static_cast<const char *>(block.getData());

+      const char* const pBody = static_cast<const char*>(block.getData());

       int len = block.getSize();

       string msgbody(pBody, len);

 

@@ -166,10 +165,10 @@
   }

 

   // 16 TOPIC

-  int topicLen = (int) byteBuffer.readByte();

+  int topicLen = (int)byteBuffer.readByte();

   MemoryBlock block;

   byteBuffer.readIntoMemoryBlock(block, topicLen);

-  const char *const pTopic = static_cast<const char *>(block.getData());

+  const char* const pTopic = static_cast<const char*>(block.getData());

   topicLen = block.getSize();

   msgExt->setTopic(pTopic, topicLen);

 

@@ -178,7 +177,7 @@
   if (propertiesLen > 0) {

     MemoryBlock block;

     byteBuffer.readIntoMemoryBlock(block, propertiesLen);

-    const char *const pProperty = static_cast<const char *>(block.getData());

+    const char* const pProperty = static_cast<const char*>(block.getData());

     int len = block.getSize();

     string propertiesString(pProperty, len);

 

@@ -189,7 +188,7 @@
   }

 

   // 18 msg ID

-  string offsetMsgId = createMessageId(msgExt->getStoreHost(), (int64) msgExt->getCommitLogOffset());

+  string offsetMsgId = createMessageId(msgExt->getStoreHost(), (int64)msgExt->getCommitLogOffset());

   msgExt->setOffsetMsgId(offsetMsgId);

 

   string msgId = msgExt->getProperty(MQMessage::PROPERTY_UNIQ_CLIENT_MESSAGE_ID_KEYIDX);

@@ -202,12 +201,12 @@
   return msgExt;

 }

 

-void MQDecoder::decodes(const MemoryBlock *mem, vector<MQMessageExt> &mqvec) {

+void MQDecoder::decodes(const MemoryBlock* mem, vector<MQMessageExt>& mqvec) {

   mqvec.clear();

   decodes(mem, mqvec, true);

 }

 

-void MQDecoder::decodes(const MemoryBlock *mem, vector<MQMessageExt> &mqvec, bool readBody) {

+void MQDecoder::decodes(const MemoryBlock* mem, vector<MQMessageExt>& mqvec, bool readBody) {

   MemoryInputStream rawInput(*mem, true);

 

   while (rawInput.getNumBytesRemaining() > 0) {

@@ -216,10 +215,10 @@
   }

 }

 

-string MQDecoder::messageProperties2String(const map<string, string> &properties) {

+string MQDecoder::messageProperties2String(const map<string, string>& properties) {

   string os;

 

-  for (const auto &it : properties) {

+  for (const auto& it : properties) {

     // os << it->first << NAME_VALUE_SEPARATOR << it->second << PROPERTY_SEPARATOR;

     os.append(it.first);

     os += NAME_VALUE_SEPARATOR;

@@ -230,7 +229,7 @@
   return os;

 }

 

-void MQDecoder::string2messageProperties(const string &propertiesString, map<string, string> &properties) {

+void MQDecoder::string2messageProperties(const string& propertiesString, map<string, string>& properties) {

   vector<string> out;

   UtilAll::Split(out, propertiesString, PROPERTY_SEPARATOR);

 

diff --git a/src/message/MQDecoder.h b/src/message/MQDecoder.h
old mode 100755
new mode 100644
diff --git a/src/message/MQMessage.cpp b/src/message/MQMessage.cpp
old mode 100755
new mode 100644
index e816879..83fe68d
--- a/src/message/MQMessage.cpp
+++ b/src/message/MQMessage.cpp
@@ -52,29 +52,34 @@
 static const string EMPTY_STRING = "";
 
 //<!************************************************************************
-MQMessage::MQMessage() { Init("", "", "", 0, "", true); }
+MQMessage::MQMessage() {
+  Init("", "", "", 0, "", true);
+}
 
 MQMessage::MQMessage(const string& topic, const string& body) {
   Init(topic, "", "", 0, body, true);
 }
 
-MQMessage::MQMessage(const string& topic, const string& tags,
-                     const string& body) {
+MQMessage::MQMessage(const string& topic, const string& tags, const string& body) {
   Init(topic, tags, "", 0, body, true);
 }
 
-MQMessage::MQMessage(const string& topic, const string& tags,
-                     const string& keys, const string& body) {
+MQMessage::MQMessage(const string& topic, const string& tags, const string& keys, const string& body) {
   Init(topic, tags, keys, 0, body, true);
 }
 
-MQMessage::MQMessage(const string& topic, const string& tags,
-                     const string& keys, const int flag, const string& body,
+MQMessage::MQMessage(const string& topic,
+                     const string& tags,
+                     const string& keys,
+                     const int flag,
+                     const string& body,
                      bool waitStoreMsgOK) {
   Init(topic, tags, keys, flag, body, waitStoreMsgOK);
 }
 
-MQMessage::~MQMessage() { m_properties.clear(); }
+MQMessage::~MQMessage() {
+  m_properties.clear();
+}
 
 MQMessage::MQMessage(const MQMessage& other) {
   m_body = other.m_body;
@@ -110,7 +115,7 @@
   m_properties[name] = value;
 }
 
-const string & MQMessage::getProperty(const string& name) const {
+const string& MQMessage::getProperty(const string& name) const {
   map<string, string>::const_iterator it = m_properties.find(name);
   if (it == m_properties.end()) {
     return EMPTY_STRING;
@@ -119,22 +124,30 @@
   }
 }
 
-const string& MQMessage::getTopic() const { return m_topic; }
+const string& MQMessage::getTopic() const {
+  return m_topic;
+}
 
-void MQMessage::setTopic(const string& topic) { m_topic = topic; }
+void MQMessage::setTopic(const string& topic) {
+  m_topic = topic;
+}
 
 void MQMessage::setTopic(const char* body, int len) {
   m_topic.clear();
   m_topic.append(body, len);
 }
 
-const string& MQMessage::getTags() const { return getProperty(PROPERTY_TAGS); }
+const string& MQMessage::getTags() const {
+  return getProperty(PROPERTY_TAGS);
+}
 
 void MQMessage::setTags(const string& tags) {
   setPropertyInternal(PROPERTY_TAGS, tags);
 }
 
-const string& MQMessage::getKeys() const { return getProperty(PROPERTY_KEYS); }
+const string& MQMessage::getKeys() const {
+  return getProperty(PROPERTY_KEYS);
+}
 
 void MQMessage::setKeys(const string& keys) {
   setPropertyInternal(PROPERTY_KEYS, keys);
@@ -190,27 +203,39 @@
   }
 }
 
-int MQMessage::getFlag() const { return m_flag; }
+int MQMessage::getFlag() const {
+  return m_flag;
+}
 
-void MQMessage::setFlag(int flag) { m_flag = flag; }
+void MQMessage::setFlag(int flag) {
+  m_flag = flag;
+}
 
-int MQMessage::getSysFlag() const { return m_sysFlag; }
+int MQMessage::getSysFlag() const {
+  return m_sysFlag;
+}
 
-void MQMessage::setSysFlag(int sysFlag) { m_sysFlag = sysFlag; }
+void MQMessage::setSysFlag(int sysFlag) {
+  m_sysFlag = sysFlag;
+}
 
-const string& MQMessage::getBody() const { return m_body; }
+const string& MQMessage::getBody() const {
+  return m_body;
+}
 
 void MQMessage::setBody(const char* body, int len) {
   m_body.clear();
   m_body.append(body, len);
 }
 
-void MQMessage::setBody(const string &body) {
+void MQMessage::setBody(const string& body) {
   m_body.clear();
   m_body.append(body);
 }
 
-map<string, string> MQMessage::getProperties() const { return m_properties; }
+map<string, string> MQMessage::getProperties() const {
+  return m_properties;
+}
 
 void MQMessage::setProperties(map<string, string>& properties) {
   m_properties = properties;
@@ -230,8 +255,11 @@
   m_properties = properties;
 }
 
-void MQMessage::Init(const string& topic, const string& tags,
-                     const string& keys, const int flag, const string& body,
+void MQMessage::Init(const string& topic,
+                     const string& tags,
+                     const string& keys,
+                     const int flag,
+                     const string& body,
                      bool waitStoreMsgOK) {
   m_topic = topic;
   m_flag = flag;
diff --git a/src/message/MQMessageExt.cpp b/src/message/MQMessageExt.cpp
old mode 100755
new mode 100644
index 43f4bf0..fc022a2
--- a/src/message/MQMessageExt.cpp
+++ b/src/message/MQMessageExt.cpp
@@ -33,8 +33,11 @@
       m_reconsumeTimes(3),
       m_msgId("") {}
 
-MQMessageExt::MQMessageExt(int queueId, int64 bornTimestamp, sockaddr bornHost,
-                           int64 storeTimestamp, sockaddr storeHost,
+MQMessageExt::MQMessageExt(int queueId,
+                           int64 bornTimestamp,
+                           sockaddr bornHost,
+                           int64 storeTimestamp,
+                           sockaddr storeHost,
                            string msgId)
     : m_queueOffset(0),
       m_commitLogOffset(0),
@@ -51,17 +54,25 @@
 
 MQMessageExt::~MQMessageExt() {}
 
-int MQMessageExt::getQueueId() const { return m_queueId; }
+int MQMessageExt::getQueueId() const {
+  return m_queueId;
+}
 
-void MQMessageExt::setQueueId(int queueId) { m_queueId = queueId; }
+void MQMessageExt::setQueueId(int queueId) {
+  m_queueId = queueId;
+}
 
-int64 MQMessageExt::getBornTimestamp() const { return m_bornTimestamp; }
+int64 MQMessageExt::getBornTimestamp() const {
+  return m_bornTimestamp;
+}
 
 void MQMessageExt::setBornTimestamp(int64 bornTimestamp) {
   m_bornTimestamp = bornTimestamp;
 }
 
-sockaddr MQMessageExt::getBornHost() const { return m_bornHost; }
+sockaddr MQMessageExt::getBornHost() const {
+  return m_bornHost;
+}
 
 string MQMessageExt::getBornHostString() const {
   return socketAddress2String(m_bornHost);
@@ -75,13 +86,17 @@
   m_bornHost = bornHost;
 }
 
-int64 MQMessageExt::getStoreTimestamp() const { return m_storeTimestamp; }
+int64 MQMessageExt::getStoreTimestamp() const {
+  return m_storeTimestamp;
+}
 
 void MQMessageExt::setStoreTimestamp(int64 storeTimestamp) {
   m_storeTimestamp = storeTimestamp;
 }
 
-sockaddr MQMessageExt::getStoreHost() const { return m_storeHost; }
+sockaddr MQMessageExt::getStoreHost() const {
+  return m_storeHost;
+}
 
 string MQMessageExt::getStoreHostString() const {
   return socketAddress2String(m_storeHost);
@@ -91,43 +106,64 @@
   m_storeHost = storeHost;
 }
 
-const string& MQMessageExt::getMsgId() const { return m_msgId; }
+const string& MQMessageExt::getMsgId() const {
+  return m_msgId;
+}
 
-void MQMessageExt::setMsgId(const string& msgId) { m_msgId = msgId; }
+void MQMessageExt::setMsgId(const string& msgId) {
+  m_msgId = msgId;
+}
 
-const string& MQMessageExt::getOffsetMsgId() const { return m_offsetMsgId; }
+const string& MQMessageExt::getOffsetMsgId() const {
+  return m_offsetMsgId;
+}
 
-void MQMessageExt::setOffsetMsgId(const string& offsetMsgId) { m_offsetMsgId = offsetMsgId; }
+void MQMessageExt::setOffsetMsgId(const string& offsetMsgId) {
+  m_offsetMsgId = offsetMsgId;
+}
 
-int MQMessageExt::getBodyCRC() const { return m_bodyCRC; }
+int MQMessageExt::getBodyCRC() const {
+  return m_bodyCRC;
+}
 
-void MQMessageExt::setBodyCRC(int bodyCRC) { m_bodyCRC = bodyCRC; }
+void MQMessageExt::setBodyCRC(int bodyCRC) {
+  m_bodyCRC = bodyCRC;
+}
 
-int64 MQMessageExt::getQueueOffset() const { return m_queueOffset; }
+int64 MQMessageExt::getQueueOffset() const {
+  return m_queueOffset;
+}
 
 void MQMessageExt::setQueueOffset(int64 queueOffset) {
   m_queueOffset = queueOffset;
 }
 
-int64 MQMessageExt::getCommitLogOffset() const { return m_commitLogOffset; }
+int64 MQMessageExt::getCommitLogOffset() const {
+  return m_commitLogOffset;
+}
 
 void MQMessageExt::setCommitLogOffset(int64 physicOffset) {
   m_commitLogOffset = physicOffset;
 }
 
-int MQMessageExt::getStoreSize() const { return m_storeSize; }
+int MQMessageExt::getStoreSize() const {
+  return m_storeSize;
+}
 
-void MQMessageExt::setStoreSize(int storeSize) { m_storeSize = storeSize; }
+void MQMessageExt::setStoreSize(int storeSize) {
+  m_storeSize = storeSize;
+}
 
 int MQMessageExt::parseTopicFilterType(int sysFlag) {
-  if ((sysFlag & MessageSysFlag::MultiTagsFlag) ==
-      MessageSysFlag::MultiTagsFlag) {
+  if ((sysFlag & MessageSysFlag::MultiTagsFlag) == MessageSysFlag::MultiTagsFlag) {
     return MULTI_TAG;
   }
   return SINGLE_TAG;
 }
 
-int MQMessageExt::getReconsumeTimes() const { return m_reconsumeTimes; }
+int MQMessageExt::getReconsumeTimes() const {
+  return m_reconsumeTimes;
+}
 
 void MQMessageExt::setReconsumeTimes(int reconsumeTimes) {
   m_reconsumeTimes = reconsumeTimes;
@@ -137,8 +173,7 @@
   return m_preparedTransactionOffset;
 }
 
-void MQMessageExt::setPreparedTransactionOffset(
-    int64 preparedTransactionOffset) {
+void MQMessageExt::setPreparedTransactionOffset(int64 preparedTransactionOffset) {
   m_preparedTransactionOffset = preparedTransactionOffset;
 }
 
diff --git a/src/message/MQMessageId.h b/src/message/MQMessageId.h
old mode 100755
new mode 100644
index 366ac20..fbe937b
--- a/src/message/MQMessageId.h
+++ b/src/message/MQMessageId.h
@@ -24,8 +24,16 @@
 //<!***************************************************************************
 class MQMessageId {
  public:
-  MQMessageId(sockaddr address, int64 offset)
-      : m_address(address), m_offset(offset) {}
+  MQMessageId() {}
+  MQMessageId(sockaddr address, int64 offset) : m_address(address), m_offset(offset) {}
+  MQMessageId& operator=(const MQMessageId& id) {
+    if (&id == this) {
+      return *this;
+    }
+    this->m_address = id.m_address;
+    this->m_offset = id.m_offset;
+    return *this;
+  }
 
   sockaddr getAddress() const { return m_address; }
 
@@ -40,6 +48,6 @@
   int64 m_offset;
 };
 
-}  //<!end namespace;
+}  // namespace rocketmq
 
 #endif
diff --git a/src/message/MQMessageQueue.cpp b/src/message/MQMessageQueue.cpp
old mode 100755
new mode 100644
index 60481e5..22b52f4
--- a/src/message/MQMessageQueue.cpp
+++ b/src/message/MQMessageQueue.cpp
@@ -24,14 +24,11 @@
   m_brokerName.clear();
 }
 
-MQMessageQueue::MQMessageQueue(const std::string& topic, const std::string& brokerName,
-                               int queueId)
+MQMessageQueue::MQMessageQueue(const std::string& topic, const std::string& brokerName, int queueId)
     : m_topic(topic), m_brokerName(brokerName), m_queueId(queueId) {}
 
 MQMessageQueue::MQMessageQueue(const MQMessageQueue& other)
-    : m_topic(other.m_topic),
-      m_brokerName(other.m_brokerName),
-      m_queueId(other.m_queueId) {}
+    : m_topic(other.m_topic), m_brokerName(other.m_brokerName), m_queueId(other.m_queueId) {}
 
 MQMessageQueue& MQMessageQueue::operator=(const MQMessageQueue& other) {
   if (this != &other) {
@@ -42,19 +39,29 @@
   return *this;
 }
 
-std::string MQMessageQueue::getTopic() const { return m_topic; }
+std::string MQMessageQueue::getTopic() const {
+  return m_topic;
+}
 
-void MQMessageQueue::setTopic(const std::string& topic) { m_topic = topic; }
+void MQMessageQueue::setTopic(const std::string& topic) {
+  m_topic = topic;
+}
 
-std::string MQMessageQueue::getBrokerName() const { return m_brokerName; }
+std::string MQMessageQueue::getBrokerName() const {
+  return m_brokerName;
+}
 
 void MQMessageQueue::setBrokerName(const std::string& brokerName) {
   m_brokerName = brokerName;
 }
 
-int MQMessageQueue::getQueueId() const { return m_queueId; }
+int MQMessageQueue::getQueueId() const {
+  return m_queueId;
+}
 
-void MQMessageQueue::setQueueId(int queueId) { m_queueId = queueId; }
+void MQMessageQueue::setQueueId(int queueId) {
+  m_queueId = queueId;
+}
 
 bool MQMessageQueue::operator==(const MQMessageQueue& mq) const {
   if (this == &mq) {
diff --git a/src/producer/DefaultMQProducer.cpp b/src/producer/DefaultMQProducer.cpp
old mode 100755
new mode 100644
index b7c3695..20ba968
--- a/src/producer/DefaultMQProducer.cpp
+++ b/src/producer/DefaultMQProducer.cpp
@@ -16,7 +16,11 @@
  */
 
 #include "DefaultMQProducer.h"
+
 #include <assert.h>
+#include <typeindex>
+
+#include "BatchMessage.h"
 #include "CommandHeader.h"
 #include "CommunicationMode.h"
 #include "Logging.h"
@@ -26,11 +30,9 @@
 #include "MQClientManager.h"
 #include "MQDecoder.h"
 #include "MQProtos.h"
+#include "StringIdMaker.h"
 #include "TopicPublishInfo.h"
 #include "Validators.h"
-#include "StringIdMaker.h"
-#include "BatchMessage.h"
-#include <typeinfo>
 
 namespace rocketmq {
 
@@ -39,7 +41,7 @@
     : m_sendMsgTimeout(3000),
       m_compressMsgBodyOverHowmuch(4 * 1024),
       m_maxMessageSize(1024 * 128),
-      //m_retryAnotherBrokerWhenNotStoreOK(false),
+      // m_retryAnotherBrokerWhenNotStoreOK(false),
       m_compressLevel(5),
       m_retryTimes(5),
       m_retryTimes4Async(1) {
@@ -54,7 +56,7 @@
 #ifndef WIN32
   /* Ignore the SIGPIPE */
   struct sigaction sa;
-  memset(&sa,0, sizeof(struct sigaction));
+  memset(&sa, 0, sizeof(struct sigaction));
   sa.sa_handler = SIG_IGN;
   sa.sa_flags = 0;
   sigaction(SIGPIPE, &sa, 0);
@@ -71,9 +73,7 @@
         m_serviceState = CREATE_JUST;
         THROW_MQEXCEPTION(
             MQClientException,
-            "The producer group[" + getGroupName() +
-                "] has been created before, specify another name please.",
-            -1);
+            "The producer group[" + getGroupName() + "] has been created before, specify another name please.", -1);
       }
 
       getFactory()->start();
@@ -118,8 +118,7 @@
   return SendResult();
 }
 
-void DefaultMQProducer::send(MQMessage& msg, SendCallback* pSendCallback,
-                             bool bSelectActiveBroker) {
+void DefaultMQProducer::send(MQMessage& msg, SendCallback* pSendCallback, bool bSelectActiveBroker) {
   Validators::checkMessage(msg, getMaxMessageSize());
   try {
     sendDefaultImpl(msg, ComMode_ASYNC, pSendCallback, bSelectActiveBroker);
@@ -154,7 +153,6 @@
 }
 
 BatchMessage DefaultMQProducer::buildBatchMessage(std::vector<MQMessage>& msgs) {
-
   if (msgs.size() < 1) {
     THROW_MQEXCEPTION(MQClientException, "msgs need one message at least", -1);
   }
@@ -173,7 +171,6 @@
         THROW_MQEXCEPTION(MQClientException, "Retry Group is not supported for batching", -1);
       }
     } else {
-
       if (msg.getDelayTimeLevel() > 0) {
         THROW_MQEXCEPTION(MQClientException, "TimeDelayLevel in not supported for batching", -1);
       }
@@ -205,8 +202,7 @@
   return SendResult();
 }
 
-void DefaultMQProducer::send(MQMessage& msg, const MQMessageQueue& mq,
-                             SendCallback* pSendCallback) {
+void DefaultMQProducer::send(MQMessage& msg, const MQMessageQueue& mq, SendCallback* pSendCallback) {
   Validators::checkMessage(msg, getMaxMessageSize());
   if (msg.getTopic() != mq.getTopic()) {
     LOG_WARN("message's topic not equal mq's topic");
@@ -242,8 +238,7 @@
   }
 }
 
-SendResult DefaultMQProducer::send(MQMessage& msg,
-                                   MessageQueueSelector* pSelector, void* arg) {
+SendResult DefaultMQProducer::send(MQMessage& msg, MessageQueueSelector* pSelector, void* arg) {
   try {
     return sendSelectImpl(msg, pSelector, arg, ComMode_SYNC, NULL);
   } catch (MQException& e) {
@@ -254,11 +249,12 @@
 }
 
 SendResult DefaultMQProducer::send(MQMessage& msg,
-                                   MessageQueueSelector* pSelector, void* arg,
-                                   int autoRetryTimes, bool bActiveBroker) {
+                                   MessageQueueSelector* pSelector,
+                                   void* arg,
+                                   int autoRetryTimes,
+                                   bool bActiveBroker) {
   try {
-    return sendAutoRetrySelectImpl(msg, pSelector, arg, ComMode_SYNC, NULL,
-                                   autoRetryTimes, bActiveBroker);
+    return sendAutoRetrySelectImpl(msg, pSelector, arg, ComMode_SYNC, NULL, autoRetryTimes, bActiveBroker);
   } catch (MQException& e) {
     LOG_ERROR(e.what());
     throw e;
@@ -266,8 +262,7 @@
   return SendResult();
 }
 
-void DefaultMQProducer::send(MQMessage& msg, MessageQueueSelector* pSelector,
-                             void* arg, SendCallback* pSendCallback) {
+void DefaultMQProducer::send(MQMessage& msg, MessageQueueSelector* pSelector, void* arg, SendCallback* pSendCallback) {
   try {
     sendSelectImpl(msg, pSelector, arg, ComMode_ASYNC, pSendCallback);
   } catch (MQException& e) {
@@ -276,8 +271,7 @@
   }
 }
 
-void DefaultMQProducer::sendOneway(MQMessage& msg,
-                                   MessageQueueSelector* pSelector, void* arg) {
+void DefaultMQProducer::sendOneway(MQMessage& msg, MessageQueueSelector* pSelector, void* arg) {
   try {
     sendSelectImpl(msg, pSelector, arg, ComMode_ONEWAY, NULL);
   } catch (MQException& e) {
@@ -286,7 +280,9 @@
   }
 }
 
-int DefaultMQProducer::getSendMsgTimeout() const { return m_sendMsgTimeout; }
+int DefaultMQProducer::getSendMsgTimeout() const {
+  return m_sendMsgTimeout;
+}
 
 void DefaultMQProducer::setSendMsgTimeout(int sendMsgTimeout) {
   m_sendMsgTimeout = sendMsgTimeout;
@@ -296,18 +292,21 @@
   return m_compressMsgBodyOverHowmuch;
 }
 
-void DefaultMQProducer::setCompressMsgBodyOverHowmuch(
-    int compressMsgBodyOverHowmuch) {
+void DefaultMQProducer::setCompressMsgBodyOverHowmuch(int compressMsgBodyOverHowmuch) {
   m_compressMsgBodyOverHowmuch = compressMsgBodyOverHowmuch;
 }
 
-int DefaultMQProducer::getMaxMessageSize() const { return m_maxMessageSize; }
+int DefaultMQProducer::getMaxMessageSize() const {
+  return m_maxMessageSize;
+}
 
 void DefaultMQProducer::setMaxMessageSize(int maxMessageSize) {
   m_maxMessageSize = maxMessageSize;
 }
 
-int DefaultMQProducer::getCompressLevel() const { return m_compressLevel; }
+int DefaultMQProducer::getCompressLevel() const {
+  return m_compressLevel;
+}
 
 void DefaultMQProducer::setCompressLevel(int compressLevel) {
   assert((compressLevel >= 0 && compressLevel <= 9) || compressLevel == -1);
@@ -324,10 +323,8 @@
   int mq_index = 0;
   for (int times = 1; times <= m_retryTimes; times++) {
     boost::weak_ptr<TopicPublishInfo> weak_topicPublishInfo(
-        getFactory()->tryToFindTopicPublishInfo(msg.getTopic(),
-                                                getSessionCredentials()));
-    boost::shared_ptr<TopicPublishInfo> topicPublishInfo(
-        weak_topicPublishInfo.lock());
+        getFactory()->tryToFindTopicPublishInfo(msg.getTopic(), getSessionCredentials()));
+    boost::shared_ptr<TopicPublishInfo> topicPublishInfo(weak_topicPublishInfo.lock());
     if (topicPublishInfo) {
       if (times == 1) {
         mq_index = topicPublishInfo->getWhichQueue();
@@ -360,8 +357,7 @@
           case ComMode_SYNC:
             if (sendResult.getSendStatus() != SEND_OK) {
               if (bActiveMQ) {
-                topicPublishInfo->updateNonServiceMessageQueue(
-                    mq, getSendMsgTimeout());
+                topicPublishInfo->updateNonServiceMessageQueue(mq, getSendMsgTimeout());
               }
               continue;
             }
@@ -370,11 +366,9 @@
             break;
         }
       } catch (...) {
-        LOG_ERROR("send failed of times:%d,brokerName:%s", times,
-                  mq.getBrokerName().c_str());
+        LOG_ERROR("send failed of times:%d,brokerName:%s", times, mq.getBrokerName().c_str());
         if (bActiveMQ) {
-          topicPublishInfo->updateNonServiceMessageQueue(mq,
-                                                         getSendMsgTimeout());
+          topicPublishInfo->updateNonServiceMessageQueue(mq, getSendMsgTimeout());
         }
         continue;
       }
@@ -389,20 +383,17 @@
                                              const MQMessageQueue& mq,
                                              int communicationMode,
                                              SendCallback* sendCallback) {
-  string brokerAddr =
-      getFactory()->findBrokerAddressInPublish(mq.getBrokerName());
+  string brokerAddr = getFactory()->findBrokerAddressInPublish(mq.getBrokerName());
 
   if (brokerAddr.empty()) {
-    getFactory()->tryToFindTopicPublishInfo(mq.getTopic(),
-                                            getSessionCredentials());
+    getFactory()->tryToFindTopicPublishInfo(mq.getTopic(), getSessionCredentials());
     brokerAddr = getFactory()->findBrokerAddressInPublish(mq.getBrokerName());
   }
 
   if (!brokerAddr.empty()) {
     try {
-      BatchMessage batchMessage;
-      bool isBatchMsg = (typeid(msg).name() == typeid(batchMessage).name());
-      //msgId is produced by client, offsetMsgId produced by broker. (same with java sdk)
+      bool isBatchMsg = std::type_index(typeid(msg)) == std::type_index(typeid(BatchMessage));
+      // msgId is produced by client, offsetMsgId produced by broker. (same with java sdk)
       if (!isBatchMsg) {
         string unique_id = StringIdMaker::get_mutable_instance().get_unique_id();
         msg.setProperty(MQMessage::PROPERTY_UNIQ_CLIENT_MESSAGE_ID_KEYIDX, unique_id);
@@ -422,45 +413,43 @@
       requestHeader->bornTimestamp = UtilAll::currentTimeMillis();
       requestHeader->flag = (msg.getFlag());
       requestHeader->batch = isBatchMsg;
-      requestHeader->properties =
-          (MQDecoder::messageProperties2String(msg.getProperties()));
+      requestHeader->properties = (MQDecoder::messageProperties2String(msg.getProperties()));
 
-      return getFactory()->getMQClientAPIImpl()->sendMessage(
-          brokerAddr, mq.getBrokerName(), msg, requestHeader,
-          getSendMsgTimeout(), getRetryTimes4Async(), communicationMode, sendCallback,
-          getSessionCredentials());
+      return getFactory()->getMQClientAPIImpl()->sendMessage(brokerAddr, mq.getBrokerName(), msg, requestHeader,
+                                                             getSendMsgTimeout(), getRetryTimes4Async(),
+                                                             communicationMode, sendCallback, getSessionCredentials());
     } catch (MQException& e) {
       throw e;
     }
   }
-  THROW_MQEXCEPTION(MQClientException,
-                    "The broker[" + mq.getBrokerName() + "] not exist", -1);
+  THROW_MQEXCEPTION(MQClientException, "The broker[" + mq.getBrokerName() + "] not exist", -1);
 }
 
 SendResult DefaultMQProducer::sendSelectImpl(MQMessage& msg,
                                              MessageQueueSelector* pSelector,
-                                             void* pArg, int communicationMode,
+                                             void* pArg,
+                                             int communicationMode,
                                              SendCallback* sendCallback) {
   Validators::checkMessage(msg, getMaxMessageSize());
 
   boost::weak_ptr<TopicPublishInfo> weak_topicPublishInfo(
-      getFactory()->tryToFindTopicPublishInfo(msg.getTopic(),
-                                              getSessionCredentials()));
-  boost::shared_ptr<TopicPublishInfo> topicPublishInfo(
-      weak_topicPublishInfo.lock());
+      getFactory()->tryToFindTopicPublishInfo(msg.getTopic(), getSessionCredentials()));
+  boost::shared_ptr<TopicPublishInfo> topicPublishInfo(weak_topicPublishInfo.lock());
   if (topicPublishInfo)  //&& topicPublishInfo->ok())
   {
-    MQMessageQueue mq =
-        pSelector->select(topicPublishInfo->getMessageQueueList(), msg, pArg);
+    MQMessageQueue mq = pSelector->select(topicPublishInfo->getMessageQueueList(), msg, pArg);
     return sendKernelImpl(msg, mq, communicationMode, sendCallback);
   }
   THROW_MQEXCEPTION(MQClientException, "No route info for this topic", -1);
 }
 
-SendResult DefaultMQProducer::sendAutoRetrySelectImpl(
-    MQMessage& msg, MessageQueueSelector* pSelector, void* pArg,
-    int communicationMode, SendCallback* pSendCallback, int autoRetryTimes,
-    bool bActiveMQ) {
+SendResult DefaultMQProducer::sendAutoRetrySelectImpl(MQMessage& msg,
+                                                      MessageQueueSelector* pSelector,
+                                                      void* pArg,
+                                                      int communicationMode,
+                                                      SendCallback* pSendCallback,
+                                                      int autoRetryTimes,
+                                                      bool bActiveMQ) {
   Validators::checkMessage(msg, getMaxMessageSize());
 
   MQMessageQueue lastmq;
@@ -468,22 +457,20 @@
   int mq_index = 0;
   for (int times = 1; times <= autoRetryTimes + 1; times++) {
     boost::weak_ptr<TopicPublishInfo> weak_topicPublishInfo(
-        getFactory()->tryToFindTopicPublishInfo(msg.getTopic(),
-                                                getSessionCredentials()));
-    boost::shared_ptr<TopicPublishInfo> topicPublishInfo(
-        weak_topicPublishInfo.lock());
+        getFactory()->tryToFindTopicPublishInfo(msg.getTopic(), getSessionCredentials()));
+    boost::shared_ptr<TopicPublishInfo> topicPublishInfo(weak_topicPublishInfo.lock());
     if (topicPublishInfo) {
       SendResult sendResult;
-      if (times == 1) {  // always send to selected MQ firstly, evenif bActiveMQ
-                         // was setted to true
-        mq = pSelector->select(topicPublishInfo->getMessageQueueList(), msg,
-                               pArg);
+      if (times == 1) {
+        // always send to selected MQ firstly, evenif bActiveMQ was setted to true
+        mq = pSelector->select(topicPublishInfo->getMessageQueueList(), msg, pArg);
         lastmq = mq;
       } else {
         LOG_INFO("sendAutoRetrySelectImpl with times:%d", times);
-        vector<MQMessageQueue> mqs(topicPublishInfo->getMessageQueueList());
+        std::vector<MQMessageQueue> mqs(topicPublishInfo->getMessageQueueList());
         for (size_t i = 0; i < mqs.size(); i++) {
-          if (mqs[i] == lastmq) mq_index = i;
+          if (mqs[i] == lastmq)
+            mq_index = i;
         }
         if (bActiveMQ)
           mq = topicPublishInfo->selectOneActiveMessageQueue(lastmq, mq_index);
@@ -508,8 +495,7 @@
           case ComMode_SYNC:
             if (sendResult.getSendStatus() != SEND_OK) {
               if (bActiveMQ) {
-                topicPublishInfo->updateNonServiceMessageQueue(
-                    mq, getSendMsgTimeout());
+                topicPublishInfo->updateNonServiceMessageQueue(mq, getSendMsgTimeout());
               }
               continue;
             }
@@ -518,11 +504,9 @@
             break;
         }
       } catch (...) {
-        LOG_ERROR("send failed of times:%d,mq:%s", times,
-                  mq.toString().c_str());
+        LOG_ERROR("send failed of times:%d,mq:%s", times, mq.toString().c_str());
         if (bActiveMQ) {
-          topicPublishInfo->updateNonServiceMessageQueue(mq,
-                                                         getSendMsgTimeout());
+          topicPublishInfo->updateNonServiceMessageQueue(mq, getSendMsgTimeout());
         }
         continue;
       }
@@ -550,7 +534,9 @@
 
   return false;
 }
-int DefaultMQProducer::getRetryTimes() const { return m_retryTimes; }
+int DefaultMQProducer::getRetryTimes() const {
+  return m_retryTimes;
+}
 void DefaultMQProducer::setRetryTimes(int times) {
   if (times <= 0) {
     LOG_WARN("set retry times illegal, use default value:5");
@@ -566,12 +552,10 @@
   m_retryTimes = times;
 }
 
-int DefaultMQProducer::getRetryTimes4Async() const 
-{ 
-  return m_retryTimes4Async; 
+int DefaultMQProducer::getRetryTimes4Async() const {
+  return m_retryTimes4Async;
 }
-void DefaultMQProducer::setRetryTimes4Async(int times) 
-{
+void DefaultMQProducer::setRetryTimes4Async(int times) {
   if (times <= 0) {
     LOG_WARN("set retry times illegal, use default value:1");
     m_retryTimes4Async = 1;
@@ -588,4 +572,4 @@
 }
 
 //<!***************************************************************************
-}  //<!end namespace;
+}  // namespace rocketmq
diff --git a/src/producer/SendResult.cpp b/src/producer/SendResult.cpp
old mode 100755
new mode 100644
index 9eabf5d..6c55769
--- a/src/producer/SendResult.cpp
+++ b/src/producer/SendResult.cpp
@@ -15,6 +15,7 @@
  * limitations under the License.
  */
 #include "SendResult.h"
+#include <sstream>
 #include "UtilAll.h"
 #include "VirtualEnvUtil.h"
 
@@ -22,8 +23,11 @@
 //<!***************************************************************************
 SendResult::SendResult() : m_sendStatus(SEND_OK), m_queueOffset(0) {}
 
-SendResult::SendResult(const SendStatus& sendStatus, const std::string& msgId, const std::string& offsetMsgId,
-                       const MQMessageQueue& messageQueue, int64 queueOffset)
+SendResult::SendResult(const SendStatus& sendStatus,
+                       const std::string& msgId,
+                       const std::string& offsetMsgId,
+                       const MQMessageQueue& messageQueue,
+                       int64 queueOffset)
     : m_sendStatus(sendStatus),
       m_msgId(msgId),
       m_offsetMsgId(offsetMsgId),
@@ -51,15 +55,37 @@
 
 SendResult::~SendResult() {}
 
-const string& SendResult::getMsgId() const { return m_msgId; }
+const string& SendResult::getMsgId() const {
+  return m_msgId;
+}
 
-const string& SendResult::getOffsetMsgId() const { return m_offsetMsgId; }
+const string& SendResult::getOffsetMsgId() const {
+  return m_offsetMsgId;
+}
 
-SendStatus SendResult::getSendStatus() const { return m_sendStatus; }
+SendStatus SendResult::getSendStatus() const {
+  return m_sendStatus;
+}
 
-MQMessageQueue SendResult::getMessageQueue() const { return m_messageQueue; }
+MQMessageQueue SendResult::getMessageQueue() const {
+  return m_messageQueue;
+}
 
-int64 SendResult::getQueueOffset() const { return m_queueOffset; }
+int64 SendResult::getQueueOffset() const {
+  return m_queueOffset;
+}
+
+std::string SendResult::toString() const {
+  stringstream ss;
+  ss << "SendResult: ";
+  ss << "sendStatus:" << m_sendStatus;
+  ss << ",msgId:" << m_msgId;
+  ss << ",offsetMsgId:" << m_offsetMsgId;
+  ss << ",queueOffset:" << m_queueOffset;
+  ss << ",transactionId:" << m_transactionId;
+  ss << ",messageQueue:" << m_messageQueue.toString();
+  return ss.str();
+}
 
 //<!************************************************************************
-}  //<!end namespace;
+}  // namespace rocketmq
diff --git a/src/producer/StringIdMaker.cpp b/src/producer/StringIdMaker.cpp
index 06bd872..1b83fd8 100644
--- a/src/producer/StringIdMaker.cpp
+++ b/src/producer/StringIdMaker.cpp
@@ -19,13 +19,12 @@
 namespace rocketmq {
 
 #ifdef WIN32
-int gettimeofdayWin(struct timeval *tp, void *tzp)
-{
+int gettimeofdayWin(struct timeval* tp, void* tzp) {
   time_t clock;
   struct tm tm;
   SYSTEMTIME wtm;
   GetLocalTime(&wtm);
-  tm.tm_year	= wtm.wYear - 1900;
+  tm.tm_year = wtm.wYear - 1900;
   tm.tm_mon = wtm.wMonth - 1;
   tm.tm_mday = wtm.wDay;
   tm.tm_hour = wtm.wHour;
@@ -111,11 +110,11 @@
 
 uint64_t StringIdMaker::get_curr_ms() {
   struct timeval time_now;
-  //windows and linux use the same function name, windows's defination as begining this file
-#ifdef  WIN32
-  gettimeofdayWin(&time_now, NULL); //  WIN32
+// windows and linux use the same function name, windows's defination as begining this file
+#ifdef WIN32
+  gettimeofdayWin(&time_now, NULL);  //  WIN32
 #else
-  gettimeofday(&time_now, NULL);    //LINUX
+  gettimeofday(&time_now, NULL);  // LINUX
 #endif
 
   uint64_t ms_time = time_now.tv_sec * 1000 + time_now.tv_usec / 1000;
@@ -124,7 +123,7 @@
 
 void StringIdMaker::set_start_and_next_tm() {
   time_t tmNow = time(NULL);
-  tm *ptmNow = localtime(&tmNow);
+  tm* ptmNow = localtime(&tmNow);
   tm mon_begin;
   mon_begin.tm_year = ptmNow->tm_year;
   mon_begin.tm_mon = ptmNow->tm_mon;
@@ -154,11 +153,11 @@
 }
 
 int StringIdMaker::atomic_incr(int id) {
-  #ifdef WIN32
-    InterlockedIncrement((LONG*)&id);
-  #else
-    __sync_add_and_fetch(&id, 1);
-  #endif
+#ifdef WIN32
+  InterlockedIncrement((LONG*)&id);
+#else
+  __sync_add_and_fetch(&id, 1);
+#endif
   return id;
 }
 std::string StringIdMaker::get_unique_id() {
@@ -171,7 +170,7 @@
   seqid = atomic_incr(seqid) & 0xFF;
 
   std::size_t prifix_len = 10;  // 10 = prefix len
-  unsigned char *write_index = _buff + prifix_len;
+  unsigned char* write_index = _buff + prifix_len;
 
   memcpy(write_index, &tm_period, 4);
   write_index += 4;
@@ -183,7 +182,7 @@
   return std::string(_0x_buff);
 }
 
-void StringIdMaker::hexdump(unsigned char *buffer, char *out_buff, unsigned long index) {
+void StringIdMaker::hexdump(unsigned char* buffer, char* out_buff, unsigned long index) {
   for (unsigned long i = 0; i < index; i++) {
     sprintf(out_buff + 2 * i, "%02X ", buffer[i]);
   }
diff --git a/src/producer/StringIdMaker.h b/src/producer/StringIdMaker.h
index e95b744..b693787 100644
--- a/src/producer/StringIdMaker.h
+++ b/src/producer/StringIdMaker.h
@@ -61,7 +61,7 @@
   int atomic_incr(int id);
   void set_start_and_next_tm();
 
-  void hexdump(unsigned char *buffer, char *out_buff, unsigned long index);
+  void hexdump(unsigned char* buffer, char* out_buff, unsigned long index);
 
  private:
   uint64_t _start_tm;
diff --git a/src/producer/TopicPublishInfo.h b/src/producer/TopicPublishInfo.h
index 4b4fbb4..5f0380e 100644
--- a/src/producer/TopicPublishInfo.h
+++ b/src/producer/TopicPublishInfo.h
@@ -32,8 +32,7 @@
 class TopicPublishInfo {
  public:
   TopicPublishInfo() : m_sendWhichQueue(0) {
-    m_async_service_thread.reset(new boost::thread(
-        boost::bind(&TopicPublishInfo::boost_asio_work, this)));
+    m_async_service_thread.reset(new boost::thread(boost::bind(&TopicPublishInfo::boost_asio_work, this)));
   }
 
   void boost_asio_work() {
@@ -42,10 +41,8 @@
                                                             // after first timer
                                                             // timeout callback
     boost::system::error_code e;
-    boost::asio::deadline_timer t(m_async_ioService,
-                                  boost::posix_time::seconds(60));
-    t.async_wait(boost::bind(
-        &TopicPublishInfo::op_resumeNonServiceMessageQueueList, this, e, &t));
+    boost::asio::deadline_timer t(m_async_ioService, boost::posix_time::seconds(60));
+    t.async_wait(boost::bind(&TopicPublishInfo::op_resumeNonServiceMessageQueueList, this, e, &t));
     boost::system::error_code ec;
     m_async_ioService.run(ec);
   }
@@ -79,23 +76,18 @@
     }
   }
 
-  void op_resumeNonServiceMessageQueueList(boost::system::error_code& ec,
-                                           boost::asio::deadline_timer* t) {
+  void op_resumeNonServiceMessageQueueList(boost::system::error_code& ec, boost::asio::deadline_timer* t) {
     resumeNonServiceMessageQueueList();
     boost::system::error_code e;
-    t->expires_from_now(t->expires_from_now() + boost::posix_time::seconds(60),
-                        e);
-    t->async_wait(boost::bind(
-        &TopicPublishInfo::op_resumeNonServiceMessageQueueList, this, e, t));
+    t->expires_from_now(t->expires_from_now() + boost::posix_time::seconds(60), e);
+    t->async_wait(boost::bind(&TopicPublishInfo::op_resumeNonServiceMessageQueueList, this, e, t));
   }
 
   void resumeNonServiceMessageQueueList() {
     boost::lock_guard<boost::mutex> lock(m_queuelock);
-    for (map<MQMessageQueue, int64>::iterator it = m_brokerTimerMap.begin();
-         it != m_brokerTimerMap.end(); ++it) {
+    for (map<MQMessageQueue, int64>::iterator it = m_brokerTimerMap.begin(); it != m_brokerTimerMap.end(); ++it) {
       if (UtilAll::currentTimeMillis() - it->second >= 1000 * 60 * 5) {
-        string key = it->first.getBrokerName() +
-                     UtilAll::to_string(it->first.getQueueId());
+        string key = it->first.getBrokerName() + UtilAll::to_string(it->first.getQueueId());
         if (m_nonSerivceQueues.find(key) != m_nonSerivceQueues.end()) {
           m_nonSerivceQueues.erase(key);
         }
@@ -104,8 +96,7 @@
     }
   }
 
-  void updateNonServiceMessageQueue(const MQMessageQueue& mq,
-                                    int timeoutMilliseconds) {
+  void updateNonServiceMessageQueue(const MQMessageQueue& mq, int timeoutMilliseconds) {
     boost::lock_guard<boost::mutex> lock(m_queuelock);
 
     string key = mq.getBrokerName() + UtilAll::to_string(mq.getQueueId());
@@ -125,17 +116,13 @@
     return m_queues;
   }
 
-  int getWhichQueue() {
-    return m_sendWhichQueue.load(boost::memory_order_acquire);
-  }
+  int getWhichQueue() { return m_sendWhichQueue.load(boost::memory_order_acquire); }
 
-  MQMessageQueue selectOneMessageQueue(const MQMessageQueue& lastmq,
-                                       int& mq_index) {
+  MQMessageQueue selectOneMessageQueue(const MQMessageQueue& lastmq, int& mq_index) {
     boost::lock_guard<boost::mutex> lock(m_queuelock);
 
     if (m_queues.size() > 0) {
-      LOG_DEBUG("selectOneMessageQueue Enter, queue size:" SIZET_FMT "",
-                m_queues.size());
+      LOG_DEBUG("selectOneMessageQueue Enter, queue size:" SIZET_FMT "", m_queues.size());
       unsigned int pos = 0;
       if (mq_index >= 0) {
         pos = mq_index % m_queues.size();
@@ -145,12 +132,12 @@
       }
       if (!lastmq.getBrokerName().empty()) {
         for (size_t i = 0; i < m_queues.size(); i++) {
-          if (m_sendWhichQueue.load(boost::memory_order_acquire) ==
-              (numeric_limits<int>::max)()) {
+          if (m_sendWhichQueue.load(boost::memory_order_acquire) == (numeric_limits<int>::max)()) {
             m_sendWhichQueue.store(0, boost::memory_order_release);
           }
 
-          if (pos >= m_queues.size()) pos = pos % m_queues.size();
+          if (pos >= m_queues.size())
+            pos = pos % m_queues.size();
 
           ++m_sendWhichQueue;
           MQMessageQueue mq = m_queues.at(pos);
@@ -165,8 +152,7 @@
         LOG_ERROR("could not find property mq");
         return MQMessageQueue();
       } else {
-        if (m_sendWhichQueue.load(boost::memory_order_acquire) ==
-            (numeric_limits<int>::max)()) {
+        if (m_sendWhichQueue.load(boost::memory_order_acquire) == (numeric_limits<int>::max)()) {
           m_sendWhichQueue.store(0, boost::memory_order_release);
         }
 
@@ -182,8 +168,7 @@
     }
   }
 
-  MQMessageQueue selectOneActiveMessageQueue(const MQMessageQueue& lastmq,
-                                             int& mq_index) {
+  MQMessageQueue selectOneActiveMessageQueue(const MQMessageQueue& lastmq, int& mq_index) {
     boost::lock_guard<boost::mutex> lock(m_queuelock);
 
     if (m_queues.size() > 0) {
@@ -196,12 +181,12 @@
       }
       if (!lastmq.getBrokerName().empty()) {
         for (size_t i = 0; i < m_queues.size(); i++) {
-          if (m_sendWhichQueue.load(boost::memory_order_acquire) ==
-              (numeric_limits<int>::max)()) {
+          if (m_sendWhichQueue.load(boost::memory_order_acquire) == (numeric_limits<int>::max)()) {
             m_sendWhichQueue.store(0, boost::memory_order_release);
           }
 
-          if (pos >= m_queues.size()) pos = pos % m_queues.size();
+          if (pos >= m_queues.size())
+            pos = pos % m_queues.size();
 
           ++m_sendWhichQueue;
           MQMessageQueue mq = m_queues.at(pos);
@@ -214,8 +199,7 @@
           ++pos;
         }
 
-        for (MQMAP::iterator it = m_nonSerivceQueues.begin();
-             it != m_nonSerivceQueues.end();
+        for (MQMAP::iterator it = m_nonSerivceQueues.begin(); it != m_nonSerivceQueues.end();
              ++it) {  // if no MQMessageQueue(except lastmq) in
                       // m_onSerivceQueues, search m_nonSerivceQueues
           if (it->second.getBrokerName().compare(lastmq.getBrokerName()) != 0)
@@ -225,11 +209,11 @@
         return MQMessageQueue();
       } else {
         for (size_t i = 0; i < m_queues.size(); i++) {
-          if (m_sendWhichQueue.load(boost::memory_order_acquire) ==
-              (numeric_limits<int>::max)()) {
+          if (m_sendWhichQueue.load(boost::memory_order_acquire) == (numeric_limits<int>::max)()) {
             m_sendWhichQueue.store(0, boost::memory_order_release);
           }
-          if (pos >= m_queues.size()) pos = pos % m_queues.size();
+          if (pos >= m_queues.size())
+            pos = pos % m_queues.size();
 
           ++m_sendWhichQueue;
           LOG_DEBUG("lastmq broker empty, m_sendWhichQueue:%d, pos:%d",
@@ -244,8 +228,7 @@
           }
         }
 
-        for (MQMAP::iterator it = m_nonSerivceQueues.begin();
-             it != m_nonSerivceQueues.end();
+        for (MQMAP::iterator it = m_nonSerivceQueues.begin(); it != m_nonSerivceQueues.end();
              ++it) {  // if no MQMessageQueue(except lastmq) in
                       // m_onSerivceQueues, search m_nonSerivceQueues
           if (it->second.getBrokerName().compare(lastmq.getBrokerName()) != 0)
diff --git a/src/producer/TransactionMQProducer.cpp b/src/producer/TransactionMQProducer.cpp
new file mode 100644
index 0000000..fbd78c5
--- /dev/null
+++ b/src/producer/TransactionMQProducer.cpp
@@ -0,0 +1,216 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "TransactionMQProducer.h"
+#include <string>
+#include "CommandHeader.h"
+#include "Logging.h"
+#include "MQClientFactory.h"
+#include "MQDecoder.h"
+#include "MessageSysFlag.h"
+#include "TransactionListener.h"
+#include "TransactionSendResult.h"
+
+using namespace std;
+namespace rocketmq {
+
+void TransactionMQProducer::initTransactionEnv() {
+  for (int i = 0; i < m_thread_num; ++i) {
+    m_threadpool.create_thread(boost::bind(&boost::asio::io_service::run, &m_ioService));
+  }
+}
+
+void TransactionMQProducer::destroyTransactionEnv() {
+  m_ioService.stop();
+  m_threadpool.join_all();
+}
+
+TransactionSendResult TransactionMQProducer::sendMessageInTransaction(MQMessage& msg, void* arg) {
+  if (!m_transactionListener) {
+    THROW_MQEXCEPTION(MQClientException, "transactionListener is null", -1);
+  }
+
+  SendResult sendResult;
+  msg.setProperty(MQMessage::PROPERTY_TRANSACTION_PREPARED, "true");
+  msg.setProperty(MQMessage::PROPERTY_PRODUCER_GROUP, getGroupName());
+  try {
+    sendResult = send(msg);
+  } catch (MQException& e) {
+    THROW_MQEXCEPTION(MQClientException, e.what(), -1);
+  }
+
+  LocalTransactionState localTransactionState = LocalTransactionState::UNKNOWN;
+  switch (sendResult.getSendStatus()) {
+    case SendStatus::SEND_OK:
+      try {
+        if (sendResult.getTransactionId() != "") {
+          msg.setProperty("__transactionId__", sendResult.getTransactionId());
+        }
+        string transactionId = msg.getProperty(MQMessage::PROPERTY_UNIQ_CLIENT_MESSAGE_ID_KEYIDX);
+        if (transactionId != "") {
+          msg.setTransactionId(transactionId);
+        }
+        LOG_DEBUG("sendMessageInTransaction, msgId:%s, transactionId:%s", sendResult.getMsgId().data(),
+                  transactionId.data());
+        localTransactionState = m_transactionListener->executeLocalTransaction(msg, arg);
+        if (localTransactionState != LocalTransactionState::COMMIT_MESSAGE) {
+          LOG_WARN("executeLocalTransaction ret not LocalTransactionState::commit, msg:%s", msg.toString().data());
+        }
+      } catch (MQException& e) {
+        THROW_MQEXCEPTION(MQClientException, e.what(), -1);
+      }
+      break;
+    case SendStatus::SEND_FLUSH_DISK_TIMEOUT:
+    case SendStatus::SEND_FLUSH_SLAVE_TIMEOUT:
+    case SendStatus::SEND_SLAVE_NOT_AVAILABLE:
+      localTransactionState = LocalTransactionState::ROLLBACK_MESSAGE;
+      LOG_WARN("sendMessageInTransaction, send not ok, rollback, result:%s", sendResult.toString().data());
+      break;
+    default:
+      break;
+  }
+
+  try {
+    endTransaction(sendResult, localTransactionState);
+  } catch (MQException& e) {
+    LOG_WARN("endTransaction exception:%s", e.what());
+  }
+
+  TransactionSendResult transactionSendResult(sendResult.getSendStatus(), sendResult.getMsgId(),
+                                              sendResult.getOffsetMsgId(), sendResult.getMessageQueue(),
+                                              sendResult.getQueueOffset());
+  transactionSendResult.setTransactionId(msg.getTransactionId());
+  transactionSendResult.setLocalTransactionState(localTransactionState);
+  return transactionSendResult;
+}
+
+void TransactionMQProducer::endTransaction(SendResult& sendResult, LocalTransactionState& localTransactionState) {
+  MQMessageId id;
+  if (sendResult.getOffsetMsgId() != "") {
+    id = MQDecoder::decodeMessageId(sendResult.getOffsetMsgId());
+  } else {
+    id = MQDecoder::decodeMessageId(sendResult.getMsgId());
+  }
+  string transId = sendResult.getTransactionId();
+
+  int commitOrRollback = MessageSysFlag::TransactionNotType;
+  switch (localTransactionState) {
+    case COMMIT_MESSAGE:
+      commitOrRollback = MessageSysFlag::TransactionCommitType;
+      break;
+    case ROLLBACK_MESSAGE:
+      commitOrRollback = MessageSysFlag::TransactionRollbackType;
+      break;
+    case UNKNOWN:
+      commitOrRollback = MessageSysFlag::TransactionNotType;
+      break;
+    default:
+      break;
+  }
+
+  bool fromTransCheck = false;
+  EndTransactionRequestHeader* requestHeader =
+      new EndTransactionRequestHeader(getGroupName(), sendResult.getQueueOffset(), id.getOffset(), commitOrRollback,
+                                      fromTransCheck, sendResult.getMsgId(), transId);
+  LOG_DEBUG("endTransaction: msg:%s", requestHeader->toString().data());
+  getFactory()->endTransactionOneway(sendResult.getMessageQueue(), requestHeader, getSessionCredentials());
+}
+
+void TransactionMQProducer::checkTransactionState(const std::string& addr,
+                                                  const MQMessageExt& message,
+                                                  long tranStateTableOffset,
+                                                  long commitLogOffset,
+                                                  const std::string& msgId,
+                                                  const std::string& transactionId,
+                                                  const std::string& offsetMsgId) {
+  LOG_DEBUG("checkTransactionState: msgId:%s, transactionId:%s", msgId.data(), transactionId.data());
+  if (!m_transactionListener) {
+    LOG_WARN("checkTransactionState, transactionListener null");
+    THROW_MQEXCEPTION(MQClientException, "checkTransactionState, transactionListener null", -1);
+  }
+
+  m_ioService.post(boost::bind(&TransactionMQProducer::checkTransactionStateImpl, this, addr, message,
+                               tranStateTableOffset, commitLogOffset, msgId, transactionId, offsetMsgId));
+}
+
+void TransactionMQProducer::checkTransactionStateImpl(const std::string& addr,
+                                                      const MQMessageExt& message,
+                                                      long tranStateTableOffset,
+                                                      long commitLogOffset,
+                                                      const std::string& msgId,
+                                                      const std::string& transactionId,
+                                                      const std::string& offsetMsgId) {
+  LOG_DEBUG("checkTransactionStateImpl: msgId:%s, transactionId:%s", msgId.data(), transactionId.data());
+  LocalTransactionState localTransactionState = UNKNOWN;
+  try {
+    localTransactionState = m_transactionListener->checkLocalTransaction(message);
+  } catch (MQException& e) {
+    LOG_INFO("checkTransactionState, checkLocalTransaction exception: %s", e.what());
+  }
+
+  EndTransactionRequestHeader* endHeader = new EndTransactionRequestHeader();
+  endHeader->m_commitLogOffset = commitLogOffset;
+  endHeader->m_producerGroup = getGroupName();
+  endHeader->m_tranStateTableOffset = tranStateTableOffset;
+  endHeader->m_fromTransactionCheck = true;
+
+  string uniqueKey = transactionId;
+  if (transactionId.empty()) {
+    uniqueKey = message.getMsgId();
+  }
+
+  endHeader->m_msgId = uniqueKey;
+  endHeader->m_transactionId = transactionId;
+  switch (localTransactionState) {
+    case COMMIT_MESSAGE:
+      endHeader->m_commitOrRollback = MessageSysFlag::TransactionCommitType;
+      break;
+    case ROLLBACK_MESSAGE:
+      endHeader->m_commitOrRollback = MessageSysFlag::TransactionRollbackType;
+      LOG_WARN("when broker check, client rollback this transaction, %s", endHeader->toString().data());
+      break;
+    case UNKNOWN:
+      endHeader->m_commitOrRollback = MessageSysFlag::TransactionNotType;
+      LOG_WARN("when broker check, client does not know this transaction state, %s", endHeader->toString().data());
+      break;
+    default:
+      break;
+  }
+
+  LOG_INFO("checkTransactionState, endTransactionOneway: uniqueKey:%s, client state:%d, end header: %s",
+           uniqueKey.data(), localTransactionState, endHeader->toString().data());
+
+  string remark;
+  try {
+    getFactory()->getMQClientAPIImpl()->endTransactionOneway(addr, endHeader, remark, getSessionCredentials());
+  } catch (MQException& e) {
+    LOG_ERROR("endTransactionOneway exception:%s", e.what());
+    throw e;
+  }
+}
+
+void TransactionMQProducer::start() {
+  initTransactionEnv();
+  DefaultMQProducer::start();
+}
+
+void TransactionMQProducer::shutdown() {
+  DefaultMQProducer::shutdown();
+  destroyTransactionEnv();
+}
+
+}  // namespace rocketmq
diff --git a/src/protocol/CommandHeader.cpp b/src/protocol/CommandHeader.cpp
index 6290ac7..2f19236 100644
--- a/src/protocol/CommandHeader.cpp
+++ b/src/protocol/CommandHeader.cpp
@@ -27,8 +27,7 @@
   outData["topic"] = topic;

 }

 

-void GetRouteInfoRequestHeader::SetDeclaredFieldOfCommandHeader(

-    map<string, string>& requestMap) {

+void GetRouteInfoRequestHeader::SetDeclaredFieldOfCommandHeader(map<string, string>& requestMap) {

   requestMap.insert(pair<string, string>("topic", topic));

 }

 //<!***************************************************************************

@@ -38,8 +37,7 @@
   outData["consumerGroup"] = consumerGroup;

 }

 

-void UnregisterClientRequestHeader::SetDeclaredFieldOfCommandHeader(

-    map<string, string>& requestMap) {

+void UnregisterClientRequestHeader::SetDeclaredFieldOfCommandHeader(map<string, string>& requestMap) {

   requestMap.insert(pair<string, string>("clientID", clientID));

   requestMap.insert(pair<string, string>("producerGroup", producerGroup));

   requestMap.insert(pair<string, string>("consumerGroup", consumerGroup));

@@ -53,18 +51,99 @@
   outData["perm"] = perm;

   outData["topicFilterType"] = topicFilterType;

 }

-void CreateTopicRequestHeader::SetDeclaredFieldOfCommandHeader(

-    map<string, string>& requestMap) {

+void CreateTopicRequestHeader::SetDeclaredFieldOfCommandHeader(map<string, string>& requestMap) {

   requestMap.insert(pair<string, string>("topic", topic));

   requestMap.insert(pair<string, string>("defaultTopic", defaultTopic));

-  requestMap.insert(

-      pair<string, string>("readQueueNums", UtilAll::to_string(readQueueNums)));

-  requestMap.insert(pair<string, string>("writeQueueNums",

-                                         UtilAll::to_string(writeQueueNums)));

+  requestMap.insert(pair<string, string>("readQueueNums", UtilAll::to_string(readQueueNums)));

+  requestMap.insert(pair<string, string>("writeQueueNums", UtilAll::to_string(writeQueueNums)));

   requestMap.insert(pair<string, string>("perm", UtilAll::to_string(perm)));

   requestMap.insert(pair<string, string>("topicFilterType", topicFilterType));

 }

 

+void CheckTransactionStateRequestHeader::Encode(Json::Value& outData) {}

+

+CommandHeader* CheckTransactionStateRequestHeader::Decode(Json::Value& ext) {

+  CheckTransactionStateRequestHeader* h = new CheckTransactionStateRequestHeader();

+  Json::Value& tempValue = ext["msgId"];

+  if (tempValue.isString()) {

+    h->m_msgId = tempValue.asString();

+  }

+

+  tempValue = ext["transactionId"];

+  if (tempValue.isString()) {

+    h->m_transactionId = tempValue.asString();

+  }

+

+  tempValue = ext["offsetMsgId"];

+  if (tempValue.isString()) {

+    h->m_offsetMsgId = tempValue.asString();

+  }

+

+  tempValue = ext["tranStateTableOffset"];

+  if (tempValue.isString()) {

+    h->m_tranStateTableOffset = UtilAll::str2ll(tempValue.asCString());

+  }

+

+  tempValue = ext["commitLogOffset"];

+  if (tempValue.isString()) {

+    h->m_commitLogOffset = UtilAll::str2ll(tempValue.asCString());

+  }

+

+  return h;

+}

+

+void CheckTransactionStateRequestHeader::SetDeclaredFieldOfCommandHeader(map<string, string>& requestMap) {

+  requestMap.insert(pair<string, string>("msgId", m_msgId));

+  requestMap.insert(pair<string, string>("transactionId", m_transactionId));

+  requestMap.insert(pair<string, string>("offsetMsgId", m_offsetMsgId));

+  requestMap.insert(pair<string, string>("commitLogOffset", UtilAll::to_string(m_commitLogOffset)));

+  requestMap.insert(pair<string, string>("tranStateTableOffset", UtilAll::to_string(m_tranStateTableOffset)));

+}

+

+std::string CheckTransactionStateRequestHeader::toString() {

+  stringstream ss;

+  ss << "CheckTransactionStateRequestHeader:";

+  ss << " msgId:" << m_msgId;

+  ss << " transactionId:" << m_transactionId;

+  ss << " offsetMsgId:" << m_offsetMsgId;

+  ss << " commitLogOffset:" << m_commitLogOffset;

+  ss << " tranStateTableOffset:" << m_tranStateTableOffset;

+  return ss.str();

+}

+

+void EndTransactionRequestHeader::Encode(Json::Value& outData) {

+  outData["msgId"] = m_msgId;

+  outData["transactionId"] = m_transactionId;

+  outData["producerGroup"] = m_producerGroup;

+  outData["tranStateTableOffset"] = UtilAll::to_string(m_tranStateTableOffset);

+  outData["commitLogOffset"] = UtilAll::to_string(m_commitLogOffset);

+  outData["commitOrRollback"] = UtilAll::to_string(m_commitOrRollback);

+  outData["fromTransactionCheck"] = UtilAll::to_string(m_fromTransactionCheck);

+}

+

+void EndTransactionRequestHeader::SetDeclaredFieldOfCommandHeader(map<string, string>& requestMap) {

+  requestMap.insert(pair<string, string>("msgId", m_msgId));

+  requestMap.insert(pair<string, string>("transactionId", m_transactionId));

+  requestMap.insert(pair<string, string>("producerGroup", m_producerGroup));

+  requestMap.insert(pair<string, string>("tranStateTableOffset", UtilAll::to_string(m_tranStateTableOffset)));

+  requestMap.insert(pair<string, string>("commitLogOffset", UtilAll::to_string(m_commitLogOffset)));

+  requestMap.insert(pair<string, string>("commitOrRollback", UtilAll::to_string(m_commitOrRollback)));

+  requestMap.insert(pair<string, string>("fromTransactionCheck", UtilAll::to_string(m_fromTransactionCheck)));

+}

+

+std::string EndTransactionRequestHeader::toString() {

+  stringstream ss;

+  ss << "EndTransactionRequestHeader:";

+  ss << " m_msgId:" << m_msgId;

+  ss << " m_transactionId:" << m_transactionId;

+  ss << " m_producerGroup:" << m_producerGroup;

+  ss << " m_tranStateTableOffset:" << m_tranStateTableOffset;

+  ss << " m_commitLogOffset:" << m_commitLogOffset;

+  ss << " m_commitOrRollback:" << m_commitOrRollback;

+  ss << " m_fromTransactionCheck:" << m_fromTransactionCheck;

+  return ss.str();

+}

+

 //<!************************************************************************

 void SendMessageRequestHeader::Encode(Json::Value& outData) {

   outData["producerGroup"] = producerGroup;

@@ -76,52 +155,41 @@
   outData["bornTimestamp"] = UtilAll::to_string(bornTimestamp);

   outData["flag"] = flag;

   outData["properties"] = properties;

-#ifdef ONS

   outData["reconsumeTimes"] = UtilAll::to_string(reconsumeTimes);

   outData["unitMode"] = UtilAll::to_string(unitMode);

-#endif

-  outData["batch"] = batch;

+  outData["batch"] = UtilAll::to_string(batch);

 }

 

-int SendMessageRequestHeader::getReconsumeTimes() { return reconsumeTimes; }

+int SendMessageRequestHeader::getReconsumeTimes() {

+  return reconsumeTimes;

+}

 

 void SendMessageRequestHeader::setReconsumeTimes(int input_reconsumeTimes) {

   reconsumeTimes = input_reconsumeTimes;

 }

 

-void SendMessageRequestHeader::SetDeclaredFieldOfCommandHeader(

-    map<string, string>& requestMap) {

+void SendMessageRequestHeader::SetDeclaredFieldOfCommandHeader(map<string, string>& requestMap) {

   LOG_DEBUG(

       "SendMessageRequestHeader producerGroup is:%s,topic is:%s, defaulttopic "

       "is:%s, properties is:%s,UtilAll::to_string( defaultTopicQueueNums) "

       "is:%s,UtilAll::to_string( queueId):%s, UtilAll::to_string( sysFlag) "

       "is:%s, UtilAll::to_string( bornTimestamp) is:%s,UtilAll::to_string( "

       "flag) is:%s",

-      producerGroup.c_str(), topic.c_str(), defaultTopic.c_str(),

-      properties.c_str(), UtilAll::to_string(defaultTopicQueueNums).c_str(),

-      UtilAll::to_string(queueId).c_str(), UtilAll::to_string(sysFlag).c_str(),

-      UtilAll::to_string(bornTimestamp).c_str(),

-      UtilAll::to_string(flag).c_str());

+      producerGroup.c_str(), topic.c_str(), defaultTopic.c_str(), properties.c_str(),

+      UtilAll::to_string(defaultTopicQueueNums).c_str(), UtilAll::to_string(queueId).c_str(),

+      UtilAll::to_string(sysFlag).c_str(), UtilAll::to_string(bornTimestamp).c_str(), UtilAll::to_string(flag).c_str());

 

   requestMap.insert(pair<string, string>("producerGroup", producerGroup));

   requestMap.insert(pair<string, string>("topic", topic));

   requestMap.insert(pair<string, string>("defaultTopic", defaultTopic));

-  requestMap.insert(pair<string, string>(

-      "defaultTopicQueueNums", UtilAll::to_string(defaultTopicQueueNums)));

-  requestMap.insert(

-      pair<string, string>("queueId", UtilAll::to_string(queueId)));

-  requestMap.insert(

-      pair<string, string>("sysFlag", UtilAll::to_string(sysFlag)));

-  requestMap.insert(

-      pair<string, string>("bornTimestamp", UtilAll::to_string(bornTimestamp)));

+  requestMap.insert(pair<string, string>("defaultTopicQueueNums", UtilAll::to_string(defaultTopicQueueNums)));

+  requestMap.insert(pair<string, string>("queueId", UtilAll::to_string(queueId)));

+  requestMap.insert(pair<string, string>("sysFlag", UtilAll::to_string(sysFlag)));

+  requestMap.insert(pair<string, string>("bornTimestamp", UtilAll::to_string(bornTimestamp)));

   requestMap.insert(pair<string, string>("flag", UtilAll::to_string(flag)));

   requestMap.insert(pair<string, string>("properties", properties));

-#ifdef ONS

-  requestMap.insert(pair<string, string>("reconsumeTimes",

-                                         UtilAll::to_string(reconsumeTimes)));

-  requestMap.insert(

-      pair<string, string>("unitMode", UtilAll::to_string(unitMode)));

-#endif

+  requestMap.insert(pair<string, string>("reconsumeTimes", UtilAll::to_string(reconsumeTimes)));

+  requestMap.insert(pair<string, string>("unitMode", UtilAll::to_string(unitMode)));

   requestMap.insert(pair<string, string>("batch", UtilAll::to_string(batch)));

 }

 

@@ -146,13 +214,10 @@
   return h;

 }

 

-void SendMessageResponseHeader::SetDeclaredFieldOfCommandHeader(

-    map<string, string>& requestMap) {

+void SendMessageResponseHeader::SetDeclaredFieldOfCommandHeader(map<string, string>& requestMap) {

   requestMap.insert(pair<string, string>("msgId", msgId));

-  requestMap.insert(

-      pair<string, string>("queueId", UtilAll::to_string(queueId)));

-  requestMap.insert(

-      pair<string, string>("queueOffset", UtilAll::to_string(queueOffset)));

+  requestMap.insert(pair<string, string>("queueId", UtilAll::to_string(queueId)));

+  requestMap.insert(pair<string, string>("queueOffset", UtilAll::to_string(queueOffset)));

 }

 //<!************************************************************************

 void PullMessageRequestHeader::Encode(Json::Value& outData) {

@@ -172,24 +237,16 @@
   outData["subscription"] = subscription;

 }

 

-void PullMessageRequestHeader::SetDeclaredFieldOfCommandHeader(

-    map<string, string>& requestMap) {

+void PullMessageRequestHeader::SetDeclaredFieldOfCommandHeader(map<string, string>& requestMap) {

   requestMap.insert(pair<string, string>("consumerGroup", consumerGroup));

   requestMap.insert(pair<string, string>("topic", topic));

-  requestMap.insert(

-      pair<string, string>("queueId", UtilAll::to_string(queueId)));

-  requestMap.insert(

-      pair<string, string>("queueOffset", UtilAll::to_string(queueOffset)));

-  requestMap.insert(

-      pair<string, string>("maxMsgNums", UtilAll::to_string(maxMsgNums)));

-  requestMap.insert(

-      pair<string, string>("sysFlag", UtilAll::to_string(sysFlag)));

-  requestMap.insert(

-      pair<string, string>("commitOffset", UtilAll::to_string(commitOffset)));

-  requestMap.insert(

-      pair<string, string>("subVersion", UtilAll::to_string(subVersion)));

-  requestMap.insert(pair<string, string>(

-      "suspendTimeoutMillis", UtilAll::to_string(suspendTimeoutMillis)));

+  requestMap.insert(pair<string, string>("queueId", UtilAll::to_string(queueId)));

+  requestMap.insert(pair<string, string>("queueOffset", UtilAll::to_string(queueOffset)));

+  requestMap.insert(pair<string, string>("maxMsgNums", UtilAll::to_string(maxMsgNums)));

+  requestMap.insert(pair<string, string>("sysFlag", UtilAll::to_string(sysFlag)));

+  requestMap.insert(pair<string, string>("commitOffset", UtilAll::to_string(commitOffset)));

+  requestMap.insert(pair<string, string>("subVersion", UtilAll::to_string(subVersion)));

+  requestMap.insert(pair<string, string>("suspendTimeoutMillis", UtilAll::to_string(suspendTimeoutMillis)));

   requestMap.insert(pair<string, string>("subscription", subscription));

 }

 //<!************************************************************************

@@ -219,35 +276,27 @@
   return h;

 }

 

-void PullMessageResponseHeader::SetDeclaredFieldOfCommandHeader(

-    map<string, string>& requestMap) {

-  requestMap.insert(pair<string, string>(

-      "suggestWhichBrokerId", UtilAll::to_string(suggestWhichBrokerId)));

-  requestMap.insert(pair<string, string>("nextBeginOffset",

-                                         UtilAll::to_string(nextBeginOffset)));

-  requestMap.insert(

-      pair<string, string>("minOffset", UtilAll::to_string(minOffset)));

-  requestMap.insert(

-      pair<string, string>("maxOffset", UtilAll::to_string(maxOffset)));

+void PullMessageResponseHeader::SetDeclaredFieldOfCommandHeader(map<string, string>& requestMap) {

+  requestMap.insert(pair<string, string>("suggestWhichBrokerId", UtilAll::to_string(suggestWhichBrokerId)));

+  requestMap.insert(pair<string, string>("nextBeginOffset", UtilAll::to_string(nextBeginOffset)));

+  requestMap.insert(pair<string, string>("minOffset", UtilAll::to_string(minOffset)));

+  requestMap.insert(pair<string, string>("maxOffset", UtilAll::to_string(maxOffset)));

 }

 //<!************************************************************************

 void GetConsumerListByGroupResponseHeader::Encode(Json::Value& outData) {

   // outData = "{}";

 }

 

-void GetConsumerListByGroupResponseHeader::SetDeclaredFieldOfCommandHeader(

-    map<string, string>& requestMap) {}

+void GetConsumerListByGroupResponseHeader::SetDeclaredFieldOfCommandHeader(map<string, string>& requestMap) {}

 //<!***************************************************************************

 void GetMinOffsetRequestHeader::Encode(Json::Value& outData) {

   outData["topic"] = topic;

   outData["queueId"] = queueId;

 }

 

-void GetMinOffsetRequestHeader::SetDeclaredFieldOfCommandHeader(

-    map<string, string>& requestMap) {

+void GetMinOffsetRequestHeader::SetDeclaredFieldOfCommandHeader(map<string, string>& requestMap) {

   requestMap.insert(pair<string, string>("topic", topic));

-  requestMap.insert(

-      pair<string, string>("queueId", UtilAll::to_string(queueId)));

+  requestMap.insert(pair<string, string>("queueId", UtilAll::to_string(queueId)));

 }

 //<!***************************************************************************

 CommandHeader* GetMinOffsetResponseHeader::Decode(Json::Value& ext) {

@@ -260,8 +309,7 @@
   return h;

 }

 

-void GetMinOffsetResponseHeader::SetDeclaredFieldOfCommandHeader(

-    map<string, string>& requestMap) {

+void GetMinOffsetResponseHeader::SetDeclaredFieldOfCommandHeader(map<string, string>& requestMap) {

   requestMap.insert(pair<string, string>("offset", UtilAll::to_string(offset)));

 }

 //<!***************************************************************************

@@ -270,11 +318,9 @@
   outData["queueId"] = queueId;

 }

 

-void GetMaxOffsetRequestHeader::SetDeclaredFieldOfCommandHeader(

-    map<string, string>& requestMap) {

+void GetMaxOffsetRequestHeader::SetDeclaredFieldOfCommandHeader(map<string, string>& requestMap) {

   requestMap.insert(pair<string, string>("topic", topic));

-  requestMap.insert(

-      pair<string, string>("queueId", UtilAll::to_string(queueId)));

+  requestMap.insert(pair<string, string>("queueId", UtilAll::to_string(queueId)));

 }

 //<!***************************************************************************

 CommandHeader* GetMaxOffsetResponseHeader::Decode(Json::Value& ext) {

@@ -287,8 +333,7 @@
   return h;

 }

 

-void GetMaxOffsetResponseHeader::SetDeclaredFieldOfCommandHeader(

-    map<string, string>& requestMap) {

+void GetMaxOffsetResponseHeader::SetDeclaredFieldOfCommandHeader(map<string, string>& requestMap) {

   requestMap.insert(pair<string, string>("offset", UtilAll::to_string(offset)));

 }

 //<!***************************************************************************

@@ -298,13 +343,10 @@
   outData["timestamp"] = UtilAll::to_string(timestamp);

 }

 

-void SearchOffsetRequestHeader::SetDeclaredFieldOfCommandHeader(

-    map<string, string>& requestMap) {

+void SearchOffsetRequestHeader::SetDeclaredFieldOfCommandHeader(map<string, string>& requestMap) {

   requestMap.insert(pair<string, string>("topic", topic));

-  requestMap.insert(

-      pair<string, string>("queueId", UtilAll::to_string(queueId)));

-  requestMap.insert(

-      pair<string, string>("timestamp", UtilAll::to_string(timestamp)));

+  requestMap.insert(pair<string, string>("queueId", UtilAll::to_string(queueId)));

+  requestMap.insert(pair<string, string>("timestamp", UtilAll::to_string(timestamp)));

 }

 //<!***************************************************************************

 CommandHeader* SearchOffsetResponseHeader::Decode(Json::Value& ext) {

@@ -317,8 +359,7 @@
   return h;

 }

 

-void SearchOffsetResponseHeader::SetDeclaredFieldOfCommandHeader(

-    map<string, string>& requestMap) {

+void SearchOffsetResponseHeader::SetDeclaredFieldOfCommandHeader(map<string, string>& requestMap) {

   requestMap.insert(pair<string, string>("offset", UtilAll::to_string(offset)));

 }

 //<!***************************************************************************

@@ -326,8 +367,7 @@
   outData["offset"] = UtilAll::to_string(offset);

 }

 

-void ViewMessageRequestHeader::SetDeclaredFieldOfCommandHeader(

-    map<string, string>& requestMap) {

+void ViewMessageRequestHeader::SetDeclaredFieldOfCommandHeader(map<string, string>& requestMap) {

   requestMap.insert(pair<string, string>("offset", UtilAll::to_string(offset)));

 }

 //<!***************************************************************************

@@ -336,17 +376,13 @@
   outData["queueId"] = queueId;

 }

 

-void GetEarliestMsgStoretimeRequestHeader::SetDeclaredFieldOfCommandHeader(

-    map<string, string>& requestMap) {

+void GetEarliestMsgStoretimeRequestHeader::SetDeclaredFieldOfCommandHeader(map<string, string>& requestMap) {

   requestMap.insert(pair<string, string>("topic", topic));

-  requestMap.insert(

-      pair<string, string>("queueId", UtilAll::to_string(queueId)));

+  requestMap.insert(pair<string, string>("queueId", UtilAll::to_string(queueId)));

 }

 //<!***************************************************************************

-CommandHeader* GetEarliestMsgStoretimeResponseHeader::Decode(

-    Json::Value& ext) {

-  GetEarliestMsgStoretimeResponseHeader* h =

-      new GetEarliestMsgStoretimeResponseHeader();

+CommandHeader* GetEarliestMsgStoretimeResponseHeader::Decode(Json::Value& ext) {

+  GetEarliestMsgStoretimeResponseHeader* h = new GetEarliestMsgStoretimeResponseHeader();

 

   Json::Value& tempValue = ext["timestamp"];

   if (tempValue.isString()) {

@@ -355,18 +391,15 @@
   return h;

 }

 

-void GetEarliestMsgStoretimeResponseHeader::SetDeclaredFieldOfCommandHeader(

-    map<string, string>& requestMap) {

-  requestMap.insert(

-      pair<string, string>("timestamp", UtilAll::to_string(timestamp)));

+void GetEarliestMsgStoretimeResponseHeader::SetDeclaredFieldOfCommandHeader(map<string, string>& requestMap) {

+  requestMap.insert(pair<string, string>("timestamp", UtilAll::to_string(timestamp)));

 }

 //<!***************************************************************************

 void GetConsumerListByGroupRequestHeader::Encode(Json::Value& outData) {

   outData["consumerGroup"] = consumerGroup;

 }

 

-void GetConsumerListByGroupRequestHeader::SetDeclaredFieldOfCommandHeader(

-    map<string, string>& requestMap) {

+void GetConsumerListByGroupRequestHeader::SetDeclaredFieldOfCommandHeader(map<string, string>& requestMap) {

   requestMap.insert(pair<string, string>("consumerGroup", consumerGroup));

 }

 //<!***************************************************************************

@@ -376,18 +409,14 @@
   outData["queueId"] = queueId;

 }

 

-void QueryConsumerOffsetRequestHeader::SetDeclaredFieldOfCommandHeader(

-    map<string, string>& requestMap) {

+void QueryConsumerOffsetRequestHeader::SetDeclaredFieldOfCommandHeader(map<string, string>& requestMap) {

   requestMap.insert(pair<string, string>("consumerGroup", consumerGroup));

   requestMap.insert(pair<string, string>("topic", topic));

-  requestMap.insert(

-      pair<string, string>("queueId", UtilAll::to_string(queueId)));

+  requestMap.insert(pair<string, string>("queueId", UtilAll::to_string(queueId)));

 }

 //<!***************************************************************************

-CommandHeader* QueryConsumerOffsetResponseHeader::Decode(

-    Json::Value& ext) {

-  QueryConsumerOffsetResponseHeader* h =

-      new QueryConsumerOffsetResponseHeader();

+CommandHeader* QueryConsumerOffsetResponseHeader::Decode(Json::Value& ext) {

+  QueryConsumerOffsetResponseHeader* h = new QueryConsumerOffsetResponseHeader();

   Json::Value& tempValue = ext["offset"];

   if (tempValue.isString()) {

     h->offset = UtilAll::str2ll(tempValue.asCString());

@@ -395,8 +424,7 @@
   return h;

 }

 

-void QueryConsumerOffsetResponseHeader::SetDeclaredFieldOfCommandHeader(

-    map<string, string>& requestMap) {

+void QueryConsumerOffsetResponseHeader::SetDeclaredFieldOfCommandHeader(map<string, string>& requestMap) {

   requestMap.insert(pair<string, string>("offset", UtilAll::to_string(offset)));

 }

 //<!***************************************************************************

@@ -407,14 +435,11 @@
   outData["commitOffset"] = UtilAll::to_string(commitOffset);

 }

 

-void UpdateConsumerOffsetRequestHeader::SetDeclaredFieldOfCommandHeader(

-    map<string, string>& requestMap) {

+void UpdateConsumerOffsetRequestHeader::SetDeclaredFieldOfCommandHeader(map<string, string>& requestMap) {

   requestMap.insert(pair<string, string>("consumerGroup", consumerGroup));

   requestMap.insert(pair<string, string>("topic", topic));

-  requestMap.insert(

-      pair<string, string>("queueId", UtilAll::to_string(queueId)));

-  requestMap.insert(

-      pair<string, string>("commitOffset", UtilAll::to_string(commitOffset)));

+  requestMap.insert(pair<string, string>("queueId", UtilAll::to_string(queueId)));

+  requestMap.insert(pair<string, string>("commitOffset", UtilAll::to_string(commitOffset)));

 }

 //<!***************************************************************************

 void ConsumerSendMsgBackRequestHeader::Encode(Json::Value& outData) {

@@ -427,16 +452,13 @@
 #endif

 }

 

-void ConsumerSendMsgBackRequestHeader::SetDeclaredFieldOfCommandHeader(

-    map<string, string>& requestMap) {

+void ConsumerSendMsgBackRequestHeader::SetDeclaredFieldOfCommandHeader(map<string, string>& requestMap) {

   requestMap.insert(pair<string, string>("group", group));

-  requestMap.insert(

-      pair<string, string>("delayLevel", UtilAll::to_string(delayLevel)));

+  requestMap.insert(pair<string, string>("delayLevel", UtilAll::to_string(delayLevel)));

   requestMap.insert(pair<string, string>("offset", UtilAll::to_string(offset)));

 }

 //<!***************************************************************************

-void GetConsumerListByGroupResponseBody::Decode(const MemoryBlock* mem,

-                                                vector<string>& cids) {

+void GetConsumerListByGroupResponseBody::Decode(const MemoryBlock* mem, vector<string>& cids) {

   cids.clear();

   //<! decode;

   const char* const pData = static_cast<const char*>(mem->getData());

@@ -456,26 +478,39 @@
   }

 }

 

-void GetConsumerListByGroupResponseBody::SetDeclaredFieldOfCommandHeader(

-    map<string, string>& requestMap) {}

+void GetConsumerListByGroupResponseBody::SetDeclaredFieldOfCommandHeader(map<string, string>& requestMap) {}

 

-void ResetOffsetRequestHeader::setTopic(const string& tmp) { topic = tmp; }

+void ResetOffsetRequestHeader::setTopic(const string& tmp) {

+  topic = tmp;

+}

 

-void ResetOffsetRequestHeader::setGroup(const string& tmp) { group = tmp; }

+void ResetOffsetRequestHeader::setGroup(const string& tmp) {

+  group = tmp;

+}

 

 void ResetOffsetRequestHeader::setTimeStamp(const int64& tmp) {

   timestamp = tmp;

 }

 

-void ResetOffsetRequestHeader::setForceFlag(const bool& tmp) { isForce = tmp; }

+void ResetOffsetRequestHeader::setForceFlag(const bool& tmp) {

+  isForce = tmp;

+}

 

-const string ResetOffsetRequestHeader::getTopic() const { return topic; }

+const string ResetOffsetRequestHeader::getTopic() const {

+  return topic;

+}

 

-const string ResetOffsetRequestHeader::getGroup() const { return group; }

+const string ResetOffsetRequestHeader::getGroup() const {

+  return group;

+}

 

-const int64 ResetOffsetRequestHeader::getTimeStamp() const { return timestamp; }

+const int64 ResetOffsetRequestHeader::getTimeStamp() const {

+  return timestamp;

+}

 

-const bool ResetOffsetRequestHeader::getForceFlag() const { return isForce; }

+const bool ResetOffsetRequestHeader::getForceFlag() const {

+  return isForce;

+}

 

 CommandHeader* ResetOffsetRequestHeader::Decode(Json::Value& ext) {

   ResetOffsetRequestHeader* h = new ResetOffsetRequestHeader();

@@ -499,16 +534,13 @@
   if (tempValue.isString()) {

     h->isForce = UtilAll::to_bool(tempValue.asCString());

   }

-  LOG_INFO("topic:%s, group:%s, timestamp:%lld, isForce:%d,isForce:%s",

-           h->topic.c_str(), h->group.c_str(), h->timestamp, h->isForce,

-           tempValue.asCString());

+  LOG_INFO("topic:%s, group:%s, timestamp:%lld, isForce:%d,isForce:%s", h->topic.c_str(), h->group.c_str(),

+           h->timestamp, h->isForce, tempValue.asCString());

   return h;

 }

 

-CommandHeader* GetConsumerRunningInfoRequestHeader::Decode(

-    Json::Value& ext) {

-  GetConsumerRunningInfoRequestHeader* h =

-      new GetConsumerRunningInfoRequestHeader();

+CommandHeader* GetConsumerRunningInfoRequestHeader::Decode(Json::Value& ext) {

+  GetConsumerRunningInfoRequestHeader* h = new GetConsumerRunningInfoRequestHeader();

 

   Json::Value& tempValue = ext["consumerGroup"];

   if (tempValue.isString()) {

@@ -524,8 +556,8 @@
   if (tempValue.isString()) {

     h->jstackEnable = UtilAll::to_bool(tempValue.asCString());

   }

-  LOG_INFO("consumerGroup:%s, clientId:%s,  jstackEnable:%d",

-           h->consumerGroup.c_str(), h->clientId.c_str(), h->jstackEnable);

+  LOG_INFO("consumerGroup:%s, clientId:%s,  jstackEnable:%d", h->consumerGroup.c_str(), h->clientId.c_str(),

+           h->jstackEnable);

   return h;

 }

 

@@ -535,20 +567,17 @@
   outData["jstackEnable"] = jstackEnable;

 }

 

-void GetConsumerRunningInfoRequestHeader::SetDeclaredFieldOfCommandHeader(

-    map<string, string>& requestMap) {

+void GetConsumerRunningInfoRequestHeader::SetDeclaredFieldOfCommandHeader(map<string, string>& requestMap) {

   requestMap.insert(pair<string, string>("consumerGroup", consumerGroup));

   requestMap.insert(pair<string, string>("clientId", clientId));

-  requestMap.insert(

-      pair<string, string>("jstackEnable", UtilAll::to_string(jstackEnable)));

+  requestMap.insert(pair<string, string>("jstackEnable", UtilAll::to_string(jstackEnable)));

 }

 

 const string GetConsumerRunningInfoRequestHeader::getConsumerGroup() const {

   return consumerGroup;

 }

 

-void GetConsumerRunningInfoRequestHeader::setConsumerGroup(

-    const string& Group) {

+void GetConsumerRunningInfoRequestHeader::setConsumerGroup(const string& Group) {

   consumerGroup = Group;

 }

 

@@ -556,8 +585,7 @@
   return clientId;

 }

 

-void GetConsumerRunningInfoRequestHeader::setClientId(

-    const string& input_clientId) {

+void GetConsumerRunningInfoRequestHeader::setClientId(const string& input_clientId) {

   clientId = input_clientId;

 }

 

@@ -565,15 +593,12 @@
   return jstackEnable;

 }

 

-void GetConsumerRunningInfoRequestHeader::setJstackEnable(

-    const bool& input_jstackEnable) {

+void GetConsumerRunningInfoRequestHeader::setJstackEnable(const bool& input_jstackEnable) {

   jstackEnable = input_jstackEnable;

 }

 

-CommandHeader* NotifyConsumerIdsChangedRequestHeader::Decode(

-    Json::Value& ext) {

-  NotifyConsumerIdsChangedRequestHeader* h =

-      new NotifyConsumerIdsChangedRequestHeader();

+CommandHeader* NotifyConsumerIdsChangedRequestHeader::Decode(Json::Value& ext) {

+  NotifyConsumerIdsChangedRequestHeader* h = new NotifyConsumerIdsChangedRequestHeader();

 

   Json::Value& tempValue = ext["consumerGroup"];

   if (tempValue.isString()) {

@@ -591,4 +616,4 @@
 }

 

 //<!************************************************************************

-}  //<!end namespace;

+}  // namespace rocketmq

diff --git a/src/protocol/CommandHeader.h b/src/protocol/CommandHeader.h
index b5ffe14..4a80ecf 100644
--- a/src/protocol/CommandHeader.h
+++ b/src/protocol/CommandHeader.h
@@ -14,10 +14,11 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
- 
+
 #ifndef __COMMANDCUSTOMHEADER_H__
 #define __COMMANDCUSTOMHEADER_H__
 
+#include <map>
 #include <string>
 #include "MQClientException.h"
 #include "MessageSysFlag.h"
@@ -32,8 +33,66 @@
  public:
   virtual ~CommandHeader() {}
   virtual void Encode(Json::Value& outData) {}
-  virtual void SetDeclaredFieldOfCommandHeader(
-      map<string, string>& requestMap) {}
+  virtual void SetDeclaredFieldOfCommandHeader(map<string, string>& requestMap) {}
+};
+
+class CheckTransactionStateRequestHeader : public CommandHeader {
+ public:
+  CheckTransactionStateRequestHeader() {}
+  CheckTransactionStateRequestHeader(long tableOffset,
+                                     long commLogOffset,
+                                     const std::string& msgid,
+                                     const std::string& transactionId,
+                                     const std::string& offsetMsgId)
+      : m_tranStateTableOffset(tableOffset),
+        m_commitLogOffset(commLogOffset),
+        m_msgId(msgid),
+        m_transactionId(transactionId),
+        m_offsetMsgId(offsetMsgId) {}
+  virtual ~CheckTransactionStateRequestHeader() {}
+  virtual void Encode(Json::Value& outData);
+  static CommandHeader* Decode(Json::Value& ext);
+  virtual void SetDeclaredFieldOfCommandHeader(std::map<std::string, std::string>& requestMap);
+  std::string toString();
+
+ public:
+  long m_tranStateTableOffset;
+  long m_commitLogOffset;
+  std::string m_msgId;
+  std::string m_transactionId;
+  std::string m_offsetMsgId;
+};
+
+class EndTransactionRequestHeader : public CommandHeader {
+ public:
+  EndTransactionRequestHeader() {}
+  EndTransactionRequestHeader(const std::string& groupName,
+                              long tableOffset,
+                              long commLogOffset,
+                              int commitOrRoll,
+                              bool fromTransCheck,
+                              const std::string& msgid,
+                              const std::string& transId)
+      : m_producerGroup(groupName),
+        m_tranStateTableOffset(tableOffset),
+        m_commitLogOffset(commLogOffset),
+        m_commitOrRollback(commitOrRoll),
+        m_fromTransactionCheck(fromTransCheck),
+        m_msgId(msgid),
+        m_transactionId(transId) {}
+  virtual ~EndTransactionRequestHeader() {}
+  virtual void Encode(Json::Value& outData);
+  virtual void SetDeclaredFieldOfCommandHeader(std::map<string, string>& requestMap);
+  std::string toString();
+
+ public:
+  std::string m_producerGroup;
+  long m_tranStateTableOffset;
+  long m_commitLogOffset;
+  int m_commitOrRollback;
+  bool m_fromTransactionCheck;
+  std::string m_msgId;
+  std::string m_transactionId;
 };
 
 //<!************************************************************************
@@ -91,7 +150,7 @@
         flag(0),
         reconsumeTimes(0),
         unitMode(false),
-        batch(false){}
+        batch(false) {}
   virtual ~SendMessageRequestHeader() {}
   virtual void Encode(Json::Value& outData);
   virtual void SetDeclaredFieldOfCommandHeader(map<string, string>& requestMap);
@@ -158,11 +217,7 @@
 //<!************************************************************************
 class PullMessageResponseHeader : public CommandHeader {
  public:
-  PullMessageResponseHeader()
-      : suggestWhichBrokerId(0),
-        nextBeginOffset(0),
-        minOffset(0),
-        maxOffset(0) {}
+  PullMessageResponseHeader() : suggestWhichBrokerId(0), nextBeginOffset(0), minOffset(0), maxOffset(0) {}
   virtual ~PullMessageResponseHeader() {}
   static CommandHeader* Decode(Json::Value& ext);
   virtual void SetDeclaredFieldOfCommandHeader(map<string, string>& requestMap);
@@ -428,6 +483,6 @@
 };
 
 //<!***************************************************************************
-}  //<!end namespace;
+}  // namespace rocketmq
 
 #endif
diff --git a/src/protocol/ConsumerRunningInfo.cpp b/src/protocol/ConsumerRunningInfo.cpp
old mode 100755
new mode 100644
index ab7f389..999686b
--- a/src/protocol/ConsumerRunningInfo.cpp
+++ b/src/protocol/ConsumerRunningInfo.cpp
@@ -19,20 +19,17 @@
 
 namespace rocketmq {
 const string ConsumerRunningInfo::PROP_NAMESERVER_ADDR = "PROP_NAMESERVER_ADDR";
-const string ConsumerRunningInfo::PROP_THREADPOOL_CORE_SIZE =
-    "PROP_THREADPOOL_CORE_SIZE";
+const string ConsumerRunningInfo::PROP_THREADPOOL_CORE_SIZE = "PROP_THREADPOOL_CORE_SIZE";
 const string ConsumerRunningInfo::PROP_CONSUME_ORDERLY = "PROP_CONSUMEORDERLY";
 const string ConsumerRunningInfo::PROP_CONSUME_TYPE = "PROP_CONSUME_TYPE";
 const string ConsumerRunningInfo::PROP_CLIENT_VERSION = "PROP_CLIENT_VERSION";
-const string ConsumerRunningInfo::PROP_CONSUMER_START_TIMESTAMP =
-    "PROP_CONSUMER_START_TIMESTAMP";
+const string ConsumerRunningInfo::PROP_CONSUMER_START_TIMESTAMP = "PROP_CONSUMER_START_TIMESTAMP";
 
 const map<string, string> ConsumerRunningInfo::getProperties() const {
   return properties;
 }
 
-void ConsumerRunningInfo::setProperties(
-    const map<string, string>& input_properties) {
+void ConsumerRunningInfo::setProperties(const map<string, string>& input_properties) {
   properties = input_properties;
 }
 
@@ -40,13 +37,11 @@
   properties[key] = value;
 }
 
-const map<MessageQueue, ProcessQueueInfo> ConsumerRunningInfo::getMqTable()
-    const {
+const map<MessageQueue, ProcessQueueInfo> ConsumerRunningInfo::getMqTable() const {
   return mqTable;
 }
 
-void ConsumerRunningInfo::setMqTable(MessageQueue queue,
-                                     ProcessQueueInfo queueInfo) {
+void ConsumerRunningInfo::setMqTable(MessageQueue queue, ProcessQueueInfo queueInfo) {
   mqTable[queue] = queueInfo;
 }
 
@@ -66,12 +61,13 @@
   return subscriptionSet;
 }
 
-void ConsumerRunningInfo::setSubscriptionSet(
-    const vector<SubscriptionData>& input_subscriptionSet) {
+void ConsumerRunningInfo::setSubscriptionSet(const vector<SubscriptionData>& input_subscriptionSet) {
   subscriptionSet = input_subscriptionSet;
 }
 
-const string ConsumerRunningInfo::getJstack() const { return jstack; }
+const string ConsumerRunningInfo::getJstack() const {
+  return jstack;
+}
 
 void ConsumerRunningInfo::setJstack(const string& input_jstack) {
   jstack = input_jstack;
@@ -83,8 +79,7 @@
   outData[PROP_NAMESERVER_ADDR] = properties[PROP_NAMESERVER_ADDR];
   outData[PROP_CONSUME_TYPE] = properties[PROP_CONSUME_TYPE];
   outData[PROP_CLIENT_VERSION] = properties[PROP_CLIENT_VERSION];
-  outData[PROP_CONSUMER_START_TIMESTAMP] =
-      properties[PROP_CONSUMER_START_TIMESTAMP];
+  outData[PROP_CONSUMER_START_TIMESTAMP] = properties[PROP_CONSUMER_START_TIMESTAMP];
   outData[PROP_CONSUME_ORDERLY] = properties[PROP_CONSUME_ORDERLY];
   outData[PROP_THREADPOOL_CORE_SIZE] = properties[PROP_THREADPOOL_CORE_SIZE];
 
@@ -105,8 +100,7 @@
   Json::Value mq;
   string key = "\"mqTable\":";
   key.append("{");
-  for (map<MessageQueue, ProcessQueueInfo>::iterator it = mqTable.begin();
-       it != mqTable.end(); ++it) {
+  for (map<MessageQueue, ProcessQueueInfo>::iterator it = mqTable.begin(); it != mqTable.end(); ++it) {
     key.append((it->first).toJson().toStyledString());
     key.erase(key.end() - 1);
     key.append(":");
diff --git a/src/protocol/ConsumerRunningInfo.h b/src/protocol/ConsumerRunningInfo.h
old mode 100755
new mode 100644
index ec1e2b9..3c83834
--- a/src/protocol/ConsumerRunningInfo.h
+++ b/src/protocol/ConsumerRunningInfo.h
@@ -49,8 +49,7 @@
   // const map<string, ConsumeStatus> getStatusTable() const;
   // void setStatusTable(const map<string, ConsumeStatus>& input_statusTable) ;
   const vector<SubscriptionData> getSubscriptionSet() const;
-  void setSubscriptionSet(
-      const vector<SubscriptionData>& input_subscriptionSet);
+  void setSubscriptionSet(const vector<SubscriptionData>& input_subscriptionSet);
   const string getJstack() const;
   void setJstack(const string& input_jstack);
   string encode();
diff --git a/src/protocol/HeartbeatData.h b/src/protocol/HeartbeatData.h
old mode 100755
new mode 100644
index 9b74280..2bd4aa7
--- a/src/protocol/HeartbeatData.h
+++ b/src/protocol/HeartbeatData.h
@@ -29,9 +29,7 @@
 class ProducerData {
  public:
   ProducerData(){};
-  bool operator<(const ProducerData& pd) const {
-    return groupName < pd.groupName;
-  }
+  bool operator<(const ProducerData& pd) const { return groupName < pd.groupName; }
   Json::Value toJson() const {
     Json::Value outJson;
     outJson["groupName"] = groupName;
@@ -47,9 +45,7 @@
  public:
   ConsumerData(){};
   virtual ~ConsumerData() { subscriptionDataSet.clear(); }
-  bool operator<(const ConsumerData& cd) const {
-    return groupName < cd.groupName;
-  }
+  bool operator<(const ConsumerData& cd) const { return groupName < cd.groupName; }
 
   Json::Value toJson() const {
     Json::Value outJson;
diff --git a/src/protocol/KVTable.h b/src/protocol/KVTable.h
old mode 100755
new mode 100644
index 6cc557f..e9b6a53
--- a/src/protocol/KVTable.h
+++ b/src/protocol/KVTable.h
@@ -27,17 +27,17 @@
 namespace rocketmq {
 //<!***************************************************************************
 class KVTable : public RemotingSerializable {
-   public:
-    virtual ~KVTable() { m_table.clear(); }
+ public:
+  virtual ~KVTable() { m_table.clear(); }
 
-    void Encode(string &outData) {}
+  void Encode(string& outData) {}
 
-    const map<string, string> &getTable() { return m_table; }
+  const map<string, string>& getTable() { return m_table; }
 
-    void setTable(const map<string, string> &table) { m_table = table; }
+  void setTable(const map<string, string>& table) { m_table = table; }
 
-   private:
-    map<string, string> m_table;
+ private:
+  map<string, string> m_table;
 };
 }  // namespace rocketmq
 
diff --git a/src/protocol/LockBatchBody.cpp b/src/protocol/LockBatchBody.cpp
old mode 100755
new mode 100644
index c56c17f..a63426d
--- a/src/protocol/LockBatchBody.cpp
+++ b/src/protocol/LockBatchBody.cpp
@@ -19,15 +19,21 @@
 #include "Logging.h"
 namespace rocketmq {  //<!end namespace;
 
-string LockBatchRequestBody::getConsumerGroup() { return consumerGroup; }
+string LockBatchRequestBody::getConsumerGroup() {
+  return consumerGroup;
+}
 void LockBatchRequestBody::setConsumerGroup(string in_consumerGroup) {
   consumerGroup = in_consumerGroup;
 }
-string LockBatchRequestBody::getClientId() { return clientId; }
+string LockBatchRequestBody::getClientId() {
+  return clientId;
+}
 void LockBatchRequestBody::setClientId(string in_clientId) {
   clientId = in_clientId;
 }
-vector<MQMessageQueue> LockBatchRequestBody::getMqSet() { return mqSet; }
+vector<MQMessageQueue> LockBatchRequestBody::getMqSet() {
+  return mqSet;
+}
 void LockBatchRequestBody::setMqSet(vector<MQMessageQueue> in_mqSet) {
   mqSet.swap(in_mqSet);
 }
@@ -56,13 +62,11 @@
 vector<MQMessageQueue> LockBatchResponseBody::getLockOKMQSet() {
   return lockOKMQSet;
 }
-void LockBatchResponseBody::setLockOKMQSet(
-    vector<MQMessageQueue> in_lockOKMQSet) {
+void LockBatchResponseBody::setLockOKMQSet(vector<MQMessageQueue> in_lockOKMQSet) {
   lockOKMQSet.swap(in_lockOKMQSet);
 }
 
-void LockBatchResponseBody::Decode(const MemoryBlock* mem,
-                                   vector<MQMessageQueue>& messageQueues) {
+void LockBatchResponseBody::Decode(const MemoryBlock* mem, vector<MQMessageQueue>& messageQueues) {
   messageQueues.clear();
   //<! decode;
   const char* const pData = static_cast<const char*>(mem->getData());
@@ -87,15 +91,21 @@
   }
 }
 
-string UnlockBatchRequestBody::getConsumerGroup() { return consumerGroup; }
+string UnlockBatchRequestBody::getConsumerGroup() {
+  return consumerGroup;
+}
 void UnlockBatchRequestBody::setConsumerGroup(string in_consumerGroup) {
   consumerGroup = in_consumerGroup;
 }
-string UnlockBatchRequestBody::getClientId() { return clientId; }
+string UnlockBatchRequestBody::getClientId() {
+  return clientId;
+}
 void UnlockBatchRequestBody::setClientId(string in_clientId) {
   clientId = in_clientId;
 }
-vector<MQMessageQueue> UnlockBatchRequestBody::getMqSet() { return mqSet; }
+vector<MQMessageQueue> UnlockBatchRequestBody::getMqSet() {
+  return mqSet;
+}
 void UnlockBatchRequestBody::setMqSet(vector<MQMessageQueue> in_mqSet) {
   mqSet.swap(in_mqSet);
 }
@@ -113,8 +123,7 @@
   outData = fastwrite.write(root);
 }
 
-Json::Value UnlockBatchRequestBody::toJson(
-    const MQMessageQueue& mq) const {
+Json::Value UnlockBatchRequestBody::toJson(const MQMessageQueue& mq) const {
   Json::Value outJson;
   outJson["topic"] = mq.getTopic();
   outJson["brokerName"] = mq.getBrokerName();
diff --git a/src/protocol/LockBatchBody.h b/src/protocol/LockBatchBody.h
old mode 100755
new mode 100644
index c1d7155..7f92e89
--- a/src/protocol/LockBatchBody.h
+++ b/src/protocol/LockBatchBody.h
@@ -51,8 +51,7 @@
   virtual ~LockBatchResponseBody() { lockOKMQSet.clear(); }
   vector<MQMessageQueue> getLockOKMQSet();
   void setLockOKMQSet(vector<MQMessageQueue> lockOKMQSet);
-  static void Decode(const MemoryBlock* mem,
-                     vector<MQMessageQueue>& messageQueues);
+  static void Decode(const MemoryBlock* mem, vector<MQMessageQueue>& messageQueues);
 
  private:
   vector<MQMessageQueue> lockOKMQSet;
diff --git a/src/protocol/MQProtos.h b/src/protocol/MQProtos.h
old mode 100755
new mode 100644
index 50c1841..19b377a
--- a/src/protocol/MQProtos.h
+++ b/src/protocol/MQProtos.h
@@ -36,9 +36,9 @@
   UPDATE_AND_CREATE_TOPIC = 17,

   // get all topic config info from broker

   GET_ALL_TOPIC_CONFIG = 21,

-  //git all topic list from broker

+  // git all topic list from broker

   GET_TOPIC_CONFIG_LIST = 22,

-  //get topic name list from broker

+  // get topic name list from broker

   GET_TOPIC_NAME_LIST = 23,

   UPDATE_BROKER_CONFIG = 25,

   GET_BROKER_CONFIG = 26,

@@ -49,23 +49,23 @@
   GET_MIN_OFFSET = 31,

   GET_EARLIEST_MSG_STORETIME = 32,

   VIEW_MESSAGE_BY_ID = 33,

-  //send heartbeat to broker, and register itself

+  // send heartbeat to broker, and register itself

   HEART_BEAT = 34,

-  //unregister client to broker

+  // unregister client to broker

   UNREGISTER_CLIENT = 35,

-  //send back consume fail msg to broker

+  // send back consume fail msg to broker

   CONSUMER_SEND_MSG_BACK = 36,

-  //Commit Or Rollback transaction

+  // Commit Or Rollback transaction

   END_TRANSACTION = 37,

   // get consumer list by group from broker

   GET_CONSUMER_LIST_BY_GROUP = 38,

 

   CHECK_TRANSACTION_STATE = 39,

-  //broker send notify to consumer when consumer lists changes

+  // broker send notify to consumer when consumer lists changes

   NOTIFY_CONSUMER_IDS_CHANGED = 40,

-  //lock mq before orderly consume

+  // lock mq before orderly consume

   LOCK_BATCH_MQ = 41,

-  //unlock mq after orderly consume

+  // unlock mq after orderly consume

   UNLOCK_BATCH_MQ = 42,

   GET_ALL_CONSUMER_OFFSET = 43,

   GET_ALL_DELAY_OFFSET = 45,

@@ -102,7 +102,6 @@
 

   GET_KVLIST_BY_NAMESPACE = 219,

 

-

   RESET_CONSUMER_CLIENT_OFFSET = 220,

 

   GET_CONSUMER_STATUS_FROM_CLIENT = 221,

@@ -145,39 +144,39 @@
 

 //<!***************************************************************************

 enum MQResponseCode {

-  //rcv success response from broker

+  // rcv success response from broker

   SUCCESS_VALUE = 0,

-  //rcv exception from broker

+  // rcv exception from broker

   SYSTEM_ERROR = 1,

-  //rcv symtem busy from broker

+  // rcv symtem busy from broker

   SYSTEM_BUSY = 2,

-  //broker don't support the request code

+  // broker don't support the request code

   REQUEST_CODE_NOT_SUPPORTED = 3,

-  //broker flush disk timeout error

+  // broker flush disk timeout error

   FLUSH_DISK_TIMEOUT = 10,

-  //broker sync double write, slave broker not available

+  // broker sync double write, slave broker not available

   SLAVE_NOT_AVAILABLE = 11,

-  //broker sync double write, slave broker flush msg timeout

+  // broker sync double write, slave broker flush msg timeout

   FLUSH_SLAVE_TIMEOUT = 12,

-  //broker rcv illegal mesage

+  // broker rcv illegal mesage

   MESSAGE_ILLEGAL = 13,

-  //service not available due to broker or namesrv in shutdown status

+  // service not available due to broker or namesrv in shutdown status

   SERVICE_NOT_AVAILABLE = 14,

-  //this version is not supported on broker or namesrv

+  // this version is not supported on broker or namesrv

   VERSION_NOT_SUPPORTED = 15,

-  //broker or Namesrv has no permission to do this operation

+  // broker or Namesrv has no permission to do this operation

   NO_PERMISSION = 16,

-  //topic is not exist on broker

+  // topic is not exist on broker

   TOPIC_NOT_EXIST = 17,

-  //broker already created this topic

+  // broker already created this topic

   TOPIC_EXIST_ALREADY = 18,

-  //pulled msg was not found

+  // pulled msg was not found

   PULL_NOT_FOUND = 19,

-  //retry later

+  // retry later

   PULL_RETRY_IMMEDIATELY = 20,

-  //pull msg with wrong offset

+  // pull msg with wrong offset

   PULL_OFFSET_MOVED = 21,

-  //could not find the query msg

+  // could not find the query msg

   QUERY_NOT_FOUND = 22,

 

   SUBSCRIPTION_PARSE_FAILED = 23,

diff --git a/src/protocol/MessageQueue.cpp b/src/protocol/MessageQueue.cpp
old mode 100755
new mode 100644
index f1b3f8f..57c353a
--- a/src/protocol/MessageQueue.cpp
+++ b/src/protocol/MessageQueue.cpp
@@ -26,14 +26,11 @@
   m_brokerName.clear();
 }
 
-MessageQueue::MessageQueue(const string& topic, const string& brokerName,
-                           int queueId)
+MessageQueue::MessageQueue(const string& topic, const string& brokerName, int queueId)
     : m_topic(topic), m_brokerName(brokerName), m_queueId(queueId) {}
 
 MessageQueue::MessageQueue(const MessageQueue& other)
-    : m_topic(other.m_topic),
-      m_brokerName(other.m_brokerName),
-      m_queueId(other.m_queueId) {}
+    : m_topic(other.m_topic), m_brokerName(other.m_brokerName), m_queueId(other.m_queueId) {}
 
 MessageQueue& MessageQueue::operator=(const MessageQueue& other) {
   if (this != &other) {
@@ -44,19 +41,29 @@
   return *this;
 }
 
-string MessageQueue::getTopic() const { return m_topic; }
+string MessageQueue::getTopic() const {
+  return m_topic;
+}
 
-void MessageQueue::setTopic(const string& topic) { m_topic = topic; }
+void MessageQueue::setTopic(const string& topic) {
+  m_topic = topic;
+}
 
-string MessageQueue::getBrokerName() const { return m_brokerName; }
+string MessageQueue::getBrokerName() const {
+  return m_brokerName;
+}
 
 void MessageQueue::setBrokerName(const string& brokerName) {
   m_brokerName = brokerName;
 }
 
-int MessageQueue::getQueueId() const { return m_queueId; }
+int MessageQueue::getQueueId() const {
+  return m_queueId;
+}
 
-void MessageQueue::setQueueId(int queueId) { m_queueId = queueId; }
+void MessageQueue::setQueueId(int queueId) {
+  m_queueId = queueId;
+}
 
 bool MessageQueue::operator==(const MessageQueue& mq) const {
   if (this == &mq) {
diff --git a/src/protocol/MessageQueue.h b/src/protocol/MessageQueue.h
old mode 100755
new mode 100644
index 0d47bf8..e9b66f4
--- a/src/protocol/MessageQueue.h
+++ b/src/protocol/MessageQueue.h
@@ -27,8 +27,7 @@
 class MessageQueue {

  public:

   MessageQueue();

-  MessageQueue(const std::string& topic, const std::string& brokerName,

-               int queueId);

+  MessageQueue(const std::string& topic, const std::string& brokerName, int queueId);

   MessageQueue(const MessageQueue& other);

   MessageQueue& operator=(const MessageQueue& other);

 

diff --git a/src/protocol/ProcessQueueInfo.h b/src/protocol/ProcessQueueInfo.h
old mode 100755
new mode 100644
index 1802673..85686f6
--- a/src/protocol/ProcessQueueInfo.h
+++ b/src/protocol/ProcessQueueInfo.h
@@ -44,9 +44,7 @@
  public:
   const uint64 getCommitOffset() const { return commitOffset; }
 
-  void setCommitOffset(uint64 input_commitOffset) {
-    commitOffset = input_commitOffset;
-  }
+  void setCommitOffset(uint64 input_commitOffset) { commitOffset = input_commitOffset; }
 
   void setLocked(bool in_locked) { locked = in_locked; }
 
@@ -59,25 +57,18 @@
   Json::Value toJson() const {
     Json::Value outJson;
     outJson["commitOffset"] = (UtilAll::to_string(commitOffset)).c_str();
-    outJson["cachedMsgMinOffset"] =
-        (UtilAll::to_string(cachedMsgMinOffset)).c_str();
-    outJson["cachedMsgMaxOffset"] =
-        (UtilAll::to_string(cachedMsgMaxOffset)).c_str();
+    outJson["cachedMsgMinOffset"] = (UtilAll::to_string(cachedMsgMinOffset)).c_str();
+    outJson["cachedMsgMaxOffset"] = (UtilAll::to_string(cachedMsgMaxOffset)).c_str();
     outJson["cachedMsgCount"] = (int)(cachedMsgCount);
-    outJson["transactionMsgMinOffset"] =
-        (UtilAll::to_string(transactionMsgMinOffset)).c_str();
-    outJson["transactionMsgMaxOffset"] =
-        (UtilAll::to_string(transactionMsgMaxOffset)).c_str();
+    outJson["transactionMsgMinOffset"] = (UtilAll::to_string(transactionMsgMinOffset)).c_str();
+    outJson["transactionMsgMaxOffset"] = (UtilAll::to_string(transactionMsgMaxOffset)).c_str();
     outJson["transactionMsgCount"] = (int)(transactionMsgCount);
     outJson["locked"] = (locked);
     outJson["tryUnlockTimes"] = (int)(tryUnlockTimes);
-    outJson["lastLockTimestamp"] =
-        (UtilAll::to_string(lastLockTimestamp)).c_str();
+    outJson["lastLockTimestamp"] = (UtilAll::to_string(lastLockTimestamp)).c_str();
     outJson["droped"] = (droped);
-    outJson["lastPullTimestamp"] =
-        (UtilAll::to_string(lastPullTimestamp)).c_str();
-    outJson["lastConsumeTimestamp"] =
-        (UtilAll::to_string(lastConsumeTimestamp)).c_str();
+    outJson["lastPullTimestamp"] = (UtilAll::to_string(lastPullTimestamp)).c_str();
+    outJson["lastConsumeTimestamp"] = (UtilAll::to_string(lastConsumeTimestamp)).c_str();
 
     return outJson;
   }
diff --git a/src/protocol/RemotingCommand.cpp b/src/protocol/RemotingCommand.cpp
index 9f9b3e5..08765de 100644
--- a/src/protocol/RemotingCommand.cpp
+++ b/src/protocol/RemotingCommand.cpp
@@ -25,21 +25,23 @@
 boost::atomic<int> RemotingCommand::s_seqNumber;
 
 //<!************************************************************************
-RemotingCommand::RemotingCommand(int code,
-                                 CommandHeader* pExtHeader /* = NULL */)
+RemotingCommand::RemotingCommand(int code, CommandHeader* pExtHeader /* = NULL */)
     : m_code(code),
       m_language("CPP"),
       m_version(MQVersion::s_CurrentVersion),
       m_flag(0),
       m_remark(""),
       m_pExtHeader(pExtHeader) {
-
   // mask sign bit
   m_opaque = s_seqNumber.fetch_add(1, boost::memory_order_relaxed) & numeric_limits<int>::max();
 }
 
-RemotingCommand::RemotingCommand(int code, string language, int version,
-                                 int opaque, int flag, string remark,
+RemotingCommand::RemotingCommand(int code,
+                                 string language,
+                                 int version,
+                                 int opaque,
+                                 int flag,
+                                 string remark,
                                  CommandHeader* pExtHeader)
     : m_code(code),
       m_language(language),
@@ -50,7 +52,7 @@
       m_pExtHeader(pExtHeader) {}
 
 RemotingCommand::RemotingCommand(const RemotingCommand& command) {
-    Assign(command);
+  Assign(command);
 }
 
 RemotingCommand& RemotingCommand::operator=(const RemotingCommand& command) {
@@ -60,9 +62,11 @@
   return *this;
 }
 
-RemotingCommand::~RemotingCommand() { m_pExtHeader = NULL; }
+RemotingCommand::~RemotingCommand() {
+  m_pExtHeader = NULL;
+}
 
-void RemotingCommand::Assign(const RemotingCommand &command) {
+void RemotingCommand::Assign(const RemotingCommand& command) {
   m_code = command.m_code;
   m_language = command.m_language;
   m_version = command.m_version;
@@ -71,14 +75,14 @@
   m_remark = command.m_remark;
   m_msgBody = command.m_msgBody;
 
-  for (auto &it : command.m_extFields) {
+  for (auto& it : command.m_extFields) {
     m_extFields[it.first] = it.second;
   }
 
   m_head = command.m_head;
   m_body = command.m_body;
   m_parsedJson = command.m_parsedJson;
-  //m_pExtHeader = command.m_pExtHeader; //ignore this filed at this moment, if need please add it
+  // m_pExtHeader = command.m_pExtHeader; //ignore this filed at this moment, if need please add it
 }
 
 void RemotingCommand::Encode() {
@@ -94,22 +98,16 @@
     Json::Value extJson;
     m_pExtHeader->Encode(extJson);
 
-    extJson[SessionCredentials::Signature] =
-        m_extFields[SessionCredentials::Signature];
-    extJson[SessionCredentials::AccessKey] =
-        m_extFields[SessionCredentials::AccessKey];
-    extJson[SessionCredentials::ONSChannelKey] =
-        m_extFields[SessionCredentials::ONSChannelKey];
+    extJson[SessionCredentials::Signature] = m_extFields[SessionCredentials::Signature];
+    extJson[SessionCredentials::AccessKey] = m_extFields[SessionCredentials::AccessKey];
+    extJson[SessionCredentials::ONSChannelKey] = m_extFields[SessionCredentials::ONSChannelKey];
 
     root["extFields"] = extJson;
   } else {  // for heartbeat
     Json::Value extJson;
-    extJson[SessionCredentials::Signature] =
-        m_extFields[SessionCredentials::Signature];
-    extJson[SessionCredentials::AccessKey] =
-        m_extFields[SessionCredentials::AccessKey];
-    extJson[SessionCredentials::ONSChannelKey] =
-        m_extFields[SessionCredentials::ONSChannelKey];
+    extJson[SessionCredentials::Signature] = m_extFields[SessionCredentials::Signature];
+    extJson[SessionCredentials::AccessKey] = m_extFields[SessionCredentials::AccessKey];
+    extJson[SessionCredentials::ONSChannelKey] = m_extFields[SessionCredentials::ONSChannelKey];
     root["extFields"] = extJson;
   }
 
@@ -129,9 +127,13 @@
   m_head.copyFrom(data.c_str(), sizeof(messageHeader), headLen);
 }
 
-const MemoryBlock* RemotingCommand::GetHead() const { return &m_head; }
+const MemoryBlock* RemotingCommand::GetHead() const {
+  return &m_head;
+}
 
-const MemoryBlock* RemotingCommand::GetBody() const { return &m_body; }
+const MemoryBlock* RemotingCommand::GetBody() const {
+  return &m_body;
+}
 
 void RemotingCommand::SetBody(const char* pData, int len) {
   m_body.reset();
@@ -172,10 +174,8 @@
   LOG_DEBUG(
       "code:%d, remark:%s, version:%d, opaque:%d, flag:%d, remark:%s, "
       "headLen:%d, bodyLen:%d ",
-      code, language.c_str(), version, opaque, flag, remark.c_str(), headLen,
-      bodyLen);
-  RemotingCommand* cmd =
-      new RemotingCommand(code, language, version, opaque, flag, remark, NULL);
+      code, language.c_str(), version, opaque, flag, remark.c_str(), headLen, bodyLen);
+  RemotingCommand* cmd = new RemotingCommand(code, language, version, opaque, flag, remark, NULL);
   cmd->setParsedJson(object);
   if (bodyLen > 0) {
     cmd->SetBody(pData + 4 + headLen, bodyLen);
@@ -203,7 +203,9 @@
   return (m_flag & bits) == bits;
 }
 
-void RemotingCommand::setOpaque(const int opa) { m_opaque = opa; }
+void RemotingCommand::setOpaque(const int opa) {
+  m_opaque = opa;
+}
 
 void RemotingCommand::SetExtHeader(int code) {
   try {
@@ -227,8 +229,7 @@
           m_pExtHeader.reset(SearchOffsetResponseHeader::Decode(ext));
           break;
         case GET_EARLIEST_MSG_STORETIME:
-          m_pExtHeader.reset(
-              GetEarliestMsgStoretimeResponseHeader::Decode(ext));
+          m_pExtHeader.reset(GetEarliestMsgStoretimeResponseHeader::Decode(ext));
           break;
         case QUERY_CONSUMER_OFFSET:
           m_pExtHeader.reset(QueryConsumerOffsetResponseHeader::Decode(ext));
@@ -240,8 +241,11 @@
           m_pExtHeader.reset(GetConsumerRunningInfoRequestHeader::Decode(ext));
           break;
         case NOTIFY_CONSUMER_IDS_CHANGED:
-          m_pExtHeader.reset(
-              NotifyConsumerIdsChangedRequestHeader::Decode(ext));
+          m_pExtHeader.reset(NotifyConsumerIdsChangedRequestHeader::Decode(ext));
+          break;
+        case CHECK_TRANSACTION_STATE:
+          m_pExtHeader.reset(CheckTransactionStateRequestHeader::Decode(ext));
+          break;
         default:
           break;
       }
@@ -251,29 +255,49 @@
   }
 }
 
-void RemotingCommand::setCode(int code) { m_code = code; }
+void RemotingCommand::setCode(int code) {
+  m_code = code;
+}
 
-int RemotingCommand::getCode() const { return m_code; }
+int RemotingCommand::getCode() const {
+  return m_code;
+}
 
-int RemotingCommand::getOpaque() const { return m_opaque; }
+int RemotingCommand::getOpaque() const {
+  return m_opaque;
+}
 
-string RemotingCommand::getRemark() const { return m_remark; }
+string RemotingCommand::getRemark() const {
+  return m_remark;
+}
 
-void RemotingCommand::setRemark(string mark) { m_remark = mark; }
+void RemotingCommand::setRemark(string mark) {
+  m_remark = mark;
+}
 
 CommandHeader* RemotingCommand::getCommandHeader() const {
   return m_pExtHeader.get();
 }
 
-void RemotingCommand::setParsedJson(Json::Value json) { m_parsedJson = json; }
+void RemotingCommand::setParsedJson(Json::Value json) {
+  m_parsedJson = json;
+}
 
-const int RemotingCommand::getFlag() const { return m_flag; }
+const int RemotingCommand::getFlag() const {
+  return m_flag;
+}
 
-const int RemotingCommand::getVersion() const { return m_version; }
+const int RemotingCommand::getVersion() const {
+  return m_version;
+}
 
-void RemotingCommand::setMsgBody(const string& body) { m_msgBody = body; }
+void RemotingCommand::setMsgBody(const string& body) {
+  m_msgBody = body;
+}
 
-string RemotingCommand::getMsgBody() const { return m_msgBody; }
+string RemotingCommand::getMsgBody() const {
+  return m_msgBody;
+}
 
 void RemotingCommand::addExtField(const string& key, const string& value) {
   m_extFields[key] = value;
@@ -281,10 +305,7 @@
 
 std::string RemotingCommand::ToString() const {
   std::stringstream ss;
-  ss << "code:" << m_code
-     << ",opaque:" << m_opaque
-     << ",flag:" << m_flag
-     << ",body.size:" << m_body.getSize()
+  ss << "code:" << m_code << ",opaque:" << m_opaque << ",flag:" << m_flag << ",body.size:" << m_body.getSize()
      << ",header.size:" << m_head.getSize();
   return ss.str();
 }
diff --git a/src/protocol/RemotingCommand.h b/src/protocol/RemotingCommand.h
old mode 100755
new mode 100644
index 254d964..bc137f7
--- a/src/protocol/RemotingCommand.h
+++ b/src/protocol/RemotingCommand.h
@@ -31,10 +31,15 @@
 //<!***************************************************************************
 class RemotingCommand {
  public:
-  RemotingCommand() : m_code(0) {};
+  RemotingCommand() : m_code(0){};
   RemotingCommand(int code, CommandHeader* pCustomHeader = NULL);
-  RemotingCommand(int code, string language, int version, int opaque, int flag,
-                  string remark, CommandHeader* pCustomHeader);
+  RemotingCommand(int code,
+                  string language,
+                  int version,
+                  int opaque,
+                  int flag,
+                  string remark,
+                  CommandHeader* pCustomHeader);
   RemotingCommand(const RemotingCommand& command);
   RemotingCommand& operator=(const RemotingCommand& command);
   virtual ~RemotingCommand();
@@ -59,12 +64,15 @@
   void addExtField(const string& key, const string& value);
   string getMsgBody() const;
   void setMsgBody(const string& body);
+
  public:
   void Encode();
   static RemotingCommand* Decode(const MemoryBlock& mem);
   std::string ToString() const;
+
  private:
- void Assign(const RemotingCommand& command);
+  void Assign(const RemotingCommand& command);
+
  private:
   int m_code;
   string m_language;
diff --git a/src/protocol/RemotingSerializable.h b/src/protocol/RemotingSerializable.h
old mode 100755
new mode 100644
diff --git a/src/protocol/TopicList.h b/src/protocol/TopicList.h
old mode 100755
new mode 100644
diff --git a/src/protocol/TopicRouteData.h b/src/protocol/TopicRouteData.h
old mode 100755
new mode 100644
index 9f70698..bce3016
--- a/src/protocol/TopicRouteData.h
+++ b/src/protocol/TopicRouteData.h
@@ -27,135 +27,134 @@
 
 //<!***************************************************************************
 struct QueueData {
-    std::string brokerName;
-    int readQueueNums;
-    int writeQueueNums;
-    int perm;
+  std::string brokerName;
+  int readQueueNums;
+  int writeQueueNums;
+  int perm;
 
-    bool operator<(const QueueData &other) const { return brokerName < other.brokerName; }
+  bool operator<(const QueueData& other) const { return brokerName < other.brokerName; }
 
-    bool operator==(const QueueData &other) const {
-        return brokerName == other.brokerName && readQueueNums == other.readQueueNums &&
-               writeQueueNums == other.writeQueueNums && perm == other.perm;
-    }
+  bool operator==(const QueueData& other) const {
+    return brokerName == other.brokerName && readQueueNums == other.readQueueNums &&
+           writeQueueNums == other.writeQueueNums && perm == other.perm;
+  }
 };
 
 //<!***************************************************************************
 struct BrokerData {
-    std::string brokerName;
-    std::map<int, string> brokerAddrs;  //<!0:master,1,2.. slave
+  std::string brokerName;
+  std::map<int, string> brokerAddrs;  //<!0:master,1,2.. slave
 
-    bool operator<(const BrokerData &other) const { return brokerName < other.brokerName; }
+  bool operator<(const BrokerData& other) const { return brokerName < other.brokerName; }
 
-    bool operator==(const BrokerData &other) const {
-        return brokerName == other.brokerName && brokerAddrs == other.brokerAddrs;
-    }
+  bool operator==(const BrokerData& other) const {
+    return brokerName == other.brokerName && brokerAddrs == other.brokerAddrs;
+  }
 };
 
 //<!************************************************************************/
 class TopicRouteData {
-   public:
-    virtual ~TopicRouteData() {
-        m_brokerDatas.clear();
-        m_queueDatas.clear();
+ public:
+  virtual ~TopicRouteData() {
+    m_brokerDatas.clear();
+    m_queueDatas.clear();
+  }
+
+  static TopicRouteData* Decode(const MemoryBlock* mem) {
+    //<!see doc/TopicRouteData.json;
+    const char* const pData = static_cast<const char*>(mem->getData());
+    string data(pData, mem->getSize());
+
+    Json::CharReaderBuilder charReaderBuilder;
+    charReaderBuilder.settings_["allowNumericKeys"] = true;
+    unique_ptr<Json::CharReader> pCharReaderPtr(charReaderBuilder.newCharReader());
+
+    const char* begin = pData;
+    const char* end = pData + mem->getSize();
+    Json::Value root;
+    string errs;
+
+    if (!pCharReaderPtr->parse(begin, end, &root, &errs)) {
+      LOG_ERROR("parse json error:%s, value isArray:%d, isObject:%d", errs.c_str(), root.isArray(), root.isObject());
+      return nullptr;
     }
 
-    static TopicRouteData *Decode(const MemoryBlock *mem) {
-        //<!see doc/TopicRouteData.json;
-        const char *const pData = static_cast<const char *>(mem->getData());
-        string data(pData, mem->getSize());
+    auto* trd = new TopicRouteData();
+    trd->setOrderTopicConf(root["orderTopicConf"].asString());
 
-        Json::CharReaderBuilder charReaderBuilder;
-        charReaderBuilder.settings_["allowNumericKeys"] = true;
-        unique_ptr<Json::CharReader> pCharReaderPtr(charReaderBuilder.newCharReader());
-
-        const char *begin = pData;
-        const char *end = pData + mem->getSize();
-        Json::Value root;
-        string errs;
-
-        if (!pCharReaderPtr->parse(begin, end, &root, &errs)) {
-            LOG_ERROR("parse json error:%s, value isArray:%d, isObject:%d", errs.c_str(), root.isArray(),
-                      root.isObject());
-            return nullptr;
-        }
-
-        auto *trd = new TopicRouteData();
-        trd->setOrderTopicConf(root["orderTopicConf"].asString());
-
-        Json::Value qds = root["queueDatas"];
-        for (auto qd : qds) {
-            QueueData d;
-            d.brokerName = qd["brokerName"].asString();
-            d.readQueueNums = qd["readQueueNums"].asInt();
-            d.writeQueueNums = qd["writeQueueNums"].asInt();
-            d.perm = qd["perm"].asInt();
-            trd->getQueueDatas().push_back(d);
-        }
-        sort(trd->getQueueDatas().begin(), trd->getQueueDatas().end());
-
-        Json::Value bds = root["brokerDatas"];
-        for (auto bd : bds) {
-            BrokerData d;
-            d.brokerName = bd["brokerName"].asString();
-            LOG_DEBUG("brokerName:%s", d.brokerName.c_str());
-            Json::Value bas = bd["brokerAddrs"];
-            Json::Value::Members mbs = bas.getMemberNames();
-            for (const auto &key : mbs) {
-                int id = atoi(key.c_str());
-                string addr = bas[key].asString();
-                d.brokerAddrs[id] = addr;
-                LOG_DEBUG("brokerId:%d, brokerAddr:%s", id, addr.c_str());
-            }
-            trd->getBrokerDatas().push_back(d);
-        }
-        sort(trd->getBrokerDatas().begin(), trd->getBrokerDatas().end());
-
-        return trd;
+    Json::Value qds = root["queueDatas"];
+    for (auto qd : qds) {
+      QueueData d;
+      d.brokerName = qd["brokerName"].asString();
+      d.readQueueNums = qd["readQueueNums"].asInt();
+      d.writeQueueNums = qd["writeQueueNums"].asInt();
+      d.perm = qd["perm"].asInt();
+      trd->getQueueDatas().push_back(d);
     }
+    sort(trd->getQueueDatas().begin(), trd->getQueueDatas().end());
 
-    /**
-     * Selects a (preferably master) broker address from the registered list.
-     * If the master's address cannot be found, a slave broker address is selected in a random manner.
-     *
-     * @return Broker address.
-     */
-    std::string selectBrokerAddr() {
-        int bdSize = m_brokerDatas.size();
-        if (bdSize > 0) {
-            int bdIndex = std::rand() % bdSize;
-            auto bd = m_brokerDatas[bdIndex];
-            auto iter = bd.brokerAddrs.find(MASTER_ID);
-            if (iter == bd.brokerAddrs.end()) {
-                int baSize = bd.brokerAddrs.size();
-                int baIndex = std::rand() % baSize;
-                iter = bd.brokerAddrs.begin();
-                for (; baIndex > 0; baIndex--) {
-                    iter++;
-                }
-            }
-            return iter->second;
+    Json::Value bds = root["brokerDatas"];
+    for (auto bd : bds) {
+      BrokerData d;
+      d.brokerName = bd["brokerName"].asString();
+      LOG_DEBUG("brokerName:%s", d.brokerName.c_str());
+      Json::Value bas = bd["brokerAddrs"];
+      Json::Value::Members mbs = bas.getMemberNames();
+      for (const auto& key : mbs) {
+        int id = atoi(key.c_str());
+        string addr = bas[key].asString();
+        d.brokerAddrs[id] = addr;
+        LOG_DEBUG("brokerId:%d, brokerAddr:%s", id, addr.c_str());
+      }
+      trd->getBrokerDatas().push_back(d);
+    }
+    sort(trd->getBrokerDatas().begin(), trd->getBrokerDatas().end());
+
+    return trd;
+  }
+
+  /**
+   * Selects a (preferably master) broker address from the registered list.
+   * If the master's address cannot be found, a slave broker address is selected in a random manner.
+   *
+   * @return Broker address.
+   */
+  std::string selectBrokerAddr() {
+    int bdSize = m_brokerDatas.size();
+    if (bdSize > 0) {
+      int bdIndex = std::rand() % bdSize;
+      auto bd = m_brokerDatas[bdIndex];
+      auto iter = bd.brokerAddrs.find(MASTER_ID);
+      if (iter == bd.brokerAddrs.end()) {
+        int baSize = bd.brokerAddrs.size();
+        int baIndex = std::rand() % baSize;
+        iter = bd.brokerAddrs.begin();
+        for (; baIndex > 0; baIndex--) {
+          iter++;
         }
-        return "";
+      }
+      return iter->second;
     }
+    return "";
+  }
 
-    std::vector<QueueData> &getQueueDatas() { return m_queueDatas; }
+  std::vector<QueueData>& getQueueDatas() { return m_queueDatas; }
 
-    std::vector<BrokerData> &getBrokerDatas() { return m_brokerDatas; }
+  std::vector<BrokerData>& getBrokerDatas() { return m_brokerDatas; }
 
-    const std::string &getOrderTopicConf() const { return m_orderTopicConf; }
+  const std::string& getOrderTopicConf() const { return m_orderTopicConf; }
 
-    void setOrderTopicConf(const string &orderTopicConf) { m_orderTopicConf = orderTopicConf; }
+  void setOrderTopicConf(const string& orderTopicConf) { m_orderTopicConf = orderTopicConf; }
 
-    bool operator==(const TopicRouteData &other) const {
-        return m_brokerDatas == other.m_brokerDatas && m_orderTopicConf == other.m_orderTopicConf &&
-               m_queueDatas == other.m_queueDatas;
-    }
+  bool operator==(const TopicRouteData& other) const {
+    return m_brokerDatas == other.m_brokerDatas && m_orderTopicConf == other.m_orderTopicConf &&
+           m_queueDatas == other.m_queueDatas;
+  }
 
-   private:
-    std::string m_orderTopicConf;
-    std::vector<QueueData> m_queueDatas;
-    std::vector<BrokerData> m_brokerDatas;
+ private:
+  std::string m_orderTopicConf;
+  std::vector<QueueData> m_queueDatas;
+  std::vector<BrokerData> m_brokerDatas;
 };
 
 }  // namespace rocketmq
diff --git a/src/thread/disruptorLFQ.h b/src/thread/disruptorLFQ.h
old mode 100755
new mode 100644
index 079bcc5..30e5a18
--- a/src/thread/disruptorLFQ.h
+++ b/src/thread/disruptorLFQ.h
@@ -39,8 +39,7 @@
   taskBatchHandler(int pullMsgThreadPoolNum);
   virtual ~taskBatchHandler() {}
 
-  virtual void OnEvent(const int64_t& sequence, const bool& end_of_batch,
-                       Task* event);
+  virtual void OnEvent(const int64_t& sequence, const bool& end_of_batch, Task* event);
   virtual void OnStart() {}
   virtual void OnShutdown() {}
   void runTaskEvent(Task event, int64_t sequence);
@@ -64,31 +63,27 @@
 
 class taskExceptionHandler : public ExceptionHandlerInterface<Task> {
  public:
-  virtual void Handle(const std::exception& exception, const int64_t& sequence,
-                      Task* event) {}
+  virtual void Handle(const std::exception& exception, const int64_t& sequence, Task* event) {}
 };
 
 class disruptorLFQ {
  public:
   disruptorLFQ(int threadCount) {
     m_task_factory.reset(new taskEventFactory());
-    m_ring_buffer.reset(new RingBuffer<Task>(
-        m_task_factory.get(),
-        1024,  // default size is 1024, must be n power of 2
-        kSingleThreadedStrategy,
-        kBlockingStrategy));  // load normal, lowest CPU occupy, but
-                                     // largest consume latency
+    m_ring_buffer.reset(new RingBuffer<Task>(m_task_factory.get(),
+                                             1024,  // default size is 1024, must be n power of 2
+                                             kSingleThreadedStrategy,
+                                             kBlockingStrategy));  // load normal, lowest CPU occupy, but
+                                                                   // largest consume latency
 
     m_sequence_to_track.reset(new std::vector<Sequence*>(0));
-    m_sequenceBarrier.reset(
-        m_ring_buffer->NewBarrier(*(m_sequence_to_track.get())));
+    m_sequenceBarrier.reset(m_ring_buffer->NewBarrier(*(m_sequence_to_track.get())));
 
     m_task_handler.reset(new taskBatchHandler(threadCount));
     m_task_exception_handler.reset(new taskExceptionHandler());
-    m_processor.reset(new BatchEventProcessor<Task>(
-        m_ring_buffer.get(),
-        (SequenceBarrierInterface*)m_sequenceBarrier.get(),
-        m_task_handler.get(), m_task_exception_handler.get()));
+    m_processor.reset(new BatchEventProcessor<Task>(m_ring_buffer.get(),
+                                                    (SequenceBarrierInterface*)m_sequenceBarrier.get(),
+                                                    m_task_handler.get(), m_task_exception_handler.get()));
 
     /*
     Publisher will try to publish BUFFER_SIZE + 1 events.
@@ -98,9 +93,8 @@
     event.
     */
     m_gating_sequences.push_back(m_processor.get()->GetSequence());
-    m_ring_buffer->set_gating_sequences(
-        m_gating_sequences);  // prevent overlap, publishEvent will be blocked
-                              // on ring_buffer_->Next();
+    m_ring_buffer->set_gating_sequences(m_gating_sequences);  // prevent overlap, publishEvent will be blocked
+                                                              // on ring_buffer_->Next();
 
     m_publisher.reset(new EventPublisher<Task>(m_ring_buffer.get()));
   }
diff --git a/src/thread/task_queue.cpp b/src/thread/task_queue.cpp
old mode 100755
new mode 100644
index e7c062e..3df2f74
--- a/src/thread/task_queue.cpp
+++ b/src/thread/task_queue.cpp
@@ -27,27 +27,23 @@
   return new Task[size];
 }
 
-taskBatchHandler::taskBatchHandler(int pullMsgThreadPoolNum)
-    : m_ioServiceWork(m_ioService) {
+taskBatchHandler::taskBatchHandler(int pullMsgThreadPoolNum) : m_ioServiceWork(m_ioService) {
 #if !defined(WIN32) && !defined(__APPLE__)
   string taskName = UtilAll::getProcessName();
   prctl(PR_SET_NAME, "PullMsgTP", 0, 0, 0);
 #endif
   for (int i = 0; i != pullMsgThreadPoolNum; ++i) {
-    m_threadpool.create_thread(
-        boost::bind(&boost::asio::io_service::run, &m_ioService));
+    m_threadpool.create_thread(boost::bind(&boost::asio::io_service::run, &m_ioService));
   }
 #if !defined(WIN32) && !defined(__APPLE__)
   prctl(PR_SET_NAME, taskName.c_str(), 0, 0, 0);
 #endif
 }
 
-void taskBatchHandler::OnEvent(const int64_t& sequence,
-                               const bool& end_of_batch, Task* event) {
+void taskBatchHandler::OnEvent(const int64_t& sequence, const bool& end_of_batch, Task* event) {
   // cp Task event out, avoid publish event override current Task event
   Task currentTask(*event);
-  m_ioService.post(boost::bind(&taskBatchHandler::runTaskEvent, this,
-                               currentTask, sequence));
+  m_ioService.post(boost::bind(&taskBatchHandler::runTaskEvent, this, currentTask, sequence));
 }
 
 void taskBatchHandler::runTaskEvent(Task event, int64_t sequence) {
diff --git a/src/thread/task_queue.h b/src/thread/task_queue.h
old mode 100755
new mode 100644
index af79e09..4c87864
--- a/src/thread/task_queue.h
+++ b/src/thread/task_queue.h
@@ -45,7 +45,8 @@
     m_arg = 0;
   }
   virtual void run() {
-    if (m_func != 0) m_func(m_arg);
+    if (m_func != 0)
+      m_func(m_arg);
   }
   virtual ITask_impl* fork() { return new Task_impl(m_func, m_arg); }
 
@@ -72,7 +73,8 @@
     return *this;
   }
   void run() {
-    if (m_pTaskImpl) m_pTaskImpl->run();
+    if (m_pTaskImpl)
+      m_pTaskImpl->run();
   }
 
  private:
@@ -131,8 +133,7 @@
       FUNCT dest_func;
       ARG1 arg1;
       ARG2 arg2;
-      lambda(FUNCT func, const ARG1& arg1, const ARG2& arg2)
-          : dest_func(func), arg1(arg1), arg2(arg2) {}
+      lambda(FUNCT func, const ARG1& arg1, const ARG2& arg2) : dest_func(func), arg1(arg1), arg2(arg2) {}
       virtual void run() { (*dest_func)(arg1, arg2); }
       virtual ITask_impl* fork() { return new lambda(dest_func, arg1, arg2); }
     };
@@ -149,15 +150,12 @@
       lambda(FUNCT func, const ARG1& arg1, const ARG2& arg2, const ARG3& arg3)
           : dest_func(func), arg1(arg1), arg2(arg2), arg3(arg3) {}
       virtual void run() { (*dest_func)(arg1, arg2, arg3); }
-      virtual ITask_impl* fork() {
-        return new lambda(dest_func, arg1, arg2, arg3);
-      }
+      virtual ITask_impl* fork() { return new lambda(dest_func, arg1, arg2, arg3); }
     };
     return Task(new lambda(func, arg1, arg2, arg3));
   }
 
-  template <typename FUNCT, typename ARG1, typename ARG2, typename ARG3,
-            typename ARG4>
+  template <typename FUNCT, typename ARG1, typename ARG2, typename ARG3, typename ARG4>
   static Task gen(FUNCT func, ARG1 arg1, ARG2 arg2, ARG3 arg3, ARG4 arg4) {
     struct lambda : public ITask_impl {
       FUNCT dest_func;
@@ -165,21 +163,16 @@
       ARG2 arg2;
       ARG3 arg3;
       ARG4 arg4;
-      lambda(FUNCT func, const ARG1& arg1, const ARG2& arg2, const ARG3& arg3,
-             const ARG4& arg4)
+      lambda(FUNCT func, const ARG1& arg1, const ARG2& arg2, const ARG3& arg3, const ARG4& arg4)
           : dest_func(func), arg1(arg1), arg2(arg2), arg3(arg3), arg4(arg4) {}
       virtual void run() { (*dest_func)(arg1, arg2, arg3, arg4); }
-      virtual ITask_impl* fork() {
-        return new lambda(dest_func, arg1, arg2, arg3, arg4);
-      }
+      virtual ITask_impl* fork() { return new lambda(dest_func, arg1, arg2, arg3, arg4); }
     };
     return Task(new lambda(func, arg1, arg2, arg3, arg4));
   }
 
-  template <typename FUNCT, typename ARG1, typename ARG2, typename ARG3,
-            typename ARG4, typename ARG5>
-  static Task gen(FUNCT func, ARG1 arg1, ARG2 arg2, ARG3 arg3, ARG4 arg4,
-                  ARG5 arg5) {
+  template <typename FUNCT, typename ARG1, typename ARG2, typename ARG3, typename ARG4, typename ARG5>
+  static Task gen(FUNCT func, ARG1 arg1, ARG2 arg2, ARG3 arg3, ARG4 arg4, ARG5 arg5) {
     struct lambda : public ITask_impl {
       FUNCT dest_func;
       ARG1 arg1;
@@ -187,26 +180,16 @@
       ARG3 arg3;
       ARG4 arg4;
       ARG5 arg5;
-      lambda(FUNCT func, const ARG1& arg1, const ARG2& arg2, const ARG3& arg3,
-             const ARG4& arg4, const ARG5& arg5)
-          : dest_func(func),
-            arg1(arg1),
-            arg2(arg2),
-            arg3(arg3),
-            arg4(arg4),
-            arg5(arg5) {}
+      lambda(FUNCT func, const ARG1& arg1, const ARG2& arg2, const ARG3& arg3, const ARG4& arg4, const ARG5& arg5)
+          : dest_func(func), arg1(arg1), arg2(arg2), arg3(arg3), arg4(arg4), arg5(arg5) {}
       virtual void run() { (*dest_func)(arg1, arg2, arg3, arg4, arg5); }
-      virtual ITask_impl* fork() {
-        return new lambda(dest_func, arg1, arg2, arg3, arg4, arg5);
-      }
+      virtual ITask_impl* fork() { return new lambda(dest_func, arg1, arg2, arg3, arg4, arg5); }
     };
     return Task(new lambda(func, arg1, arg2, arg3, arg4, arg5));
   }
 
-  template <typename FUNCT, typename ARG1, typename ARG2, typename ARG3,
-            typename ARG4, typename ARG5, typename ARG6>
-  static Task gen(FUNCT func, ARG1 arg1, ARG2 arg2, ARG3 arg3, ARG4 arg4,
-                  ARG5 arg5, ARG6 arg6) {
+  template <typename FUNCT, typename ARG1, typename ARG2, typename ARG3, typename ARG4, typename ARG5, typename ARG6>
+  static Task gen(FUNCT func, ARG1 arg1, ARG2 arg2, ARG3 arg3, ARG4 arg4, ARG5 arg5, ARG6 arg6) {
     struct lambda : public ITask_impl {
       FUNCT dest_func;
       ARG1 arg1;
@@ -215,27 +198,29 @@
       ARG4 arg4;
       ARG5 arg5;
       ARG6 arg6;
-      lambda(FUNCT func, const ARG1& arg1, const ARG2& arg2, const ARG3& arg3,
-             const ARG4& arg4, const ARG5& arg5, const ARG6& arg6)
-          : dest_func(func),
-            arg1(arg1),
-            arg2(arg2),
-            arg3(arg3),
-            arg4(arg4),
-            arg5(arg5),
-            arg6(arg6) {}
+      lambda(FUNCT func,
+             const ARG1& arg1,
+             const ARG2& arg2,
+             const ARG3& arg3,
+             const ARG4& arg4,
+             const ARG5& arg5,
+             const ARG6& arg6)
+          : dest_func(func), arg1(arg1), arg2(arg2), arg3(arg3), arg4(arg4), arg5(arg5), arg6(arg6) {}
       virtual void run() { (*dest_func)(arg1, arg2, arg3, arg4, arg5, arg6); }
-      virtual ITask_impl* fork() {
-        return new lambda(dest_func, arg1, arg2, arg3, arg4, arg5, arg6);
-      }
+      virtual ITask_impl* fork() { return new lambda(dest_func, arg1, arg2, arg3, arg4, arg5, arg6); }
     };
     return Task(new lambda(func, arg1, arg2, arg3, arg4, arg5, arg6));
   }
 
-  template <typename FUNCT, typename ARG1, typename ARG2, typename ARG3,
-            typename ARG4, typename ARG5, typename ARG6, typename ARG7>
-  static Task gen(FUNCT func, ARG1 arg1, ARG2 arg2, ARG3 arg3, ARG4 arg4,
-                  ARG5 arg5, ARG6 arg6, ARG7 arg7) {
+  template <typename FUNCT,
+            typename ARG1,
+            typename ARG2,
+            typename ARG3,
+            typename ARG4,
+            typename ARG5,
+            typename ARG6,
+            typename ARG7>
+  static Task gen(FUNCT func, ARG1 arg1, ARG2 arg2, ARG3 arg3, ARG4 arg4, ARG5 arg5, ARG6 arg6, ARG7 arg7) {
     struct lambda : public ITask_impl {
       FUNCT dest_func;
       ARG1 arg1;
@@ -245,32 +230,31 @@
       ARG5 arg5;
       ARG6 arg6;
       ARG7 arg7;
-      lambda(FUNCT func, const ARG1& arg1, const ARG2& arg2, const ARG3& arg3,
-             const ARG4& arg4, const ARG5& arg5, const ARG6& arg6,
+      lambda(FUNCT func,
+             const ARG1& arg1,
+             const ARG2& arg2,
+             const ARG3& arg3,
+             const ARG4& arg4,
+             const ARG5& arg5,
+             const ARG6& arg6,
              const ARG7& arg7)
-          : dest_func(func),
-            arg1(arg1),
-            arg2(arg2),
-            arg3(arg3),
-            arg4(arg4),
-            arg5(arg5),
-            arg6(arg6),
-            arg7(arg7) {}
-      virtual void run() {
-        (*dest_func)(arg1, arg2, arg3, arg4, arg5, arg6, arg7);
-      }
-      virtual ITask_impl* fork() {
-        return new lambda(dest_func, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
-      }
+          : dest_func(func), arg1(arg1), arg2(arg2), arg3(arg3), arg4(arg4), arg5(arg5), arg6(arg6), arg7(arg7) {}
+      virtual void run() { (*dest_func)(arg1, arg2, arg3, arg4, arg5, arg6, arg7); }
+      virtual ITask_impl* fork() { return new lambda(dest_func, arg1, arg2, arg3, arg4, arg5, arg6, arg7); }
     };
     return Task(new lambda(func, arg1, arg2, arg3, arg4, arg5, arg6, arg7));
   }
 
-  template <typename FUNCT, typename ARG1, typename ARG2, typename ARG3,
-            typename ARG4, typename ARG5, typename ARG6, typename ARG7,
+  template <typename FUNCT,
+            typename ARG1,
+            typename ARG2,
+            typename ARG3,
+            typename ARG4,
+            typename ARG5,
+            typename ARG6,
+            typename ARG7,
             typename ARG8>
-  static Task gen(FUNCT func, ARG1 arg1, ARG2 arg2, ARG3 arg3, ARG4 arg4,
-                  ARG5 arg5, ARG6 arg6, ARG7 arg7, ARG8 arg8) {
+  static Task gen(FUNCT func, ARG1 arg1, ARG2 arg2, ARG3 arg3, ARG4 arg4, ARG5 arg5, ARG6 arg6, ARG7 arg7, ARG8 arg8) {
     struct lambda : public ITask_impl {
       FUNCT dest_func;
       ARG1 arg1;
@@ -281,9 +265,15 @@
       ARG6 arg6;
       ARG7 arg7;
       ARG8 arg8;
-      lambda(FUNCT func, const ARG1& arg1, const ARG2& arg2, const ARG3& arg3,
-             const ARG4& arg4, const ARG5& arg5, const ARG6& arg6,
-             const ARG7& arg7, const ARG8& arg8)
+      lambda(FUNCT func,
+             const ARG1& arg1,
+             const ARG2& arg2,
+             const ARG3& arg3,
+             const ARG4& arg4,
+             const ARG5& arg5,
+             const ARG6& arg6,
+             const ARG7& arg7,
+             const ARG8& arg8)
           : dest_func(func),
             arg1(arg1),
             arg2(arg2),
@@ -293,23 +283,24 @@
             arg6(arg6),
             arg7(arg7),
             arg8(arg8) {}
-      virtual void run() {
-        (*dest_func)(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
-      }
-      virtual ITask_impl* fork() {
-        return new lambda(dest_func, arg1, arg2, arg3, arg4, arg5, arg6, arg7,
-                          arg8);
-      }
+      virtual void run() { (*dest_func)(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); }
+      virtual ITask_impl* fork() { return new lambda(dest_func, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); }
     };
-    return Task(
-        new lambda(func, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8));
+    return Task(new lambda(func, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8));
   }
 
-  template <typename FUNCT, typename ARG1, typename ARG2, typename ARG3,
-            typename ARG4, typename ARG5, typename ARG6, typename ARG7,
-            typename ARG8, typename ARG9>
-  static Task gen(FUNCT func, ARG1 arg1, ARG2 arg2, ARG3 arg3, ARG4 arg4,
-                  ARG5 arg5, ARG6 arg6, ARG7 arg7, ARG8 arg8, ARG9 arg9) {
+  template <typename FUNCT,
+            typename ARG1,
+            typename ARG2,
+            typename ARG3,
+            typename ARG4,
+            typename ARG5,
+            typename ARG6,
+            typename ARG7,
+            typename ARG8,
+            typename ARG9>
+  static Task
+  gen(FUNCT func, ARG1 arg1, ARG2 arg2, ARG3 arg3, ARG4 arg4, ARG5 arg5, ARG6 arg6, ARG7 arg7, ARG8 arg8, ARG9 arg9) {
     struct lambda : public ITask_impl {
       FUNCT dest_func;
       ARG1 arg1;
@@ -321,9 +312,16 @@
       ARG7 arg7;
       ARG8 arg8;
       ARG9 arg9;
-      lambda(FUNCT func, const ARG1& arg1, const ARG2& arg2, const ARG3& arg3,
-             const ARG4& arg4, const ARG5& arg5, const ARG6& arg6,
-             const ARG7& arg7, const ARG8& arg8, const ARG9& arg9)
+      lambda(FUNCT func,
+             const ARG1& arg1,
+             const ARG2& arg2,
+             const ARG3& arg3,
+             const ARG4& arg4,
+             const ARG5& arg5,
+             const ARG6& arg6,
+             const ARG7& arg7,
+             const ARG8& arg8,
+             const ARG9& arg9)
           : dest_func(func),
             arg1(arg1),
             arg2(arg2),
@@ -334,16 +332,10 @@
             arg7(arg7),
             arg8(arg8),
             arg9(arg9) {}
-      virtual void run() {
-        (*dest_func)(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9);
-      }
-      virtual ITask_impl* fork() {
-        return new lambda(dest_func, arg1, arg2, arg3, arg4, arg5, arg6, arg7,
-                          arg8, arg9);
-      }
+      virtual void run() { (*dest_func)(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); }
+      virtual ITask_impl* fork() { return new lambda(dest_func, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); }
     };
-    return Task(
-        new lambda(func, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9));
+    return Task(new lambda(func, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9));
   }
 
   //<!***************************************************************************
@@ -367,59 +359,62 @@
       RET (T::*dest_func)(FARG1);
       T* obj;
       ARG1 arg1;
-      lambda(RET (T::*pfunc)(FARG1), T* obj, const ARG1& arg1)
-          : dest_func(pfunc), obj(obj), arg1(arg1) {}
+      lambda(RET (T::*pfunc)(FARG1), T* obj, const ARG1& arg1) : dest_func(pfunc), obj(obj), arg1(arg1) {}
       virtual void run() { (obj->*dest_func)(arg1); }
       virtual ITask_impl* fork() { return new lambda(dest_func, obj, arg1); }
     };
     return Task(new lambda(func, obj, arg1));
   }
 
-  template <typename T, typename RET, typename FARG1, typename FARG2,
-            typename ARG1, typename ARG2>
+  template <typename T, typename RET, typename FARG1, typename FARG2, typename ARG1, typename ARG2>
   static Task gen(RET (T::*func)(FARG1, FARG2), T* obj, ARG1 arg1, ARG2 arg2) {
     struct lambda : public ITask_impl {
       RET (T::*dest_func)(FARG1, FARG2);
       T* obj;
       ARG1 arg1;
       ARG2 arg2;
-      lambda(RET (T::*func)(FARG1, FARG2), T* obj, const ARG1& arg1,
-             const ARG2& arg2)
+      lambda(RET (T::*func)(FARG1, FARG2), T* obj, const ARG1& arg1, const ARG2& arg2)
           : dest_func(func), obj(obj), arg1(arg1), arg2(arg2) {}
       virtual void run() { (obj->*dest_func)(arg1, arg2); }
-      virtual ITask_impl* fork() {
-        return new lambda(dest_func, obj, arg1, arg2);
-      }
+      virtual ITask_impl* fork() { return new lambda(dest_func, obj, arg1, arg2); }
     };
     return Task(new lambda(func, obj, arg1, arg2));
   }
 
-  template <typename T, typename RET, typename FARG1, typename FARG2,
-            typename FARG3, typename ARG1, typename ARG2, typename ARG3>
-  static Task gen(RET (T::*func)(FARG1, FARG2, FARG3), T* obj, ARG1 arg1,
-                  ARG2 arg2, ARG3 arg3) {
+  template <typename T,
+            typename RET,
+            typename FARG1,
+            typename FARG2,
+            typename FARG3,
+            typename ARG1,
+            typename ARG2,
+            typename ARG3>
+  static Task gen(RET (T::*func)(FARG1, FARG2, FARG3), T* obj, ARG1 arg1, ARG2 arg2, ARG3 arg3) {
     struct lambda : public ITask_impl {
       RET (T::*dest_func)(FARG1, FARG2, FARG3);
       T* obj;
       ARG1 arg1;
       ARG2 arg2;
       ARG3 arg3;
-      lambda(RET (T::*func)(FARG1, FARG2, FARG3), T* obj, const ARG1& arg1,
-             const ARG2& arg2, const ARG3& arg3)
+      lambda(RET (T::*func)(FARG1, FARG2, FARG3), T* obj, const ARG1& arg1, const ARG2& arg2, const ARG3& arg3)
           : dest_func(func), obj(obj), arg1(arg1), arg2(arg2), arg3(arg3) {}
       virtual void run() { (obj->*dest_func)(arg1, arg2, arg3); }
-      virtual ITask_impl* fork() {
-        return new lambda(dest_func, obj, arg1, arg2, arg3);
-      }
+      virtual ITask_impl* fork() { return new lambda(dest_func, obj, arg1, arg2, arg3); }
     };
     return Task(new lambda(func, obj, arg1, arg2, arg3));
   }
 
-  template <typename T, typename RET, typename FARG1, typename FARG2,
-            typename FARG3, typename FARG4, typename ARG1, typename ARG2,
-            typename ARG3, typename ARG4>
-  static Task gen(RET (T::*func)(FARG1, FARG2, FARG3, FARG4), T* obj, ARG1 arg1,
-                  ARG2 arg2, ARG3 arg3, ARG4 arg4) {
+  template <typename T,
+            typename RET,
+            typename FARG1,
+            typename FARG2,
+            typename FARG3,
+            typename FARG4,
+            typename ARG1,
+            typename ARG2,
+            typename ARG3,
+            typename ARG4>
+  static Task gen(RET (T::*func)(FARG1, FARG2, FARG3, FARG4), T* obj, ARG1 arg1, ARG2 arg2, ARG3 arg3, ARG4 arg4) {
     struct lambda : public ITask_impl {
       RET (T::*dest_func)(FARG1, FARG2, FARG3, FARG4);
       T* obj;
@@ -427,28 +422,38 @@
       ARG2 arg2;
       ARG3 arg3;
       ARG4 arg4;
-      lambda(RET (T::*func)(FARG1, FARG2, FARG3, FARG4), T* obj,
-             const ARG1& arg1, const ARG2& arg2, const ARG3& arg3,
+      lambda(RET (T::*func)(FARG1, FARG2, FARG3, FARG4),
+             T* obj,
+             const ARG1& arg1,
+             const ARG2& arg2,
+             const ARG3& arg3,
              const ARG4& arg4)
-          : dest_func(func),
-            obj(obj),
-            arg1(arg1),
-            arg2(arg2),
-            arg3(arg3),
-            arg4(arg4) {}
+          : dest_func(func), obj(obj), arg1(arg1), arg2(arg2), arg3(arg3), arg4(arg4) {}
       virtual void run() { (obj->*dest_func)(arg1, arg2, arg3, arg4); }
-      virtual ITask_impl* fork() {
-        return new lambda(dest_func, obj, arg1, arg2, arg3, arg4);
-      }
+      virtual ITask_impl* fork() { return new lambda(dest_func, obj, arg1, arg2, arg3, arg4); }
     };
     return Task(new lambda(func, obj, arg1, arg2, arg3, arg4));
   }
 
-  template <typename T, typename RET, typename FARG1, typename FARG2,
-            typename FARG3, typename FARG4, typename FARG5, typename ARG1,
-            typename ARG2, typename ARG3, typename ARG4, typename ARG5>
-  static Task gen(RET (T::*func)(FARG1, FARG2, FARG3, FARG4, FARG5), T* obj,
-                  ARG1 arg1, ARG2 arg2, ARG3 arg3, ARG4 arg4, ARG5 arg5) {
+  template <typename T,
+            typename RET,
+            typename FARG1,
+            typename FARG2,
+            typename FARG3,
+            typename FARG4,
+            typename FARG5,
+            typename ARG1,
+            typename ARG2,
+            typename ARG3,
+            typename ARG4,
+            typename ARG5>
+  static Task gen(RET (T::*func)(FARG1, FARG2, FARG3, FARG4, FARG5),
+                  T* obj,
+                  ARG1 arg1,
+                  ARG2 arg2,
+                  ARG3 arg3,
+                  ARG4 arg4,
+                  ARG5 arg5) {
     struct lambda : public ITask_impl {
       RET (T::*dest_func)(FARG1, FARG2, FARG3, FARG4, FARG5);
       T* obj;
@@ -457,30 +462,41 @@
       ARG3 arg3;
       ARG4 arg4;
       ARG5 arg5;
-      lambda(RET (T::*func)(FARG1, FARG2, FARG3, FARG4, FARG5), T* obj,
-             const ARG1& arg1, const ARG2& arg2, const ARG3& arg3,
-             const ARG4& arg4, const ARG5& arg5)
-          : dest_func(func),
-            obj(obj),
-            arg1(arg1),
-            arg2(arg2),
-            arg3(arg3),
-            arg4(arg4),
-            arg5(arg5) {}
+      lambda(RET (T::*func)(FARG1, FARG2, FARG3, FARG4, FARG5),
+             T* obj,
+             const ARG1& arg1,
+             const ARG2& arg2,
+             const ARG3& arg3,
+             const ARG4& arg4,
+             const ARG5& arg5)
+          : dest_func(func), obj(obj), arg1(arg1), arg2(arg2), arg3(arg3), arg4(arg4), arg5(arg5) {}
       virtual void run() { (obj->*dest_func)(arg1, arg2, arg3, arg4, arg5); }
-      virtual ITask_impl* fork() {
-        return new lambda(dest_func, obj, arg1, arg2, arg3, arg4, arg5);
-      }
+      virtual ITask_impl* fork() { return new lambda(dest_func, obj, arg1, arg2, arg3, arg4, arg5); }
     };
     return Task(new lambda(func, obj, arg1, arg2, arg3, arg4, arg5));
   }
 
-  template <typename T, typename RET, typename FARG1, typename FARG2,
-            typename FARG3, typename FARG4, typename FARG5, typename FARG6,
-            typename ARG1, typename ARG2, typename ARG3, typename ARG4,
-            typename ARG5, typename ARG6>
+  template <typename T,
+            typename RET,
+            typename FARG1,
+            typename FARG2,
+            typename FARG3,
+            typename FARG4,
+            typename FARG5,
+            typename FARG6,
+            typename ARG1,
+            typename ARG2,
+            typename ARG3,
+            typename ARG4,
+            typename ARG5,
+            typename ARG6>
   static Task gen(RET (T::*func)(FARG1, FARG2, FARG3, FARG4, FARG5, FARG6),
-                  T* obj, ARG1 arg1, ARG2 arg2, ARG3 arg3, ARG4 arg4, ARG5 arg5,
+                  T* obj,
+                  ARG1 arg1,
+                  ARG2 arg2,
+                  ARG3 arg3,
+                  ARG4 arg4,
+                  ARG5 arg5,
                   ARG6 arg6) {
     struct lambda : public ITask_impl {
       RET (T::*dest_func)(FARG1, FARG2, FARG3, FARG4, FARG5, FARG6);
@@ -491,35 +507,46 @@
       ARG4 arg4;
       ARG5 arg5;
       ARG6 arg6;
-      lambda(RET (T::*func)(FARG1, FARG2, FARG3, FARG4, FARG5, FARG6), T* obj,
-             const ARG1& arg1, const ARG2& arg2, const ARG3& arg3,
-             const ARG4& arg4, const ARG5& arg5, const ARG6& arg6)
-          : dest_func(func),
-            obj(obj),
-            arg1(arg1),
-            arg2(arg2),
-            arg3(arg3),
-            arg4(arg4),
-            arg5(arg5),
-            arg6(arg6) {}
-      virtual void run() {
-        (obj->*dest_func)(arg1, arg2, arg3, arg4, arg5, arg6);
-      }
-      virtual ITask_impl* fork() {
-        return new lambda(dest_func, obj, arg1, arg2, arg3, arg4, arg5, arg6);
-      }
+      lambda(RET (T::*func)(FARG1, FARG2, FARG3, FARG4, FARG5, FARG6),
+             T* obj,
+             const ARG1& arg1,
+             const ARG2& arg2,
+             const ARG3& arg3,
+             const ARG4& arg4,
+             const ARG5& arg5,
+             const ARG6& arg6)
+          : dest_func(func), obj(obj), arg1(arg1), arg2(arg2), arg3(arg3), arg4(arg4), arg5(arg5), arg6(arg6) {}
+      virtual void run() { (obj->*dest_func)(arg1, arg2, arg3, arg4, arg5, arg6); }
+      virtual ITask_impl* fork() { return new lambda(dest_func, obj, arg1, arg2, arg3, arg4, arg5, arg6); }
     };
     return Task(new lambda(func, obj, arg1, arg2, arg3, arg4, arg5, arg6));
   }
 
-  template <typename T, typename RET, typename FARG1, typename FARG2,
-            typename FARG3, typename FARG4, typename FARG5, typename FARG6,
-            typename FARG7, typename ARG1, typename ARG2, typename ARG3,
-            typename ARG4, typename ARG5, typename ARG6, typename ARG7>
-  static Task gen(RET (T::*func)(FARG1, FARG2, FARG3, FARG4, FARG5, FARG6,
-                                 FARG7),
-                  T* obj, ARG1 arg1, ARG2 arg2, ARG3 arg3, ARG4 arg4, ARG5 arg5,
-                  ARG6 arg6, ARG7 arg7) {
+  template <typename T,
+            typename RET,
+            typename FARG1,
+            typename FARG2,
+            typename FARG3,
+            typename FARG4,
+            typename FARG5,
+            typename FARG6,
+            typename FARG7,
+            typename ARG1,
+            typename ARG2,
+            typename ARG3,
+            typename ARG4,
+            typename ARG5,
+            typename ARG6,
+            typename ARG7>
+  static Task gen(RET (T::*func)(FARG1, FARG2, FARG3, FARG4, FARG5, FARG6, FARG7),
+                  T* obj,
+                  ARG1 arg1,
+                  ARG2 arg2,
+                  ARG3 arg3,
+                  ARG4 arg4,
+                  ARG5 arg5,
+                  ARG6 arg6,
+                  ARG7 arg7) {
     struct lambda : public ITask_impl {
       RET (T::*dest_func)(FARG1, FARG2, FARG3, FARG4, FARG5, FARG6, FARG7);
       T* obj;
@@ -531,8 +558,13 @@
       ARG6 arg6;
       ARG7 arg7;
       lambda(RET (T::*func)(FARG1, FARG2, FARG3, FARG4, FARG5, FARG6, FARG7),
-             T* obj, const ARG1& arg1, const ARG2& arg2, const ARG3& arg3,
-             const ARG4& arg4, const ARG5& arg5, const ARG6& arg6,
+             T* obj,
+             const ARG1& arg1,
+             const ARG2& arg2,
+             const ARG3& arg3,
+             const ARG4& arg4,
+             const ARG5& arg5,
+             const ARG6& arg6,
              const ARG7& arg7)
           : dest_func(func),
             obj(obj),
@@ -543,29 +575,42 @@
             arg5(arg5),
             arg6(arg6),
             arg7(arg7) {}
-      virtual void run() {
-        (obj->*dest_func)(arg1, arg2, arg3, arg4, arg5, arg6, arg7);
-      }
-      virtual ITask_impl* fork() {
-        return new lambda(dest_func, obj, arg1, arg2, arg3, arg4, arg5, arg6,
-                          arg7);
-      }
+      virtual void run() { (obj->*dest_func)(arg1, arg2, arg3, arg4, arg5, arg6, arg7); }
+      virtual ITask_impl* fork() { return new lambda(dest_func, obj, arg1, arg2, arg3, arg4, arg5, arg6, arg7); }
     };
-    return Task(
-        new lambda(func, obj, arg1, arg2, arg3, arg4, arg5, arg6, arg7));
+    return Task(new lambda(func, obj, arg1, arg2, arg3, arg4, arg5, arg6, arg7));
   }
 
-  template <typename T, typename RET, typename FARG1, typename FARG2,
-            typename FARG3, typename FARG4, typename FARG5, typename FARG6,
-            typename FARG7, typename FARG8, typename ARG1, typename ARG2,
-            typename ARG3, typename ARG4, typename ARG5, typename ARG6,
-            typename ARG7, typename ARG8>
-  static Task gen(RET (T::*func)(FARG1, FARG2, FARG3, FARG4, FARG5, FARG6,
-                                 FARG7, FARG8),
-                  T* obj, ARG1 arg1, ARG2 arg2, ARG3 arg3, ARG4 arg4, ARG5 arg5,
-                  ARG6 arg6, ARG7 arg7, ARG8 arg8) {
+  template <typename T,
+            typename RET,
+            typename FARG1,
+            typename FARG2,
+            typename FARG3,
+            typename FARG4,
+            typename FARG5,
+            typename FARG6,
+            typename FARG7,
+            typename FARG8,
+            typename ARG1,
+            typename ARG2,
+            typename ARG3,
+            typename ARG4,
+            typename ARG5,
+            typename ARG6,
+            typename ARG7,
+            typename ARG8>
+  static Task gen(RET (T::*func)(FARG1, FARG2, FARG3, FARG4, FARG5, FARG6, FARG7, FARG8),
+                  T* obj,
+                  ARG1 arg1,
+                  ARG2 arg2,
+                  ARG3 arg3,
+                  ARG4 arg4,
+                  ARG5 arg5,
+                  ARG6 arg6,
+                  ARG7 arg7,
+                  ARG8 arg8) {
     struct lambda : public ITask_impl {
-      RET (T::*dest_func)
+      RET(T::*dest_func)
       (FARG1, FARG2, FARG3, FARG4, FARG5, FARG6, FARG7, FARG8);
       T* obj;
       ARG1 arg1;
@@ -576,11 +621,16 @@
       ARG6 arg6;
       ARG7 arg7;
       ARG8 arg8;
-      lambda(RET (T::*func)(FARG1, FARG2, FARG3, FARG4, FARG5, FARG6, FARG7,
-                            FARG8),
-             T* obj, const ARG1& arg1, const ARG2& arg2, const ARG3& arg3,
-             const ARG4& arg4, const ARG5& arg5, const ARG6& arg6,
-             const ARG7& arg7, const ARG8& arg8)
+      lambda(RET (T::*func)(FARG1, FARG2, FARG3, FARG4, FARG5, FARG6, FARG7, FARG8),
+             T* obj,
+             const ARG1& arg1,
+             const ARG2& arg2,
+             const ARG3& arg3,
+             const ARG4& arg4,
+             const ARG5& arg5,
+             const ARG6& arg6,
+             const ARG7& arg7,
+             const ARG8& arg8)
           : dest_func(func),
             obj(obj),
             arg1(arg1),
@@ -591,29 +641,45 @@
             arg6(arg6),
             arg7(arg7),
             arg8(arg8) {}
-      virtual void run() {
-        (obj->*dest_func)(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
-      }
-      virtual ITask_impl* fork() {
-        return new lambda(dest_func, obj, arg1, arg2, arg3, arg4, arg5, arg6,
-                          arg7, arg8);
-      }
+      virtual void run() { (obj->*dest_func)(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); }
+      virtual ITask_impl* fork() { return new lambda(dest_func, obj, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); }
     };
-    return Task(
-        new lambda(func, obj, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8));
+    return Task(new lambda(func, obj, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8));
   }
 
-  template <typename T, typename RET, typename FARG1, typename FARG2,
-            typename FARG3, typename FARG4, typename FARG5, typename FARG6,
-            typename FARG7, typename FARG8, typename FARG9, typename ARG1,
-            typename ARG2, typename ARG3, typename ARG4, typename ARG5,
-            typename ARG6, typename ARG7, typename ARG8, typename ARG9>
-  static Task gen(RET (T::*func)(FARG1, FARG2, FARG3, FARG4, FARG5, FARG6,
-                                 FARG7, FARG8, FARG9),
-                  T* obj, ARG1 arg1, ARG2 arg2, ARG3 arg3, ARG4 arg4, ARG5 arg5,
-                  ARG6 arg6, ARG7 arg7, ARG8 arg8, ARG9 arg9) {
+  template <typename T,
+            typename RET,
+            typename FARG1,
+            typename FARG2,
+            typename FARG3,
+            typename FARG4,
+            typename FARG5,
+            typename FARG6,
+            typename FARG7,
+            typename FARG8,
+            typename FARG9,
+            typename ARG1,
+            typename ARG2,
+            typename ARG3,
+            typename ARG4,
+            typename ARG5,
+            typename ARG6,
+            typename ARG7,
+            typename ARG8,
+            typename ARG9>
+  static Task gen(RET (T::*func)(FARG1, FARG2, FARG3, FARG4, FARG5, FARG6, FARG7, FARG8, FARG9),
+                  T* obj,
+                  ARG1 arg1,
+                  ARG2 arg2,
+                  ARG3 arg3,
+                  ARG4 arg4,
+                  ARG5 arg5,
+                  ARG6 arg6,
+                  ARG7 arg7,
+                  ARG8 arg8,
+                  ARG9 arg9) {
     struct lambda : public ITask_impl {
-      RET (T::*dest_func)
+      RET(T::*dest_func)
       (FARG1, FARG2, FARG3, FARG4, FARG5, FARG6, FARG7, FARG8, FARG9);
       T* obj;
       ARG1 arg1;
@@ -625,11 +691,17 @@
       ARG7 arg7;
       ARG8 arg8;
       ARG9 arg9;
-      lambda(RET (T::*func)(FARG1, FARG2, FARG3, FARG4, FARG5, FARG6, FARG7,
-                            FARG8, FARG9),
-             T* obj, const ARG1& arg1, const ARG2& arg2, const ARG3& arg3,
-             const ARG4& arg4, const ARG5& arg5, const ARG6& arg6,
-             const ARG7& arg7, const ARG8& arg8, const ARG9& arg9)
+      lambda(RET (T::*func)(FARG1, FARG2, FARG3, FARG4, FARG5, FARG6, FARG7, FARG8, FARG9),
+             T* obj,
+             const ARG1& arg1,
+             const ARG2& arg2,
+             const ARG3& arg3,
+             const ARG4& arg4,
+             const ARG5& arg5,
+             const ARG6& arg6,
+             const ARG7& arg7,
+             const ARG8& arg8,
+             const ARG9& arg9)
           : dest_func(func),
             obj(obj),
             arg1(arg1),
@@ -641,16 +713,12 @@
             arg7(arg7),
             arg8(arg8),
             arg9(arg9) {}
-      virtual void run() {
-        (obj->*dest_func)(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9);
-      }
+      virtual void run() { (obj->*dest_func)(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); }
       virtual ITask_impl* fork() {
-        return new lambda(dest_func, obj, arg1, arg2, arg3, arg4, arg5, arg6,
-                          arg7, arg8, arg9);
+        return new lambda(dest_func, obj, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9);
       }
     };
-    return Task(new lambda(func, obj, arg1, arg2, arg3, arg4, arg5, arg6, arg7,
-                           arg8, arg9));
+    return Task(new lambda(func, obj, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9));
   }
 };
 
diff --git a/src/transport/ClientRemotingProcessor.cpp b/src/transport/ClientRemotingProcessor.cpp
old mode 100755
new mode 100644
index 5e1a98b..63736c5
--- a/src/transport/ClientRemotingProcessor.cpp
+++ b/src/transport/ClientRemotingProcessor.cpp
@@ -22,18 +22,16 @@
 
 namespace rocketmq {
 
-ClientRemotingProcessor::ClientRemotingProcessor(
-    MQClientFactory* mqClientFactory)
+ClientRemotingProcessor::ClientRemotingProcessor(MQClientFactory* mqClientFactory)
     : m_mqClientFactory(mqClientFactory) {}
 
 ClientRemotingProcessor::~ClientRemotingProcessor() {}
 
-RemotingCommand* ClientRemotingProcessor::processRequest(
-    const string& addr, RemotingCommand* request) {
-  LOG_DEBUG("request Command received:processRequest");
+RemotingCommand* ClientRemotingProcessor::processRequest(const string& addr, RemotingCommand* request) {
+  LOG_INFO("request Command received:processRequest, addr:%s, code:%d", addr.data(), request->getCode());
   switch (request->getCode()) {
     case CHECK_TRANSACTION_STATE:
-      //  return checkTransactionState( request);
+      return checkTransactionState(addr, request);
       break;
     case NOTIFY_CONSUMER_IDS_CHANGED:
       return notifyConsumerIdsChanged(request);
@@ -55,21 +53,16 @@
   return NULL;
 }
 
-RemotingCommand* ClientRemotingProcessor::resetOffset(
-    RemotingCommand* request) {
+RemotingCommand* ClientRemotingProcessor::resetOffset(RemotingCommand* request) {
   request->SetExtHeader(request->getCode());
   const MemoryBlock* pbody = request->GetBody();
   if (pbody->getSize()) {
     ResetOffsetBody* offsetBody = ResetOffsetBody::Decode(pbody);
-    ResetOffsetRequestHeader* offsetHeader =
-        (ResetOffsetRequestHeader*)request->getCommandHeader();
+    ResetOffsetRequestHeader* offsetHeader = (ResetOffsetRequestHeader*)request->getCommandHeader();
     if (offsetBody) {
-      m_mqClientFactory->resetOffset(offsetHeader->getGroup(),
-                                     offsetHeader->getTopic(),
-                                     offsetBody->getOffsetTable());
+      m_mqClientFactory->resetOffset(offsetHeader->getGroup(), offsetHeader->getTopic(), offsetBody->getOffsetTable());
     } else {
-      LOG_ERROR(
-          "resetOffset failed as received data could not be unserialized");
+      LOG_ERROR("resetOffset failed as received data could not be unserialized");
     }
   }
   return NULL;  // as resetOffset is oneWayRPC, do not need return any response
@@ -104,29 +97,25 @@
     mq.setQueueId(qd["queueId"].asInt());
     mq.setTopic(qd["topic"].asString());
     int64 offset = qd["offset"].asInt64();
-    LOG_INFO("ResetOffsetBody brokerName:%s, queueID:%d, topic:%s, offset:%lld",
-             mq.getBrokerName().c_str(), mq.getQueueId(), mq.getTopic().c_str(),
-             offset);
+    LOG_INFO("ResetOffsetBody brokerName:%s, queueID:%d, topic:%s, offset:%lld", mq.getBrokerName().c_str(),
+             mq.getQueueId(), mq.getTopic().c_str(), offset);
     rfb->setOffsetTable(mq, offset);
   }
   return rfb;
 }
 
-RemotingCommand* ClientRemotingProcessor::getConsumerRunningInfo(
-    const string& addr, RemotingCommand* request) {
+RemotingCommand* ClientRemotingProcessor::getConsumerRunningInfo(const string& addr, RemotingCommand* request) {
   request->SetExtHeader(request->getCode());
   GetConsumerRunningInfoRequestHeader* requestHeader =
       (GetConsumerRunningInfoRequestHeader*)request->getCommandHeader();
-  LOG_INFO("getConsumerRunningInfo:%s",
-           requestHeader->getConsumerGroup().c_str());
+  LOG_INFO("getConsumerRunningInfo:%s", requestHeader->getConsumerGroup().c_str());
 
-  RemotingCommand* pResponse = new RemotingCommand(
-      request->getCode(), "CPP", request->getVersion(), request->getOpaque(),
-      request->getFlag(), request->getRemark(), NULL);
+  RemotingCommand* pResponse =
+      new RemotingCommand(request->getCode(), "CPP", request->getVersion(), request->getOpaque(), request->getFlag(),
+                          request->getRemark(), NULL);
 
   unique_ptr<ConsumerRunningInfo> runningInfo(
-      m_mqClientFactory->consumerRunningInfo(
-          requestHeader->getConsumerGroup()));
+      m_mqClientFactory->consumerRunningInfo(requestHeader->getConsumerGroup()));
   if (runningInfo) {
     if (requestHeader->isJstackEnable()) {
       /*string jstack = UtilAll::jstack();
@@ -142,21 +131,63 @@
   }
 
   SessionCredentials sessionCredentials;
-  m_mqClientFactory->getSessionCredentialFromConsumer(
-      requestHeader->getConsumerGroup(), sessionCredentials);
+  m_mqClientFactory->getSessionCredentialFromConsumer(requestHeader->getConsumerGroup(), sessionCredentials);
   ClientRPCHook rpcHook(sessionCredentials);
   rpcHook.doBeforeRequest(addr, *pResponse);
   pResponse->Encode();
   return pResponse;
 }
 
-RemotingCommand* ClientRemotingProcessor::notifyConsumerIdsChanged(
-    RemotingCommand* request) {
+RemotingCommand* ClientRemotingProcessor::notifyConsumerIdsChanged(RemotingCommand* request) {
   request->SetExtHeader(request->getCode());
   NotifyConsumerIdsChangedRequestHeader* requestHeader =
       (NotifyConsumerIdsChangedRequestHeader*)request->getCommandHeader();
-  LOG_INFO("notifyConsumerIdsChanged:%s", requestHeader->getGroup().c_str());
+  if (requestHeader == nullptr) {
+    LOG_ERROR("notifyConsumerIdsChanged requestHeader null");
+    return NULL;
+  }
+  string group = requestHeader->getGroup();
+  LOG_INFO("notifyConsumerIdsChanged:%s", group.c_str());
   m_mqClientFactory->doRebalanceByConsumerGroup(requestHeader->getGroup());
   return NULL;
 }
+
+RemotingCommand* ClientRemotingProcessor::checkTransactionState(const std::string& addr, RemotingCommand* request) {
+  if (!request) {
+    LOG_ERROR("checkTransactionState request null");
+    return nullptr;
+  }
+
+  LOG_INFO("checkTransactionState addr:%s, request: %s", addr.data(), request->ToString().data());
+
+  request->SetExtHeader(request->getCode());
+  CheckTransactionStateRequestHeader* requestHeader = (CheckTransactionStateRequestHeader*)request->getCommandHeader();
+  if (!requestHeader) {
+    LOG_ERROR("checkTransactionState CheckTransactionStateRequestHeader requestHeader null");
+    return nullptr;
+  }
+  LOG_INFO("checkTransactionState request: %s", requestHeader->toString().data());
+
+  const MemoryBlock* block = request->GetBody();
+  if (block && block->getSize() > 0) {
+    std::vector<MQMessageExt> mqvec;
+    MQDecoder::decodes(block, mqvec);
+    if (mqvec.size() == 0) {
+      LOG_ERROR("checkTransactionState decodes MQMessageExt fail, request:%s", requestHeader->toString().data());
+      return nullptr;
+    }
+
+    MQMessageExt& messageExt = mqvec[0];
+    string transactionId = messageExt.getProperty(MQMessage::PROPERTY_UNIQ_CLIENT_MESSAGE_ID_KEYIDX);
+    if (transactionId != "") {
+      messageExt.setTransactionId(transactionId);
+    }
+
+    m_mqClientFactory->checkTransactionState(addr, messageExt, *requestHeader);
+  } else {
+    LOG_ERROR("checkTransactionState getbody null or size 0, request Header:%s", requestHeader->toString().data());
+  }
+  return nullptr;
 }
+
+}  // namespace rocketmq
diff --git a/src/transport/ClientRemotingProcessor.h b/src/transport/ClientRemotingProcessor.h
old mode 100755
new mode 100644
index c4d4ce6..c88b8bb
--- a/src/transport/ClientRemotingProcessor.h
+++ b/src/transport/ClientRemotingProcessor.h
@@ -31,9 +31,9 @@
 
   RemotingCommand* processRequest(const string& addr, RemotingCommand* request);
   RemotingCommand* resetOffset(RemotingCommand* request);
-  RemotingCommand* getConsumerRunningInfo(const string& addr,
-                                          RemotingCommand* request);
+  RemotingCommand* getConsumerRunningInfo(const string& addr, RemotingCommand* request);
   RemotingCommand* notifyConsumerIdsChanged(RemotingCommand* request);
+  RemotingCommand* checkTransactionState(const string& addr, RemotingCommand* request);
 
  private:
   MQClientFactory* m_mqClientFactory;
@@ -50,6 +50,18 @@
  private:
   std::map<MQMessageQueue, int64> m_offsetTable;
 };
+
+class CheckTransactionStateBody {
+ public:
+  CheckTransactionStateBody() {}
+  virtual ~CheckTransactionStateBody() { m_offsetTable.clear(); }
+  void setOffsetTable(MQMessageQueue mq, int64 offset);
+  std::map<MQMessageQueue, int64> getOffsetTable();
+  static ResetOffsetBody* Decode(const MemoryBlock* mem);
+
+ private:
+  std::map<MQMessageQueue, int64> m_offsetTable;
+};
 }
 
 #endif
diff --git a/src/transport/EventLoop.cpp b/src/transport/EventLoop.cpp
new file mode 100644
index 0000000..3d67405
--- /dev/null
+++ b/src/transport/EventLoop.cpp
@@ -0,0 +1,241 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include "EventLoop.h"
+
+#if !defined(WIN32) && !defined(__APPLE__)
+#include <sys/prctl.h>
+#endif
+
+#include <event2/thread.h>
+
+#include "Logging.h"
+#include "UtilAll.h"
+
+namespace rocketmq {
+
+EventLoop* EventLoop::GetDefaultEventLoop() {
+  static EventLoop defaultEventLoop;
+  return &defaultEventLoop;
+}
+
+EventLoop::EventLoop(const struct event_config* config, bool run_immediately)
+    : m_eventBase(nullptr), m_loopThread(nullptr), _is_running(false) {
+  // tell libevent support multi-threads
+#ifdef WIN32
+  evthread_use_windows_threads();
+#else
+  evthread_use_pthreads();
+#endif
+
+  if (config == nullptr) {
+    m_eventBase = event_base_new();
+  } else {
+    m_eventBase = event_base_new_with_config(config);
+  }
+
+  if (m_eventBase == nullptr) {
+    // failure...
+    LOG_ERROR("Failed to create event base!");
+    return;
+  }
+
+  evthread_make_base_notifiable(m_eventBase);
+
+  if (run_immediately) {
+    start();
+  }
+}
+
+EventLoop::~EventLoop() {
+  stop();
+
+  if (m_eventBase != nullptr) {
+    event_base_free(m_eventBase);
+    m_eventBase = nullptr;
+  }
+}
+
+void EventLoop::start() {
+  if (m_loopThread == nullptr) {
+    // start event loop
+#if !defined(WIN32) && !defined(__APPLE__)
+    string taskName = UtilAll::getProcessName();
+    prctl(PR_SET_NAME, "EventLoop", 0, 0, 0);
+#endif
+    m_loopThread = new std::thread(&EventLoop::runLoop, this);
+#if !defined(WIN32) && !defined(__APPLE__)
+    prctl(PR_SET_NAME, taskName.c_str(), 0, 0, 0);
+#endif
+  }
+}
+
+void EventLoop::stop() {
+  if (m_loopThread != nullptr /*&& m_loopThread.joinable()*/) {
+    _is_running = false;
+    m_loopThread->join();
+
+    delete m_loopThread;
+    m_loopThread = nullptr;
+  }
+}
+
+void EventLoop::runLoop() {
+  _is_running = true;
+
+  while (_is_running) {
+    int ret;
+
+    ret = event_base_dispatch(m_eventBase);
+    //    ret = event_base_loop(m_eventBase, EVLOOP_NONBLOCK);
+
+    if (ret == 1) {
+      // no event
+      std::this_thread::sleep_for(std::chrono::milliseconds(1));
+    }
+  }
+}
+
+#define OPT_UNLOCK_CALLBACKS (BEV_OPT_DEFER_CALLBACKS | BEV_OPT_UNLOCK_CALLBACKS)
+
+BufferEvent* EventLoop::createBufferEvent(socket_t fd, int options) {
+  struct bufferevent* event = bufferevent_socket_new(m_eventBase, fd, options);
+  if (event == nullptr) {
+    return nullptr;
+  }
+
+  bool unlock = (options & OPT_UNLOCK_CALLBACKS) == OPT_UNLOCK_CALLBACKS;
+
+  return new BufferEvent(event, unlock);
+}
+
+BufferEvent::BufferEvent(struct bufferevent* event, bool unlockCallbacks)
+    : m_bufferEvent(event),
+      m_unlockCallbacks(unlockCallbacks),
+      m_readCallback(nullptr),
+      m_writeCallback(nullptr),
+      m_eventCallback(nullptr),
+      m_callbackTransport() {
+#ifdef ROCKETMQ_BUFFEREVENT_PROXY_ALL_CALLBACK
+  if (m_bufferEvent != nullptr) {
+    bufferevent_setcb(m_bufferEvent, read_callback, write_callback, event_callback, this);
+  }
+#endif  // ROCKETMQ_BUFFEREVENT_PROXY_ALL_CALLBACK
+}
+
+BufferEvent::~BufferEvent() {
+  if (m_bufferEvent != nullptr) {
+    // free function will set all callbacks to NULL first.
+    bufferevent_free(m_bufferEvent);
+    m_bufferEvent = nullptr;
+  }
+}
+
+void BufferEvent::setCallback(BufferEventDataCallback readCallback,
+                              BufferEventDataCallback writeCallback,
+                              BufferEventEventCallback eventCallback,
+                              std::shared_ptr<TcpTransport> transport) {
+  // use lock in bufferevent
+  bufferevent_lock(m_bufferEvent);
+
+  // wrap callback
+  m_readCallback = readCallback;
+  m_writeCallback = writeCallback;
+  m_eventCallback = eventCallback;
+  m_callbackTransport = transport;
+
+#ifndef ROCKETMQ_BUFFEREVENT_PROXY_ALL_CALLBACK
+  bufferevent_data_cb readcb = readCallback != nullptr ? read_callback : nullptr;
+  bufferevent_data_cb writecb = writeCallback != nullptr ? write_callback : nullptr;
+  bufferevent_event_cb eventcb = eventCallback != nullptr ? event_callback : nullptr;
+
+  bufferevent_setcb(m_bufferEvent, readcb, writecb, eventcb, this);
+#endif  // ROCKETMQ_BUFFEREVENT_PROXY_ALL_CALLBACK
+
+  bufferevent_unlock(m_bufferEvent);
+}
+
+void BufferEvent::read_callback(struct bufferevent* bev, void* ctx) {
+  auto event = static_cast<BufferEvent*>(ctx);
+
+  if (event->m_unlockCallbacks)
+    bufferevent_lock(event->m_bufferEvent);
+
+  BufferEventDataCallback callback = event->m_readCallback;
+  std::shared_ptr<TcpTransport> transport = event->m_callbackTransport.lock();
+
+  if (event->m_unlockCallbacks)
+    bufferevent_unlock(event->m_bufferEvent);
+
+  if (callback) {
+    callback(event, transport.get());
+  }
+}
+
+void BufferEvent::write_callback(struct bufferevent* bev, void* ctx) {
+  auto event = static_cast<BufferEvent*>(ctx);
+
+  if (event->m_unlockCallbacks)
+    bufferevent_lock(event->m_bufferEvent);
+
+  BufferEventDataCallback callback = event->m_writeCallback;
+  std::shared_ptr<TcpTransport> transport = event->m_callbackTransport.lock();
+
+  if (event->m_unlockCallbacks)
+    bufferevent_unlock(event->m_bufferEvent);
+
+  if (callback) {
+    callback(event, transport.get());
+  }
+}
+
+static std::string buildPeerAddrPort(socket_t fd) {
+  sockaddr_in addr;
+  socklen_t len = sizeof(addr);
+
+  getpeername(fd, (struct sockaddr*)&addr, &len);
+
+  LOG_DEBUG("socket: %d, addr: %s, port: %d", fd, inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
+  std::string addrPort(inet_ntoa(addr.sin_addr));
+  addrPort.append(":");
+  addrPort.append(UtilAll::to_string(ntohs(addr.sin_port)));
+
+  return addrPort;
+}
+
+void BufferEvent::event_callback(struct bufferevent* bev, short what, void* ctx) {
+  auto event = static_cast<BufferEvent*>(ctx);
+
+  if (what & BEV_EVENT_CONNECTED) {
+    socket_t fd = event->getfd();
+    event->m_peerAddrPort = buildPeerAddrPort(fd);
+  }
+
+  if (event->m_unlockCallbacks)
+    bufferevent_lock(event->m_bufferEvent);
+
+  BufferEventEventCallback callback = event->m_eventCallback;
+  std::shared_ptr<TcpTransport> transport = event->m_callbackTransport.lock();
+
+  if (event->m_unlockCallbacks)
+    bufferevent_unlock(event->m_bufferEvent);
+
+  if (callback) {
+    callback(event, what, transport.get());
+  }
+}
+
+}  // namespace rocketmq
diff --git a/src/transport/EventLoop.h b/src/transport/EventLoop.h
new file mode 100644
index 0000000..c974479
--- /dev/null
+++ b/src/transport/EventLoop.h
@@ -0,0 +1,117 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#ifndef __EVENTLOOP_H__
+#define __EVENTLOOP_H__
+
+#include <memory>
+#include <thread>
+
+#include <event2/buffer.h>
+#include <event2/bufferevent.h>
+#include <event2/event.h>
+
+#include "noncopyable.h"
+
+using socket_t = evutil_socket_t;
+
+namespace rocketmq {
+
+class BufferEvent;
+
+class EventLoop : public noncopyable {
+ public:
+  static EventLoop* GetDefaultEventLoop();
+
+ public:
+  explicit EventLoop(const struct event_config* config = nullptr, bool run_immediately = true);
+  virtual ~EventLoop();
+
+  void start();
+  void stop();
+
+  BufferEvent* createBufferEvent(socket_t fd, int options);
+
+ private:
+  void runLoop();
+
+ private:
+  struct event_base* m_eventBase;
+  std::thread* m_loopThread;
+
+  bool _is_running;  // aotmic is unnecessary
+};
+
+class TcpTransport;
+
+using BufferEventDataCallback = void (*)(BufferEvent* event, TcpTransport* transport);
+using BufferEventEventCallback = void (*)(BufferEvent* event, short what, TcpTransport* transport);
+
+class BufferEvent : public noncopyable {
+ public:
+  virtual ~BufferEvent();
+
+  void setCallback(BufferEventDataCallback readCallback,
+                   BufferEventDataCallback writeCallback,
+                   BufferEventEventCallback eventCallback,
+                   std::shared_ptr<TcpTransport> transport);
+
+  void setWatermark(short events, size_t lowmark, size_t highmark) {
+    bufferevent_setwatermark(m_bufferEvent, events, lowmark, highmark);
+  }
+
+  int enable(short event) { return bufferevent_enable(m_bufferEvent, event); }
+
+  int connect(const struct sockaddr* addr, int socklen) {
+    return bufferevent_socket_connect(m_bufferEvent, (struct sockaddr*)addr, socklen);
+  }
+
+  int write(const void* data, size_t size) { return bufferevent_write(m_bufferEvent, data, size); }
+
+  size_t read(void* data, size_t size) { return bufferevent_read(m_bufferEvent, data, size); }
+
+  struct evbuffer* getInput() {
+    return bufferevent_get_input(m_bufferEvent);
+  }
+
+  socket_t getfd() const { return bufferevent_getfd(m_bufferEvent); }
+
+  std::string getPeerAddrPort() const { return m_peerAddrPort; }
+
+ private:
+  BufferEvent(struct bufferevent* event, bool unlockCallbacks);
+  friend EventLoop;
+
+  static void read_callback(struct bufferevent* bev, void* ctx);
+  static void write_callback(struct bufferevent* bev, void* ctx);
+  static void event_callback(struct bufferevent* bev, short what, void* ctx);
+
+ private:
+  struct bufferevent* m_bufferEvent;
+  const bool m_unlockCallbacks;
+
+  BufferEventDataCallback m_readCallback;
+  BufferEventDataCallback m_writeCallback;
+  BufferEventEventCallback m_eventCallback;
+  std::weak_ptr<TcpTransport> m_callbackTransport;  // avoid reference cycle
+
+  // cache properties
+  std::string m_peerAddrPort;
+};
+
+}  // namespace rocketmq
+
+#endif  //__EVENTLOOP_H__
diff --git a/src/transport/ResponseFuture.cpp b/src/transport/ResponseFuture.cpp
index a304e3f..b0b2613 100755
--- a/src/transport/ResponseFuture.cpp
+++ b/src/transport/ResponseFuture.cpp
@@ -15,193 +15,159 @@
  * limitations under the License.
  */
 #include "ResponseFuture.h"
+
+#include <chrono>
+
 #include "Logging.h"
 #include "TcpRemotingClient.h"
 
 namespace rocketmq {
+
 //<!************************************************************************
-ResponseFuture::ResponseFuture(int requestCode, int opaque,
-                               TcpRemotingClient* powner, int64 timeout,
-                               bool bAsync /* = false */,
-                               AsyncCallbackWrap* pcall /* = NULL */) {
-  m_bAsync.store(bAsync);
-  m_requestCode = requestCode;
-  m_opaque = opaque;
-  m_timeout = timeout;
-  m_pCallbackWrap = pcall;
-  m_pResponseCommand = NULL;
-  m_sendRequestOK = false;
-  m_maxRetrySendTimes = 1;
-  m_retrySendTimes = 1;
+ResponseFuture::ResponseFuture(int requestCode,
+                               int opaque,
+                               TcpRemotingClient* powner,
+                               int64 timeout,
+                               bool bAsync,
+                               AsyncCallbackWrap* pCallback)
+    : m_requestCode(requestCode),
+      m_opaque(opaque),
+      m_timeout(timeout),
+      m_bAsync(bAsync),
+      m_pCallbackWrap(pCallback),
+      m_asyncCallbackStatus(ASYNC_CALLBACK_STATUS_INIT),
+      m_haveResponse(false),
+      m_sendRequestOK(false),
+      m_pResponseCommand(nullptr),
+      m_maxRetrySendTimes(1),
+      m_retrySendTimes(1) {
   m_brokerAddr = "";
   m_beginTimestamp = UtilAll::currentTimeMillis();
-  m_asyncCallbackStatus = asyncCallBackStatus_init;
-  if (getASyncFlag()) {
-    m_asyncResponse.store(false);
-    m_syncResponse.store(true);
-  } else {
-    m_asyncResponse.store(true);
-    m_syncResponse.store(false);
-  }
 }
 
 ResponseFuture::~ResponseFuture() {
   deleteAndZero(m_pCallbackWrap);
   /*
-    do not set m_pResponseCommand to NULL when destruct, as m_pResponseCommand
-    is used by MQClientAPIImpl concurrently, and will be released by producer or
-    consumer;
-    m_pResponseCommand = NULL;
-  */
+    do not delete m_pResponseCommand when destruct, as m_pResponseCommand
+    is used by MQClientAPIImpl concurrently, and will be released by producer or consumer;
+   */
 }
 
-void ResponseFuture::releaseThreadCondition() { m_defaultEvent.notify_all(); }
+void ResponseFuture::releaseThreadCondition() {
+  m_defaultEvent.notify_all();
+}
 
 RemotingCommand* ResponseFuture::waitResponse(int timeoutMillis) {
-  boost::unique_lock<boost::mutex> lk(m_defaultEventLock);
-  if (!m_defaultEvent.timed_wait(
-          lk, boost::posix_time::milliseconds(timeoutMillis))) {
-    LOG_WARN("waitResponse of code:%d with opaque:%d timeout", m_requestCode,
-             m_opaque);
-    m_syncResponse.store(true);
+  std::unique_lock<std::mutex> eventLock(m_defaultEventLock);
+  if (!m_haveResponse) {
+    if (timeoutMillis <= 0) {
+      timeoutMillis = m_timeout;
+    }
+    if (m_defaultEvent.wait_for(eventLock, std::chrono::milliseconds(timeoutMillis)) == std::cv_status::timeout) {
+      LOG_WARN("waitResponse of code:%d with opaque:%d timeout", m_requestCode, m_opaque);
+      m_haveResponse = true;
+    }
   }
   return m_pResponseCommand;
 }
 
-void ResponseFuture::setResponse(RemotingCommand* pResponseCommand) {
-  // LOG_DEBUG("setResponse of opaque:%d",m_opaque);
+bool ResponseFuture::setResponse(RemotingCommand* pResponseCommand) {
+  std::unique_lock<std::mutex> eventLock(m_defaultEventLock);
+
+  if (m_haveResponse) {
+    return false;
+  }
+
   m_pResponseCommand = pResponseCommand;
+  m_haveResponse = true;
 
-  if (!getASyncFlag()) {
-    if (m_syncResponse.load() == false) {
-      m_defaultEvent.notify_all();
-      m_syncResponse.store(true);
-    }
-  }
-}
-
-const bool ResponseFuture::getSyncResponseFlag() {
-  if (m_syncResponse.load() == true) {
-    return true;
-  }
-  return false;
-}
-
-const bool ResponseFuture::getAsyncResponseFlag() {
-  if (m_asyncResponse.load() == true) {
-    // LOG_DEBUG("ASYNC flag is TRUE,opaque is:%d",getOpaque() );
-    return true;
+  if (!getAsyncFlag()) {
+    m_defaultEvent.notify_all();
   }
 
-  return false;
+  return true;
 }
 
-void ResponseFuture::setAsyncResponseFlag() { m_asyncResponse.store(true); }
-
-const bool ResponseFuture::getASyncFlag() {
-  if (m_bAsync.load() == true) {
-    // LOG_DEBUG("ASYNC flag is TRUE,opaque is:%d",getOpaque() );
-    return true;
-  }
-  return false;
+const bool ResponseFuture::getAsyncFlag() {
+  return m_bAsync;
 }
 
-bool ResponseFuture::isSendRequestOK() { return m_sendRequestOK; }
+bool ResponseFuture::isSendRequestOK() const {
+  return m_sendRequestOK;
+}
 
 void ResponseFuture::setSendRequestOK(bool sendRequestOK) {
   m_sendRequestOK = sendRequestOK;
 }
 
-int ResponseFuture::getOpaque() const { return m_opaque; }
-
-int ResponseFuture::getRequestCode() const { return m_requestCode; }
-
-void ResponseFuture::setAsyncCallBackStatus(
-    asyncCallBackStatus asyncCallbackStatus) {
-  boost::lock_guard<boost::mutex> lock(m_asyncCallbackLock);
-  if (m_asyncCallbackStatus == asyncCallBackStatus_init) {
-    m_asyncCallbackStatus = asyncCallbackStatus;
-  }
+int ResponseFuture::getOpaque() const {
+  return m_opaque;
 }
 
-void ResponseFuture::executeInvokeCallback() {
-  if (m_pCallbackWrap == NULL) {
+int ResponseFuture::getRequestCode() const {
+  return m_requestCode;
+}
+
+void ResponseFuture::invokeCompleteCallback() {
+  if (m_pCallbackWrap == nullptr) {
     deleteAndZero(m_pResponseCommand);
     return;
   } else {
-    if (m_asyncCallbackStatus == asyncCallBackStatus_response) {
-      m_pCallbackWrap->operationComplete(this, true);
-    } else {
-      if (m_pResponseCommand)
-        deleteAndZero(m_pResponseCommand);  // the responseCommand from
-                                            // RemotingCommand::Decode(mem) will
-                                            // only deleted by operationComplete
-                                            // automatically
-      LOG_WARN(
-          "timeout and response incoming concurrently of opaque:%d, and "
-          "executeInvokeCallbackException was called earlier",
-          m_opaque);
-    }
+    m_pCallbackWrap->operationComplete(this, true);
   }
 }
 
-void ResponseFuture::executeInvokeCallbackException() {
-  if (m_pCallbackWrap == NULL) {
+void ResponseFuture::invokeExceptionCallback() {
+  if (m_pCallbackWrap == nullptr) {
     LOG_ERROR("m_pCallbackWrap is NULL, critical error");
     return;
   } else {
-    if (m_asyncCallbackStatus == asyncCallBackStatus_timeout) {
+    // here no need retrySendTimes process because of it have timeout
+    LOG_ERROR("send msg, callback timeout, opaque:%d, sendTimes:%d, maxRetryTimes:%d", getOpaque(), getRetrySendTimes(),
+              getMaxRetrySendTimes());
 
-    //here no need retrySendTimes process because of it have timeout
-    LOG_ERROR("send msg, callback timeout, opaque:%d, sendTimes:%d, maxRetryTimes:%d", getOpaque(), getRetrySendTimes(), getMaxRetrySendTimes());
-
-      m_pCallbackWrap->onException();
-    } else {
-      LOG_WARN(
-          "timeout and response incoming concurrently of opaque:%d, and "
-          "executeInvokeCallback was called earlier",
-          m_opaque);
-    }
+    m_pCallbackWrap->onException();
   }
 }
 
 bool ResponseFuture::isTimeOut() const {
   int64 diff = UtilAll::currentTimeMillis() - m_beginTimestamp;
   //<!only async;
-  return m_bAsync.load() == 1 && diff > m_timeout;
+  return m_bAsync && diff > m_timeout;
 }
 
 int ResponseFuture::getMaxRetrySendTimes() const {
-    return m_maxRetrySendTimes;
-} 
+  return m_maxRetrySendTimes;
+}
 int ResponseFuture::getRetrySendTimes() const {
-    return m_retrySendTimes;
+  return m_retrySendTimes;
 }
 
 void ResponseFuture::setMaxRetrySendTimes(int maxRetryTimes) {
-    m_maxRetrySendTimes = maxRetryTimes;
+  m_maxRetrySendTimes = maxRetryTimes;
 }
 void ResponseFuture::setRetrySendTimes(int retryTimes) {
-    m_retrySendTimes = retryTimes;
+  m_retrySendTimes = retryTimes;
 }
 
 void ResponseFuture::setBrokerAddr(const std::string& brokerAddr) {
-    m_brokerAddr = brokerAddr;
-}
-void ResponseFuture::setRequestCommand(const RemotingCommand& requestCommand) {
-    m_requestCommand = requestCommand;
+  m_brokerAddr = brokerAddr;
 }
 
-const RemotingCommand& ResponseFuture::getRequestCommand() {
-    return m_requestCommand;
-}
 std::string ResponseFuture::getBrokerAddr() const {
-    return m_brokerAddr;
+  return m_brokerAddr;
+}
+
+void ResponseFuture::setRequestCommand(const RemotingCommand& requestCommand) {
+  m_requestCommand = requestCommand;
+}
+const RemotingCommand& ResponseFuture::getRequestCommand() {
+  return m_requestCommand;
 }
 
 int64 ResponseFuture::leftTime() const {
-    int64 diff = UtilAll::currentTimeMillis() - m_beginTimestamp;
-    return m_timeout - diff;
+  int64 diff = UtilAll::currentTimeMillis() - m_beginTimestamp;
+  return m_timeout - diff;
 }
 
 RemotingCommand* ResponseFuture::getCommand() const {
@@ -213,4 +179,4 @@
 }
 
 //<!************************************************************************
-}  //<!end namespace;
+}  // namespace rocketmq
diff --git a/src/transport/ResponseFuture.h b/src/transport/ResponseFuture.h
index 6564f53..66be663 100755
--- a/src/transport/ResponseFuture.h
+++ b/src/transport/ResponseFuture.h
@@ -16,81 +16,89 @@
  */
 #ifndef __RESPONSEFUTURE_H__
 #define __RESPONSEFUTURE_H__
-#include <boost/atomic.hpp>
-#include <boost/thread/condition_variable.hpp>
+
+#include <atomic>
+#include <condition_variable>
+
 #include "AsyncCallbackWrap.h"
 #include "RemotingCommand.h"
 #include "UtilAll.h"
 
 namespace rocketmq {
 
-typedef enum asyncCallBackStatus {
-  asyncCallBackStatus_init = 0,
-  asyncCallBackStatus_response = 1,
-  asyncCallBackStatus_timeout = 2
-} asyncCallBackStatus;
+typedef enum AsyncCallbackStatus {
+  ASYNC_CALLBACK_STATUS_INIT = 0,
+  ASYNC_CALLBACK_STATUS_RESPONSE = 1,
+  ASYNC_CALLBACK_STATUS_TIMEOUT = 2
+} AsyncCallbAackStatus;
 
 class TcpRemotingClient;
 //<!***************************************************************************
 class ResponseFuture {
  public:
-  ResponseFuture(int requestCode, int opaque, TcpRemotingClient* powner,
-                 int64 timeoutMilliseconds, bool bAsync = false,
-                 AsyncCallbackWrap* pcall = NULL);
+  ResponseFuture(int requestCode,
+                 int opaque,
+                 TcpRemotingClient* powner,
+                 int64 timeoutMilliseconds,
+                 bool bAsync = false,
+                 AsyncCallbackWrap* pCallback = nullptr);
   virtual ~ResponseFuture();
+
   void releaseThreadCondition();
-  RemotingCommand* waitResponse(int timeoutMillis);
+  RemotingCommand* waitResponse(int timeoutMillis = 0);
   RemotingCommand* getCommand() const;
 
-  void setResponse(RemotingCommand* pResponseCommand);
-  bool isSendRequestOK();
+  bool setResponse(RemotingCommand* pResponseCommand);
+
+  bool isSendRequestOK() const;
   void setSendRequestOK(bool sendRequestOK);
   int getRequestCode() const;
   int getOpaque() const;
 
   //<!callback;
-  void executeInvokeCallback();
-  void executeInvokeCallbackException();
-  bool isTimeOut() const; 
-  int getMaxRetrySendTimes() const; 
-  int getRetrySendTimes() const;   
+  void invokeCompleteCallback();
+  void invokeExceptionCallback();
+  bool isTimeOut() const;
+  int getMaxRetrySendTimes() const;
+  int getRetrySendTimes() const;
   int64 leftTime() const;
-  // bool    isTimeOutMoreThan30s() const;
-  const bool getASyncFlag();
-  void setAsyncResponseFlag();
-  const bool getAsyncResponseFlag();
-  const bool getSyncResponseFlag();
+  const bool getAsyncFlag();
   AsyncCallbackWrap* getAsyncCallbackWrap();
-  void setAsyncCallBackStatus(asyncCallBackStatus asyncCallbackStatus);
-  void setMaxRetrySendTimes(int maxRetryTimes); 
-  void setRetrySendTimes(int retryTimes);   
-  void setBrokerAddr(const std::string& brokerAddr); 
+
+  void setMaxRetrySendTimes(int maxRetryTimes);
+  void setRetrySendTimes(int retryTimes);
+  void setBrokerAddr(const std::string& brokerAddr);
   void setRequestCommand(const RemotingCommand& requestCommand);
   const RemotingCommand& getRequestCommand();
   std::string getBrokerAddr() const;
+
  private:
   int m_requestCode;
   int m_opaque;
-  bool m_sendRequestOK;
-  boost::mutex m_defaultEventLock;
-  boost::condition_variable_any m_defaultEvent;
-  int64 m_beginTimestamp;
   int64 m_timeout;  // ms
-  boost::atomic<bool> m_bAsync;
-  RemotingCommand* m_pResponseCommand;  //<!delete outside;
-  AsyncCallbackWrap* m_pCallbackWrap;
-  boost::mutex m_asyncCallbackLock;
-  asyncCallBackStatus m_asyncCallbackStatus;
-  boost::atomic<bool> m_asyncResponse;
-  boost::atomic<bool> m_syncResponse;
 
-  int   m_maxRetrySendTimes;
-  int   m_retrySendTimes; 
+  const bool m_bAsync;
+  AsyncCallbackWrap* m_pCallbackWrap;
+
+  AsyncCallbackStatus m_asyncCallbackStatus;
+  std::mutex m_asyncCallbackLock;
+
+  bool m_haveResponse;
+  std::mutex m_defaultEventLock;
+  std::condition_variable m_defaultEvent;
+
+  int64 m_beginTimestamp;
+  bool m_sendRequestOK;
+  RemotingCommand* m_pResponseCommand;  //<!delete outside;
+
+  int m_maxRetrySendTimes;
+  int m_retrySendTimes;
+
   std::string m_brokerAddr;
   RemotingCommand m_requestCommand;
-  // TcpRemotingClient*    m_tcpRemoteClient;
 };
+
 //<!************************************************************************
-}  //<!end namespace;
+}  // namespace rocketmq
 
 #endif
diff --git a/src/transport/SocketUtil.cpp b/src/transport/SocketUtil.cpp
old mode 100755
new mode 100644
index d428f24..daa369c
--- a/src/transport/SocketUtil.cpp
+++ b/src/transport/SocketUtil.cpp
@@ -72,15 +72,18 @@
 #ifdef ENDIANMODE_BIG
   return v;
 #else
-  uint64 ret = ((v << 56) | ((v & 0xff00) << 40) | ((v & 0xff0000) << 24) |
-                ((v & 0xff000000) << 8) | ((v >> 8) & 0xff000000) |
-                ((v >> 24) & 0xff0000) | ((v >> 40) & 0xff00) | (v >> 56));
+  uint64 ret = ((v << 56) | ((v & 0xff00) << 40) | ((v & 0xff0000) << 24) | ((v & 0xff000000) << 8) |
+                ((v >> 8) & 0xff000000) | ((v >> 24) & 0xff0000) | ((v >> 40) & 0xff00) | (v >> 56));
 
   return ret;
 #endif
 }
 
-uint64 h2nll(uint64 v) { return swapll(v); }
+uint64 h2nll(uint64 v) {
+  return swapll(v);
+}
 
-uint64 n2hll(uint64 v) { return swapll(v); }
+uint64 n2hll(uint64 v) {
+  return swapll(v);
+}
 }  //<!end namespace;
diff --git a/src/transport/SocketUtil.h b/src/transport/SocketUtil.h
old mode 100755
new mode 100644
diff --git a/src/transport/TcpRemotingClient.cpp b/src/transport/TcpRemotingClient.cpp
index 7b9dff9..1708151 100755
--- a/src/transport/TcpRemotingClient.cpp
+++ b/src/transport/TcpRemotingClient.cpp
@@ -1,758 +1,642 @@
-/*

- * Licensed to the Apache Software Foundation (ASF) under one or more

- * contributor license agreements.  See the NOTICE file distributed with

- * this work for additional information regarding copyright ownership.

- * The ASF licenses this file to You under the Apache License, Version 2.0

- * (the "License"); you may not use this file except in compliance with

- * the License.  You may obtain a copy of the License at

- *

- *     http://www.apache.org/licenses/LICENSE-2.0

- *

- * Unless required by applicable law or agreed to in writing, software

- * distributed under the License is distributed on an "AS IS" BASIS,

- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- * See the License for the specific language governing permissions and

- * limitations under the License.

- */

-#include "TcpRemotingClient.h"

-#include <stddef.h>

-#if !defined(WIN32) && !defined(__APPLE__)

-#include <sys/prctl.h>

-#endif

-#include "Logging.h"

-#include "MemoryOutputStream.h"

-#include "TopAddressing.h"

-#include "UtilAll.h"

-

-namespace rocketmq {

-

-//<!************************************************************************

-TcpRemotingClient::TcpRemotingClient(int pullThreadNum,

-                                     uint64_t tcpConnectTimeout,

-                                     uint64_t tcpTransportTryLockTimeout)

-    : m_pullThreadNum(pullThreadNum),

-      m_tcpConnectTimeout(tcpConnectTimeout),

-      m_tcpTransportTryLockTimeout(tcpTransportTryLockTimeout),

-      m_namesrvIndex(0),

-      m_ioServiceWork(m_ioService) {

-#if !defined(WIN32) && !defined(__APPLE__)  

-  string taskName = UtilAll::getProcessName();

-  prctl(PR_SET_NAME, "networkTP", 0, 0, 0);

-#endif

-  for (int i = 0; i != pullThreadNum; ++i) {

-    m_threadpool.create_thread(

-        boost::bind(&boost::asio::io_service::run, &m_ioService));

-  }

-#if !defined(WIN32) && !defined(__APPLE__)

-  prctl(PR_SET_NAME, taskName.c_str(), 0, 0, 0);

-#endif

-  LOG_INFO(

-      "m_tcpConnectTimeout:%ju, m_tcpTransportTryLockTimeout:%ju, "

-      "m_pullThreadNum:%d",

-      m_tcpConnectTimeout, m_tcpTransportTryLockTimeout, m_pullThreadNum);

-  m_async_service_thread.reset(new boost::thread(

-      boost::bind(&TcpRemotingClient::boost_asio_work, this)));

-}

-

-void TcpRemotingClient::boost_asio_work() {

-  LOG_INFO("TcpRemotingClient::boost asio async service runing");

-  boost::asio::io_service::work work(m_async_ioService);  // avoid async io

-                                                          // service stops after

-                                                          // first timer timeout

-                                                          // callback

-  m_async_ioService.run();

-}

-

-TcpRemotingClient::~TcpRemotingClient() {

-  m_tcpTable.clear();

-  m_futureTable.clear();

-  m_asyncFutureTable.clear();

-  m_namesrvAddrList.clear();

-  removeAllTimerCallback();

-}

-

-void TcpRemotingClient::stopAllTcpTransportThread() {

-  LOG_DEBUG("TcpRemotingClient::stopAllTcpTransportThread Begin");

-  m_async_ioService.stop();

-  m_async_service_thread->interrupt();

-  m_async_service_thread->join();

-  removeAllTimerCallback();

-

-  {

-    TcpMap::iterator it = m_tcpTable.begin();

-    for (; it != m_tcpTable.end(); ++it) {

-      it->second->disconnect(it->first);

-    }

-    m_tcpTable.clear();

-  }

-

-  m_ioService.stop();

-  m_threadpool.join_all();

-

-  {

-    boost::lock_guard<boost::mutex> lock(m_futureTableMutex);

-    for (ResMap::iterator it = m_futureTable.begin(); it != m_futureTable.end();

-         ++it) {

-      if (it->second) it->second->releaseThreadCondition();

-    }

-  }

-  LOG_DEBUG("TcpRemotingClient::stopAllTcpTransportThread End");

-}

-

-void TcpRemotingClient::updateNameServerAddressList(const string& addrs) {

-  if (!addrs.empty()) {

-    boost::unique_lock<boost::timed_mutex> lock(m_namesrvlock,

-                                                boost::try_to_lock);

-    if (!lock.owns_lock()) {

-      if (!lock.timed_lock(boost::get_system_time() +

-                           boost::posix_time::seconds(10))) {

-        LOG_ERROR("updateNameServerAddressList get timed_mutex timeout");

-        return;

-      }

-    }

-    // clear first;

-    m_namesrvAddrList.clear();

-

-    vector<string> out;

-    UtilAll::Split(out, addrs, ";");

-    for (size_t i = 0; i < out.size(); i++) {

-      string addr = out[i];

-      UtilAll::Trim(addr);

-

-      string hostName;

-      short portNumber;

-      if (UtilAll::SplitURL(addr, hostName, portNumber)) {

-        LOG_INFO("update Namesrv:%s", addr.c_str());

-        m_namesrvAddrList.push_back(addr);

-      }

-    }

-    out.clear();

-  }

-}

-

-bool TcpRemotingClient::invokeHeartBeat(const string& addr,

-                                        RemotingCommand& request) {

-  boost::shared_ptr<TcpTransport> pTcp = GetTransport(addr, true);

-  if (pTcp != NULL) {

-    int code = request.getCode();

-    int opaque = request.getOpaque();

-    boost::shared_ptr<ResponseFuture> responseFuture(

-        new ResponseFuture(code, opaque, this, 3000, false, NULL));

-    addResponseFuture(opaque, responseFuture);

-    // LOG_INFO("invokeHeartbeat success, addr:%s, code:%d, opaque:%d,

-    // timeoutms:%d", addr.c_str(), code, opaque, 3000);

-

-    if (SendCommand(pTcp, request)) {

-      responseFuture->setSendRequestOK(true);

-      unique_ptr<RemotingCommand> pRsp(responseFuture->waitResponse(3000));

-      if (pRsp == NULL) {

-        LOG_ERROR(

-            "wait response timeout of heartbeat, so closeTransport of addr:%s",

-            addr.c_str());

-        CloseTransport(addr, pTcp);

-        return false;

-      } else if (pRsp->getCode() == SUCCESS_VALUE) {

-        return true;

-      } else {

-        LOG_WARN("get error response:%d of heartbeat to addr:%s",

-                 pRsp->getCode(), addr.c_str());

-        return false;

-      }

-    } else {

-      CloseTransport(addr, pTcp);

-    }

-  }

-  return false;

-}

-

-RemotingCommand* TcpRemotingClient::invokeSync(const string& addr,

-                                               RemotingCommand& request,

-                                               int timeoutMillis /* = 3000 */) {

-  boost::shared_ptr<TcpTransport> pTcp = GetTransport(addr, true);

-  if (pTcp != NULL) {

-    int code = request.getCode();

-    int opaque = request.getOpaque();

-    boost::shared_ptr<ResponseFuture> responseFuture(

-        new ResponseFuture(code, opaque, this, timeoutMillis, false, NULL));

-    addResponseFuture(opaque, responseFuture);

-

-    if (SendCommand(pTcp, request)) {

-      // LOG_INFO("invokeSync success, addr:%s, code:%d, opaque:%d,

-      // timeoutms:%d", addr.c_str(), code, opaque, timeoutMillis);

-      responseFuture->setSendRequestOK(true);

-      RemotingCommand* pRsp = responseFuture->waitResponse(timeoutMillis);

-      if (pRsp == NULL) {

-        if (code != GET_CONSUMER_LIST_BY_GROUP) {

-          LOG_WARN(

-              "wait response timeout or get NULL response of code:%d, so "

-              "closeTransport of addr:%s",

-              code, addr.c_str());

-          CloseTransport(addr, pTcp);

-        }

-        // avoid responseFuture leak;

-        findAndDeleteResponseFuture(opaque);

-        return NULL;

-      } else {

-        return pRsp;

-      }

-    } else {

-      // avoid responseFuture leak;

-      findAndDeleteResponseFuture(opaque);

-      CloseTransport(addr, pTcp);

-    }

-  }

-  return NULL;

-}

-

-bool TcpRemotingClient::invokeAsync(const string& addr,

-                                    RemotingCommand& request,

-                                    AsyncCallbackWrap* cbw,

-                                    int64 timeoutMilliseconds,

-                                    int maxRetrySendTimes,

-                                    int retrySendTimes) {

-  boost::shared_ptr<TcpTransport> pTcp = GetTransport(addr, true);

-  if (pTcp != NULL) {

-    //<!not delete, for callback to delete;

-    int code = request.getCode();

-    int opaque = request.getOpaque();

-    boost::shared_ptr<ResponseFuture> responseFuture(

-        new ResponseFuture(code, opaque, this, timeoutMilliseconds, true, cbw));

-    responseFuture->setMaxRetrySendTimes(maxRetrySendTimes);

-    responseFuture->setRetrySendTimes(retrySendTimes);

-    responseFuture->setBrokerAddr(addr);

-    responseFuture->setRequestCommand(request);    

-    addAsyncResponseFuture(opaque, responseFuture);

-    if (cbw) {

-      boost::asio::deadline_timer* t = new boost::asio::deadline_timer(

-          m_async_ioService,

-          boost::posix_time::milliseconds(timeoutMilliseconds));

-      addTimerCallback(t, opaque);

-      boost::system::error_code e;

-      t->async_wait(

-          boost::bind(&TcpRemotingClient::handleAsyncPullForResponseTimeout,

-                      this, e, opaque));

-    }

-

-    if (SendCommand(pTcp, request))  // Even if send failed, asyncTimerThread

-                                     // will trigger next pull request or report

-                                     // send msg failed

-    {

-      LOG_DEBUG("invokeAsync success, addr:%s, code:%d, opaque:%d",

-                addr.c_str(), code, opaque);

-      responseFuture->setSendRequestOK(true);

-    }

-    return true;

-  }

-  LOG_ERROR("invokeAsync failed of addr:%s", addr.c_str());

-  return false;

-}

-

-void TcpRemotingClient::invokeOneway(const string& addr,

-                                     RemotingCommand& request) {

-  //<!not need callback;

-  boost::shared_ptr<TcpTransport> pTcp = GetTransport(addr, true);

-  if (pTcp != NULL) {

-    request.markOnewayRPC();

-    LOG_DEBUG("invokeOneway success, addr:%s, code:%d", addr.c_str(),

-              request.getCode());

-    SendCommand(pTcp, request);

-  }

-}

-

-boost::shared_ptr<TcpTransport> TcpRemotingClient::GetTransport(

-    const string& addr, bool needRespons) {

-  if (addr.empty()) return CreateNameserverTransport(needRespons);

-

-  return CreateTransport(addr, needRespons);

-}

-

-boost::shared_ptr<TcpTransport> TcpRemotingClient::CreateTransport(

-    const string& addr, bool needRespons) {

-  boost::shared_ptr<TcpTransport> tts;

-  {

-    // try get m_tcpLock util m_tcpTransportTryLockTimeout to avoid blocking

-    // long

-    // time, if could not get m_tcpLock, return NULL

-    bool bGetMutex = false;

-    boost::unique_lock<boost::timed_mutex> lock(m_tcpLock, boost::try_to_lock);

-    if (!lock.owns_lock()) {

-      if (!lock.timed_lock(

-              boost::get_system_time() +

-              boost::posix_time::seconds(m_tcpTransportTryLockTimeout))) {

-        LOG_ERROR("GetTransport of:%s get timed_mutex timeout", addr.c_str());

-        boost::shared_ptr<TcpTransport> pTcp;

-        return pTcp;

-      } else {

-        bGetMutex = true;

-      }

-    } else {

-      bGetMutex = true;

-    }

-    if (bGetMutex) {

-      if (m_tcpTable.find(addr) != m_tcpTable.end()) {

-        boost::weak_ptr<TcpTransport> weakPtcp(m_tcpTable[addr]);

-        boost::shared_ptr<TcpTransport> tcp = weakPtcp.lock();

-        if (tcp) {

-          tcpConnectStatus connectStatus = tcp->getTcpConnectStatus();

-          if (connectStatus == e_connectWaitResponse) {

-            boost::shared_ptr<TcpTransport> pTcp;

-            return pTcp;

-          } else if (connectStatus == e_connectFail) {

-            LOG_ERROR("tcpTransport with server disconnected, erase server:%s",

-                      addr.c_str());

-            tcp->disconnect(

-                addr);  // avoid coredump when connection with broker was broken

-            m_tcpTable.erase(addr);

-          } else if (connectStatus == e_connectSuccess) {

-            return tcp;

-          } else {

-            LOG_ERROR(

-                "go to fault state, erase:%s from tcpMap, and reconnect "

-                "it",

-                addr.c_str());

-            m_tcpTable.erase(addr);

-          }

-        }

-      }

-

-      //<!callback;

-      READ_CALLBACK callback =

-          needRespons ? &TcpRemotingClient::static_messageReceived : NULL;

-

-      tts.reset(new TcpTransport(this, callback));

-      tcpConnectStatus connectStatus = tts->connect(addr, m_tcpConnectTimeout);

-      if (connectStatus != e_connectWaitResponse) {

-        LOG_WARN("can not connect to :%s", addr.c_str());

-        tts->disconnect(addr);

-        boost::shared_ptr<TcpTransport> pTcp;

-        return pTcp;

-      } else {

-        m_tcpTable[addr] = tts;  // even if connecting failed finally, this

-                                 // server transport will be erased by next

-                                 // CreateTransport

-      }

-    } else {

-      LOG_WARN("get tcpTransport mutex failed :%s", addr.c_str());

-      boost::shared_ptr<TcpTransport> pTcp;

-      return pTcp;

-    }

-  }

-

-  tcpConnectStatus connectStatus =

-      tts->waitTcpConnectEvent(m_tcpConnectTimeout);

-  if (connectStatus != e_connectSuccess) {

-    LOG_WARN("can not connect to server:%s", addr.c_str());

-    tts->disconnect(addr);

-    boost::shared_ptr<TcpTransport> pTcp;

-    return pTcp;

-  } else {

-    LOG_INFO("connect server with addr:%s success", addr.c_str());

-    return tts;

-  }

-}

-

-boost::shared_ptr<TcpTransport> TcpRemotingClient::CreateNameserverTransport(

-    bool needRespons) {

-  // m_namesrvLock was added to avoid operation of nameServer was blocked by

-  // m_tcpLock, it was used by single Thread mostly, so no performance impact

-  // try get m_tcpLock util m_tcpTransportTryLockTimeout to avoid blocking long

-  // time, if could not get m_namesrvlock, return NULL

-  bool bGetMutex = false;

-  boost::unique_lock<boost::timed_mutex> lock(m_namesrvlock,

-                                              boost::try_to_lock);

-  if (!lock.owns_lock()) {

-    if (!lock.timed_lock(

-            boost::get_system_time() +

-            boost::posix_time::seconds(m_tcpTransportTryLockTimeout))) {

-      LOG_ERROR("CreateNameserverTransport get timed_mutex timeout");

-      boost::shared_ptr<TcpTransport> pTcp;

-      return pTcp;

-    } else {

-      bGetMutex = true;

-    }

-  } else {

-    bGetMutex = true;

-  }

-

-  if (bGetMutex) {

-    if (!m_namesrvAddrChoosed.empty()) {

-      boost::shared_ptr<TcpTransport> pTcp =

-          GetTransport(m_namesrvAddrChoosed, true);

-      if (pTcp)

-        return pTcp;

-      else

-        m_namesrvAddrChoosed.clear();

-    }

-

-    vector<string>::iterator itp = m_namesrvAddrList.begin();

-    for (; itp != m_namesrvAddrList.end(); ++itp) {

-      unsigned int index = m_namesrvIndex % m_namesrvAddrList.size();

-      if (m_namesrvIndex == numeric_limits<unsigned int>::max())

-        m_namesrvIndex = 0;

-      m_namesrvIndex++;

-      LOG_INFO("namesrvIndex is:%d, index:%d, namesrvaddrlist size:" SIZET_FMT

-               "",

-               m_namesrvIndex, index, m_namesrvAddrList.size());

-      boost::shared_ptr<TcpTransport> pTcp =

-          GetTransport(m_namesrvAddrList[index], true);

-      if (pTcp) {

-        m_namesrvAddrChoosed = m_namesrvAddrList[index];

-        return pTcp;

-      }

-    }

-    boost::shared_ptr<TcpTransport> pTcp;

-    return pTcp;

-  } else {

-    LOG_WARN("get nameServer tcpTransport mutex failed");

-    boost::shared_ptr<TcpTransport> pTcp;

-    return pTcp;

-  }

-}

-

-void TcpRemotingClient::CloseTransport(const string& addr,

-                                       boost::shared_ptr<TcpTransport> pTcp) {

-  if (addr.empty()) {

-    return CloseNameServerTransport(pTcp);

-  }

-

-  bool bGetMutex = false;

-  boost::unique_lock<boost::timed_mutex> lock(m_tcpLock, boost::try_to_lock);

-  if (!lock.owns_lock()) {

-    if (!lock.timed_lock(

-            boost::get_system_time() +

-            boost::posix_time::seconds(m_tcpTransportTryLockTimeout))) {

-      LOG_ERROR("CloseTransport of:%s get timed_mutex timeout", addr.c_str());

-      return;

-    } else {

-      bGetMutex = true;

-    }

-  } else {

-    bGetMutex = true;

-  }

-  LOG_ERROR("CloseTransport of:%s", addr.c_str());

-  if (bGetMutex) {

-    bool removeItemFromTable = true;

-    if (m_tcpTable.find(addr) != m_tcpTable.end()) {

-      if (m_tcpTable[addr]->getStartTime() != pTcp->getStartTime()) {

-        LOG_INFO(

-            "tcpTransport with addr:%s has been closed before, and has been "

-            "created again, nothing to do",

-            addr.c_str());

-        removeItemFromTable = false;

-      }

-    } else {

-      LOG_INFO(

-          "tcpTransport with addr:%s had been removed from tcpTable before",

-          addr.c_str());

-      removeItemFromTable = false;

-    }

-

-    if (removeItemFromTable == true) {

-      LOG_WARN("closeTransport: disconnect broker:%s with state:%d",

-               addr.c_str(), m_tcpTable[addr]->getTcpConnectStatus());

-      if (m_tcpTable[addr]->getTcpConnectStatus() == e_connectSuccess)

-        m_tcpTable[addr]->disconnect(

-            addr);  // avoid coredump when connection with server was broken

-      LOG_WARN("closeTransport: erase broker: %s", addr.c_str());

-      m_tcpTable.erase(addr);

-    }

-  } else {

-    LOG_WARN("CloseTransport::get tcpTransport mutex failed:%s", addr.c_str());

-    return;

-  }

-  LOG_ERROR("CloseTransport of:%s end", addr.c_str());

-}

-

-void TcpRemotingClient::CloseNameServerTransport(

-    boost::shared_ptr<TcpTransport> pTcp) {

-  bool bGetMutex = false;

-  boost::unique_lock<boost::timed_mutex> lock(m_namesrvlock,

-                                              boost::try_to_lock);

-  if (!lock.owns_lock()) {

-    if (!lock.timed_lock(

-            boost::get_system_time() +

-            boost::posix_time::seconds(m_tcpTransportTryLockTimeout))) {

-      LOG_ERROR("CreateNameserverTransport get timed_mutex timeout");

-      return;

-    } else {

-      bGetMutex = true;

-    }

-  } else {

-    bGetMutex = true;

-  }

-  if (bGetMutex) {

-    string addr = m_namesrvAddrChoosed;

-    bool removeItemFromTable = true;

-    if (m_tcpTable.find(addr) != m_tcpTable.end()) {

-      if (m_tcpTable[addr]->getStartTime() != pTcp->getStartTime()) {

-        LOG_INFO(

-            "tcpTransport with addr:%s has been closed before, and has been "

-            "created again, nothing to do",

-            addr.c_str());

-        removeItemFromTable = false;

-      }

-    } else {

-      LOG_INFO(

-          "tcpTransport with addr:%s had been removed from tcpTable before",

-          addr.c_str());

-      removeItemFromTable = false;

-    }

-

-    if (removeItemFromTable == true) {

-      m_tcpTable[addr]->disconnect(

-          addr);  // avoid coredump when connection with server was broken

-      LOG_WARN("closeTransport: erase broker: %s", addr.c_str());

-      m_tcpTable.erase(addr);

-      m_namesrvAddrChoosed.clear();

-    }

-  } else {

-    LOG_WARN("CloseNameServerTransport::get tcpTransport mutex failed:%s",

-             m_namesrvAddrChoosed.c_str());

-    return;

-  }

-}

-

-bool TcpRemotingClient::SendCommand(boost::shared_ptr<TcpTransport> pTts,

-                                    RemotingCommand& msg) {

-  const MemoryBlock* phead = msg.GetHead();

-  const MemoryBlock* pbody = msg.GetBody();

-

-  unique_ptr<MemoryOutputStream> result(new MemoryOutputStream(1024));

-  if (phead->getData()) {

-    result->write(phead->getData(), phead->getSize());

-  }

-  if (pbody->getData()) {

-    result->write(pbody->getData(), pbody->getSize());

-  }

-  const char* pData = static_cast<const char*>(result->getData());

-  int len = result->getDataSize();

-  return pTts->sendMessage(pData, len);

-}

-

-void TcpRemotingClient::static_messageReceived(void* context,

-                                               const MemoryBlock& mem,

-                                               const string& addr) {

-  TcpRemotingClient* pTcpRemotingClient = (TcpRemotingClient*)context;

-  if (pTcpRemotingClient) pTcpRemotingClient->messageReceived(mem, addr);

-}

-

-void TcpRemotingClient::messageReceived(const MemoryBlock& mem,

-                                        const string& addr) {

-  m_ioService.post(

-      boost::bind(&TcpRemotingClient::ProcessData, this, mem, addr));

-}

-

-void TcpRemotingClient::ProcessData(const MemoryBlock& mem,

-                                    const string& addr) {

-  RemotingCommand* pRespondCmd = NULL;

-  try {

-    pRespondCmd = RemotingCommand::Decode(mem);

-  } catch (...) {

-    LOG_ERROR("processData_error");

-    return;

-  }

-

-  int opaque = pRespondCmd->getOpaque();

-

-  //<!process self;

-  if (pRespondCmd->isResponseType()) {

-    boost::shared_ptr<ResponseFuture> pFuture(

-        findAndDeleteAsyncResponseFuture(opaque));

-    if (!pFuture) {

-      pFuture = findAndDeleteResponseFuture(opaque);

-      if (pFuture) {

-        if (pFuture->getSyncResponseFlag()) {

-          LOG_WARN("waitResponse already timeout of opaque:%d", opaque);

-          deleteAndZero(pRespondCmd);

-          return;

-        }

-        LOG_DEBUG("find_response opaque:%d", opaque);

-      } else {

-        LOG_DEBUG("responseFuture was deleted by timeout of opaque:%d", opaque);

-        deleteAndZero(pRespondCmd);

-        return;

-      }

-    }

-    processResponseCommand(pRespondCmd, pFuture);

-  } else {

-    processRequestCommand(pRespondCmd, addr);

-  }

-}

-

-void TcpRemotingClient::processResponseCommand(

-    RemotingCommand* pCmd, boost::shared_ptr<ResponseFuture> pfuture) {

-  int code = pfuture->getRequestCode();

-  int opaque = pCmd->getOpaque();

-  LOG_DEBUG("processResponseCommand, code:%d,opaque:%d, maxRetryTimes:%d, retrySendTimes:%d", code, opaque, pfuture->getMaxRetrySendTimes(), pfuture->getRetrySendTimes());

-  pCmd->SetExtHeader(code);  // set head , for response use

-

-  pfuture->setResponse(pCmd);

-

-  if (pfuture->getASyncFlag()) {

-    if (!pfuture->getAsyncResponseFlag()) {

-      pfuture->setAsyncResponseFlag();

-      pfuture->setAsyncCallBackStatus(asyncCallBackStatus_response);

-      cancelTimerCallback(opaque);

-      pfuture->executeInvokeCallback();      

-    }

-  }

-}

-

-void TcpRemotingClient::processRequestCommand(RemotingCommand* pCmd,

-                                              const string& addr) {

-  unique_ptr<RemotingCommand> pRequestCommand(pCmd);

-  int requestCode = pRequestCommand->getCode();

-  if (m_requestTable.find(requestCode) == m_requestTable.end()) {

-    LOG_ERROR("can_not_find request:%d processor", requestCode);

-  } else {

-    unique_ptr<RemotingCommand> pResponse(

-        m_requestTable[requestCode]->processRequest(addr,

-                                                    pRequestCommand.get()));

-    if (!pRequestCommand->isOnewayRPC()) {

-      if (pResponse) {

-        pResponse->setOpaque(pRequestCommand->getOpaque());

-        pResponse->markResponseType();

-        pResponse->Encode();

-

-        invokeOneway(addr, *pResponse);

-      }

-    }

-  }

-}

-

-void TcpRemotingClient::addResponseFuture(

-    int opaque, boost::shared_ptr<ResponseFuture> pfuture) {

-  boost::lock_guard<boost::mutex> lock(m_futureTableMutex);

-  m_futureTable[opaque] = pfuture;

-}

-

-// Note: after call this function, shared_ptr of m_syncFutureTable[opaque] will

-// be erased, so caller must ensure the life cycle of returned shared_ptr;

-boost::shared_ptr<ResponseFuture>

-TcpRemotingClient::findAndDeleteResponseFuture(int opaque) {

-  boost::lock_guard<boost::mutex> lock(m_futureTableMutex);

-  boost::shared_ptr<ResponseFuture> pResponseFuture;

-  if (m_futureTable.find(opaque) != m_futureTable.end()) {

-    pResponseFuture = m_futureTable[opaque];

-    m_futureTable.erase(opaque);

-  }

-  return pResponseFuture;

-}

-

-void TcpRemotingClient::handleAsyncPullForResponseTimeout(

-    const boost::system::error_code& e, int opaque) {

-  if (e == boost::asio::error::operation_aborted) {

-    LOG_INFO("handleAsyncPullForResponseTimeout aborted opaque:%d, e_code:%d, msg:%s", opaque, e.value(), e.message().data());

-    return;

-  }

-

-  LOG_DEBUG("handleAsyncPullForResponseTimeout opaque:%d, e_code:%d, msg:%s", opaque, e.value(), e.message().data());

-  boost::shared_ptr<ResponseFuture> pFuture(

-      findAndDeleteAsyncResponseFuture(opaque));

-  if (pFuture && pFuture->getASyncFlag() && (pFuture->getAsyncCallbackWrap())) {

-    if ((pFuture->getAsyncResponseFlag() !=

-         true))  // if no response received, then check timeout or not

-    {

-      LOG_ERROR("no response got for opaque:%d", opaque);

-      pFuture->setAsyncCallBackStatus(asyncCallBackStatus_timeout);

-      pFuture->executeInvokeCallbackException();

-    }

-  }

-

-  eraseTimerCallback(opaque);

-}

-

-void TcpRemotingClient::addAsyncResponseFuture(

-    int opaque, boost::shared_ptr<ResponseFuture> pfuture) {

-  boost::lock_guard<boost::mutex> lock(m_asyncFutureLock);

-  m_asyncFutureTable[opaque] = pfuture;

-}

-

-// Note: after call this function, shared_ptr of m_asyncFutureTable[opaque] will

-// be erased, so caller must ensure the life cycle of returned shared_ptr;

-boost::shared_ptr<ResponseFuture>

-TcpRemotingClient::findAndDeleteAsyncResponseFuture(int opaque) {

-  boost::lock_guard<boost::mutex> lock(m_asyncFutureLock);

-  boost::shared_ptr<ResponseFuture> pResponseFuture;

-  if (m_asyncFutureTable.find(opaque) != m_asyncFutureTable.end()) {

-    pResponseFuture = m_asyncFutureTable[opaque];

-    m_asyncFutureTable.erase(opaque);

-  }

-

-  return pResponseFuture;

-}

-

-void TcpRemotingClient::registerProcessor(

-    MQRequestCode requestCode,

-    ClientRemotingProcessor* clientRemotingProcessor) {

-  if (m_requestTable.find(requestCode) != m_requestTable.end())

-    m_requestTable.erase(requestCode);

-  m_requestTable[requestCode] = clientRemotingProcessor;

-}

-

-void TcpRemotingClient::addTimerCallback(boost::asio::deadline_timer* t,

-                                         int opaque) {

-  boost::lock_guard<boost::mutex> lock(m_timerMapMutex);

-  if (m_async_timer_map.find(opaque) != m_async_timer_map.end()) {

-    LOG_DEBUG("addTimerCallback:erase timerCallback opaque:%lld", opaque);

-    boost::asio::deadline_timer* old_t = m_async_timer_map[opaque];

-    old_t->cancel();

-    delete old_t;

-    old_t = NULL;

-    m_async_timer_map.erase(opaque);

-  }

-  m_async_timer_map[opaque] = t;

-}

-

-void TcpRemotingClient::eraseTimerCallback(int opaque) {

-  boost::lock_guard<boost::mutex> lock(m_timerMapMutex);

-  if (m_async_timer_map.find(opaque) != m_async_timer_map.end()) {

-    LOG_DEBUG("eraseTimerCallback: opaque:%lld", opaque);

-    boost::asio::deadline_timer* t = m_async_timer_map[opaque];

-    delete t;

-    t = NULL;

-    m_async_timer_map.erase(opaque);

-  }

-}

-

-void TcpRemotingClient::cancelTimerCallback(int opaque) {

-  boost::lock_guard<boost::mutex> lock(m_timerMapMutex);

-  if (m_async_timer_map.find(opaque) != m_async_timer_map.end()) {

-    LOG_DEBUG("cancelTimerCallback: opaque:%lld", opaque);    

-    boost::asio::deadline_timer* t = m_async_timer_map[opaque];

-    t->cancel();

-    delete t;

-    t = NULL;

-    m_async_timer_map.erase(opaque);

-  }

-}

-

-void TcpRemotingClient::removeAllTimerCallback() {

-  boost::lock_guard<boost::mutex> lock(m_timerMapMutex);

-  for (asyncTimerMap::iterator it = m_async_timer_map.begin();

-       it != m_async_timer_map.end(); ++it) {

-    boost::asio::deadline_timer* t = it->second;

-    t->cancel();

-    delete t;

-    t = NULL;

-  }

-  m_async_timer_map.clear();

-}

-

-void TcpRemotingClient::deleteOpaqueForDropPullRequest(const MQMessageQueue& mq, int opaque) {

-  //delete the map record of opaque<->ResponseFuture, so the answer for the pull request will discard when receive it later

-  boost::shared_ptr<ResponseFuture> pFuture(findAndDeleteAsyncResponseFuture(opaque));

-  if (!pFuture) {

-    pFuture = findAndDeleteResponseFuture(opaque);

-    if (pFuture) {

-      LOG_DEBUG("succ deleted the sync pullrequest for opaque:%d, mq:%s", opaque, mq.toString().data());

-    }

-  } else {

-    LOG_DEBUG("succ deleted the async pullrequest for opaque:%d, mq:%s", opaque, mq.toString().data()); 

-  }

-  //delete the timeout timer for opaque for pullrequest

-  cancelTimerCallback(opaque);

-}

-

-//<!************************************************************************

-}  //<!end namespace;

+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include "TcpRemotingClient.h"
+#include <stddef.h>
+#if !defined(WIN32) && !defined(__APPLE__)
+#include <sys/prctl.h>
+#endif
+
+#include "Logging.h"
+#include "MemoryOutputStream.h"
+#include "TopAddressing.h"
+#include "UtilAll.h"
+
+namespace rocketmq {
+
+//<!************************************************************************
+TcpRemotingClient::TcpRemotingClient(int pullThreadNum, uint64_t tcpConnectTimeout, uint64_t tcpTransportTryLockTimeout)
+    : m_dispatchThreadNum(1),
+      m_pullThreadNum(pullThreadNum),
+      m_tcpConnectTimeout(tcpConnectTimeout),
+      m_tcpTransportTryLockTimeout(tcpTransportTryLockTimeout),
+      m_namesrvIndex(0),
+      m_dispatchServiceWork(m_dispatchService),
+      m_handleServiceWork(m_handleService) {
+#if !defined(WIN32) && !defined(__APPLE__)
+  string taskName = UtilAll::getProcessName();
+  prctl(PR_SET_NAME, "DispatchTP", 0, 0, 0);
+#endif
+  for (int i = 0; i != m_dispatchThreadNum; ++i) {
+    m_dispatchThreadPool.create_thread(boost::bind(&boost::asio::io_service::run, &m_dispatchService));
+  }
+#if !defined(WIN32) && !defined(__APPLE__)
+  prctl(PR_SET_NAME, taskName.c_str(), 0, 0, 0);
+#endif
+
+#if !defined(WIN32) && !defined(__APPLE__)
+  prctl(PR_SET_NAME, "NetworkTP", 0, 0, 0);
+#endif
+  for (int i = 0; i != m_pullThreadNum; ++i) {
+    m_handleThreadPool.create_thread(boost::bind(&boost::asio::io_service::run, &m_handleService));
+  }
+#if !defined(WIN32) && !defined(__APPLE__)
+  prctl(PR_SET_NAME, taskName.c_str(), 0, 0, 0);
+#endif
+
+  LOG_INFO("m_tcpConnectTimeout:%ju, m_tcpTransportTryLockTimeout:%ju, m_pullThreadNum:%d", m_tcpConnectTimeout,
+           m_tcpTransportTryLockTimeout, m_pullThreadNum);
+
+  m_timerServiceThread.reset(new boost::thread(boost::bind(&TcpRemotingClient::boost_asio_work, this)));
+}
+
+void TcpRemotingClient::boost_asio_work() {
+  LOG_INFO("TcpRemotingClient::boost asio async service running");
+
+#if !defined(WIN32) && !defined(__APPLE__)
+  prctl(PR_SET_NAME, "RemotingAsioT", 0, 0, 0);
+#endif
+
+  // avoid async io service stops after first timer timeout callback
+  boost::asio::io_service::work work(m_timerService);
+
+  m_timerService.run();
+}
+
+TcpRemotingClient::~TcpRemotingClient() {
+  m_tcpTable.clear();
+  m_futureTable.clear();
+  m_namesrvAddrList.clear();
+  removeAllTimerCallback();
+}
+
+void TcpRemotingClient::stopAllTcpTransportThread() {
+  LOG_DEBUG("TcpRemotingClient::stopAllTcpTransportThread Begin");
+
+  m_timerService.stop();
+  m_timerServiceThread->interrupt();
+  m_timerServiceThread->join();
+  removeAllTimerCallback();
+
+  {
+    std::lock_guard<std::timed_mutex> lock(m_tcpTableLock);
+    for (const auto& trans : m_tcpTable) {
+      trans.second->disconnect(trans.first);
+    }
+    m_tcpTable.clear();
+  }
+
+  m_handleService.stop();
+  m_handleThreadPool.join_all();
+
+  m_dispatchService.stop();
+  m_dispatchThreadPool.join_all();
+
+  {
+    std::lock_guard<std::mutex> lock(m_futureTableLock);
+    for (const auto& future : m_futureTable) {
+      if (future.second) {
+        if (!future.second->getAsyncFlag()) {
+          future.second->releaseThreadCondition();
+        }
+      }
+    }
+  }
+
+  LOG_ERROR("TcpRemotingClient::stopAllTcpTransportThread End, m_tcpTable:%lu", m_tcpTable.size());
+}
+
+void TcpRemotingClient::updateNameServerAddressList(const string& addrs) {
+  LOG_INFO("updateNameServerAddressList: [%s]", addrs.c_str());
+
+  if (addrs.empty()) {
+    return;
+  }
+
+  std::unique_lock<std::timed_mutex> lock(m_namesrvLock, std::try_to_lock);
+  if (!lock.owns_lock()) {
+    if (!lock.try_lock_for(std::chrono::seconds(10))) {
+      LOG_ERROR("updateNameServerAddressList get timed_mutex timeout");
+      return;
+    }
+  }
+
+  // clear first;
+  m_namesrvAddrList.clear();
+
+  vector<string> out;
+  UtilAll::Split(out, addrs, ";");
+  for (auto addr : out) {
+    UtilAll::Trim(addr);
+
+    string hostName;
+    short portNumber;
+    if (UtilAll::SplitURL(addr, hostName, portNumber)) {
+      LOG_INFO("update Namesrv:%s", addr.c_str());
+      m_namesrvAddrList.push_back(addr);
+    } else {
+      LOG_INFO("This may be invalid namer server: [%s]", addr.c_str());
+    }
+  }
+  out.clear();
+}
+
+bool TcpRemotingClient::invokeHeartBeat(const string& addr, RemotingCommand& request, int timeoutMillis) {
+  std::shared_ptr<TcpTransport> pTcp = GetTransport(addr, true);
+  if (pTcp != nullptr) {
+    int code = request.getCode();
+    int opaque = request.getOpaque();
+
+    std::shared_ptr<ResponseFuture> responseFuture(new ResponseFuture(code, opaque, this, timeoutMillis));
+    addResponseFuture(opaque, responseFuture);
+
+    if (SendCommand(pTcp, request)) {
+      responseFuture->setSendRequestOK(true);
+      unique_ptr<RemotingCommand> pRsp(responseFuture->waitResponse());
+      if (pRsp == nullptr) {
+        LOG_ERROR("wait response timeout of heartbeat, so closeTransport of addr:%s", addr.c_str());
+        // avoid responseFuture leak;
+        findAndDeleteResponseFuture(opaque);
+        CloseTransport(addr, pTcp);
+        return false;
+      } else if (pRsp->getCode() == SUCCESS_VALUE) {
+        return true;
+      } else {
+        LOG_WARN("get error response:%d of heartbeat to addr:%s", pRsp->getCode(), addr.c_str());
+        return false;
+      }
+    } else {
+      // avoid responseFuture leak;
+      findAndDeleteResponseFuture(opaque);
+      CloseTransport(addr, pTcp);
+    }
+  }
+  return false;
+}
+
+RemotingCommand* TcpRemotingClient::invokeSync(const string& addr, RemotingCommand& request, int timeoutMillis) {
+  LOG_DEBUG("InvokeSync:", addr.c_str());
+  std::shared_ptr<TcpTransport> pTcp = GetTransport(addr, true);
+  if (pTcp != nullptr) {
+    int code = request.getCode();
+    int opaque = request.getOpaque();
+
+    std::shared_ptr<ResponseFuture> responseFuture(new ResponseFuture(code, opaque, this, timeoutMillis));
+    addResponseFuture(opaque, responseFuture);
+
+    if (SendCommand(pTcp, request)) {
+      responseFuture->setSendRequestOK(true);
+      RemotingCommand* pRsp = responseFuture->waitResponse();
+      if (pRsp == nullptr) {
+        if (code != GET_CONSUMER_LIST_BY_GROUP) {
+          LOG_WARN("wait response timeout or get NULL response of code:%d, so closeTransport of addr:%s", code,
+                   addr.c_str());
+          CloseTransport(addr, pTcp);
+        }
+        // avoid responseFuture leak;
+        findAndDeleteResponseFuture(opaque);
+        return nullptr;
+      } else {
+        return pRsp;
+      }
+    } else {
+      // avoid responseFuture leak;
+      findAndDeleteResponseFuture(opaque);
+      CloseTransport(addr, pTcp);
+    }
+  }
+  LOG_DEBUG("InvokeSync [%s] Failed: Cannot Get Transport.", addr.c_str());
+  return nullptr;
+}
+
+bool TcpRemotingClient::invokeAsync(const string& addr,
+                                    RemotingCommand& request,
+                                    AsyncCallbackWrap* callback,
+                                    int64 timeoutMillis,
+                                    int maxRetrySendTimes,
+                                    int retrySendTimes) {
+  std::shared_ptr<TcpTransport> pTcp = GetTransport(addr, true);
+  if (pTcp != nullptr) {
+    int code = request.getCode();
+    int opaque = request.getOpaque();
+
+    // delete in callback
+    std::shared_ptr<ResponseFuture> responseFuture(
+        new ResponseFuture(code, opaque, this, timeoutMillis, true, callback));
+    responseFuture->setMaxRetrySendTimes(maxRetrySendTimes);
+    responseFuture->setRetrySendTimes(retrySendTimes);
+    responseFuture->setBrokerAddr(addr);
+    responseFuture->setRequestCommand(request);
+    addResponseFuture(opaque, responseFuture);
+
+    if (callback) {
+      boost::asio::deadline_timer* t =
+          new boost::asio::deadline_timer(m_timerService, boost::posix_time::milliseconds(timeoutMillis));
+      addTimerCallback(t, opaque);
+      t->async_wait(
+          boost::bind(&TcpRemotingClient::handleAsyncRequestTimeout, this, boost::asio::placeholders::error, opaque));
+    }
+
+    // even if send failed, asyncTimerThread will trigger next pull request or report send msg failed
+    if (SendCommand(pTcp, request)) {
+      LOG_DEBUG("invokeAsync success, addr:%s, code:%d, opaque:%d", addr.c_str(), code, opaque);
+      responseFuture->setSendRequestOK(true);
+    }
+    return true;
+  }
+
+  LOG_ERROR("invokeAsync failed of addr:%s", addr.c_str());
+  return false;
+}
+
+void TcpRemotingClient::invokeOneway(const string& addr, RemotingCommand& request) {
+  //<!not need callback;
+  std::shared_ptr<TcpTransport> pTcp = GetTransport(addr, true);
+  if (pTcp != nullptr) {
+    request.markOnewayRPC();
+    if (SendCommand(pTcp, request)) {
+      LOG_DEBUG("invokeOneway success. addr:%s, code:%d", addr.c_str(), request.getCode());
+    } else {
+      LOG_WARN("invokeOneway failed. addr:%s, code:%d", addr.c_str(), request.getCode());
+    }
+  } else {
+    LOG_WARN("invokeOneway failed: NULL transport. addr:%s, code:%d", addr.c_str(), request.getCode());
+  }
+}
+
+std::shared_ptr<TcpTransport> TcpRemotingClient::GetTransport(const string& addr, bool needResponse) {
+  if (addr.empty()) {
+    LOG_DEBUG("GetTransport of NameServer");
+    return CreateNameServerTransport(needResponse);
+  }
+  return CreateTransport(addr, needResponse);
+}
+
+std::shared_ptr<TcpTransport> TcpRemotingClient::CreateTransport(const string& addr, bool needResponse) {
+  std::shared_ptr<TcpTransport> tts;
+
+  {
+    // try get m_tcpLock util m_tcpTransportTryLockTimeout to avoid blocking
+    // long time, if could not get m_tcpLock, return NULL
+    std::unique_lock<std::timed_mutex> lock(m_tcpTableLock, std::try_to_lock);
+    if (!lock.owns_lock()) {
+      if (!lock.try_lock_for(std::chrono::seconds(m_tcpTransportTryLockTimeout))) {
+        LOG_ERROR("GetTransport of:%s get timed_mutex timeout", addr.c_str());
+        std::shared_ptr<TcpTransport> pTcp;
+        return pTcp;
+      }
+    }
+
+    // check for reuse
+    if (m_tcpTable.find(addr) != m_tcpTable.end()) {
+      std::shared_ptr<TcpTransport> tcp = m_tcpTable[addr];
+
+      if (tcp) {
+        TcpConnectStatus connectStatus = tcp->getTcpConnectStatus();
+        if (connectStatus == TCP_CONNECT_STATUS_SUCCESS) {
+          return tcp;
+        } else if (connectStatus == TCP_CONNECT_STATUS_WAIT) {
+          std::shared_ptr<TcpTransport> pTcp;
+          return pTcp;
+        } else if (connectStatus == TCP_CONNECT_STATUS_FAILED) {
+          LOG_ERROR("tcpTransport with server disconnected, erase server:%s", addr.c_str());
+          tcp->disconnect(addr);  // avoid coredump when connection with broker was broken
+          m_tcpTable.erase(addr);
+        } else {
+          LOG_ERROR("go to fault state, erase:%s from tcpMap, and reconnect it", addr.c_str());
+          m_tcpTable.erase(addr);
+        }
+      }
+    }
+
+    //<!callback;
+    TcpTransportReadCallback callback = needResponse ? &TcpRemotingClient::static_messageReceived : nullptr;
+
+    tts = TcpTransport::CreateTransport(this, callback);
+    TcpConnectStatus connectStatus = tts->connect(addr, 0);  // use non-block
+    if (connectStatus != TCP_CONNECT_STATUS_WAIT) {
+      LOG_WARN("can not connect to:%s", addr.c_str());
+      tts->disconnect(addr);
+      std::shared_ptr<TcpTransport> pTcp;
+      return pTcp;
+    } else {
+      // even if connecting failed finally, this server transport will be erased by next CreateTransport
+      m_tcpTable[addr] = tts;
+    }
+  }
+
+  TcpConnectStatus connectStatus = tts->waitTcpConnectEvent(static_cast<int>(m_tcpConnectTimeout));
+  if (connectStatus != TCP_CONNECT_STATUS_SUCCESS) {
+    LOG_WARN("can not connect to server:%s", addr.c_str());
+    tts->disconnect(addr);
+    std::shared_ptr<TcpTransport> pTcp;
+    return pTcp;
+  } else {
+    LOG_INFO("connect server with addr:%s success", addr.c_str());
+    return tts;
+  }
+}
+
+std::shared_ptr<TcpTransport> TcpRemotingClient::CreateNameServerTransport(bool needResponse) {
+  // m_namesrvLock was added to avoid operation of nameServer was blocked by
+  // m_tcpLock, it was used by single Thread mostly, so no performance impact
+  // try get m_tcpLock until m_tcpTransportTryLockTimeout to avoid blocking long
+  // time, if could not get m_namesrvlock, return NULL
+  LOG_DEBUG("--CreateNameserverTransport--");
+  std::unique_lock<std::timed_mutex> lock(m_namesrvLock, std::try_to_lock);
+  if (!lock.owns_lock()) {
+    if (!lock.try_lock_for(std::chrono::seconds(m_tcpTransportTryLockTimeout))) {
+      LOG_ERROR("CreateNameserverTransport get timed_mutex timeout");
+      std::shared_ptr<TcpTransport> pTcp;
+      return pTcp;
+    }
+  }
+
+  if (!m_namesrvAddrChoosed.empty()) {
+    std::shared_ptr<TcpTransport> pTcp = CreateTransport(m_namesrvAddrChoosed, true);
+    if (pTcp)
+      return pTcp;
+    else
+      m_namesrvAddrChoosed.clear();
+  }
+
+  for (int i = 0; i < m_namesrvAddrList.size(); i++) {
+    unsigned int index = m_namesrvIndex++ % m_namesrvAddrList.size();
+    LOG_INFO("namesrvIndex is:%d, index:%d, namesrvaddrlist size:" SIZET_FMT "", m_namesrvIndex, index,
+             m_namesrvAddrList.size());
+    std::shared_ptr<TcpTransport> pTcp = CreateTransport(m_namesrvAddrList[index], true);
+    if (pTcp) {
+      m_namesrvAddrChoosed = m_namesrvAddrList[index];
+      return pTcp;
+    }
+  }
+
+  std::shared_ptr<TcpTransport> pTcp;
+  return pTcp;
+}
+
+bool TcpRemotingClient::CloseTransport(const string& addr, std::shared_ptr<TcpTransport> pTcp) {
+  if (addr.empty()) {
+    return CloseNameServerTransport(pTcp);
+  }
+
+  std::unique_lock<std::timed_mutex> lock(m_tcpTableLock, std::try_to_lock);
+  if (!lock.owns_lock()) {
+    if (!lock.try_lock_for(std::chrono::seconds(m_tcpTransportTryLockTimeout))) {
+      LOG_ERROR("CloseTransport of:%s get timed_mutex timeout", addr.c_str());
+      return false;
+    }
+  }
+
+  LOG_ERROR("CloseTransport of:%s", addr.c_str());
+
+  bool removeItemFromTable = true;
+  if (m_tcpTable.find(addr) != m_tcpTable.end()) {
+    if (m_tcpTable[addr]->getStartTime() != pTcp->getStartTime()) {
+      LOG_INFO("tcpTransport with addr:%s has been closed before, and has been created again, nothing to do",
+               addr.c_str());
+      removeItemFromTable = false;
+    }
+  } else {
+    LOG_INFO("tcpTransport with addr:%s had been removed from tcpTable before", addr.c_str());
+    removeItemFromTable = false;
+  }
+
+  if (removeItemFromTable) {
+    LOG_WARN("closeTransport: disconnect:%s with state:%d", addr.c_str(), m_tcpTable[addr]->getTcpConnectStatus());
+    if (m_tcpTable[addr]->getTcpConnectStatus() == TCP_CONNECT_STATUS_SUCCESS)
+      m_tcpTable[addr]->disconnect(addr);  // avoid coredump when connection with server was broken
+    LOG_WARN("closeTransport: erase broker: %s", addr.c_str());
+    m_tcpTable.erase(addr);
+  }
+
+  LOG_ERROR("CloseTransport of:%s end", addr.c_str());
+
+  return removeItemFromTable;
+}
+
+bool TcpRemotingClient::CloseNameServerTransport(std::shared_ptr<TcpTransport> pTcp) {
+  std::unique_lock<std::timed_mutex> lock(m_namesrvLock, std::try_to_lock);
+  if (!lock.owns_lock()) {
+    if (!lock.try_lock_for(std::chrono::seconds(m_tcpTransportTryLockTimeout))) {
+      LOG_ERROR("CreateNameServerTransport get timed_mutex timeout");
+      return false;
+    }
+  }
+
+  string addr = m_namesrvAddrChoosed;
+
+  bool removeItemFromTable = CloseTransport(addr, pTcp);
+  if (removeItemFromTable) {
+    m_namesrvAddrChoosed.clear();
+  }
+
+  return removeItemFromTable;
+}
+
+bool TcpRemotingClient::SendCommand(std::shared_ptr<TcpTransport> pTts, RemotingCommand& msg) {
+  const MemoryBlock* pHead = msg.GetHead();
+  const MemoryBlock* pBody = msg.GetBody();
+
+  unique_ptr<MemoryOutputStream> buffer(new MemoryOutputStream(1024));
+  if (pHead->getSize() > 0) {
+    buffer->write(pHead->getData(), static_cast<size_t>(pHead->getSize()));
+  }
+  if (pBody->getSize() > 0) {
+    buffer->write(pBody->getData(), static_cast<size_t>(pBody->getSize()));
+  }
+
+  const char* pData = static_cast<const char*>(buffer->getData());
+  size_t len = buffer->getDataSize();
+  return pTts->sendMessage(pData, len);
+}
+
+void TcpRemotingClient::static_messageReceived(void* context, const MemoryBlock& mem, const string& addr) {
+  auto* pTcpRemotingClient = reinterpret_cast<TcpRemotingClient*>(context);
+  if (pTcpRemotingClient)
+    pTcpRemotingClient->messageReceived(mem, addr);
+}
+
+void TcpRemotingClient::messageReceived(const MemoryBlock& mem, const string& addr) {
+  m_dispatchService.post(boost::bind(&TcpRemotingClient::ProcessData, this, mem, addr));
+}
+
+void TcpRemotingClient::ProcessData(const MemoryBlock& mem, const string& addr) {
+  RemotingCommand* pRespondCmd = nullptr;
+  try {
+    pRespondCmd = RemotingCommand::Decode(mem);
+  } catch (...) {
+    LOG_ERROR("processData error");
+    return;
+  }
+
+  int opaque = pRespondCmd->getOpaque();
+
+  //<!process self;
+  if (pRespondCmd->isResponseType()) {
+    std::shared_ptr<ResponseFuture> pFuture = findAndDeleteResponseFuture(opaque);
+    if (!pFuture) {
+      LOG_DEBUG("responseFuture was deleted by timeout of opaque:%d", opaque);
+      deleteAndZero(pRespondCmd);
+      return;
+    }
+
+    LOG_DEBUG("find_response opaque:%d", opaque);
+    processResponseCommand(pRespondCmd, pFuture);
+  } else {
+    m_handleService.post(boost::bind(&TcpRemotingClient::processRequestCommand, this, pRespondCmd, addr));
+  }
+}
+
+void TcpRemotingClient::processResponseCommand(RemotingCommand* pCmd, std::shared_ptr<ResponseFuture> pFuture) {
+  int code = pFuture->getRequestCode();
+  pCmd->SetExtHeader(code);  // set head, for response use
+
+  int opaque = pCmd->getOpaque();
+  LOG_DEBUG("processResponseCommand, code:%d, opaque:%d, maxRetryTimes:%d, retrySendTimes:%d", code, opaque,
+            pFuture->getMaxRetrySendTimes(), pFuture->getRetrySendTimes());
+
+  if (!pFuture->setResponse(pCmd)) {
+    // this branch is unreachable normally.
+    LOG_WARN("response already timeout of opaque:%d", opaque);
+    deleteAndZero(pCmd);
+    return;
+  }
+
+  if (pFuture->getAsyncFlag()) {
+    cancelTimerCallback(opaque);
+
+    m_handleService.post(boost::bind(&ResponseFuture::invokeCompleteCallback, pFuture));
+  }
+}
+
+void TcpRemotingClient::handleAsyncRequestTimeout(const boost::system::error_code& e, int opaque) {
+  if (e == boost::asio::error::operation_aborted) {
+    LOG_DEBUG("handleAsyncRequestTimeout aborted opaque:%d, e_code:%d, msg:%s", opaque, e.value(), e.message().data());
+    return;
+  }
+
+  LOG_DEBUG("handleAsyncRequestTimeout opaque:%d, e_code:%d, msg:%s", opaque, e.value(), e.message().data());
+
+  std::shared_ptr<ResponseFuture> pFuture(findAndDeleteResponseFuture(opaque));
+  if (pFuture) {
+    LOG_ERROR("no response got for opaque:%d", opaque);
+    eraseTimerCallback(opaque);
+    if (pFuture->getAsyncCallbackWrap()) {
+      m_handleService.post(boost::bind(&ResponseFuture::invokeExceptionCallback, pFuture));
+    }
+  }
+}
+
+void TcpRemotingClient::processRequestCommand(RemotingCommand* pCmd, const string& addr) {
+  unique_ptr<RemotingCommand> pRequestCommand(pCmd);
+  int requestCode = pRequestCommand->getCode();
+  if (m_requestTable.find(requestCode) == m_requestTable.end()) {
+    LOG_ERROR("can_not_find request:%d processor", requestCode);
+  } else {
+    unique_ptr<RemotingCommand> pResponse(m_requestTable[requestCode]->processRequest(addr, pRequestCommand.get()));
+    if (!pRequestCommand->isOnewayRPC()) {
+      if (pResponse) {
+        pResponse->setOpaque(pRequestCommand->getOpaque());
+        pResponse->markResponseType();
+        pResponse->Encode();
+
+        invokeOneway(addr, *pResponse);
+      }
+    }
+  }
+}
+
+void TcpRemotingClient::addResponseFuture(int opaque, std::shared_ptr<ResponseFuture> pFuture) {
+  std::lock_guard<std::mutex> lock(m_futureTableLock);
+  m_futureTable[opaque] = pFuture;
+}
+
+// Note: after call this function, shared_ptr of m_syncFutureTable[opaque] will
+// be erased, so caller must ensure the life cycle of returned shared_ptr;
+std::shared_ptr<ResponseFuture> TcpRemotingClient::findAndDeleteResponseFuture(int opaque) {
+  std::lock_guard<std::mutex> lock(m_futureTableLock);
+  std::shared_ptr<ResponseFuture> pResponseFuture;
+  if (m_futureTable.find(opaque) != m_futureTable.end()) {
+    pResponseFuture = m_futureTable[opaque];
+    m_futureTable.erase(opaque);
+  }
+  return pResponseFuture;
+}
+
+void TcpRemotingClient::registerProcessor(MQRequestCode requestCode, ClientRemotingProcessor* clientRemotingProcessor) {
+  if (m_requestTable.find(requestCode) != m_requestTable.end())
+    m_requestTable.erase(requestCode);
+  m_requestTable[requestCode] = clientRemotingProcessor;
+}
+
+void TcpRemotingClient::addTimerCallback(boost::asio::deadline_timer* t, int opaque) {
+  std::lock_guard<std::mutex> lock(m_asyncTimerTableLock);
+  if (m_asyncTimerTable.find(opaque) != m_asyncTimerTable.end()) {
+    LOG_DEBUG("addTimerCallback:erase timerCallback opaque:%lld", opaque);
+    boost::asio::deadline_timer* old_t = m_asyncTimerTable[opaque];
+    m_asyncTimerTable.erase(opaque);
+    try {
+      old_t->cancel();
+    } catch (const std::exception& ec) {
+      LOG_WARN("encounter exception when cancel old timer: %s", ec.what());
+    }
+    delete old_t;
+  }
+  m_asyncTimerTable[opaque] = t;
+}
+
+void TcpRemotingClient::eraseTimerCallback(int opaque) {
+  std::lock_guard<std::mutex> lock(m_asyncTimerTableLock);
+  if (m_asyncTimerTable.find(opaque) != m_asyncTimerTable.end()) {
+    LOG_DEBUG("eraseTimerCallback: opaque:%lld", opaque);
+    boost::asio::deadline_timer* t = m_asyncTimerTable[opaque];
+    m_asyncTimerTable.erase(opaque);
+    delete t;
+  }
+}
+
+void TcpRemotingClient::cancelTimerCallback(int opaque) {
+  std::lock_guard<std::mutex> lock(m_asyncTimerTableLock);
+  if (m_asyncTimerTable.find(opaque) != m_asyncTimerTable.end()) {
+    LOG_DEBUG("cancelTimerCallback: opaque:%lld", opaque);
+    boost::asio::deadline_timer* t = m_asyncTimerTable[opaque];
+    m_asyncTimerTable.erase(opaque);
+    try {
+      t->cancel();
+    } catch (const std::exception& ec) {
+      LOG_WARN("encounter exception when cancel timer: %s", ec.what());
+    }
+    delete t;
+  }
+}
+
+void TcpRemotingClient::removeAllTimerCallback() {
+  std::lock_guard<std::mutex> lock(m_asyncTimerTableLock);
+  for (const auto& timer : m_asyncTimerTable) {
+    boost::asio::deadline_timer* t = timer.second;
+    try {
+      t->cancel();
+    } catch (const std::exception& ec) {
+      LOG_WARN("encounter exception when cancel timer: %s", ec.what());
+    }
+    delete t;
+  }
+  m_asyncTimerTable.clear();
+}
+
+//<!************************************************************************
+}  // namespace rocketmq
diff --git a/src/transport/TcpRemotingClient.h b/src/transport/TcpRemotingClient.h
index c338d53..c612e9d 100755
--- a/src/transport/TcpRemotingClient.h
+++ b/src/transport/TcpRemotingClient.h
@@ -1,133 +1,132 @@
-/*

- * Licensed to the Apache Software Foundation (ASF) under one or more

- * contributor license agreements.  See the NOTICE file distributed with

- * this work for additional information regarding copyright ownership.

- * The ASF licenses this file to You under the Apache License, Version 2.0

- * (the "License"); you may not use this file except in compliance with

- * the License.  You may obtain a copy of the License at

- *

- *     http://www.apache.org/licenses/LICENSE-2.0

- *

- * Unless required by applicable law or agreed to in writing, software

- * distributed under the License is distributed on an "AS IS" BASIS,

- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- * See the License for the specific language governing permissions and

- * limitations under the License.

- */

-#ifndef __TCPREMOTINGCLIENT_H__

-#define __TCPREMOTINGCLIENT_H__

-

-#include <boost/asio.hpp>

-#include <boost/asio/io_service.hpp>

-#include <boost/bind.hpp>

-#include <boost/date_time/posix_time/posix_time.hpp>

-#include <boost/weak_ptr.hpp>

-#include <map>

-#include "ClientRemotingProcessor.h"

-#include "RemotingCommand.h"

-#include "ResponseFuture.h"

-#include "SocketUtil.h"

-#include "TcpTransport.h"

-

-namespace rocketmq {

-//<!************************************************************************

-

-class TcpRemotingClient {

- public:

-  TcpRemotingClient(int pullThreadNum, uint64_t tcpConnectTimeout,

-                    uint64_t tcpTransportTryLockTimeout);

-  virtual ~TcpRemotingClient();

-  void stopAllTcpTransportThread();

-  void updateNameServerAddressList(const string& addrs);

-

-  //<!delete outsite;

-  RemotingCommand* invokeSync(const string& addr, RemotingCommand& request,

-                              int timeoutMillis = 3000);

-

-  bool invokeHeartBeat(const string& addr, RemotingCommand& request);

-

-  bool invokeAsync(const string& addr, RemotingCommand& request, AsyncCallbackWrap* cbw, 

-                   int64 timeoutMilliseconds, int maxRetrySendTimes=1, int retrySendTimes=1);

-  void invokeOneway(const string& addr, RemotingCommand& request);

-  

-  void ProcessData(const MemoryBlock& mem, const string& addr);

-

-  void registerProcessor(MQRequestCode requestCode,

-                         ClientRemotingProcessor* clientRemotingProcessor);

-

-  void boost_asio_work();

-  void handleAsyncPullForResponseTimeout(const boost::system::error_code& e,

-                                         int opaque);

-  void deleteOpaqueForDropPullRequest(const MQMessageQueue& mq, int opaque);

-

- private:

-  static void static_messageReceived(void* context, const MemoryBlock& mem,

-                                     const string& addr);

-  void messageReceived(const MemoryBlock& mem, const string& addr);

-  boost::shared_ptr<TcpTransport> GetTransport(const string& addr,

-                                               bool needRespons);

-  boost::shared_ptr<TcpTransport> CreateTransport(const string& addr,

-                                                  bool needRespons);

-  boost::shared_ptr<TcpTransport> CreateNameserverTransport(bool needRespons);

-  void CloseTransport(const string& addr, boost::shared_ptr<TcpTransport> pTcp);

-  void CloseNameServerTransport(boost::shared_ptr<TcpTransport> pTcp);

-  bool SendCommand(boost::shared_ptr<TcpTransport> pTts, RemotingCommand& msg);

-  void processRequestCommand(RemotingCommand* pCmd, const string& addr);

-  void processResponseCommand(RemotingCommand* pCmd,

-                              boost::shared_ptr<ResponseFuture> pfuture);

-

-  void addResponseFuture(int opaque, boost::shared_ptr<ResponseFuture> pfuture);

-  boost::shared_ptr<ResponseFuture> findAndDeleteResponseFuture(int opaque);

-

-  void addAsyncResponseFuture(int opaque,

-                              boost::shared_ptr<ResponseFuture> pfuture);

-  boost::shared_ptr<ResponseFuture> findAndDeleteAsyncResponseFuture(

-      int opaque);

-

-  void addTimerCallback(boost::asio::deadline_timer* t, int opaque);

-  void eraseTimerCallback(int opaque);

-  void cancelTimerCallback(int opaque);

-  void removeAllTimerCallback();

-

- private:

-  typedef map<string, boost::shared_ptr<TcpTransport>> TcpMap;

-  typedef map<int, boost::shared_ptr<ResponseFuture>> ResMap;

-

-  typedef map<int, ClientRemotingProcessor*> RequestMap;

-  RequestMap m_requestTable;

-

-  boost::mutex m_futureTableMutex;

-  ResMap m_futureTable;  //<! id->future;

-

-  ResMap m_asyncFutureTable;

-  boost::mutex m_asyncFutureLock;

-

-  TcpMap m_tcpTable;  //<! ip->tcp;

-  boost::timed_mutex m_tcpLock;

-

-  // ThreadPool        m_threadpool;

-  int m_pullThreadNum;

-  uint64_t m_tcpConnectTimeout;           // ms

-  uint64_t m_tcpTransportTryLockTimeout;  // s

-

-  //<! Nameserver

-  boost::timed_mutex m_namesrvlock;

-  vector<string> m_namesrvAddrList;

-  string m_namesrvAddrChoosed;

-  unsigned int m_namesrvIndex;

-  boost::asio::io_service m_ioService;

-  boost::thread_group m_threadpool;

-  boost::asio::io_service::work m_ioServiceWork;

-

-  boost::asio::io_service m_async_ioService;

-  unique_ptr<boost::thread> m_async_service_thread;

-

-  typedef map<int, boost::asio::deadline_timer*> asyncTimerMap;

-  boost::mutex m_timerMapMutex;

-  asyncTimerMap m_async_timer_map;

-};

-

-//<!************************************************************************

-}  //<!end namespace;

-

-#endif

+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#ifndef __TCPREMOTINGCLIENT_H__
+#define __TCPREMOTINGCLIENT_H__
+
+#include <map>
+#include <mutex>
+
+#include <boost/asio.hpp>
+#include <boost/asio/io_service.hpp>
+#include <boost/bind.hpp>
+#include <boost/date_time/posix_time/posix_time.hpp>
+
+#include "ClientRemotingProcessor.h"
+#include "RemotingCommand.h"
+#include "ResponseFuture.h"
+#include "SocketUtil.h"
+#include "TcpTransport.h"
+
+namespace rocketmq {
+//<!************************************************************************
+
+class TcpRemotingClient {
+ public:
+  TcpRemotingClient(int pullThreadNum, uint64_t tcpConnectTimeout, uint64_t tcpTransportTryLockTimeout);
+  virtual ~TcpRemotingClient();
+
+  void stopAllTcpTransportThread();
+  void updateNameServerAddressList(const string& addrs);
+
+  bool invokeHeartBeat(const string& addr, RemotingCommand& request, int timeoutMillis = 3000);
+
+  // delete outsite;
+  RemotingCommand* invokeSync(const string& addr, RemotingCommand& request, int timeoutMillis = 3000);
+
+  bool invokeAsync(const string& addr,
+                   RemotingCommand& request,
+                   AsyncCallbackWrap* cbw,
+                   int64 timeoutMilliseconds,
+                   int maxRetrySendTimes = 1,
+                   int retrySendTimes = 1);
+
+  void invokeOneway(const string& addr, RemotingCommand& request);
+
+  void registerProcessor(MQRequestCode requestCode, ClientRemotingProcessor* clientRemotingProcessor);
+
+ private:
+  static void static_messageReceived(void* context, const MemoryBlock& mem, const string& addr);
+
+  void messageReceived(const MemoryBlock& mem, const string& addr);
+  void ProcessData(const MemoryBlock& mem, const string& addr);
+  void processRequestCommand(RemotingCommand* pCmd, const string& addr);
+  void processResponseCommand(RemotingCommand* pCmd, std::shared_ptr<ResponseFuture> pFuture);
+  void handleAsyncRequestTimeout(const boost::system::error_code& e, int opaque);
+
+  std::shared_ptr<TcpTransport> GetTransport(const string& addr, bool needResponse);
+  std::shared_ptr<TcpTransport> CreateTransport(const string& addr, bool needResponse);
+  std::shared_ptr<TcpTransport> CreateNameServerTransport(bool needResponse);
+
+  bool CloseTransport(const string& addr, std::shared_ptr<TcpTransport> pTcp);
+  bool CloseNameServerTransport(std::shared_ptr<TcpTransport> pTcp);
+
+  bool SendCommand(std::shared_ptr<TcpTransport> pTts, RemotingCommand& msg);
+
+  void addResponseFuture(int opaque, std::shared_ptr<ResponseFuture> pFuture);
+  std::shared_ptr<ResponseFuture> findAndDeleteResponseFuture(int opaque);
+
+  void addTimerCallback(boost::asio::deadline_timer* t, int opaque);
+  void eraseTimerCallback(int opaque);
+  void cancelTimerCallback(int opaque);
+  void removeAllTimerCallback();
+
+  void boost_asio_work();
+
+ private:
+  using RequestMap = map<int, ClientRemotingProcessor*>;
+  using TcpMap = map<string, std::shared_ptr<TcpTransport>>;
+  using ResMap = map<int, std::shared_ptr<ResponseFuture>>;
+  using AsyncTimerMap = map<int, boost::asio::deadline_timer*>;
+
+  RequestMap m_requestTable;
+
+  TcpMap m_tcpTable;  //<! addr->tcp;
+  std::timed_mutex m_tcpTableLock;
+
+  ResMap m_futureTable;  //<! id->future;
+  std::mutex m_futureTableLock;
+
+  AsyncTimerMap m_asyncTimerTable;
+  std::mutex m_asyncTimerTableLock;
+
+  int m_dispatchThreadNum;
+  int m_pullThreadNum;
+  uint64_t m_tcpConnectTimeout;           // ms
+  uint64_t m_tcpTransportTryLockTimeout;  // s
+
+  //<! NameServer
+  std::timed_mutex m_namesrvLock;
+  vector<string> m_namesrvAddrList;
+  string m_namesrvAddrChoosed;
+  unsigned int m_namesrvIndex;
+
+  boost::asio::io_service m_dispatchService;
+  boost::asio::io_service::work m_dispatchServiceWork;
+  boost::thread_group m_dispatchThreadPool;
+
+  boost::asio::io_service m_handleService;
+  boost::asio::io_service::work m_handleServiceWork;
+  boost::thread_group m_handleThreadPool;
+
+  boost::asio::io_service m_timerService;
+  unique_ptr<boost::thread> m_timerServiceThread;
+};
+
+//<!************************************************************************
+}  // namespace rocketmq
+
+#endif
diff --git a/src/transport/TcpTransport.cpp b/src/transport/TcpTransport.cpp
index bbebc37..c56e5d1 100644
--- a/src/transport/TcpTransport.cpp
+++ b/src/transport/TcpTransport.cpp
@@ -15,11 +15,15 @@
  * limitations under the License.
  */
 #include "TcpTransport.h"
+
+#include <chrono>
+
 #ifndef WIN32
 #include <arpa/inet.h>  // for sockaddr_in and inet_ntoa...
 #include <netinet/tcp.h>
 #include <sys/socket.h>  // for socket(), bind(), and connect()...
 #endif
+
 #include "Logging.h"
 #include "TcpRemotingClient.h"
 #include "UtilAll.h"
@@ -27,278 +31,204 @@
 namespace rocketmq {
 
 //<!************************************************************************
-TcpTransport::TcpTransport(TcpRemotingClient *pTcpRemointClient,
-                           READ_CALLBACK handle /* = NULL */)
-    : m_tcpConnectStatus(e_connectInit),
-      m_event_base_status(false),
-      m_event_base_mtx(),
-      m_event_base_cv(),
-      m_ReadDatathread(NULL),
-      m_readcallback(handle),
+TcpTransport::TcpTransport(TcpRemotingClient* pTcpRemointClient, TcpTransportReadCallback handle)
+    : m_event(nullptr),
+      m_tcpConnectStatus(TCP_CONNECT_STATUS_INIT),
+      m_connectEventLock(),
+      m_connectEvent(),
+      m_readCallback(handle),
       m_tcpRemotingClient(pTcpRemointClient) {
   m_startTime = UtilAll::currentTimeMillis();
-#ifdef WIN32
-  evthread_use_windows_threads();
-#else
-  evthread_use_pthreads();
-#endif
-  m_eventBase = NULL;
-  m_bufferEvent = NULL;
 }
+
 TcpTransport::~TcpTransport() {
-  m_readcallback = NULL;
-  m_bufferEvent = NULL;
-  m_eventBase = NULL;
+  freeBufferEvent();
+  m_readCallback = nullptr;
 }
 
-tcpConnectStatus TcpTransport::connect(const string &strServerURL,
-                                       int timeOutMillisecs /* = 3000 */) {
-  string hostName;
-  short portNumber;
-  if (!UtilAll::SplitURL(strServerURL, hostName, portNumber)) {
-    return e_connectFail;
+void TcpTransport::freeBufferEvent() {
+  // freeBufferEvent is idempotent.
+
+  // first, unlink BufferEvent
+  if (m_event != nullptr) {
+    m_event->setCallback(nullptr, nullptr, nullptr, nullptr);
   }
 
-  boost::lock_guard<boost::mutex> lock(m_socketLock);
-
-  struct sockaddr_in sin;
-  memset(&sin, 0, sizeof(sin));
-  sin.sin_family = AF_INET;
-  sin.sin_addr.s_addr = getInetAddr(hostName);
- 
-  sin.sin_port = htons(portNumber);
-
-  m_eventBase = event_base_new();
-  m_bufferEvent = bufferevent_socket_new(
-      m_eventBase, -1, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_THREADSAFE);
-  bufferevent_setcb(m_bufferEvent, readNextMessageIntCallback, NULL, eventcb,
-                    this);
-  bufferevent_enable(m_bufferEvent, EV_READ | EV_WRITE);
-  bufferevent_setwatermark(m_bufferEvent, EV_READ, 4, 0);
-
-  setTcpConnectStatus(e_connectWaitResponse);
-  if (bufferevent_socket_connect(m_bufferEvent, (struct sockaddr *)&sin,
-                                 sizeof(sin)) < 0) {
-    LOG_INFO("connect to fd:%d failed", bufferevent_getfd(m_bufferEvent));
-    setTcpConnectStatus(e_connectFail);
-    freeBufferEvent();
-    return e_connectFail;
-  } else {
-    int fd = bufferevent_getfd(m_bufferEvent);
-    LOG_INFO("try to connect to fd:%d, addr:%s", fd, (hostName.c_str()));
-
-    evthread_make_base_notifiable(m_eventBase);
-
-    m_ReadDatathread =
-        new boost::thread(boost::bind(&TcpTransport::runThread, this));
-
-    while (!m_event_base_status) {
-      LOG_INFO("Wait till event base is looping");
-      boost::system_time const timeout =
-          boost::get_system_time() + boost::posix_time::milliseconds(1000);
-      boost::unique_lock<boost::mutex> lock(m_event_base_mtx);
-      m_event_base_cv.timed_wait(lock, timeout);
-    }
-
-    return e_connectWaitResponse;
-  }
+  // then, release BufferEvent
+  m_event.reset();
 }
 
-void TcpTransport::setTcpConnectStatus(tcpConnectStatus connectStatus) {
+void TcpTransport::setTcpConnectStatus(TcpConnectStatus connectStatus) {
   m_tcpConnectStatus = connectStatus;
 }
 
-tcpConnectStatus TcpTransport::getTcpConnectStatus() {
+TcpConnectStatus TcpTransport::getTcpConnectStatus() {
   return m_tcpConnectStatus;
 }
 
-tcpConnectStatus TcpTransport::waitTcpConnectEvent(int timeoutMillisecs) {
-  boost::unique_lock<boost::mutex> lk(m_connectEventLock);
-  if (!m_connectEvent.timed_wait(
-          lk, boost::posix_time::milliseconds(timeoutMillisecs))) {
-    LOG_INFO("connect timeout");
-  }
-  return getTcpConnectStatus();
-}
-
-void TcpTransport::setTcpConnectEvent(tcpConnectStatus connectStatus) {
-  tcpConnectStatus baseStatus(getTcpConnectStatus());
-  setTcpConnectStatus(connectStatus);
-  if (baseStatus == e_connectWaitResponse) {
-    LOG_INFO("received libevent callback event");
-    m_connectEvent.notify_all();
-  }
-}
-
-u_long TcpTransport::getInetAddr(string &hostname)
-{
-	u_long addr = inet_addr(hostname.c_str());
-
-	if (INADDR_NONE == addr) {
-		constexpr size_t length = 128;
-		struct evutil_addrinfo hints;
-		struct evutil_addrinfo *answer = NULL;
-		/* Build the hints to tell getaddrinfo how to act. */
-		memset(&hints, 0, sizeof(hints));
-		hints.ai_family = AF_UNSPEC; /* v4 or v6 is fine. */
-		//Look up the hostname.
-		int err = evutil_getaddrinfo(hostname.c_str(), NULL, &hints, &answer);
-		if (err != 0) {
-			string info = "Failed to resolve  host name(" + hostname + "): " + evutil_gai_strerror(err);
-			THROW_MQEXCEPTION(MQClientException, info, -1);
-		}
-
-		struct evutil_addrinfo *addressInfo;
-		for (addressInfo = answer; addressInfo; addressInfo = addressInfo->ai_next) {
-			char buf[length];
-			const char *address = NULL;
-			if (addressInfo->ai_family == AF_INET) {
-				struct sockaddr_in *sin = (struct sockaddr_in*)addressInfo->ai_addr;
-				address = evutil_inet_ntop(AF_INET, &sin->sin_addr, buf, length);
-			}
-			else if (addressInfo->ai_family == AF_INET6) {
-				struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)addressInfo->ai_addr;
-				address = evutil_inet_ntop(AF_INET6, &sin6->sin6_addr, buf, length);
-			}
-			if (address) {
-				addr = inet_addr(address);
-				if (addr != INADDR_NONE) {
-					break;
-				}
-			}
-		}
-	}
-
-	return addr;
-}
-
-void TcpTransport::disconnect(const string &addr) {
-  boost::lock_guard<boost::mutex> lock(m_socketLock);
-  if (getTcpConnectStatus() != e_connectInit) {
-    clearBufferEventCallback();
-    LOG_INFO("disconnect:%s start", addr.c_str());
-    m_connectEvent.notify_all();
-    setTcpConnectStatus(e_connectInit);
-    if (m_ReadDatathread) {
-      m_ReadDatathread->interrupt();
-      exitBaseDispatch();
-      while (m_ReadDatathread->timed_join(boost::posix_time::seconds(1)) ==
-             false) {
-        LOG_WARN("join readDataThread fail, retry");
-        m_ReadDatathread->interrupt();
-        exitBaseDispatch();
-      }
-      delete m_ReadDatathread;
-      m_ReadDatathread = NULL;
+TcpConnectStatus TcpTransport::waitTcpConnectEvent(int timeoutMillis) {
+  std::unique_lock<std::mutex> eventLock(m_connectEventLock);
+  if (m_tcpConnectStatus == TCP_CONNECT_STATUS_WAIT) {
+    if (m_connectEvent.wait_for(eventLock, std::chrono::milliseconds(timeoutMillis)) == std::cv_status::timeout) {
+      LOG_INFO("connect timeout");
     }
+  }
+  return m_tcpConnectStatus;
+}
+
+// internal method
+void TcpTransport::setTcpConnectEvent(TcpConnectStatus connectStatus) {
+  TcpConnectStatus baseStatus = m_tcpConnectStatus.exchange(connectStatus, std::memory_order_relaxed);
+  if (baseStatus == TCP_CONNECT_STATUS_WAIT) {
+    std::unique_lock<std::mutex> eventLock(m_connectEventLock);
+    m_connectEvent.notify_all();
+  }
+}
+
+u_long TcpTransport::getInetAddr(string& hostname) {
+  u_long addr = inet_addr(hostname.c_str());
+
+  if (INADDR_NONE == addr) {
+    constexpr size_t length = 128;
+    struct evutil_addrinfo hints;
+    struct evutil_addrinfo* answer = NULL;
+    /* Build the hints to tell getaddrinfo how to act. */
+    memset(&hints, 0, sizeof(hints));
+    hints.ai_family = AF_UNSPEC; /* v4 or v6 is fine. */
+    // Look up the hostname.
+    int err = evutil_getaddrinfo(hostname.c_str(), NULL, &hints, &answer);
+    if (err != 0) {
+      string info = "Failed to resolve  host name(" + hostname + "): " + evutil_gai_strerror(err);
+      THROW_MQEXCEPTION(MQClientException, info, -1);
+    }
+
+    struct evutil_addrinfo* addressInfo;
+    for (addressInfo = answer; addressInfo; addressInfo = addressInfo->ai_next) {
+      char buf[length];
+      const char* address = NULL;
+      if (addressInfo->ai_family == AF_INET) {
+        struct sockaddr_in* sin = (struct sockaddr_in*)addressInfo->ai_addr;
+        address = evutil_inet_ntop(AF_INET, &sin->sin_addr, buf, length);
+      } else if (addressInfo->ai_family == AF_INET6) {
+        struct sockaddr_in6* sin6 = (struct sockaddr_in6*)addressInfo->ai_addr;
+        address = evutil_inet_ntop(AF_INET6, &sin6->sin6_addr, buf, length);
+      }
+      if (address) {
+        addr = inet_addr(address);
+        if (addr != INADDR_NONE) {
+          break;
+        }
+      }
+    }
+  }
+
+  return addr;
+}
+
+void TcpTransport::disconnect(const string& addr) {
+  // disconnect is idempotent.
+  std::lock_guard<std::mutex> lock(m_eventLock);
+  if (getTcpConnectStatus() != TCP_CONNECT_STATUS_INIT) {
+    LOG_INFO("disconnect:%s start. event:%p", addr.c_str(), m_event.get());
     freeBufferEvent();
+    setTcpConnectEvent(TCP_CONNECT_STATUS_INIT);
     LOG_INFO("disconnect:%s completely", addr.c_str());
   }
 }
 
-void TcpTransport::clearBufferEventCallback() {
-  if (m_bufferEvent) {
-    // Bufferevents are internally reference-counted, so if the bufferevent has
-    // pending deferred callbacks when you free it, it won't be deleted until
-    // the callbacks are done.
-    // so just empty callback to avoid future callback by libevent
-    bufferevent_setcb(m_bufferEvent, NULL, NULL, NULL, NULL);
+TcpConnectStatus TcpTransport::connect(const string& strServerURL, int timeoutMillis) {
+  string hostname;
+  short port;
+  LOG_DEBUG("connect to [%s].", strServerURL.c_str());
+  if (!UtilAll::SplitURL(strServerURL, hostname, port)) {
+    LOG_INFO("connect to [%s] failed, Invalid url.", strServerURL.c_str());
+    return TCP_CONNECT_STATUS_FAILED;
   }
-}
 
-void TcpTransport::freeBufferEvent() {
-  if (m_bufferEvent) {
-    bufferevent_free(m_bufferEvent);
-    m_bufferEvent = NULL;
-  }
-  if (m_eventBase) {
-    event_base_free(m_eventBase);
-    m_eventBase = NULL;
-  }
-}
-void TcpTransport::exitBaseDispatch() {
-  if (m_eventBase) {
-    event_base_loopbreak(m_eventBase);
-    // event_base_loopexit(m_eventBase, NULL);  //Note: memory leak will be
-    // occured when timer callback was not done;
-  }
-}
+  {
+    std::lock_guard<std::mutex> lock(m_eventLock);
 
-void TcpTransport::runThread() {
-  if (m_eventBase != NULL) {
-    if (!m_event_base_status) {
-      boost::mutex::scoped_lock lock(m_event_base_mtx);
-      m_event_base_status.store(true);
-      m_event_base_cv.notify_all();
-      LOG_INFO("Notify on event_base_dispatch");
+    struct sockaddr_in sin;
+    memset(&sin, 0, sizeof(sin));
+    sin.sin_family = AF_INET;
+    sin.sin_addr.s_addr = getInetAddr(hostname);
+    sin.sin_port = htons(port);
+
+    m_event.reset(EventLoop::GetDefaultEventLoop()->createBufferEvent(-1, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_THREADSAFE));
+    m_event->setCallback(readNextMessageIntCallback, nullptr, eventCallback, shared_from_this());
+    m_event->setWatermark(EV_READ, 4, 0);
+    m_event->enable(EV_READ | EV_WRITE);
+
+    setTcpConnectStatus(TCP_CONNECT_STATUS_WAIT);
+    if (m_event->connect((struct sockaddr*)&sin, sizeof(sin)) < 0) {
+      LOG_INFO("connect to fd:%d failed", m_event->getfd());
+      freeBufferEvent();
+      setTcpConnectStatus(TCP_CONNECT_STATUS_FAILED);
+      return TCP_CONNECT_STATUS_FAILED;
     }
-    event_base_dispatch(m_eventBase);
-    // event_base_loop(m_eventBase, EVLOOP_ONCE);//EVLOOP_NONBLOCK should not
-    // be used, as could not callback event immediatly
   }
-  LOG_INFO("event_base_dispatch exit once");
-  boost::this_thread::sleep(boost::posix_time::milliseconds(1));
-  if (getTcpConnectStatus() != e_connectSuccess) return;
+
+  if (timeoutMillis <= 0) {
+    LOG_INFO("try to connect to fd:%d, addr:%s", m_event->getfd(), hostname.c_str());
+    return TCP_CONNECT_STATUS_WAIT;
+  }
+
+  TcpConnectStatus connectStatus = waitTcpConnectEvent(timeoutMillis);
+  if (connectStatus != TCP_CONNECT_STATUS_SUCCESS) {
+    LOG_WARN("can not connect to server:%s", strServerURL.c_str());
+
+    std::lock_guard<std::mutex> lock(m_eventLock);
+    freeBufferEvent();
+    setTcpConnectStatus(TCP_CONNECT_STATUS_FAILED);
+    return TCP_CONNECT_STATUS_FAILED;
+  }
+
+  return TCP_CONNECT_STATUS_SUCCESS;
 }
 
-void TcpTransport::timeoutcb(evutil_socket_t fd, short what, void *arg) {
-  LOG_INFO("timeoutcb: received  event:%d on fd:%d", what, fd);
-  TcpTransport *tcpTrans = (TcpTransport *)arg;
-  if (tcpTrans->getTcpConnectStatus() != e_connectSuccess) {
-    LOG_INFO("timeoutcb: after connect time, tcp was not established on fd:%d",
-             fd);
-    tcpTrans->setTcpConnectStatus(e_connectFail);
-  } else {
-    LOG_INFO("timeoutcb: after connect time, tcp was established on fd:%d", fd);
-  }
-}
-
-void TcpTransport::eventcb(struct bufferevent *bev, short what, void *ctx) {
-  evutil_socket_t fd = bufferevent_getfd(bev);
-  TcpTransport *tcpTrans = (TcpTransport *)ctx;
+void TcpTransport::eventCallback(BufferEvent* event, short what, TcpTransport* transport) {
+  socket_t fd = event->getfd();
   LOG_INFO("eventcb: received event:%x on fd:%d", what, fd);
   if (what & BEV_EVENT_CONNECTED) {
+    LOG_INFO("eventcb: connect to fd:%d successfully", fd);
+
+    // disable Nagle
     int val = 1;
-    setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
-    LOG_INFO("eventcb:connect to fd:%d successfully", fd);
-    tcpTrans->setTcpConnectEvent(e_connectSuccess);
-  } else if (what & (BEV_EVENT_ERROR | BEV_EVENT_EOF | BEV_EVENT_READING |
-                     BEV_EVENT_WRITING)) {
-    LOG_INFO("eventcb:rcv error event cb:%x on fd:%d", what, fd);
-    tcpTrans->setTcpConnectEvent(e_connectFail);
-    bufferevent_setcb(bev, NULL, NULL, NULL, NULL);
-    // bufferevent_disable(bev, EV_READ|EV_WRITE);
-    // bufferevent_free(bev);
+    setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (void*)&val, sizeof(val));
+    transport->setTcpConnectEvent(TCP_CONNECT_STATUS_SUCCESS);
+  } else if (what & (BEV_EVENT_ERROR | BEV_EVENT_EOF | BEV_EVENT_READING | BEV_EVENT_WRITING)) {
+    LOG_INFO("eventcb: received error event cb:%x on fd:%d", what, fd);
+    // if error, stop callback.
+    event->setCallback(nullptr, nullptr, nullptr, nullptr);
+    transport->setTcpConnectEvent(TCP_CONNECT_STATUS_FAILED);
   } else {
     LOG_ERROR("eventcb: received error event:%d on fd:%d", what, fd);
   }
 }
 
-void TcpTransport::readNextMessageIntCallback(struct bufferevent *bev,
-                                              void *ctx) {
+void TcpTransport::readNextMessageIntCallback(BufferEvent* event, TcpTransport* transport) {
   /* This callback is invoked when there is data to read on bev. */
 
   // protocol:  <length> <header length> <header data> <body data>
-  //                    1                   2                       3 4
+  //               1            2               3           4
   // rocketmq protocol contains 4 parts as following:
   //     1, big endian 4 bytes int, its length is sum of 2,3 and 4
   //     2, big endian 4 bytes int, its length is 3
   //     3, use json to serialization data
-  //     4, application could self-defination binary data
+  //     4, application could self-defined binary data
 
-  struct evbuffer *input = bufferevent_get_input(bev);
+  struct evbuffer* input = event->getInput();
   while (1) {
     struct evbuffer_iovec v[4];
     int n = evbuffer_peek(input, 4, NULL, v, sizeof(v) / sizeof(v[0]));
 
-    int idx = 0;
     char hdr[4];
-    char *p = hdr;
-    unsigned int needed = 4;
+    char* p = hdr;
+    size_t needed = 4;
 
-    for (idx = 0; idx < n; idx++) {
-      if (needed) {
-        unsigned int tmp = needed < v[idx].iov_len ? needed : v[idx].iov_len;
+    for (int idx = 0; idx < n; idx++) {
+      if (needed > 0) {
+        size_t tmp = needed < v[idx].iov_len ? needed : v[idx].iov_len;
         memcpy(p, v[idx].iov_base, tmp);
         p += tmp;
         needed -= tmp;
@@ -307,88 +237,58 @@
       }
     }
 
-    if (needed) {
-      LOG_DEBUG(" too little data received with sum = %d ", 4 - needed);
+    if (needed > 0) {
+      LOG_DEBUG("too little data received with sum = %d", 4 - needed);
       return;
     }
-    uint32 totalLenOfOneMsg =
-        *(uint32 *)hdr;  // first 4 bytes, which indicates 1st part of protocol
-    uint32 bytesInMessage = ntohl(totalLenOfOneMsg);
-    LOG_DEBUG("fd:%d, totalLen:" SIZET_FMT ", bytesInMessage:%d",
-              bufferevent_getfd(bev), v[0].iov_len, bytesInMessage);
 
-    uint32 len = evbuffer_get_length(input);
-    if (len >= bytesInMessage + 4) {
-      LOG_DEBUG("had received all data with len:%d from fd:%d", len,
-                bufferevent_getfd(bev));
+    uint32 totalLenOfOneMsg = *(uint32*)hdr;  // first 4 bytes, which indicates 1st part of protocol
+    uint32 msgLen = ntohl(totalLenOfOneMsg);
+    size_t recvLen = evbuffer_get_length(input);
+    if (recvLen >= msgLen + 4) {
+      LOG_DEBUG("had received all data. msgLen:%d, from:%d, recvLen:%d", msgLen, event->getfd(), recvLen);
     } else {
-      LOG_DEBUG(
-          "didn't received whole bytesInMessage:%d, from fd:%d, totalLen:%d",
-          bytesInMessage, bufferevent_getfd(bev), len);
+      LOG_DEBUG("didn't received whole. msgLen:%d, from:%d, recvLen:%d", msgLen, event->getfd(), recvLen);
       return;  // consider large data which was not received completely by now
     }
 
-    if (bytesInMessage > 0) {
-      MemoryBlock messageData(bytesInMessage, true);
-      uint32 bytesRead = 0;
-      char *data = messageData.getData() + bytesRead;
-      bufferevent_read(bev, data, 4);
-      bytesRead = bufferevent_read(bev, data, bytesInMessage);
+    if (msgLen > 0) {
+      MemoryBlock msg(msgLen, true);
 
-      TcpTransport *tcpTrans = (TcpTransport *)ctx;
-      tcpTrans->messageReceived(messageData);
+      event->read(hdr, 4);  // skip length field
+      size_t bytesRead = event->read(msg.getData(), msgLen);
+
+      transport->messageReceived(msg, event->getPeerAddrPort());
     }
   }
 }
 
-bool TcpTransport::sendMessage(const char *pData, int len) {
-  boost::lock_guard<boost::mutex> lock(m_socketLock);
-  if (getTcpConnectStatus() != e_connectSuccess) {
+void TcpTransport::messageReceived(const MemoryBlock& mem, const std::string& addr) {
+  if (m_readCallback != nullptr) {
+    m_readCallback(m_tcpRemotingClient, mem, addr);
+  }
+}
+
+bool TcpTransport::sendMessage(const char* pData, size_t len) {
+  std::lock_guard<std::mutex> lock(m_eventLock);
+  if (getTcpConnectStatus() != TCP_CONNECT_STATUS_SUCCESS) {
     return false;
   }
 
-  int bytes_left = len;
-  int bytes_written = 0;
-  const char *ptr = pData;
-
-  /*NOTE:
-      1. do not need to consider large data which could not send by once, as
-     bufferevent could handle this case;
-  */
-  if (m_bufferEvent) {
-    bytes_written = bufferevent_write(m_bufferEvent, ptr, bytes_left);
-    if (bytes_written == 0)
-      return true;
-    else
-      return false;
-  }
-  return false;
-}
-
-void TcpTransport::messageReceived(const MemoryBlock &mem) {
-  if (m_readcallback) {
-    m_readcallback(m_tcpRemotingClient, mem, getPeerAddrAndPort());
-  }
+  /* NOTE:
+      do not need to consider large data which could not send by once, as
+      bufferevent could handle this case;
+   */
+  return m_event != nullptr && m_event->write(pData, len) == 0;
 }
 
 const string TcpTransport::getPeerAddrAndPort() {
-  struct sockaddr_in broker;
-  socklen_t cLen = sizeof(broker);
-
-  // getsockname(m_socket->getRawSocketHandle(), (struct sockaddr*) &s, &sLen);
-  // // ! use connectSock here.
-  getpeername(bufferevent_getfd(m_bufferEvent), (struct sockaddr *)&broker,
-              &cLen);  // ! use connectSock here.
-  LOG_DEBUG("broker addr: %s, broker port: %d", inet_ntoa(broker.sin_addr),
-            ntohs(broker.sin_port));
-  string brokerAddr(inet_ntoa(broker.sin_addr));
-  brokerAddr.append(":");
-  string brokerPort(UtilAll::to_string(ntohs(broker.sin_port)));
-  brokerAddr.append(brokerPort);
-  LOG_DEBUG("brokerAddr:%s", brokerAddr.c_str());
-  return brokerAddr;
+  std::lock_guard<std::mutex> lock(m_eventLock);
+  return m_event ? m_event->getPeerAddrPort() : "";
 }
 
-const uint64_t TcpTransport::getStartTime() const { return m_startTime; }
+const uint64_t TcpTransport::getStartTime() const {
+  return m_startTime;
+}
 
 }  // namespace rocketmq
diff --git a/src/transport/TcpTransport.h b/src/transport/TcpTransport.h
index fa4da85..bff23dd 100755
--- a/src/transport/TcpTransport.h
+++ b/src/transport/TcpTransport.h
@@ -17,81 +17,77 @@
 #ifndef __TCPTRANSPORT_H__
 #define __TCPTRANSPORT_H__
 
-#include <boost/atomic.hpp>
-#include <boost/thread/condition_variable.hpp>
-#include <boost/thread/mutex.hpp>
-#include <boost/thread/thread.hpp>
+#include <atomic>
+#include <condition_variable>
+#include <mutex>
+
+#include "EventLoop.h"
 #include "dataBlock.h"
 
-extern "C" {
-#include "event2/buffer.h"
-#include "event2/bufferevent.h"
-#include "event2/event.h"
-#include "event2/thread.h"
-}
-
 namespace rocketmq {
-//<!***************************************************************************
-typedef enum {
-  e_connectInit = 0,
-  e_connectWaitResponse = 1,
-  e_connectSuccess = 2,
-  e_connectFail = 3
-} tcpConnectStatus;
 
-typedef void (*READ_CALLBACK)(void *context, const MemoryBlock &,
-                              const std::string &);
+//<!***************************************************************************
+typedef enum TcpConnectStatus {
+  TCP_CONNECT_STATUS_INIT = 0,
+  TCP_CONNECT_STATUS_WAIT = 1,
+  TCP_CONNECT_STATUS_SUCCESS = 2,
+  TCP_CONNECT_STATUS_FAILED = 3
+} TcpConnectStatus;
+
+using TcpTransportReadCallback = void (*)(void* context, const MemoryBlock&, const std::string&);
+
 class TcpRemotingClient;
-class TcpTransport {
+
+class TcpTransport : public std::enable_shared_from_this<TcpTransport> {
  public:
-  TcpTransport(TcpRemotingClient *pTcpRemointClient,
-               READ_CALLBACK handle = NULL);
+  static std::shared_ptr<TcpTransport> CreateTransport(TcpRemotingClient* pTcpRemotingClient,
+                                                       TcpTransportReadCallback handle = nullptr) {
+    // transport must be managed by smart pointer
+    std::shared_ptr<TcpTransport> transport(new TcpTransport(pTcpRemotingClient, handle));
+    return transport;
+  }
+
   virtual ~TcpTransport();
 
-  tcpConnectStatus connect(const std::string &strServerURL,
-                           int timeOutMillisecs = 3000);
-  void disconnect(const std::string &addr);
-  tcpConnectStatus waitTcpConnectEvent(int timeoutMillisecs = 3000);
-  void setTcpConnectStatus(tcpConnectStatus connectStatus);
-  tcpConnectStatus getTcpConnectStatus();
-  bool sendMessage(const char *pData, int len);
+  void disconnect(const std::string& addr);
+  TcpConnectStatus connect(const std::string& strServerURL, int timeoutMillis = 3000);
+  TcpConnectStatus waitTcpConnectEvent(int timeoutMillis = 3000);
+  TcpConnectStatus getTcpConnectStatus();
+
+  bool sendMessage(const char* pData, size_t len);
   const std::string getPeerAddrAndPort();
   const uint64_t getStartTime() const;
 
  private:
-  void messageReceived(const MemoryBlock &mem);
-  static void readNextMessageIntCallback(struct bufferevent *bev, void *ctx);
-  static void eventcb(struct bufferevent *bev, short what, void *ctx);
-  static void timeoutcb(evutil_socket_t fd, short what, void *arg);
-  void runThread();
-  void clearBufferEventCallback();
-  void freeBufferEvent();
-  void exitBaseDispatch();
-  void setTcpConnectEvent(tcpConnectStatus connectStatus);
-  u_long getInetAddr(std::string &hostname);
+  TcpTransport(TcpRemotingClient* pTcpRemotingClient, TcpTransportReadCallback handle = nullptr);
+
+  static void readNextMessageIntCallback(BufferEvent* event, TcpTransport* transport);
+  static void eventCallback(BufferEvent* event, short what, TcpTransport* transport);
+
+  void messageReceived(const MemoryBlock& mem, const std::string& addr);
+  void freeBufferEvent();  // not thread-safe
+
+  void setTcpConnectEvent(TcpConnectStatus connectStatus);
+  void setTcpConnectStatus(TcpConnectStatus connectStatus);
+
+  u_long getInetAddr(std::string& hostname);
 
  private:
   uint64_t m_startTime;
-  boost::mutex m_socketLock;
-  struct event_base *m_eventBase;
-  struct bufferevent *m_bufferEvent;
-  boost::atomic<tcpConnectStatus> m_tcpConnectStatus;
-  boost::mutex m_connectEventLock;
-  boost::condition_variable_any m_connectEvent;
 
-  boost::atomic<bool> m_event_base_status;
-  boost::mutex        m_event_base_mtx;
-  boost::condition_variable_any m_event_base_cv;
+  std::shared_ptr<BufferEvent> m_event;  // NOTE: use m_event in callback is unsafe.
+  std::mutex m_eventLock;
+  std::atomic<TcpConnectStatus> m_tcpConnectStatus;
 
-  //<!read data thread
-  boost::thread *m_ReadDatathread;
+  std::mutex m_connectEventLock;
+  std::condition_variable m_connectEvent;
 
   //<! read data callback
-  READ_CALLBACK m_readcallback;
-  TcpRemotingClient *m_tcpRemotingClient;
+  TcpTransportReadCallback m_readCallback;
+  TcpRemotingClient* m_tcpRemotingClient;
 };
 
 //<!************************************************************************
-}  //<!end namespace;
+}  // namespace rocketmq
 
 #endif
diff --git a/test/src/BatchMessageTest.cpp b/test/src/BatchMessageTest.cpp
index 81bd7bb..789e09b 100644
--- a/test/src/BatchMessageTest.cpp
+++ b/test/src/BatchMessageTest.cpp
@@ -30,43 +30,43 @@
 using testing::Return;
 
 TEST(BatchMessageEncodeTest, encodeMQMessage) {
-    MQMessage msg1("topic", "*", "test");
-    //const map<string,string>& properties = msg1.getProperties();
-    //for (auto& pair : properties) {
-    //    std::cout << pair.first << " : " << pair.second << std::endl;
-    //}
+  MQMessage msg1("topic", "*", "test");
+  // const map<string,string>& properties = msg1.getProperties();
+  // for (auto& pair : properties) {
+  //    std::cout << pair.first << " : " << pair.second << std::endl;
+  //}
 
-    EXPECT_EQ(msg1.getProperties().size(), 2);
-    EXPECT_EQ(msg1.getBody().size(), 4);
-    //20 + bodyLen + 2 + propertiesLength;
-    string encodeMessage = BatchMessage::encode(msg1);
-    EXPECT_EQ(encodeMessage.size(), 43);
+  EXPECT_EQ(msg1.getProperties().size(), 2);
+  EXPECT_EQ(msg1.getBody().size(), 4);
+  // 20 + bodyLen + 2 + propertiesLength;
+  string encodeMessage = BatchMessage::encode(msg1);
+  EXPECT_EQ(encodeMessage.size(), 43);
 
-    msg1.setProperty(MQMessage::PROPERTY_UNIQ_CLIENT_MESSAGE_ID_KEYIDX, "1");
-    encodeMessage = BatchMessage::encode(msg1);
-    EXPECT_EQ(encodeMessage.size(), 54);
+  msg1.setProperty(MQMessage::PROPERTY_UNIQ_CLIENT_MESSAGE_ID_KEYIDX, "1");
+  encodeMessage = BatchMessage::encode(msg1);
+  EXPECT_EQ(encodeMessage.size(), 54);
 }
 
 TEST(BatchMessageEncodeTest, encodeMQMessages) {
-    std::vector<MQMessage> msgs;
-    MQMessage msg1("topic", "*", "test1");
-    //const map<string,string>& properties = msg1.getProperties();
-    //for (auto& pair : properties) {
-    //    std::cout << pair.first << " : " << pair.second << std::endl;
-    //}
-    msgs.push_back(msg1);
-    //20 + bodyLen + 2 + propertiesLength;
-    string encodeMessage = BatchMessage::encode(msgs);
-    EXPECT_EQ(encodeMessage.size(), 86);
-    MQMessage msg2("topic", "*", "test2");
-    MQMessage msg3("topic", "*", "test3");
-    msgs.push_back(msg2);
-    msgs.push_back(msg3);
-    encodeMessage = BatchMessage::encode(msgs);
-    EXPECT_EQ(encodeMessage.size(), 258);//86*3
+  std::vector<MQMessage> msgs;
+  MQMessage msg1("topic", "*", "test1");
+  // const map<string,string>& properties = msg1.getProperties();
+  // for (auto& pair : properties) {
+  //    std::cout << pair.first << " : " << pair.second << std::endl;
+  //}
+  msgs.push_back(msg1);
+  // 20 + bodyLen + 2 + propertiesLength;
+  string encodeMessage = BatchMessage::encode(msgs);
+  EXPECT_EQ(encodeMessage.size(), 86);
+  MQMessage msg2("topic", "*", "test2");
+  MQMessage msg3("topic", "*", "test3");
+  msgs.push_back(msg2);
+  msgs.push_back(msg3);
+  encodeMessage = BatchMessage::encode(msgs);
+  EXPECT_EQ(encodeMessage.size(), 258);  // 86*3
 }
 
 int main(int argc, char* argv[]) {
-    InitGoogleMock(&argc, argv);
-    return RUN_ALL_TESTS();
+  InitGoogleMock(&argc, argv);
+  return RUN_ALL_TESTS();
 }
diff --git a/test/src/StringIdMakerTest.cpp b/test/src/StringIdMakerTest.cpp
index 8889d28..4fa25d3 100644
--- a/test/src/StringIdMakerTest.cpp
+++ b/test/src/StringIdMakerTest.cpp
@@ -27,12 +27,12 @@
 using testing::Return;
 
 TEST(StringIdMakerTest, get_unique_id) {
-    string unique_id = StringIdMaker::get_mutable_instance().get_unique_id();
-    cout << "unique_id: " << unique_id << endl;
-    EXPECT_EQ(unique_id.size(), 32);
+  string unique_id = StringIdMaker::get_mutable_instance().get_unique_id();
+  cout << "unique_id: " << unique_id << endl;
+  EXPECT_EQ(unique_id.size(), 32);
 }
 
 int main(int argc, char* argv[]) {
-    InitGoogleMock(&argc, argv);
-    return RUN_ALL_TESTS();
+  InitGoogleMock(&argc, argv);
+  return RUN_ALL_TESTS();
 }
diff --git a/test/src/UrlTest.cpp b/test/src/UrlTest.cpp
index b347e22..636c2de 100644
--- a/test/src/UrlTest.cpp
+++ b/test/src/UrlTest.cpp
@@ -44,33 +44,33 @@
 using testing::Return;
 
 class MockTopicConfig : public TopicConfig {
-   public:
-    MOCK_METHOD0(getReadQueueNums, int());
+ public:
+  MOCK_METHOD0(getReadQueueNums, int());
 };
 
 TEST(Url, Url) {
-    Url url_s("172.17.0.2:9876");
-    EXPECT_EQ(url_s.protocol_, "172.17.0.2:9876");
+  Url url_s("172.17.0.2:9876");
+  EXPECT_EQ(url_s.protocol_, "172.17.0.2:9876");
 
-    Url url_z("https://www.aliyun.com/RocketMQ?5.0");
-    EXPECT_EQ(url_z.protocol_, "https");
-    EXPECT_EQ(url_z.host_, "www.aliyun.com");
-    EXPECT_EQ(url_z.port_, "80");
-    EXPECT_EQ(url_z.path_, "/RocketMQ");
-    EXPECT_EQ(url_z.query_, "5.0");
+  Url url_z("https://www.aliyun.com/RocketMQ?5.0");
+  EXPECT_EQ(url_z.protocol_, "https");
+  EXPECT_EQ(url_z.host_, "www.aliyun.com");
+  EXPECT_EQ(url_z.port_, "80");
+  EXPECT_EQ(url_z.path_, "/RocketMQ");
+  EXPECT_EQ(url_z.query_, "5.0");
 
-    Url url_path("https://www.aliyun.com:9876/RocketMQ?5.0");
-    EXPECT_EQ(url_path.port_, "9876");
-    MockTopicConfig topicConfig;
-    EXPECT_CALL(topicConfig, getReadQueueNums()).WillRepeatedly(Return(-1));
-    int nums = topicConfig.getReadQueueNums();
-    cout << nums << endl;
+  Url url_path("https://www.aliyun.com:9876/RocketMQ?5.0");
+  EXPECT_EQ(url_path.port_, "9876");
+  MockTopicConfig topicConfig;
+  EXPECT_CALL(topicConfig, getReadQueueNums()).WillRepeatedly(Return(-1));
+  int nums = topicConfig.getReadQueueNums();
+  cout << nums << endl;
 }
 
-int main(int argc, char *argv[]) {
-    InitGoogleMock(&argc, argv);
-    testing::GTEST_FLAG(filter) = "Url.Url";
-    int itestts = RUN_ALL_TESTS();
-    ;
-    return itestts;
+int main(int argc, char* argv[]) {
+  InitGoogleMock(&argc, argv);
+  testing::GTEST_FLAG(filter) = "Url.Url";
+  int itestts = RUN_ALL_TESTS();
+  ;
+  return itestts;
 }
diff --git a/test/src/common/ClientRPCHookTest.cpp b/test/src/common/ClientRPCHookTest.cpp
index eb6cd69..6fd48b6 100644
--- a/test/src/common/ClientRPCHookTest.cpp
+++ b/test/src/common/ClientRPCHookTest.cpp
@@ -33,28 +33,28 @@
 using rocketmq::ClientRPCHook;
 
 TEST(clientRPCHook, doBeforeRequest) {
-    SessionCredentials sessionCredentials;
-    sessionCredentials.setAccessKey("accessKey");
-    sessionCredentials.setSecretKey("secretKey");
-    sessionCredentials.setAuthChannel("onsChannel");
+  SessionCredentials sessionCredentials;
+  sessionCredentials.setAccessKey("accessKey");
+  sessionCredentials.setSecretKey("secretKey");
+  sessionCredentials.setAuthChannel("onsChannel");
 
-    ClientRPCHook clientRPCHook(sessionCredentials);
+  ClientRPCHook clientRPCHook(sessionCredentials);
 
-    RemotingCommand remotingCommand;
-    clientRPCHook.doBeforeRequest("127.0.0.1:9876", remotingCommand);
+  RemotingCommand remotingCommand;
+  clientRPCHook.doBeforeRequest("127.0.0.1:9876", remotingCommand);
 
-    SendMessageRequestHeader *sendMessageRequestHeader = new SendMessageRequestHeader();
-    RemotingCommand headeRremotingCommand(17, sendMessageRequestHeader);
-    clientRPCHook.doBeforeRequest("127.0.0.1:9876", headeRremotingCommand);
+  SendMessageRequestHeader* sendMessageRequestHeader = new SendMessageRequestHeader();
+  RemotingCommand headeRremotingCommand(17, sendMessageRequestHeader);
+  clientRPCHook.doBeforeRequest("127.0.0.1:9876", headeRremotingCommand);
 
-    headeRremotingCommand.setMsgBody("1231231");
-    clientRPCHook.doBeforeRequest("127.0.0.1:9876", headeRremotingCommand);
+  headeRremotingCommand.setMsgBody("1231231");
+  clientRPCHook.doBeforeRequest("127.0.0.1:9876", headeRremotingCommand);
 }
 
-int main(int argc, char *argv[]) {
-    InitGoogleMock(&argc, argv);
-    testing::GTEST_FLAG(throw_on_failure) = true;
-    testing::GTEST_FLAG(filter) = "clientRPCHook.doBeforeRequest";
-    int itestts = RUN_ALL_TESTS();
-    return itestts;
+int main(int argc, char* argv[]) {
+  InitGoogleMock(&argc, argv);
+  testing::GTEST_FLAG(throw_on_failure) = true;
+  testing::GTEST_FLAG(filter) = "clientRPCHook.doBeforeRequest";
+  int itestts = RUN_ALL_TESTS();
+  return itestts;
 }
diff --git a/test/src/common/MemoryBlockTest.cpp b/test/src/common/MemoryBlockTest.cpp
index e1f350d..bfd7b92 100644
--- a/test/src/common/MemoryBlockTest.cpp
+++ b/test/src/common/MemoryBlockTest.cpp
@@ -30,146 +30,145 @@
 using rocketmq::MemoryBlock;
 
 TEST(memoryBlock, init) {
-    MemoryBlock memoryBlock;
-    EXPECT_EQ(memoryBlock.getSize(), 0);
-    EXPECT_TRUE(memoryBlock.getData() == nullptr);
+  MemoryBlock memoryBlock;
+  EXPECT_EQ(memoryBlock.getSize(), 0);
+  EXPECT_TRUE(memoryBlock.getData() == nullptr);
 
-    MemoryBlock twoMemoryBlock(-1, true);
-    EXPECT_EQ(twoMemoryBlock.getSize(), 0);
-    EXPECT_TRUE(twoMemoryBlock.getData() == nullptr);
+  MemoryBlock twoMemoryBlock(-1, true);
+  EXPECT_EQ(twoMemoryBlock.getSize(), 0);
+  EXPECT_TRUE(twoMemoryBlock.getData() == nullptr);
 
-    MemoryBlock threeMemoryBlock(10, true);
-    EXPECT_EQ(threeMemoryBlock.getSize(), 10);
-    EXPECT_TRUE(threeMemoryBlock.getData() != nullptr);
+  MemoryBlock threeMemoryBlock(10, true);
+  EXPECT_EQ(threeMemoryBlock.getSize(), 10);
+  EXPECT_TRUE(threeMemoryBlock.getData() != nullptr);
 
-    MemoryBlock frouMemoryBlock(12, false);
-    EXPECT_EQ(frouMemoryBlock.getSize(), 12);
-    EXPECT_TRUE(frouMemoryBlock.getData() != nullptr);
+  MemoryBlock frouMemoryBlock(12, false);
+  EXPECT_EQ(frouMemoryBlock.getSize(), 12);
+  EXPECT_TRUE(frouMemoryBlock.getData() != nullptr);
 
-    char *buf = (char *) malloc(sizeof(char) * 9);
-    strcpy(buf, "RocketMQ");
-    MemoryBlock fiveMemoryBlock(buf, -1);
-    EXPECT_EQ(fiveMemoryBlock.getSize(), -1);
-    EXPECT_TRUE(fiveMemoryBlock.getData() == nullptr);
+  char* buf = (char*)malloc(sizeof(char) * 9);
+  strcpy(buf, "RocketMQ");
+  MemoryBlock fiveMemoryBlock(buf, -1);
+  EXPECT_EQ(fiveMemoryBlock.getSize(), -1);
+  EXPECT_TRUE(fiveMemoryBlock.getData() == nullptr);
 
-    char *bufNull = NULL;
-    MemoryBlock sixMemoryBlock(bufNull, 16);
-    EXPECT_EQ(sixMemoryBlock.getSize(), 16);
-    EXPECT_TRUE(sixMemoryBlock.getData() != nullptr);
+  char* bufNull = NULL;
+  MemoryBlock sixMemoryBlock(bufNull, 16);
+  EXPECT_EQ(sixMemoryBlock.getSize(), 16);
+  EXPECT_TRUE(sixMemoryBlock.getData() != nullptr);
 
-    MemoryBlock sevenMemoryBlock(buf, 20);
-    EXPECT_EQ(sevenMemoryBlock.getSize(), 20);
-    sevenMemoryBlock.getData();
-    EXPECT_EQ(string(sevenMemoryBlock.getData()), string(buf));
+  MemoryBlock sevenMemoryBlock(buf, 20);
+  EXPECT_EQ(sevenMemoryBlock.getSize(), 20);
+  sevenMemoryBlock.getData();
+  EXPECT_EQ(string(sevenMemoryBlock.getData()), string(buf));
 
-    MemoryBlock nineMemoryBlock(sevenMemoryBlock);
-    EXPECT_EQ(nineMemoryBlock.getSize(), sevenMemoryBlock.getSize());
-    EXPECT_EQ(string(nineMemoryBlock.getData()), string(sevenMemoryBlock.getData()));
+  MemoryBlock nineMemoryBlock(sevenMemoryBlock);
+  EXPECT_EQ(nineMemoryBlock.getSize(), sevenMemoryBlock.getSize());
+  EXPECT_EQ(string(nineMemoryBlock.getData()), string(sevenMemoryBlock.getData()));
 
-    MemoryBlock eightMemoryBlock(fiveMemoryBlock);
-    EXPECT_EQ(eightMemoryBlock.getSize(), fiveMemoryBlock.getSize());
-    EXPECT_TRUE(eightMemoryBlock.getData() == nullptr);
+  MemoryBlock eightMemoryBlock(fiveMemoryBlock);
+  EXPECT_EQ(eightMemoryBlock.getSize(), fiveMemoryBlock.getSize());
+  EXPECT_TRUE(eightMemoryBlock.getData() == nullptr);
 
-    free(buf);
+  free(buf);
 }
 
 TEST(memoryBlock, operators) {
-    MemoryBlock memoryBlock(12, false);
+  MemoryBlock memoryBlock(12, false);
 
-    MemoryBlock operaterMemoryBlock = memoryBlock;
+  MemoryBlock operaterMemoryBlock = memoryBlock;
 
-    EXPECT_TRUE(operaterMemoryBlock == memoryBlock);
+  EXPECT_TRUE(operaterMemoryBlock == memoryBlock);
 
-    char *buf = (char *) malloc(sizeof(char) * 9);
-    strcpy(buf, "RocketMQ");
-    MemoryBlock twoMemoryBlock(buf, 12);
-    EXPECT_FALSE(memoryBlock == twoMemoryBlock);
+  char* buf = (char*)malloc(sizeof(char) * 16);
+  memset(buf, 0, 16);
+  strcpy(buf, "RocketMQ");
+  MemoryBlock twoMemoryBlock(buf, 12);
+  EXPECT_FALSE(memoryBlock == twoMemoryBlock);
 
-    MemoryBlock threeMemoryBlock(buf, 16);
-    EXPECT_FALSE(memoryBlock == threeMemoryBlock);
-    EXPECT_TRUE(twoMemoryBlock != threeMemoryBlock);
+  MemoryBlock threeMemoryBlock(buf, 16);
+  EXPECT_FALSE(memoryBlock == threeMemoryBlock);
+  EXPECT_TRUE(twoMemoryBlock != threeMemoryBlock);
 
-    threeMemoryBlock.fillWith(49);
-    EXPECT_EQ(string(threeMemoryBlock.getData()), "1111111111111111");
+  threeMemoryBlock.fillWith(49);
+  EXPECT_EQ(string(threeMemoryBlock.getData(), 16), "1111111111111111");
 
-    threeMemoryBlock.reset();
-    EXPECT_EQ(threeMemoryBlock.getSize(), 0);
-    EXPECT_TRUE(threeMemoryBlock.getData() == nullptr);
+  threeMemoryBlock.reset();
+  EXPECT_EQ(threeMemoryBlock.getSize(), 0);
+  EXPECT_TRUE(threeMemoryBlock.getData() == nullptr);
 
-    threeMemoryBlock.setSize(16, 0);
-    EXPECT_EQ(threeMemoryBlock.getSize(), 16);
-    // EXPECT_EQ(threeMemoryBlock.getData() , buf);
+  threeMemoryBlock.setSize(16, 0);
+  EXPECT_EQ(threeMemoryBlock.getSize(), 16);
+  // EXPECT_EQ(threeMemoryBlock.getData() , buf);
 
-    threeMemoryBlock.setSize(0, 0);
-    EXPECT_EQ(threeMemoryBlock.getSize(), 0);
-    EXPECT_TRUE(threeMemoryBlock.getData() == nullptr);
+  threeMemoryBlock.setSize(0, 0);
+  EXPECT_EQ(threeMemoryBlock.getSize(), 0);
+  EXPECT_TRUE(threeMemoryBlock.getData() == nullptr);
 
-    MemoryBlock appendMemoryBlock;
-    EXPECT_EQ(appendMemoryBlock.getSize(), 0);
-    EXPECT_TRUE(appendMemoryBlock.getData() == nullptr);
+  MemoryBlock appendMemoryBlock;
+  EXPECT_EQ(appendMemoryBlock.getSize(), 0);
+  EXPECT_TRUE(appendMemoryBlock.getData() == nullptr);
 
-    appendMemoryBlock.append(buf, -1);
-    EXPECT_EQ(appendMemoryBlock.getSize(), 0);
-    EXPECT_TRUE(appendMemoryBlock.getData() == nullptr);
+  appendMemoryBlock.append(buf, -1);
+  EXPECT_EQ(appendMemoryBlock.getSize(), 0);
+  EXPECT_TRUE(appendMemoryBlock.getData() == nullptr);
 
-    appendMemoryBlock.append(buf, 8);
-    EXPECT_EQ(appendMemoryBlock.getSize(), 8);
+  appendMemoryBlock.append(buf, 8);
+  EXPECT_EQ(appendMemoryBlock.getSize(), 8);
 
-    EXPECT_EQ(string(appendMemoryBlock.getData()), "RocketMQ11111111");
+  MemoryBlock replaceWithMemoryBlock;
+  replaceWithMemoryBlock.append(buf, 8);
 
-    MemoryBlock replaceWithMemoryBlock;
-    replaceWithMemoryBlock.append(buf, 8);
+  char* aliyunBuf = (char*)malloc(sizeof(char) * 8);
+  memset(aliyunBuf, 0, 8);
+  strcpy(aliyunBuf, "aliyun");
+  replaceWithMemoryBlock.replaceWith(aliyunBuf, 0);
+  EXPECT_EQ(replaceWithMemoryBlock.getSize(), 8);
+  EXPECT_EQ(string(replaceWithMemoryBlock.getData(), 8), "RocketMQ");
 
-    char *aliyunBuf = (char *) malloc(sizeof(char) * 8);
-    strcpy(aliyunBuf, "aliyun");
-    replaceWithMemoryBlock.replaceWith(aliyunBuf, 0);
-    EXPECT_EQ(replaceWithMemoryBlock.getSize(), 8);
-    EXPECT_EQ(string(replaceWithMemoryBlock.getData()), "RocketMQ");
+  replaceWithMemoryBlock.replaceWith(aliyunBuf, 6);
+  EXPECT_EQ(replaceWithMemoryBlock.getSize(), 6);
+  EXPECT_EQ(string(replaceWithMemoryBlock.getData(), strlen(aliyunBuf)), "aliyun");
 
-    replaceWithMemoryBlock.replaceWith(aliyunBuf, 6);
-    EXPECT_EQ(replaceWithMemoryBlock.getSize(), 6);
-    EXPECT_EQ(string(replaceWithMemoryBlock.getData()), "aliyunMQ");
+  MemoryBlock insertMemoryBlock;
+  insertMemoryBlock.append(buf, 8);
+  insertMemoryBlock.insert(aliyunBuf, -1, -1);
+  EXPECT_EQ(string(insertMemoryBlock.getData(), 8), "RocketMQ");
 
-    MemoryBlock insertMemoryBlock;
-    insertMemoryBlock.append(buf, 8);
+  /*    MemoryBlock fourInsertMemoryBlock;
+   fourInsertMemoryBlock.append(buf , 8);
+   // 6+ (-1)
+   fourInsertMemoryBlock.insert(aliyunBuf , 8 , -1);
+   string fourStr( fourInsertMemoryBlock.getData());
+   EXPECT_TRUE( fourStr == "liyun");*/
 
-    insertMemoryBlock.insert(aliyunBuf, -1, -1);
-    EXPECT_EQ(string(insertMemoryBlock.getData()), "RocketMQ");
+  MemoryBlock twoInsertMemoryBlock;
+  twoInsertMemoryBlock.append(buf, 8);
+  twoInsertMemoryBlock.insert(aliyunBuf, strlen(aliyunBuf), 0);
+  EXPECT_EQ(string(twoInsertMemoryBlock.getData(), 8 + strlen(aliyunBuf)), "aliyunRocketMQ");
 
-    /*    MemoryBlock fourInsertMemoryBlock;
-     fourInsertMemoryBlock.append(buf , 8);
-     // 6+ (-1)
-     fourInsertMemoryBlock.insert(aliyunBuf , 8 , -1);
-     string fourStr( fourInsertMemoryBlock.getData());
-     EXPECT_TRUE( fourStr == "liyun");*/
+  MemoryBlock threeInsertMemoryBlock;
+  threeInsertMemoryBlock.append(buf, 8);
+  threeInsertMemoryBlock.insert(aliyunBuf, 6, 100);
+  EXPECT_EQ(string(threeInsertMemoryBlock.getData(), 8 + strlen(aliyunBuf)), "RocketMQaliyun");
 
-    MemoryBlock twoInsertMemoryBlock;
-    twoInsertMemoryBlock.append(buf, 8);
-    twoInsertMemoryBlock.insert(aliyunBuf, 8, 0);
-    EXPECT_EQ(string(twoInsertMemoryBlock.getData()), "aliyun");
+  MemoryBlock removeSectionMemoryBlock(buf, 8);
+  removeSectionMemoryBlock.removeSection(8, -1);
+  EXPECT_EQ(string(removeSectionMemoryBlock.getData(), 8), "RocketMQ");
 
-    MemoryBlock threeInsertMemoryBlock;
-    threeInsertMemoryBlock.append(buf, 8);
-    threeInsertMemoryBlock.insert(aliyunBuf, 6, 100);
-    EXPECT_EQ(string(threeInsertMemoryBlock.getData()), "RocketMQaliyun");
+  MemoryBlock twoRemoveSectionMemoryBlock(buf, 8);
+  twoRemoveSectionMemoryBlock.removeSection(1, 4);
+  string str(twoRemoveSectionMemoryBlock.getData(), 4);
+  EXPECT_TRUE(str == "RtMQ");
 
-    MemoryBlock removeSectionMemoryBlock(buf, 8);
-    removeSectionMemoryBlock.removeSection(8, -1);
-    EXPECT_EQ(string(removeSectionMemoryBlock.getData()), "RocketMQ");
-
-    MemoryBlock twoRemoveSectionMemoryBlock(buf, 8);
-    twoRemoveSectionMemoryBlock.removeSection(1, 4);
-    string str(twoRemoveSectionMemoryBlock.getData(), 4);
-    EXPECT_TRUE(str == "RtMQ");
-
-    free(buf);
-    free(aliyunBuf);
+  free(buf);
+  free(aliyunBuf);
 }
 
-int main(int argc, char *argv[]) {
-    InitGoogleMock(&argc, argv);
-    testing::GTEST_FLAG(throw_on_failure) = true;
-    testing::GTEST_FLAG(filter) = "memoryBlock.*";
-    int itestts = RUN_ALL_TESTS();
-    return itestts;
+int main(int argc, char* argv[]) {
+  InitGoogleMock(&argc, argv);
+  testing::GTEST_FLAG(throw_on_failure) = true;
+  testing::GTEST_FLAG(filter) = "memoryBlock.*";
+  int itestts = RUN_ALL_TESTS();
+  return itestts;
 }
diff --git a/test/src/common/MemoryOutputStreamTest.cpp b/test/src/common/MemoryOutputStreamTest.cpp
index 6cf1015..05af181 100644
--- a/test/src/common/MemoryOutputStreamTest.cpp
+++ b/test/src/common/MemoryOutputStreamTest.cpp
@@ -34,191 +34,191 @@
 using rocketmq::MemoryOutputStream;
 
 TEST(memoryOutputStream, init) {
-    MemoryOutputStream memoryOutput;
-    EXPECT_EQ(memoryOutput.getMemoryBlock().getSize(), 0);
-    EXPECT_TRUE(memoryOutput.getData() != nullptr);
+  MemoryOutputStream memoryOutput;
+  EXPECT_EQ(memoryOutput.getMemoryBlock().getSize(), 0);
+  EXPECT_TRUE(memoryOutput.getData() != nullptr);
 
-    EXPECT_EQ(memoryOutput.getPosition(), 0);
-    EXPECT_EQ(memoryOutput.getDataSize(), 0);
+  EXPECT_EQ(memoryOutput.getPosition(), 0);
+  EXPECT_EQ(memoryOutput.getDataSize(), 0);
 
-    MemoryOutputStream twoMemoryOutput(512);
-    EXPECT_EQ(memoryOutput.getMemoryBlock().getSize(), 0);
+  MemoryOutputStream twoMemoryOutput(512);
+  EXPECT_EQ(memoryOutput.getMemoryBlock().getSize(), 0);
 
-    MemoryBlock memoryBlock(12, false);
-    MemoryOutputStream threeMemoryOutput(memoryBlock, false);
-    EXPECT_EQ(threeMemoryOutput.getPosition(), 0);
-    EXPECT_EQ(threeMemoryOutput.getDataSize(), 0);
+  MemoryBlock memoryBlock(12, false);
+  MemoryOutputStream threeMemoryOutput(memoryBlock, false);
+  EXPECT_EQ(threeMemoryOutput.getPosition(), 0);
+  EXPECT_EQ(threeMemoryOutput.getDataSize(), 0);
 
-    MemoryOutputStream frouMemoryOutput(memoryBlock, true);
-    EXPECT_EQ(frouMemoryOutput.getPosition(), memoryBlock.getSize());
-    EXPECT_EQ(frouMemoryOutput.getDataSize(), memoryBlock.getSize());
+  MemoryOutputStream frouMemoryOutput(memoryBlock, true);
+  EXPECT_EQ(frouMemoryOutput.getPosition(), memoryBlock.getSize());
+  EXPECT_EQ(frouMemoryOutput.getDataSize(), memoryBlock.getSize());
 
-    char *buf = (char *) malloc(sizeof(char) * 9);
-    strcpy(buf, "RocketMQ");
-    MemoryOutputStream fiveMemoryOutputStream(buf, 8);
-    EXPECT_EQ(fiveMemoryOutputStream.getData(), buf);
+  char* buf = (char*)malloc(sizeof(char) * 9);
+  strcpy(buf, "RocketMQ");
+  MemoryOutputStream fiveMemoryOutputStream(buf, 8);
+  EXPECT_EQ(fiveMemoryOutputStream.getData(), buf);
 
-    fiveMemoryOutputStream.reset();
-    EXPECT_EQ(memoryOutput.getPosition(), 0);
-    EXPECT_EQ(memoryOutput.getDataSize(), 0);
-    free(buf);
+  fiveMemoryOutputStream.reset();
+  EXPECT_EQ(memoryOutput.getPosition(), 0);
+  EXPECT_EQ(memoryOutput.getDataSize(), 0);
+  free(buf);
 }
 
 TEST(memoryOutputStream, flush) {
-    char *buf = (char *) malloc(sizeof(char) * 9);
-    strcpy(buf, "RocketMQ");
-    MemoryOutputStream memoryOutput;
-    memoryOutput.write(buf, 9);
-    memoryOutput.flush();
-    EXPECT_FALSE(memoryOutput.getData() == buf);
-    free(buf);
+  char* buf = (char*)malloc(sizeof(char) * 9);
+  strcpy(buf, "RocketMQ");
+  MemoryOutputStream memoryOutput;
+  memoryOutput.write(buf, 9);
+  memoryOutput.flush();
+  EXPECT_FALSE(memoryOutput.getData() == buf);
+  free(buf);
 }
 
 TEST(memoryOutputStream, preallocate) {
-    MemoryOutputStream memoryOutput;
-    memoryOutput.preallocate(250);
+  MemoryOutputStream memoryOutput;
+  memoryOutput.preallocate(250);
 
-    memoryOutput.preallocate(256);
+  memoryOutput.preallocate(256);
 }
 
 TEST(memoryOutputStream, getMemoryBlock) {
-    char *buf = (char *) malloc(sizeof(char) * 9);
-    strcpy(buf, "RocketMQ");
-    MemoryOutputStream memoryOutput;
-    memoryOutput.write(buf, 9);
-    MemoryBlock memoryBlock = memoryOutput.getMemoryBlock();
-    EXPECT_EQ(memoryBlock.getSize(), memoryOutput.getDataSize());
-    free(buf);
+  char* buf = (char*)malloc(sizeof(char) * 9);
+  strcpy(buf, "RocketMQ");
+  MemoryOutputStream memoryOutput;
+  memoryOutput.write(buf, 9);
+  MemoryBlock memoryBlock = memoryOutput.getMemoryBlock();
+  EXPECT_EQ(memoryBlock.getSize(), memoryOutput.getDataSize());
+  free(buf);
 }
 
 TEST(memoryOutputStream, prepareToWriteAndGetData) {
-    char *buf = (char *) malloc(sizeof(char) * 9);
-    strcpy(buf, "RocketMQ");
-    MemoryOutputStream memoryOutput(buf, 9);
-    EXPECT_EQ(memoryOutput.getData(), buf);
+  char* buf = (char*)malloc(sizeof(char) * 9);
+  strcpy(buf, "RocketMQ");
+  MemoryOutputStream memoryOutput(buf, 9);
+  EXPECT_EQ(memoryOutput.getData(), buf);
 
-    // prepareToWrite
-    // EXPECT_TRUE(memoryOutput.writeIntBigEndian(123));
-    EXPECT_TRUE(memoryOutput.writeByte('r'));
-    const char *data = static_cast<const char *>(memoryOutput.getData());
-    EXPECT_EQ(string(data), "rocketMQ");
+  // prepareToWrite
+  // EXPECT_TRUE(memoryOutput.writeIntBigEndian(123));
+  EXPECT_TRUE(memoryOutput.writeByte('r'));
+  const char* data = static_cast<const char*>(memoryOutput.getData());
+  EXPECT_EQ(string(data), "rocketMQ");
 
-    MemoryOutputStream blockMmoryOutput(8);
-    char *memoryData = (char *) blockMmoryOutput.getData();
+  MemoryOutputStream blockMmoryOutput(8);
+  char* memoryData = (char*)blockMmoryOutput.getData();
 
-    EXPECT_EQ(memoryData[blockMmoryOutput.getDataSize()], 0);
+  EXPECT_EQ(memoryData[blockMmoryOutput.getDataSize()], 0);
 
-    blockMmoryOutput.write(buf, 8);
-    blockMmoryOutput.write(buf, 8);
-    data = static_cast<const char *>(blockMmoryOutput.getData());
-    EXPECT_EQ(string(data), "rocketMQrocketMQ");
-    free(buf);
+  blockMmoryOutput.write(buf, 8);
+  blockMmoryOutput.write(buf, 8);
+  data = static_cast<const char*>(blockMmoryOutput.getData());
+  EXPECT_EQ(string(data), "rocketMQrocketMQ");
+  free(buf);
 }
 
 TEST(memoryOutputStream, position) {
-    char *buf = (char *) malloc(sizeof(char) * 9);
-    strcpy(buf, "RocketMQ");
+  char* buf = (char*)malloc(sizeof(char) * 9);
+  strcpy(buf, "RocketMQ");
 
-    MemoryOutputStream memoryOutput;
-    EXPECT_EQ(memoryOutput.getPosition(), 0);
+  MemoryOutputStream memoryOutput;
+  EXPECT_EQ(memoryOutput.getPosition(), 0);
 
-    memoryOutput.write(buf, 8);
-    EXPECT_EQ(memoryOutput.getPosition(), 8);
+  memoryOutput.write(buf, 8);
+  EXPECT_EQ(memoryOutput.getPosition(), 8);
 
-    EXPECT_FALSE(memoryOutput.setPosition(9));
+  EXPECT_FALSE(memoryOutput.setPosition(9));
 
-    EXPECT_TRUE(memoryOutput.setPosition(-1));
-    EXPECT_EQ(memoryOutput.getPosition(), 0);
+  EXPECT_TRUE(memoryOutput.setPosition(-1));
+  EXPECT_EQ(memoryOutput.getPosition(), 0);
 
-    EXPECT_TRUE(memoryOutput.setPosition(8));
-    EXPECT_EQ(memoryOutput.getPosition(), 8);
+  EXPECT_TRUE(memoryOutput.setPosition(8));
+  EXPECT_EQ(memoryOutput.getPosition(), 8);
 
-    EXPECT_TRUE(memoryOutput.setPosition(7));
-    EXPECT_EQ(memoryOutput.getPosition(), 7);
-    free(buf);
+  EXPECT_TRUE(memoryOutput.setPosition(7));
+  EXPECT_EQ(memoryOutput.getPosition(), 7);
+  free(buf);
 }
 
 TEST(memoryOutputStream, write) {
-    MemoryOutputStream memoryOutput;
-    MemoryInputStream memoryInput(memoryOutput.getData(), 256, false);
+  MemoryOutputStream memoryOutput;
+  MemoryInputStream memoryInput(memoryOutput.getData(), 256, false);
 
-    EXPECT_TRUE(memoryOutput.writeBool(true));
-    EXPECT_TRUE(memoryInput.readBool());
+  EXPECT_TRUE(memoryOutput.writeBool(true));
+  EXPECT_TRUE(memoryInput.readBool());
 
-    EXPECT_TRUE(memoryOutput.writeBool(false));
-    EXPECT_FALSE(memoryInput.readBool());
+  EXPECT_TRUE(memoryOutput.writeBool(false));
+  EXPECT_FALSE(memoryInput.readBool());
 
-    EXPECT_TRUE(memoryOutput.writeByte('a'));
-    EXPECT_EQ(memoryInput.readByte(), 'a');
+  EXPECT_TRUE(memoryOutput.writeByte('a'));
+  EXPECT_EQ(memoryInput.readByte(), 'a');
 
-    EXPECT_TRUE(memoryOutput.writeShortBigEndian(128));
-    EXPECT_EQ(memoryInput.readShortBigEndian(), 128);
+  EXPECT_TRUE(memoryOutput.writeShortBigEndian(128));
+  EXPECT_EQ(memoryInput.readShortBigEndian(), 128);
 
-    EXPECT_TRUE(memoryOutput.writeIntBigEndian(123));
-    EXPECT_EQ(memoryInput.readIntBigEndian(), 123);
+  EXPECT_TRUE(memoryOutput.writeIntBigEndian(123));
+  EXPECT_EQ(memoryInput.readIntBigEndian(), 123);
 
-    EXPECT_TRUE(memoryOutput.writeInt64BigEndian(123123));
-    EXPECT_EQ(memoryInput.readInt64BigEndian(), 123123);
+  EXPECT_TRUE(memoryOutput.writeInt64BigEndian(123123));
+  EXPECT_EQ(memoryInput.readInt64BigEndian(), 123123);
 
-    EXPECT_TRUE(memoryOutput.writeDoubleBigEndian(12.71));
-    EXPECT_EQ(memoryInput.readDoubleBigEndian(), 12.71);
+  EXPECT_TRUE(memoryOutput.writeDoubleBigEndian(12.71));
+  EXPECT_EQ(memoryInput.readDoubleBigEndian(), 12.71);
 
-    EXPECT_TRUE(memoryOutput.writeFloatBigEndian(12.1));
-    float f = 12.1;
-    EXPECT_EQ(memoryInput.readFloatBigEndian(), f);
+  EXPECT_TRUE(memoryOutput.writeFloatBigEndian(12.1));
+  float f = 12.1;
+  EXPECT_EQ(memoryInput.readFloatBigEndian(), f);
 
-    // EXPECT_TRUE(memoryOutput.writeRepeatedByte(8 , 8));
+  // EXPECT_TRUE(memoryOutput.writeRepeatedByte(8 , 8));
 }
 
 TEST(memoryInputStream, info) {
-    char *buf = (char *) malloc(sizeof(char) * 9);
-    strcpy(buf, "RocketMQ");
+  char* buf = (char*)malloc(sizeof(char) * 9);
+  strcpy(buf, "RocketMQ");
 
-    MemoryInputStream memoryInput(buf, 8, false);
+  MemoryInputStream memoryInput(buf, 8, false);
 
-    char *memoryData = (char *) memoryInput.getData();
-    EXPECT_EQ(memoryData, buf);
+  char* memoryData = (char*)memoryInput.getData();
+  EXPECT_EQ(memoryData, buf);
 
-    EXPECT_EQ(memoryInput.getTotalLength(), 8);
+  EXPECT_EQ(memoryInput.getTotalLength(), 8);
 
-    MemoryInputStream twoMemoryInput(buf, 8, true);
-    EXPECT_NE(twoMemoryInput.getData(), buf);
+  MemoryInputStream twoMemoryInput(buf, 8, true);
+  EXPECT_NE(twoMemoryInput.getData(), buf);
 
-    memoryData = (char *) twoMemoryInput.getData();
-    EXPECT_NE(&memoryData, &buf);
+  memoryData = (char*)twoMemoryInput.getData();
+  EXPECT_NE(&memoryData, &buf);
 
-    MemoryBlock memoryBlock(buf, 8);
-    MemoryInputStream threeMemoryInput(memoryBlock, false);
-    memoryData = (char *) threeMemoryInput.getData();
-    EXPECT_EQ(memoryData, threeMemoryInput.getData());
-    EXPECT_EQ(threeMemoryInput.getTotalLength(), 8);
+  MemoryBlock memoryBlock(buf, 8);
+  MemoryInputStream threeMemoryInput(memoryBlock, false);
+  memoryData = (char*)threeMemoryInput.getData();
+  EXPECT_EQ(memoryData, threeMemoryInput.getData());
+  EXPECT_EQ(threeMemoryInput.getTotalLength(), 8);
 
-    MemoryInputStream frouMemoryInput(memoryBlock, true);
-    EXPECT_NE(frouMemoryInput.getData(), memoryBlock.getData());
-    free(buf);
+  MemoryInputStream frouMemoryInput(memoryBlock, true);
+  EXPECT_NE(frouMemoryInput.getData(), memoryBlock.getData());
+  free(buf);
 }
 
 TEST(memoryInputStream, position) {
-    char *buf = (char *) malloc(sizeof(char) * 9);
-    strcpy(buf, "RocketMQ");
+  char* buf = (char*)malloc(sizeof(char) * 9);
+  strcpy(buf, "RocketMQ");
 
-    MemoryInputStream memoryInput(buf, 8, false);
-    EXPECT_EQ(memoryInput.getPosition(), 0);
-    EXPECT_FALSE(memoryInput.isExhausted());
+  MemoryInputStream memoryInput(buf, 8, false);
+  EXPECT_EQ(memoryInput.getPosition(), 0);
+  EXPECT_FALSE(memoryInput.isExhausted());
 
-    memoryInput.setPosition(9);
-    EXPECT_EQ(memoryInput.getPosition(), 8);
-    EXPECT_TRUE(memoryInput.isExhausted());
+  memoryInput.setPosition(9);
+  EXPECT_EQ(memoryInput.getPosition(), 8);
+  EXPECT_TRUE(memoryInput.isExhausted());
 
-    memoryInput.setPosition(-1);
-    EXPECT_EQ(memoryInput.getPosition(), 0);
-    free(buf);
+  memoryInput.setPosition(-1);
+  EXPECT_EQ(memoryInput.getPosition(), 0);
+  free(buf);
 }
 
-int main(int argc, char *argv[]) {
-    InitGoogleMock(&argc, argv);
-    testing::GTEST_FLAG(throw_on_failure) = true;
-    testing::GTEST_FLAG(filter) = "*.*";
-    int itestts = RUN_ALL_TESTS();
-    return itestts;
+int main(int argc, char* argv[]) {
+  InitGoogleMock(&argc, argv);
+  testing::GTEST_FLAG(throw_on_failure) = true;
+  testing::GTEST_FLAG(filter) = "*.*";
+  int itestts = RUN_ALL_TESTS();
+  return itestts;
 }
diff --git a/test/src/common/NamesrvConfigTest.cpp b/test/src/common/NamesrvConfigTest.cpp
index 1ac2c13..e4e1206 100644
--- a/test/src/common/NamesrvConfigTest.cpp
+++ b/test/src/common/NamesrvConfigTest.cpp
@@ -31,20 +31,20 @@
 using rocketmq::NamesrvConfig;
 
 TEST(namesrvConfig, init) {
-    NamesrvConfig namesrvConfig;
+  NamesrvConfig namesrvConfig;
 
-    const string home = "/home/rocketmq";
-    namesrvConfig.setRocketmqHome(home);
-    EXPECT_EQ(namesrvConfig.getRocketmqHome(), "/home/rocketmq");
+  const string home = "/home/rocketmq";
+  namesrvConfig.setRocketmqHome(home);
+  EXPECT_EQ(namesrvConfig.getRocketmqHome(), "/home/rocketmq");
 
-    namesrvConfig.setKvConfigPath("/home/rocketmq");
-    EXPECT_EQ(namesrvConfig.getKvConfigPath(), "/home/rocketmq");
+  namesrvConfig.setKvConfigPath("/home/rocketmq");
+  EXPECT_EQ(namesrvConfig.getKvConfigPath(), "/home/rocketmq");
 }
 
-int main(int argc, char *argv[]) {
-    InitGoogleMock(&argc, argv);
-    testing::GTEST_FLAG(throw_on_failure) = true;
-    testing::GTEST_FLAG(filter) = "namesrvConfig.init";
-    int itestts = RUN_ALL_TESTS();
-    return itestts;
+int main(int argc, char* argv[]) {
+  InitGoogleMock(&argc, argv);
+  testing::GTEST_FLAG(throw_on_failure) = true;
+  testing::GTEST_FLAG(filter) = "namesrvConfig.init";
+  int itestts = RUN_ALL_TESTS();
+  return itestts;
 }
diff --git a/test/src/common/PermNametTest.cpp b/test/src/common/PermNametTest.cpp
index 1a98e31..3296b84 100644
--- a/test/src/common/PermNametTest.cpp
+++ b/test/src/common/PermNametTest.cpp
@@ -26,21 +26,21 @@
 using rocketmq::PermName;
 
 TEST(permName, perm2String) {
-    EXPECT_EQ(PermName::perm2String(0), "---");
-    EXPECT_EQ(PermName::perm2String(1), "--X");
-    EXPECT_EQ(PermName::perm2String(2), "-W");
-    EXPECT_EQ(PermName::perm2String(3), "-WX");
-    EXPECT_EQ(PermName::perm2String(4), "R--");
-    EXPECT_EQ(PermName::perm2String(5), "R-X");
-    EXPECT_EQ(PermName::perm2String(6), "RW");
-    EXPECT_EQ(PermName::perm2String(7), "RWX");
-    EXPECT_EQ(PermName::perm2String(8), "---");
+  EXPECT_EQ(PermName::perm2String(0), "---");
+  EXPECT_EQ(PermName::perm2String(1), "--X");
+  EXPECT_EQ(PermName::perm2String(2), "-W");
+  EXPECT_EQ(PermName::perm2String(3), "-WX");
+  EXPECT_EQ(PermName::perm2String(4), "R--");
+  EXPECT_EQ(PermName::perm2String(5), "R-X");
+  EXPECT_EQ(PermName::perm2String(6), "RW");
+  EXPECT_EQ(PermName::perm2String(7), "RWX");
+  EXPECT_EQ(PermName::perm2String(8), "---");
 }
 
-int main(int argc, char *argv[]) {
-    InitGoogleMock(&argc, argv);
-    testing::GTEST_FLAG(throw_on_failure) = true;
-    testing::GTEST_FLAG(filter) = "permName.perm2String";
-    int itestts = RUN_ALL_TESTS();
-    return itestts;
+int main(int argc, char* argv[]) {
+  InitGoogleMock(&argc, argv);
+  testing::GTEST_FLAG(throw_on_failure) = true;
+  testing::GTEST_FLAG(filter) = "permName.perm2String";
+  int itestts = RUN_ALL_TESTS();
+  return itestts;
 }
diff --git a/test/src/common/PullSysFlagTest.cpp b/test/src/common/PullSysFlagTest.cpp
index 4e5ebd5..7b7c9db 100644
--- a/test/src/common/PullSysFlagTest.cpp
+++ b/test/src/common/PullSysFlagTest.cpp
@@ -26,70 +26,70 @@
 using rocketmq::PullSysFlag;
 
 TEST(pullSysFlag, flag) {
-    EXPECT_EQ(PullSysFlag::buildSysFlag(false, false, false, false), 0);
+  EXPECT_EQ(PullSysFlag::buildSysFlag(false, false, false, false), 0);
 
-    EXPECT_EQ(PullSysFlag::buildSysFlag(true, false, false, false), 1);
-    EXPECT_EQ(PullSysFlag::buildSysFlag(true, true, false, false), 3);
-    EXPECT_EQ(PullSysFlag::buildSysFlag(true, true, true, false), 7);
-    EXPECT_EQ(PullSysFlag::buildSysFlag(true, true, true, true), 15);
+  EXPECT_EQ(PullSysFlag::buildSysFlag(true, false, false, false), 1);
+  EXPECT_EQ(PullSysFlag::buildSysFlag(true, true, false, false), 3);
+  EXPECT_EQ(PullSysFlag::buildSysFlag(true, true, true, false), 7);
+  EXPECT_EQ(PullSysFlag::buildSysFlag(true, true, true, true), 15);
 
-    EXPECT_EQ(PullSysFlag::buildSysFlag(false, true, false, false), 2);
-    EXPECT_EQ(PullSysFlag::buildSysFlag(false, true, true, false), 6);
-    EXPECT_EQ(PullSysFlag::buildSysFlag(false, true, true, true), 14);
+  EXPECT_EQ(PullSysFlag::buildSysFlag(false, true, false, false), 2);
+  EXPECT_EQ(PullSysFlag::buildSysFlag(false, true, true, false), 6);
+  EXPECT_EQ(PullSysFlag::buildSysFlag(false, true, true, true), 14);
 
-    EXPECT_EQ(PullSysFlag::buildSysFlag(false, false, true, false), 4);
-    EXPECT_EQ(PullSysFlag::buildSysFlag(false, false, true, true), 12);
+  EXPECT_EQ(PullSysFlag::buildSysFlag(false, false, true, false), 4);
+  EXPECT_EQ(PullSysFlag::buildSysFlag(false, false, true, true), 12);
 
-    EXPECT_EQ(PullSysFlag::buildSysFlag(false, false, false, true), 8);
+  EXPECT_EQ(PullSysFlag::buildSysFlag(false, false, false, true), 8);
 
-    int FLAG_COMMIT_OFFSET = 0x1 << 0;
-    int FLAG_SUSPEND = 0x1 << 1;
-    int FLAG_SUBSCRIPTION = 0x1 << 2;
-    int FLAG_CLASS_FILTER = 0x1 << 3;
+  int FLAG_COMMIT_OFFSET = 0x1 << 0;
+  int FLAG_SUSPEND = 0x1 << 1;
+  int FLAG_SUBSCRIPTION = 0x1 << 2;
+  int FLAG_CLASS_FILTER = 0x1 << 3;
 
-    for (int i = 0; i < 16; i++) {
-        if ((i & FLAG_COMMIT_OFFSET) == FLAG_COMMIT_OFFSET) {
-            EXPECT_TRUE(PullSysFlag::hasCommitOffsetFlag(i));
-        } else {
-            EXPECT_FALSE(PullSysFlag::hasCommitOffsetFlag(i));
-        }
-
-        if ((i & FLAG_SUSPEND) == FLAG_SUSPEND) {
-            EXPECT_TRUE(PullSysFlag::hasSuspendFlag(i));
-        } else {
-            EXPECT_FALSE(PullSysFlag::hasSuspendFlag(i));
-        }
-
-        if ((i & FLAG_SUBSCRIPTION) == FLAG_SUBSCRIPTION) {
-            EXPECT_TRUE(PullSysFlag::hasSubscriptionFlag(i));
-        } else {
-            EXPECT_FALSE(PullSysFlag::hasSubscriptionFlag(i));
-        }
-
-        if ((i & FLAG_CLASS_FILTER) == FLAG_CLASS_FILTER) {
-            EXPECT_TRUE(PullSysFlag::hasClassFilterFlag(i));
-        } else {
-            EXPECT_FALSE(PullSysFlag::hasClassFilterFlag(i));
-        }
-
-        if ((i & FLAG_COMMIT_OFFSET) == FLAG_COMMIT_OFFSET) {
-            EXPECT_TRUE(PullSysFlag::hasCommitOffsetFlag(i));
-        } else {
-            EXPECT_FALSE(PullSysFlag::hasCommitOffsetFlag(i));
-        }
-
-        if (i == 0 || i == 1) {
-            EXPECT_EQ(PullSysFlag::clearCommitOffsetFlag(i), 0);
-        } else {
-            EXPECT_TRUE(PullSysFlag::clearCommitOffsetFlag(i) > 0);
-        }
+  for (int i = 0; i < 16; i++) {
+    if ((i & FLAG_COMMIT_OFFSET) == FLAG_COMMIT_OFFSET) {
+      EXPECT_TRUE(PullSysFlag::hasCommitOffsetFlag(i));
+    } else {
+      EXPECT_FALSE(PullSysFlag::hasCommitOffsetFlag(i));
     }
+
+    if ((i & FLAG_SUSPEND) == FLAG_SUSPEND) {
+      EXPECT_TRUE(PullSysFlag::hasSuspendFlag(i));
+    } else {
+      EXPECT_FALSE(PullSysFlag::hasSuspendFlag(i));
+    }
+
+    if ((i & FLAG_SUBSCRIPTION) == FLAG_SUBSCRIPTION) {
+      EXPECT_TRUE(PullSysFlag::hasSubscriptionFlag(i));
+    } else {
+      EXPECT_FALSE(PullSysFlag::hasSubscriptionFlag(i));
+    }
+
+    if ((i & FLAG_CLASS_FILTER) == FLAG_CLASS_FILTER) {
+      EXPECT_TRUE(PullSysFlag::hasClassFilterFlag(i));
+    } else {
+      EXPECT_FALSE(PullSysFlag::hasClassFilterFlag(i));
+    }
+
+    if ((i & FLAG_COMMIT_OFFSET) == FLAG_COMMIT_OFFSET) {
+      EXPECT_TRUE(PullSysFlag::hasCommitOffsetFlag(i));
+    } else {
+      EXPECT_FALSE(PullSysFlag::hasCommitOffsetFlag(i));
+    }
+
+    if (i == 0 || i == 1) {
+      EXPECT_EQ(PullSysFlag::clearCommitOffsetFlag(i), 0);
+    } else {
+      EXPECT_TRUE(PullSysFlag::clearCommitOffsetFlag(i) > 0);
+    }
+  }
 }
 
-int main(int argc, char *argv[]) {
-    InitGoogleMock(&argc, argv);
-    testing::GTEST_FLAG(throw_on_failure) = true;
-    testing::GTEST_FLAG(filter) = "pullSysFlag.flag";
-    int itestts = RUN_ALL_TESTS();
-    return itestts;
+int main(int argc, char* argv[]) {
+  InitGoogleMock(&argc, argv);
+  testing::GTEST_FLAG(throw_on_failure) = true;
+  testing::GTEST_FLAG(filter) = "pullSysFlag.flag";
+  int itestts = RUN_ALL_TESTS();
+  return itestts;
 }
diff --git a/test/src/common/TopicConfigTest.cpp b/test/src/common/TopicConfigTest.cpp
index d435ba6..8c16394 100644
--- a/test/src/common/TopicConfigTest.cpp
+++ b/test/src/common/TopicConfigTest.cpp
@@ -34,60 +34,60 @@
 using rocketmq::TopicFilterType;
 
 TEST(topicConfig, encodeAndDecode) {
-    TopicConfig topicConfig("testTopic", 4, 4, PermName::PERM_READ);
-    string str = topicConfig.encode();
+  TopicConfig topicConfig("testTopic", 4, 4, PermName::PERM_READ);
+  string str = topicConfig.encode();
 
-    TopicConfig topicDecodeConfig;
-    topicDecodeConfig.decode(str);
-    EXPECT_EQ(str, topicDecodeConfig.encode());
+  TopicConfig topicDecodeConfig;
+  topicDecodeConfig.decode(str);
+  EXPECT_EQ(str, topicDecodeConfig.encode());
 }
 
 TEST(topicConfig, info) {
-    TopicConfig topicConfig;
+  TopicConfig topicConfig;
 
-    topicConfig.setTopicName("testTopic");
-    EXPECT_EQ(topicConfig.getTopicName(), "testTopic");
+  topicConfig.setTopicName("testTopic");
+  EXPECT_EQ(topicConfig.getTopicName(), "testTopic");
 
-    topicConfig.setReadQueueNums(4);
-    EXPECT_EQ(topicConfig.getReadQueueNums(), 4);
+  topicConfig.setReadQueueNums(4);
+  EXPECT_EQ(topicConfig.getReadQueueNums(), 4);
 
-    topicConfig.setWriteQueueNums(4);
-    EXPECT_EQ(topicConfig.getWriteQueueNums(), 4);
+  topicConfig.setWriteQueueNums(4);
+  EXPECT_EQ(topicConfig.getWriteQueueNums(), 4);
 
-    topicConfig.setPerm(PermName::PERM_READ);
-    EXPECT_EQ(topicConfig.getPerm(), PermName::PERM_READ);
+  topicConfig.setPerm(PermName::PERM_READ);
+  EXPECT_EQ(topicConfig.getPerm(), PermName::PERM_READ);
 
-    topicConfig.setTopicFilterType(TopicFilterType::MULTI_TAG);
-    EXPECT_EQ(topicConfig.getTopicFilterType(), TopicFilterType::MULTI_TAG);
+  topicConfig.setTopicFilterType(TopicFilterType::MULTI_TAG);
+  EXPECT_EQ(topicConfig.getTopicFilterType(), TopicFilterType::MULTI_TAG);
 }
 
 TEST(topicConfig, init) {
-    TopicConfig topicConfig;
-    EXPECT_TRUE(topicConfig.getTopicName() == "");
-    EXPECT_EQ(topicConfig.getReadQueueNums(), TopicConfig::DefaultReadQueueNums);
-    EXPECT_EQ(topicConfig.getWriteQueueNums(), TopicConfig::DefaultWriteQueueNums);
-    EXPECT_EQ(topicConfig.getPerm(), PermName::PERM_READ | PermName::PERM_WRITE);
-    EXPECT_EQ(topicConfig.getTopicFilterType(), TopicFilterType::SINGLE_TAG);
+  TopicConfig topicConfig;
+  EXPECT_TRUE(topicConfig.getTopicName() == "");
+  EXPECT_EQ(topicConfig.getReadQueueNums(), TopicConfig::DefaultReadQueueNums);
+  EXPECT_EQ(topicConfig.getWriteQueueNums(), TopicConfig::DefaultWriteQueueNums);
+  EXPECT_EQ(topicConfig.getPerm(), PermName::PERM_READ | PermName::PERM_WRITE);
+  EXPECT_EQ(topicConfig.getTopicFilterType(), TopicFilterType::SINGLE_TAG);
 
-    TopicConfig twoTopicConfig("testTopic");
-    EXPECT_EQ(twoTopicConfig.getTopicName(), "testTopic");
-    EXPECT_EQ(twoTopicConfig.getReadQueueNums(), TopicConfig::DefaultReadQueueNums);
-    EXPECT_EQ(twoTopicConfig.getWriteQueueNums(), TopicConfig::DefaultWriteQueueNums);
-    EXPECT_EQ(twoTopicConfig.getPerm(), PermName::PERM_READ | PermName::PERM_WRITE);
-    EXPECT_EQ(twoTopicConfig.getTopicFilterType(), TopicFilterType::SINGLE_TAG);
+  TopicConfig twoTopicConfig("testTopic");
+  EXPECT_EQ(twoTopicConfig.getTopicName(), "testTopic");
+  EXPECT_EQ(twoTopicConfig.getReadQueueNums(), TopicConfig::DefaultReadQueueNums);
+  EXPECT_EQ(twoTopicConfig.getWriteQueueNums(), TopicConfig::DefaultWriteQueueNums);
+  EXPECT_EQ(twoTopicConfig.getPerm(), PermName::PERM_READ | PermName::PERM_WRITE);
+  EXPECT_EQ(twoTopicConfig.getTopicFilterType(), TopicFilterType::SINGLE_TAG);
 
-    TopicConfig threeTopicConfig("testTopic", 4, 4, PermName::PERM_READ);
-    EXPECT_EQ(threeTopicConfig.getTopicName(), "testTopic");
-    EXPECT_EQ(threeTopicConfig.getReadQueueNums(), 4);
-    EXPECT_EQ(threeTopicConfig.getWriteQueueNums(), 4);
-    EXPECT_EQ(threeTopicConfig.getPerm(), PermName::PERM_READ);
-    EXPECT_EQ(threeTopicConfig.getTopicFilterType(), TopicFilterType::SINGLE_TAG);
+  TopicConfig threeTopicConfig("testTopic", 4, 4, PermName::PERM_READ);
+  EXPECT_EQ(threeTopicConfig.getTopicName(), "testTopic");
+  EXPECT_EQ(threeTopicConfig.getReadQueueNums(), 4);
+  EXPECT_EQ(threeTopicConfig.getWriteQueueNums(), 4);
+  EXPECT_EQ(threeTopicConfig.getPerm(), PermName::PERM_READ);
+  EXPECT_EQ(threeTopicConfig.getTopicFilterType(), TopicFilterType::SINGLE_TAG);
 }
 
-int main(int argc, char *argv[]) {
-    InitGoogleMock(&argc, argv);
-    testing::GTEST_FLAG(throw_on_failure) = true;
-    testing::GTEST_FLAG(filter) = "topicConfig.*";
-    int itestts = RUN_ALL_TESTS();
-    return itestts;
+int main(int argc, char* argv[]) {
+  InitGoogleMock(&argc, argv);
+  testing::GTEST_FLAG(throw_on_failure) = true;
+  testing::GTEST_FLAG(filter) = "topicConfig.*";
+  int itestts = RUN_ALL_TESTS();
+  return itestts;
 }
diff --git a/test/src/common/ValidatorsTest.cpp b/test/src/common/ValidatorsTest.cpp
index 807ab38..23594cd 100644
--- a/test/src/common/ValidatorsTest.cpp
+++ b/test/src/common/ValidatorsTest.cpp
@@ -34,49 +34,49 @@
 using rocketmq::Validators;
 
 TEST(validators, regularExpressionMatcher) {
-    EXPECT_FALSE(Validators::regularExpressionMatcher(string(), string()));
+  EXPECT_FALSE(Validators::regularExpressionMatcher(string(), string()));
 
-    EXPECT_TRUE(Validators::regularExpressionMatcher(string("123456"), string()));
+  EXPECT_TRUE(Validators::regularExpressionMatcher(string("123456"), string()));
 
-    EXPECT_TRUE(Validators::regularExpressionMatcher(string("123456"), string("123")));
+  EXPECT_TRUE(Validators::regularExpressionMatcher(string("123456"), string("123")));
 }
 
 TEST(validators, getGroupWithRegularExpression) {
-    EXPECT_EQ(Validators::getGroupWithRegularExpression(string(), string()), "");
+  EXPECT_EQ(Validators::getGroupWithRegularExpression(string(), string()), "");
 }
 
 TEST(validators, checkTopic) {
-    EXPECT_THROW(Validators::checkTopic(string()), MQClientException);
-    string exceptionTopic = "1234567890";
-    for (int i = 0; i < 25; i++) {
-        exceptionTopic.append("1234567890");
-    }
-    EXPECT_THROW(Validators::checkTopic(exceptionTopic), MQClientException);
+  EXPECT_THROW(Validators::checkTopic(string()), MQClientException);
+  string exceptionTopic = "1234567890";
+  for (int i = 0; i < 25; i++) {
+    exceptionTopic.append("1234567890");
+  }
+  EXPECT_THROW(Validators::checkTopic(exceptionTopic), MQClientException);
 
-    EXPECT_THROW(Validators::checkTopic("TBW102"), MQClientException);
+  EXPECT_THROW(Validators::checkTopic("TBW102"), MQClientException);
 }
 
 TEST(validators, checkGroup) {
-    EXPECT_THROW(Validators::checkGroup(string()), MQClientException);
-    string exceptionTopic = "1234567890";
-    for (int i = 0; i < 25; i++) {
-        exceptionTopic.append("1234567890");
-    }
-    EXPECT_THROW(Validators::checkGroup(exceptionTopic), MQClientException);
+  EXPECT_THROW(Validators::checkGroup(string()), MQClientException);
+  string exceptionTopic = "1234567890";
+  for (int i = 0; i < 25; i++) {
+    exceptionTopic.append("1234567890");
+  }
+  EXPECT_THROW(Validators::checkGroup(exceptionTopic), MQClientException);
 }
 
 TEST(validators, checkMessage) {
-    MQMessage message("testTopic", string());
+  MQMessage message("testTopic", string());
 
-    EXPECT_THROW(Validators::checkMessage(MQMessage("testTopic", string()), 1), MQClientException);
+  EXPECT_THROW(Validators::checkMessage(MQMessage("testTopic", string()), 1), MQClientException);
 
-    EXPECT_THROW(Validators::checkMessage(MQMessage("testTopic", string("123")), 2), MQClientException);
+  EXPECT_THROW(Validators::checkMessage(MQMessage("testTopic", string("123")), 2), MQClientException);
 }
 
-int main(int argc, char *argv[]) {
-    InitGoogleMock(&argc, argv);
-    testing::GTEST_FLAG(throw_on_failure) = true;
-    testing::GTEST_FLAG(filter) = "validators.*";
-    int itestts = RUN_ALL_TESTS();
-    return itestts;
+int main(int argc, char* argv[]) {
+  InitGoogleMock(&argc, argv);
+  testing::GTEST_FLAG(throw_on_failure) = true;
+  testing::GTEST_FLAG(filter) = "validators.*";
+  int itestts = RUN_ALL_TESTS();
+  return itestts;
 }
diff --git a/test/src/common/VirtualEnvUtilTest.cpp b/test/src/common/VirtualEnvUtilTest.cpp
index 305b0cd..f02889c 100644
--- a/test/src/common/VirtualEnvUtilTest.cpp
+++ b/test/src/common/VirtualEnvUtilTest.cpp
@@ -32,20 +32,20 @@
 VirtualEnvUtil virtualEnvUtil;
 
 TEST(virtualEnvUtil, buildWithProjectGroup) {
-    string origin = "origin";
-    string projectGroup;
-    EXPECT_EQ(virtualEnvUtil.buildWithProjectGroup(origin, string()), origin);
+  string origin = "origin";
+  string projectGroup;
+  EXPECT_EQ(virtualEnvUtil.buildWithProjectGroup(origin, string()), origin);
 
-    EXPECT_EQ(virtualEnvUtil.buildWithProjectGroup(origin, string("123")), origin);
+  EXPECT_EQ(virtualEnvUtil.buildWithProjectGroup(origin, string("123")), origin);
 }
 
 TEST(virtualEnvUtil, clearProjectGroup) {}
 
-int main(int argc, char *argv[]) {
-    InitGoogleMock(&argc, argv);
+int main(int argc, char* argv[]) {
+  InitGoogleMock(&argc, argv);
 
-    testing::GTEST_FLAG(throw_on_failure) = true;
-    testing::GTEST_FLAG(filter) = "messageExt.init";
-    int itestts = RUN_ALL_TESTS();
-    return itestts;
+  testing::GTEST_FLAG(throw_on_failure) = true;
+  testing::GTEST_FLAG(filter) = "messageExt.init";
+  int itestts = RUN_ALL_TESTS();
+  return itestts;
 }
diff --git a/test/src/common/big_endianTest.cpp b/test/src/common/big_endianTest.cpp
index d4c6fe3..5469ded 100644
--- a/test/src/common/big_endianTest.cpp
+++ b/test/src/common/big_endianTest.cpp
@@ -29,72 +29,72 @@
 using rocketmq::BigEndianWriter;
 
 TEST(big_endian, bigEndianObject) {
-    char *buf = (char *) malloc(sizeof(char) * 32);
+  char* buf = (char*)malloc(sizeof(char) * 32);
 
-    BigEndianWriter writer(buf, 32);
-    BigEndianReader reader(buf, 32);
+  BigEndianWriter writer(buf, 32);
+  BigEndianReader reader(buf, 32);
 
-    uint8_t *unit8 = (uint8_t *) malloc(sizeof(uint8_t));
-    EXPECT_TRUE(writer.WriteU8((uint8_t) 12));
-    EXPECT_TRUE(reader.ReadU8(unit8));
-    EXPECT_EQ(*unit8, 12);
-    free(unit8);
+  uint8_t* unit8 = (uint8_t*)malloc(sizeof(uint8_t));
+  EXPECT_TRUE(writer.WriteU8((uint8_t)12));
+  EXPECT_TRUE(reader.ReadU8(unit8));
+  EXPECT_EQ(*unit8, 12);
+  free(unit8);
 
-    uint16_t *unit16 = (uint16_t *) malloc(sizeof(uint16_t));
-    EXPECT_TRUE(writer.WriteU16((uint16_t) 1200));
-    EXPECT_TRUE(reader.ReadU16(unit16));
-    EXPECT_EQ(*unit16, 1200);
-    free(unit16);
+  uint16_t* unit16 = (uint16_t*)malloc(sizeof(uint16_t));
+  EXPECT_TRUE(writer.WriteU16((uint16_t)1200));
+  EXPECT_TRUE(reader.ReadU16(unit16));
+  EXPECT_EQ(*unit16, 1200);
+  free(unit16);
 
-    uint32_t *unit32 = (uint32_t *) malloc(sizeof(uint32_t));
+  uint32_t* unit32 = (uint32_t*)malloc(sizeof(uint32_t));
 
-    EXPECT_TRUE(writer.WriteU32((uint32_t) 120000));
-    EXPECT_TRUE(reader.ReadU32(unit32));
-    EXPECT_EQ(*unit32, 120000);
-    free(unit32);
+  EXPECT_TRUE(writer.WriteU32((uint32_t)120000));
+  EXPECT_TRUE(reader.ReadU32(unit32));
+  EXPECT_EQ(*unit32, 120000);
+  free(unit32);
 
-    uint64_t *unit64 = (uint64_t *) malloc(sizeof(uint64_t));
+  uint64_t* unit64 = (uint64_t*)malloc(sizeof(uint64_t));
 
-    EXPECT_TRUE(writer.WriteU64((uint64_t) 120000));
-    EXPECT_TRUE(reader.ReadU64(unit64));
-    EXPECT_EQ(*unit64, 120000);
-    free(unit64);
+  EXPECT_TRUE(writer.WriteU64((uint64_t)120000));
+  EXPECT_TRUE(reader.ReadU64(unit64));
+  EXPECT_EQ(*unit64, 120000);
+  free(unit64);
 
-    char *newBuf = (char *) malloc(sizeof(char) * 8);
-    char *writeBuf = (char *) malloc(sizeof(char) * 8);
-    strcpy(writeBuf, "RocketMQ");
-    EXPECT_TRUE(writer.WriteBytes(writeBuf, (size_t) 8));
-    EXPECT_TRUE(reader.ReadBytes(newBuf, (size_t) 8));
-    EXPECT_EQ(*writeBuf, *newBuf);
+  char* newBuf = (char*)malloc(sizeof(char) * 8);
+  char* writeBuf = (char*)malloc(sizeof(char) * 8);
+  strcpy(writeBuf, "RocketMQ");
+  EXPECT_TRUE(writer.WriteBytes(writeBuf, (size_t)8));
+  EXPECT_TRUE(reader.ReadBytes(newBuf, (size_t)8));
+  EXPECT_EQ(*writeBuf, *newBuf);
 
-    free(newBuf);
-    free(writeBuf);
+  free(newBuf);
+  free(writeBuf);
 }
 
 TEST(big_endian, bigEndian) {
-    char writeBuf[8];
+  char writeBuf[8];
 
-    /*TODO
-        char *newBuf = (char *) malloc(sizeof(char) * 8);
-        strcpy(newBuf, "RocketMQ");
+  /*TODO
+      char *newBuf = (char *) malloc(sizeof(char) * 8);
+      strcpy(newBuf, "RocketMQ");
 
-        char readBuf[8];
-        rocketmq::WriteBigEndian(writeBuf, newBuf);
-        rocketmq::ReadBigEndian(writeBuf, readBuf);
-        EXPECT_EQ(writeBuf, readBuf);
-    */
+      char readBuf[8];
+      rocketmq::WriteBigEndian(writeBuf, newBuf);
+      rocketmq::ReadBigEndian(writeBuf, readBuf);
+      EXPECT_EQ(writeBuf, readBuf);
+  */
 
-    rocketmq::WriteBigEndian(writeBuf, (uint8_t) 12);
-    uint8_t *out = (uint8_t *) malloc(sizeof(uint8_t));
-    rocketmq::ReadBigEndian(writeBuf, out);
-    EXPECT_EQ(*out, 12);
-    free(out);
+  rocketmq::WriteBigEndian(writeBuf, (uint8_t)12);
+  uint8_t* out = (uint8_t*)malloc(sizeof(uint8_t));
+  rocketmq::ReadBigEndian(writeBuf, out);
+  EXPECT_EQ(*out, 12);
+  free(out);
 }
 
-int main(int argc, char *argv[]) {
-    InitGoogleMock(&argc, argv);
-    testing::GTEST_FLAG(throw_on_failure) = true;
-    testing::GTEST_FLAG(filter) = "big_endian.*";
-    int itestts = RUN_ALL_TESTS();
-    return itestts;
+int main(int argc, char* argv[]) {
+  InitGoogleMock(&argc, argv);
+  testing::GTEST_FLAG(throw_on_failure) = true;
+  testing::GTEST_FLAG(filter) = "big_endian.*";
+  int itestts = RUN_ALL_TESTS();
+  return itestts;
 }
diff --git a/test/src/extern/CMessageExtTest.cpp b/test/src/extern/CMessageExtTest.cpp
index 3471c9e..8752d5c 100644
--- a/test/src/extern/CMessageExtTest.cpp
+++ b/test/src/extern/CMessageExtTest.cpp
@@ -29,78 +29,78 @@
 using rocketmq::MQMessageExt;
 
 TEST(cmessageExt, info) {
-    MQMessageExt *mqMessageExt = new MQMessageExt();
-    CMessageExt *messageExt = (CMessageExt *) mqMessageExt;
+  MQMessageExt* mqMessageExt = new MQMessageExt();
+  CMessageExt* messageExt = (CMessageExt*)mqMessageExt;
 
-    mqMessageExt->setTopic("testTopic");
-    EXPECT_EQ(GetMessageTopic(messageExt), mqMessageExt->getTopic());
+  mqMessageExt->setTopic("testTopic");
+  EXPECT_EQ(GetMessageTopic(messageExt), mqMessageExt->getTopic());
 
-    mqMessageExt->setTags("testTags");
-    EXPECT_EQ(GetMessageTags(messageExt), mqMessageExt->getTags());
+  mqMessageExt->setTags("testTags");
+  EXPECT_EQ(GetMessageTags(messageExt), mqMessageExt->getTags());
 
-    mqMessageExt->setKeys("testKeys");
-    EXPECT_EQ(GetMessageKeys(messageExt), mqMessageExt->getKeys());
+  mqMessageExt->setKeys("testKeys");
+  EXPECT_EQ(GetMessageKeys(messageExt), mqMessageExt->getKeys());
 
-    mqMessageExt->setBody("testBody");
-    EXPECT_EQ(GetMessageBody(messageExt), mqMessageExt->getBody());
+  mqMessageExt->setBody("testBody");
+  EXPECT_EQ(GetMessageBody(messageExt), mqMessageExt->getBody());
 
-    mqMessageExt->setProperty("testKey", "testValues");
-    EXPECT_EQ(GetMessageProperty(messageExt, "testKey"), mqMessageExt->getProperty("testKey"));
+  mqMessageExt->setProperty("testKey", "testValues");
+  EXPECT_EQ(GetMessageProperty(messageExt, "testKey"), mqMessageExt->getProperty("testKey"));
 
-    mqMessageExt->setMsgId("msgId123456");
-    EXPECT_EQ(GetMessageId(messageExt), mqMessageExt->getMsgId());
+  mqMessageExt->setMsgId("msgId123456");
+  EXPECT_EQ(GetMessageId(messageExt), mqMessageExt->getMsgId());
 
-    mqMessageExt->setDelayTimeLevel(1);
-    EXPECT_EQ(GetMessageDelayTimeLevel(messageExt), mqMessageExt->getDelayTimeLevel());
+  mqMessageExt->setDelayTimeLevel(1);
+  EXPECT_EQ(GetMessageDelayTimeLevel(messageExt), mqMessageExt->getDelayTimeLevel());
 
-    mqMessageExt->setQueueId(4);
-    EXPECT_EQ(GetMessageQueueId(messageExt), mqMessageExt->getQueueId());
+  mqMessageExt->setQueueId(4);
+  EXPECT_EQ(GetMessageQueueId(messageExt), mqMessageExt->getQueueId());
 
-    mqMessageExt->setReconsumeTimes(1234567);
-    EXPECT_EQ(GetMessageReconsumeTimes(messageExt), mqMessageExt->getReconsumeTimes());
+  mqMessageExt->setReconsumeTimes(1234567);
+  EXPECT_EQ(GetMessageReconsumeTimes(messageExt), mqMessageExt->getReconsumeTimes());
 
-    mqMessageExt->setStoreSize(127);
-    EXPECT_EQ(GetMessageStoreSize(messageExt), mqMessageExt->getStoreSize());
+  mqMessageExt->setStoreSize(127);
+  EXPECT_EQ(GetMessageStoreSize(messageExt), mqMessageExt->getStoreSize());
 
-    mqMessageExt->setBornTimestamp(9876543);
-    EXPECT_EQ(GetMessageBornTimestamp(messageExt), mqMessageExt->getBornTimestamp());
+  mqMessageExt->setBornTimestamp(9876543);
+  EXPECT_EQ(GetMessageBornTimestamp(messageExt), mqMessageExt->getBornTimestamp());
 
-    mqMessageExt->setStoreTimestamp(123123);
-    EXPECT_EQ(GetMessageStoreTimestamp(messageExt), mqMessageExt->getStoreTimestamp());
+  mqMessageExt->setStoreTimestamp(123123);
+  EXPECT_EQ(GetMessageStoreTimestamp(messageExt), mqMessageExt->getStoreTimestamp());
 
-    mqMessageExt->setQueueOffset(1024);
-    EXPECT_EQ(GetMessageQueueOffset(messageExt), mqMessageExt->getQueueOffset());
+  mqMessageExt->setQueueOffset(1024);
+  EXPECT_EQ(GetMessageQueueOffset(messageExt), mqMessageExt->getQueueOffset());
 
-    mqMessageExt->setCommitLogOffset(2048);
-    EXPECT_EQ(GetMessageCommitLogOffset(messageExt), mqMessageExt->getCommitLogOffset());
+  mqMessageExt->setCommitLogOffset(2048);
+  EXPECT_EQ(GetMessageCommitLogOffset(messageExt), mqMessageExt->getCommitLogOffset());
 
-    mqMessageExt->setPreparedTransactionOffset(4096);
-    EXPECT_EQ(GetMessagePreparedTransactionOffset(messageExt), mqMessageExt->getPreparedTransactionOffset());
+  mqMessageExt->setPreparedTransactionOffset(4096);
+  EXPECT_EQ(GetMessagePreparedTransactionOffset(messageExt), mqMessageExt->getPreparedTransactionOffset());
 
-    delete mqMessageExt;
+  delete mqMessageExt;
 }
 
 TEST(cmessageExt, null) {
-    EXPECT_TRUE(GetMessageTopic(NULL) == NULL);
-    EXPECT_TRUE(GetMessageTags(NULL) == NULL);
-    EXPECT_TRUE(GetMessageKeys(NULL) == NULL);
-    EXPECT_TRUE(GetMessageBody(NULL) == NULL);
-    EXPECT_TRUE(GetMessageProperty(NULL, NULL) == NULL);
-    EXPECT_TRUE(GetMessageId(NULL) == NULL);
-    EXPECT_EQ(GetMessageDelayTimeLevel(NULL), NULL_POINTER);
-    EXPECT_EQ(GetMessageQueueId(NULL), NULL_POINTER);
-    EXPECT_EQ(GetMessageReconsumeTimes(NULL), NULL_POINTER);
-    EXPECT_EQ(GetMessageStoreSize(NULL), NULL_POINTER);
-    EXPECT_EQ(GetMessageBornTimestamp(NULL), NULL_POINTER);
-    EXPECT_EQ(GetMessageStoreTimestamp(NULL), NULL_POINTER);
-    EXPECT_EQ(GetMessageQueueOffset(NULL), NULL_POINTER);
-    EXPECT_EQ(GetMessageCommitLogOffset(NULL), NULL_POINTER);
-    EXPECT_EQ(GetMessagePreparedTransactionOffset(NULL), NULL_POINTER);
+  EXPECT_TRUE(GetMessageTopic(NULL) == NULL);
+  EXPECT_TRUE(GetMessageTags(NULL) == NULL);
+  EXPECT_TRUE(GetMessageKeys(NULL) == NULL);
+  EXPECT_TRUE(GetMessageBody(NULL) == NULL);
+  EXPECT_TRUE(GetMessageProperty(NULL, NULL) == NULL);
+  EXPECT_TRUE(GetMessageId(NULL) == NULL);
+  EXPECT_EQ(GetMessageDelayTimeLevel(NULL), NULL_POINTER);
+  EXPECT_EQ(GetMessageQueueId(NULL), NULL_POINTER);
+  EXPECT_EQ(GetMessageReconsumeTimes(NULL), NULL_POINTER);
+  EXPECT_EQ(GetMessageStoreSize(NULL), NULL_POINTER);
+  EXPECT_EQ(GetMessageBornTimestamp(NULL), NULL_POINTER);
+  EXPECT_EQ(GetMessageStoreTimestamp(NULL), NULL_POINTER);
+  EXPECT_EQ(GetMessageQueueOffset(NULL), NULL_POINTER);
+  EXPECT_EQ(GetMessageCommitLogOffset(NULL), NULL_POINTER);
+  EXPECT_EQ(GetMessagePreparedTransactionOffset(NULL), NULL_POINTER);
 }
 
-int main(int argc, char *argv[]) {
-    InitGoogleMock(&argc, argv);
-    testing::GTEST_FLAG(filter) = "cmessageExt.*";
-    int itestts = RUN_ALL_TESTS();
-    return itestts;
+int main(int argc, char* argv[]) {
+  InitGoogleMock(&argc, argv);
+  testing::GTEST_FLAG(filter) = "cmessageExt.*";
+  int itestts = RUN_ALL_TESTS();
+  return itestts;
 }
diff --git a/test/src/extern/CMessageTest.cpp b/test/src/extern/CMessageTest.cpp
index 51c40cb..f6da8fa 100644
--- a/test/src/extern/CMessageTest.cpp
+++ b/test/src/extern/CMessageTest.cpp
@@ -28,54 +28,54 @@
 using rocketmq::MQMessage;
 
 TEST(cmessages, info) {
-    CMessage *message = CreateMessage(NULL);
-    MQMessage *mqMessage = (MQMessage *) message;
-    EXPECT_EQ(mqMessage->getTopic(), "");
+  CMessage* message = CreateMessage(NULL);
+  MQMessage* mqMessage = (MQMessage*)message;
+  EXPECT_EQ(mqMessage->getTopic(), "");
 
-    SetMessageTopic(message, "testTopic");
-    EXPECT_EQ(mqMessage->getTopic(), "testTopic");
+  SetMessageTopic(message, "testTopic");
+  EXPECT_EQ(mqMessage->getTopic(), "testTopic");
 
-    SetMessageTags(message, "testTags");
-    EXPECT_EQ(mqMessage->getTags(), "testTags");
+  SetMessageTags(message, "testTags");
+  EXPECT_EQ(mqMessage->getTags(), "testTags");
 
-    SetMessageKeys(message, "testKeys");
-    EXPECT_EQ(mqMessage->getKeys(), "testKeys");
+  SetMessageKeys(message, "testKeys");
+  EXPECT_EQ(mqMessage->getKeys(), "testKeys");
 
-    SetMessageBody(message, "testBody");
-    EXPECT_EQ(mqMessage->getBody(), "testBody");
+  SetMessageBody(message, "testBody");
+  EXPECT_EQ(mqMessage->getBody(), "testBody");
 
-    SetByteMessageBody(message, "testBody", 5);
-    EXPECT_EQ(mqMessage->getBody(), "testB");
+  SetByteMessageBody(message, "testBody", 5);
+  EXPECT_EQ(mqMessage->getBody(), "testB");
 
-    SetMessageProperty(message, "testKey", "testValue");
-    EXPECT_EQ(mqMessage->getProperty("testKey"), "testValue");
+  SetMessageProperty(message, "testKey", "testValue");
+  EXPECT_EQ(mqMessage->getProperty("testKey"), "testValue");
 
-    SetDelayTimeLevel(message, 1);
-    EXPECT_EQ(mqMessage->getDelayTimeLevel(), 1);
+  SetDelayTimeLevel(message, 1);
+  EXPECT_EQ(mqMessage->getDelayTimeLevel(), 1);
 
-    EXPECT_EQ(DestroyMessage(message), OK);
+  EXPECT_EQ(DestroyMessage(message), OK);
 
-    CMessage *twomessage = CreateMessage("testTwoTopic");
-    MQMessage *twoMqMessage = (MQMessage *) twomessage;
-    EXPECT_EQ(twoMqMessage->getTopic(), "testTwoTopic");
+  CMessage* twomessage = CreateMessage("testTwoTopic");
+  MQMessage* twoMqMessage = (MQMessage*)twomessage;
+  EXPECT_EQ(twoMqMessage->getTopic(), "testTwoTopic");
 
-    EXPECT_EQ(DestroyMessage(twomessage), OK);
+  EXPECT_EQ(DestroyMessage(twomessage), OK);
 }
 
 TEST(cmessages, null) {
-    EXPECT_EQ(SetMessageTopic(NULL, NULL), NULL_POINTER);
-    EXPECT_EQ(SetMessageTags(NULL, NULL), NULL_POINTER);
-    EXPECT_EQ(SetMessageKeys(NULL, NULL), NULL_POINTER);
-    EXPECT_EQ(SetMessageBody(NULL, NULL), NULL_POINTER);
-    EXPECT_EQ(SetByteMessageBody(NULL, NULL, 0), NULL_POINTER);
-    EXPECT_EQ(SetMessageProperty(NULL, NULL, NULL), NULL_POINTER);
-    EXPECT_EQ(SetDelayTimeLevel(NULL, NULL), NULL_POINTER);
+  EXPECT_EQ(SetMessageTopic(NULL, NULL), NULL_POINTER);
+  EXPECT_EQ(SetMessageTags(NULL, NULL), NULL_POINTER);
+  EXPECT_EQ(SetMessageKeys(NULL, NULL), NULL_POINTER);
+  EXPECT_EQ(SetMessageBody(NULL, NULL), NULL_POINTER);
+  EXPECT_EQ(SetByteMessageBody(NULL, NULL, 0), NULL_POINTER);
+  EXPECT_EQ(SetMessageProperty(NULL, NULL, NULL), NULL_POINTER);
+  EXPECT_EQ(SetDelayTimeLevel(NULL, 0), NULL_POINTER);
 }
 
-int main(int argc, char *argv[]) {
-    InitGoogleMock(&argc, argv);
+int main(int argc, char* argv[]) {
+  InitGoogleMock(&argc, argv);
 
-    testing::GTEST_FLAG(filter) = "cmessages.null";
-    int itestts = RUN_ALL_TESTS();
-    return itestts;
+  testing::GTEST_FLAG(filter) = "cmessages.null";
+  int itestts = RUN_ALL_TESTS();
+  return itestts;
 }
diff --git a/test/src/extern/CProducerTest.cpp b/test/src/extern/CProducerTest.cpp
index ccfdc64..56b1cca 100644
--- a/test/src/extern/CProducerTest.cpp
+++ b/test/src/extern/CProducerTest.cpp
@@ -50,187 +50,189 @@
 using rocketmq::SessionCredentials;
 
 class MockDefaultMQProducer : public DefaultMQProducer {
-   public:
-    MockDefaultMQProducer(const string &groupname) : DefaultMQProducer(groupname) {}
-    MOCK_METHOD0(start, void());
-    MOCK_METHOD0(shutdown, void());
-    MOCK_METHOD2(setLogFileSizeAndNum, void(int, long));
-    MOCK_METHOD1(SetProducerLogLevel, void(elogLevel));
-    MOCK_METHOD2(send, SendResult(MQMessage &, bool));
-    MOCK_METHOD3(send, void(MQMessage &, SendCallback *, bool));
-    MOCK_METHOD2(sendOneway, void(MQMessage &, bool));
-    MOCK_METHOD5(send, SendResult(MQMessage &, MessageQueueSelector *, void *, int, bool));
+ public:
+  MockDefaultMQProducer(const string& groupname) : DefaultMQProducer(groupname) {}
+  MOCK_METHOD0(start, void());
+  MOCK_METHOD0(shutdown, void());
+  MOCK_METHOD2(setLogFileSizeAndNum, void(int, long));
+  MOCK_METHOD1(SetProducerLogLevel, void(elogLevel));
+  MOCK_METHOD2(send, SendResult(MQMessage&, bool));
+  MOCK_METHOD3(send, void(MQMessage&, SendCallback*, bool));
+  MOCK_METHOD2(sendOneway, void(MQMessage&, bool));
+  MOCK_METHOD5(send, SendResult(MQMessage&, MessageQueueSelector*, void*, int, bool));
 };
 
+void CSendSuccessCallbackFunc(CSendResult result) {}
+void cSendExceptionCallbackFunc(CMQException e) {}
+
 TEST(cProducer, SendMessageAsync) {
-    MockDefaultMQProducer *mockProducer = new MockDefaultMQProducer("testGroup");
-    CProducer *cProducer = (CProducer *) mockProducer;
-    CMessage *msg = (CMessage *) new MQMessage();
+  MockDefaultMQProducer* mockProducer = new MockDefaultMQProducer("testGroup");
+  CProducer* cProducer = (CProducer*)mockProducer;
+  CMessage* msg = (CMessage*)new MQMessage();
 
-    CSendSuccessCallback cSendSuccessCallback;
-    CSendExceptionCallback cSendExceptionCallback;
+  EXPECT_EQ(SendMessageAsync(NULL, NULL, NULL, NULL), NULL_POINTER);
+  EXPECT_EQ(SendMessageAsync(cProducer, NULL, NULL, NULL), NULL_POINTER);
+  EXPECT_EQ(SendMessageAsync(cProducer, msg, CSendSuccessCallbackFunc, NULL), NULL_POINTER);
 
-    EXPECT_EQ(SendMessageAsync(NULL, NULL, NULL, NULL), NULL_POINTER);
-    EXPECT_EQ(SendMessageAsync(cProducer, NULL, NULL, NULL), NULL_POINTER);
-    EXPECT_EQ(SendMessageAsync(cProducer, msg, cSendSuccessCallback, NULL), NULL_POINTER);
+  EXPECT_CALL(*mockProducer, send(_, _)).Times(1);
+  EXPECT_EQ(SendMessageAsync(cProducer, msg, CSendSuccessCallbackFunc, cSendExceptionCallbackFunc), OK);
+  Mock::AllowLeak(mockProducer);
+  DestroyMessage(msg);
+}
 
-    EXPECT_CALL(*mockProducer, send(_, _)).Times(1);
-    EXPECT_EQ(SendMessageAsync(cProducer, msg, cSendSuccessCallback, cSendExceptionCallback), OK);
-    Mock::AllowLeak(mockProducer);
-    DestroyMessage(msg);
+int QueueSelectorCallbackFunc(int size, CMessage* msg, void* arg) {
+  return 0;
 }
 
 TEST(cProducer, sendMessageOrderly) {
-    MockDefaultMQProducer *mockProducer = new MockDefaultMQProducer("testGroup");
-    CProducer *cProducer = (CProducer *) mockProducer;
-    CMessage *msg = (CMessage *) new MQMessage();
-    CSendResult *result;
-    MQMessageQueue messageQueue;
-    QueueSelectorCallback callback;
+  MockDefaultMQProducer* mockProducer = new MockDefaultMQProducer("testGroup");
+  CProducer* cProducer = (CProducer*)mockProducer;
+  CMessage* msg = (CMessage*)new MQMessage();
+  MQMessageQueue messageQueue;
 
-    EXPECT_EQ(SendMessageOrderly(NULL, NULL, NULL, msg, 1, NULL), NULL_POINTER);
-    EXPECT_EQ(SendMessageOrderly(cProducer, NULL, NULL, msg, 1, NULL), NULL_POINTER);
-    EXPECT_EQ(SendMessageOrderly(cProducer, msg, NULL, msg, 1, NULL), NULL_POINTER);
-    EXPECT_EQ(SendMessageOrderly(cProducer, msg, callback, NULL, 1, NULL), NULL_POINTER);
-    EXPECT_EQ(SendMessageOrderly(cProducer, msg, callback, msg, 1, NULL), NULL_POINTER);
+  EXPECT_EQ(SendMessageOrderly(NULL, NULL, NULL, msg, 1, NULL), NULL_POINTER);
+  EXPECT_EQ(SendMessageOrderly(cProducer, NULL, NULL, msg, 1, NULL), NULL_POINTER);
+  EXPECT_EQ(SendMessageOrderly(cProducer, msg, NULL, msg, 1, NULL), NULL_POINTER);
+  EXPECT_EQ(SendMessageOrderly(cProducer, msg, QueueSelectorCallbackFunc, NULL, 1, NULL), NULL_POINTER);
+  EXPECT_EQ(SendMessageOrderly(cProducer, msg, QueueSelectorCallbackFunc, msg, 1, NULL), NULL_POINTER);
 
-    EXPECT_CALL(*mockProducer, send(_, _, _, _, _))
-        .WillOnce(Return(SendResult(SendStatus::SEND_OK, "3", "offset1", messageQueue, 14)));
-    // EXPECT_EQ(SendMessageOrderly(cProducer, msg, callback, msg, 1, result), OK);
-    Mock::AllowLeak(mockProducer);
-    DestroyMessage(msg);
-    // free(result);
+  EXPECT_CALL(*mockProducer, send(_, _, _, _, _))
+      .WillOnce(Return(SendResult(SendStatus::SEND_OK, "3", "offset1", messageQueue, 14)));
+  // EXPECT_EQ(SendMessageOrderly(cProducer, msg, callback, msg, 1, result), OK);
+  Mock::AllowLeak(mockProducer);
+  DestroyMessage(msg);
+  // free(result);
 }
 
 TEST(cProducer, sendOneway) {
-    MockDefaultMQProducer *mockProducer = new MockDefaultMQProducer("testGroup");
-    CProducer *cProducer = (CProducer *) mockProducer;
-    CMessage *msg = (CMessage *) new MQMessage();
+  MockDefaultMQProducer* mockProducer = new MockDefaultMQProducer("testGroup");
+  CProducer* cProducer = (CProducer*)mockProducer;
+  CMessage* msg = (CMessage*)new MQMessage();
 
-    EXPECT_EQ(SendMessageOneway(NULL, NULL), NULL_POINTER);
-    EXPECT_EQ(SendMessageOneway(cProducer, NULL), NULL_POINTER);
+  EXPECT_EQ(SendMessageOneway(NULL, NULL), NULL_POINTER);
+  EXPECT_EQ(SendMessageOneway(cProducer, NULL), NULL_POINTER);
 
-    EXPECT_CALL(*mockProducer, sendOneway(_, _)).Times(1);
-    EXPECT_EQ(SendMessageOneway(cProducer, msg), OK);
-    Mock::AllowLeak(mockProducer);
-    DestroyMessage(msg);
+  EXPECT_CALL(*mockProducer, sendOneway(_, _)).Times(1);
+  EXPECT_EQ(SendMessageOneway(cProducer, msg), OK);
+  Mock::AllowLeak(mockProducer);
+  DestroyMessage(msg);
 }
 
 TEST(cProducer, sendMessageSync) {
-    MockDefaultMQProducer *mockProducer = new MockDefaultMQProducer("testGroup");
-    CProducer *cProducer = (CProducer *) mockProducer;
+  MockDefaultMQProducer* mockProducer = new MockDefaultMQProducer("testGroup");
+  CProducer* cProducer = (CProducer*)mockProducer;
 
-    MQMessage *mqMessage = new MQMessage();
-    CMessage *msg = (CMessage *) mqMessage;
-    CSendResult *result;
-    MQMessageQueue messageQueue;
-    EXPECT_EQ(SendMessageSync(NULL, NULL, NULL), NULL_POINTER);
-    EXPECT_EQ(SendMessageSync(cProducer, NULL, NULL), NULL_POINTER);
+  MQMessage* mqMessage = new MQMessage();
+  CMessage* msg = (CMessage*)mqMessage;
+  CSendResult* result;
+  MQMessageQueue messageQueue;
+  EXPECT_EQ(SendMessageSync(NULL, NULL, NULL), NULL_POINTER);
+  EXPECT_EQ(SendMessageSync(cProducer, NULL, NULL), NULL_POINTER);
 
-    EXPECT_EQ(SendMessageSync(cProducer, msg, NULL), NULL_POINTER);
+  EXPECT_EQ(SendMessageSync(cProducer, msg, NULL), NULL_POINTER);
 
-    result = (CSendResult *) malloc(sizeof(CSendResult));
+  result = (CSendResult*)malloc(sizeof(CSendResult));
 
-    EXPECT_CALL(*mockProducer, send(_, _))
-        .Times(5)
-        .WillOnce(Return(SendResult(SendStatus::SEND_FLUSH_DISK_TIMEOUT, "1", "offset1", messageQueue, 14)))
-        .WillOnce(Return(SendResult(SendStatus::SEND_FLUSH_SLAVE_TIMEOUT, "2", "offset1", messageQueue, 14)))
-        .WillOnce(Return(SendResult(SendStatus::SEND_SLAVE_NOT_AVAILABLE, "3", "offset1", messageQueue, 14)))
-        .WillOnce(Return(SendResult(SendStatus::SEND_OK, "3", "offset1", messageQueue, 14)))
-        .WillOnce(Return(SendResult((SendStatus) -1, "4", "offset1", messageQueue, 14)));
+  EXPECT_CALL(*mockProducer, send(_, _))
+      .Times(5)
+      .WillOnce(Return(SendResult(SendStatus::SEND_FLUSH_DISK_TIMEOUT, "1", "offset1", messageQueue, 14)))
+      .WillOnce(Return(SendResult(SendStatus::SEND_FLUSH_SLAVE_TIMEOUT, "2", "offset1", messageQueue, 14)))
+      .WillOnce(Return(SendResult(SendStatus::SEND_SLAVE_NOT_AVAILABLE, "3", "offset1", messageQueue, 14)))
+      .WillOnce(Return(SendResult(SendStatus::SEND_OK, "3", "offset1", messageQueue, 14)))
+      .WillOnce(Return(SendResult((SendStatus)-1, "4", "offset1", messageQueue, 14)));
 
-    EXPECT_EQ(SendMessageSync(cProducer, msg, result), OK);
-    EXPECT_EQ(result->sendStatus, E_SEND_FLUSH_DISK_TIMEOUT);
+  EXPECT_EQ(SendMessageSync(cProducer, msg, result), OK);
+  EXPECT_EQ(result->sendStatus, E_SEND_FLUSH_DISK_TIMEOUT);
 
-    EXPECT_EQ(SendMessageSync(cProducer, msg, result), OK);
-    EXPECT_EQ(result->sendStatus, E_SEND_FLUSH_SLAVE_TIMEOUT);
+  EXPECT_EQ(SendMessageSync(cProducer, msg, result), OK);
+  EXPECT_EQ(result->sendStatus, E_SEND_FLUSH_SLAVE_TIMEOUT);
 
-    EXPECT_EQ(SendMessageSync(cProducer, msg, result), OK);
-    EXPECT_EQ(result->sendStatus, E_SEND_SLAVE_NOT_AVAILABLE);
+  EXPECT_EQ(SendMessageSync(cProducer, msg, result), OK);
+  EXPECT_EQ(result->sendStatus, E_SEND_SLAVE_NOT_AVAILABLE);
 
-    EXPECT_EQ(SendMessageSync(cProducer, msg, result), OK);
-    EXPECT_EQ(result->sendStatus, E_SEND_OK);
+  EXPECT_EQ(SendMessageSync(cProducer, msg, result), OK);
+  EXPECT_EQ(result->sendStatus, E_SEND_OK);
 
-    EXPECT_EQ(SendMessageSync(cProducer, msg, result), OK);
-    EXPECT_EQ(result->sendStatus, E_SEND_OK);
-    Mock::AllowLeak(mockProducer);
-    DestroyMessage(msg);
-    free(result);
+  EXPECT_EQ(SendMessageSync(cProducer, msg, result), OK);
+  EXPECT_EQ(result->sendStatus, E_SEND_OK);
+  Mock::AllowLeak(mockProducer);
+  DestroyMessage(msg);
+  free(result);
 }
 
 TEST(cProducer, infoMock) {
-    MockDefaultMQProducer *mockProducer = new MockDefaultMQProducer("testGroup");
-    CProducer *cProducer = (CProducer *) mockProducer;
+  MockDefaultMQProducer* mockProducer = new MockDefaultMQProducer("testGroup");
+  CProducer* cProducer = (CProducer*)mockProducer;
 
-    EXPECT_CALL(*mockProducer, start()).Times(1);
-    EXPECT_EQ(StartProducer(cProducer), OK);
+  EXPECT_CALL(*mockProducer, start()).Times(1);
+  EXPECT_EQ(StartProducer(cProducer), OK);
 
-    EXPECT_CALL(*mockProducer, shutdown()).Times(1);
-    EXPECT_EQ(ShutdownProducer(cProducer), OK);
+  EXPECT_CALL(*mockProducer, shutdown()).Times(1);
+  EXPECT_EQ(ShutdownProducer(cProducer), OK);
 
-    EXPECT_CALL(*mockProducer, setLogFileSizeAndNum(_, _)).Times(1);
-    EXPECT_EQ(SetProducerLogFileNumAndSize(cProducer, 1, 1), OK);
+  EXPECT_CALL(*mockProducer, setLogFileSizeAndNum(_, _)).Times(1);
+  EXPECT_EQ(SetProducerLogFileNumAndSize(cProducer, 1, 1), OK);
 
-    EXPECT_CALL(*mockProducer, SetProducerLogLevel(_)).Times(1);
-    EXPECT_EQ(SetProducerLogLevel(cProducer, E_LOG_LEVEL_FATAL), OK);
-    Mock::AllowLeak(mockProducer);
+  EXPECT_CALL(*mockProducer, SetProducerLogLevel(_)).Times(1);
+  EXPECT_EQ(SetProducerLogLevel(cProducer, E_LOG_LEVEL_FATAL), OK);
+  Mock::AllowLeak(mockProducer);
 }
 
 TEST(cProducer, info) {
-    CProducer *cProducer = CreateProducer("groupTest");
-    DefaultMQProducer *defaultMQProducer = (DefaultMQProducer *) cProducer;
-    EXPECT_TRUE(cProducer != NULL);
-    EXPECT_EQ(defaultMQProducer->getGroupName(), "groupTest");
+  CProducer* cProducer = CreateProducer("groupTest");
+  DefaultMQProducer* defaultMQProducer = (DefaultMQProducer*)cProducer;
+  EXPECT_TRUE(cProducer != NULL);
+  EXPECT_EQ(defaultMQProducer->getGroupName(), "groupTest");
 
-    EXPECT_EQ(SetProducerNameServerAddress(cProducer, "127.0.0.1:9876"), OK);
-    EXPECT_EQ(defaultMQProducer->getNamesrvAddr(), "127.0.0.1:9876");
+  EXPECT_EQ(SetProducerNameServerAddress(cProducer, "127.0.0.1:9876"), OK);
+  EXPECT_EQ(defaultMQProducer->getNamesrvAddr(), "127.0.0.1:9876");
 
-    EXPECT_EQ(SetProducerNameServerDomain(cProducer, "domain"), OK);
-    EXPECT_EQ(defaultMQProducer->getNamesrvDomain(), "domain");
+  EXPECT_EQ(SetProducerNameServerDomain(cProducer, "domain"), OK);
+  EXPECT_EQ(defaultMQProducer->getNamesrvDomain(), "domain");
 
-    EXPECT_EQ(SetProducerGroupName(cProducer, "testGroup"), OK);
-    EXPECT_EQ(defaultMQProducer->getGroupName(), "testGroup");
+  EXPECT_EQ(SetProducerGroupName(cProducer, "testGroup"), OK);
+  EXPECT_EQ(defaultMQProducer->getGroupName(), "testGroup");
 
-    EXPECT_EQ(SetProducerInstanceName(cProducer, "instance"), OK);
-    EXPECT_EQ(defaultMQProducer->getInstanceName(), "instance");
+  EXPECT_EQ(SetProducerInstanceName(cProducer, "instance"), OK);
+  EXPECT_EQ(defaultMQProducer->getInstanceName(), "instance");
 
-    EXPECT_EQ(SetProducerSendMsgTimeout(cProducer, 1), OK);
-    EXPECT_EQ(defaultMQProducer->getSendMsgTimeout(), 1);
+  EXPECT_EQ(SetProducerSendMsgTimeout(cProducer, 1), OK);
+  EXPECT_EQ(defaultMQProducer->getSendMsgTimeout(), 1);
 
-    EXPECT_EQ(SetProducerMaxMessageSize(cProducer, 2), OK);
-    EXPECT_EQ(defaultMQProducer->getMaxMessageSize(), 2);
+  EXPECT_EQ(SetProducerMaxMessageSize(cProducer, 2), OK);
+  EXPECT_EQ(defaultMQProducer->getMaxMessageSize(), 2);
 
-    EXPECT_EQ(SetProducerCompressLevel(cProducer, 1), OK);
-    EXPECT_EQ(defaultMQProducer->getCompressLevel(), 1);
+  EXPECT_EQ(SetProducerCompressLevel(cProducer, 1), OK);
+  EXPECT_EQ(defaultMQProducer->getCompressLevel(), 1);
 
-    EXPECT_EQ(SetProducerSessionCredentials(NULL, NULL, NULL, NULL), NULL_POINTER);
-    EXPECT_EQ(SetProducerSessionCredentials(cProducer, "accessKey", "secretKey", "channel"), OK);
-    SessionCredentials sessionCredentials = defaultMQProducer->getSessionCredentials();
-    EXPECT_EQ(sessionCredentials.getAccessKey(), "accessKey");
-    Mock::AllowLeak(defaultMQProducer);
+  EXPECT_EQ(SetProducerSessionCredentials(NULL, NULL, NULL, NULL), NULL_POINTER);
+  EXPECT_EQ(SetProducerSessionCredentials(cProducer, "accessKey", "secretKey", "channel"), OK);
+  SessionCredentials sessionCredentials = defaultMQProducer->getSessionCredentials();
+  EXPECT_EQ(sessionCredentials.getAccessKey(), "accessKey");
+  Mock::AllowLeak(defaultMQProducer);
 }
 
 TEST(cProducer, null) {
-    EXPECT_TRUE(CreateProducer(NULL) == NULL);
-    EXPECT_EQ(StartProducer(NULL), NULL_POINTER);
-    EXPECT_EQ(ShutdownProducer(NULL), NULL_POINTER);
-    EXPECT_EQ(SetProducerNameServerAddress(NULL, NULL), NULL_POINTER);
-    EXPECT_EQ(SetProducerNameServerDomain(NULL, NULL), NULL_POINTER);
-    EXPECT_EQ(SetProducerGroupName(NULL, NULL), NULL_POINTER);
-    EXPECT_EQ(SetProducerInstanceName(NULL, NULL), NULL_POINTER);
-    EXPECT_EQ(SetProducerSessionCredentials(NULL, NULL, NULL, NULL), NULL_POINTER);
-    EXPECT_EQ(SetProducerLogLevel(NULL, E_LOG_LEVEL_FATAL), NULL_POINTER);
-    EXPECT_EQ(SetProducerSendMsgTimeout(NULL, 1), NULL_POINTER);
-    EXPECT_EQ(SetProducerCompressLevel(NULL, 1), NULL_POINTER);
-    EXPECT_EQ(SetProducerMaxMessageSize(NULL, 2), NULL_POINTER);
-    EXPECT_EQ(SetProducerLogLevel(NULL, E_LOG_LEVEL_FATAL), NULL_POINTER);
-    EXPECT_EQ(DestroyProducer(NULL), NULL_POINTER);
+  EXPECT_TRUE(CreateProducer(NULL) == NULL);
+  EXPECT_EQ(StartProducer(NULL), NULL_POINTER);
+  EXPECT_EQ(ShutdownProducer(NULL), NULL_POINTER);
+  EXPECT_EQ(SetProducerNameServerAddress(NULL, NULL), NULL_POINTER);
+  EXPECT_EQ(SetProducerNameServerDomain(NULL, NULL), NULL_POINTER);
+  EXPECT_EQ(SetProducerGroupName(NULL, NULL), NULL_POINTER);
+  EXPECT_EQ(SetProducerInstanceName(NULL, NULL), NULL_POINTER);
+  EXPECT_EQ(SetProducerSessionCredentials(NULL, NULL, NULL, NULL), NULL_POINTER);
+  EXPECT_EQ(SetProducerLogLevel(NULL, E_LOG_LEVEL_FATAL), NULL_POINTER);
+  EXPECT_EQ(SetProducerSendMsgTimeout(NULL, 1), NULL_POINTER);
+  EXPECT_EQ(SetProducerCompressLevel(NULL, 1), NULL_POINTER);
+  EXPECT_EQ(SetProducerMaxMessageSize(NULL, 2), NULL_POINTER);
+  EXPECT_EQ(SetProducerLogLevel(NULL, E_LOG_LEVEL_FATAL), NULL_POINTER);
+  EXPECT_EQ(DestroyProducer(NULL), NULL_POINTER);
 }
 
-int main(int argc, char *argv[]) {
-    InitGoogleMock(&argc, argv);
-    testing::GTEST_FLAG(throw_on_failure) = true;
-    testing::GTEST_FLAG(filter) = "cProducer.*";
-    int itestts = RUN_ALL_TESTS();
-    return itestts;
+int main(int argc, char* argv[]) {
+  InitGoogleMock(&argc, argv);
+  testing::GTEST_FLAG(throw_on_failure) = true;
+  testing::GTEST_FLAG(filter) = "cProducer.*";
+  int itestts = RUN_ALL_TESTS();
+  return itestts;
 }
diff --git a/test/src/extern/CPullConsumerTest.cpp b/test/src/extern/CPullConsumerTest.cpp
index 6a1118d..e326e74 100644
--- a/test/src/extern/CPullConsumerTest.cpp
+++ b/test/src/extern/CPullConsumerTest.cpp
@@ -51,161 +51,161 @@
 using rocketmq::SessionCredentials;
 
 class MockDefaultMQPullConsumer : public DefaultMQPullConsumer {
-   public:
-    MockDefaultMQPullConsumer(const string &groupname) : DefaultMQPullConsumer(groupname) {}
-    MOCK_METHOD0(start, void());
-    MOCK_METHOD0(shutdown, void());
-    MOCK_METHOD2(setLogFileSizeAndNum, void(int, long));
-    MOCK_METHOD1(setLogLevel, void(elogLevel));
-    MOCK_METHOD2(fetchSubscribeMessageQueues, void(const string &, vector<MQMessageQueue> &));
-    MOCK_METHOD4(pull, PullResult(const MQMessageQueue &, const string &, int64, int));
+ public:
+  MockDefaultMQPullConsumer(const string& groupname) : DefaultMQPullConsumer(groupname) {}
+  MOCK_METHOD0(start, void());
+  MOCK_METHOD0(shutdown, void());
+  MOCK_METHOD2(setLogFileSizeAndNum, void(int, long));
+  MOCK_METHOD1(setLogLevel, void(elogLevel));
+  MOCK_METHOD2(fetchSubscribeMessageQueues, void(const string&, vector<MQMessageQueue>&));
+  MOCK_METHOD4(pull, PullResult(const MQMessageQueue&, const string&, int64, int));
 };
 
 TEST(cpullConsumer, pull) {
-    MockDefaultMQPullConsumer *mqPullConsumer = new MockDefaultMQPullConsumer("groudId");
-    CPullConsumer *pullConsumer = (CPullConsumer *) mqPullConsumer;
+  MockDefaultMQPullConsumer* mqPullConsumer = new MockDefaultMQPullConsumer("groudId");
+  CPullConsumer* pullConsumer = (CPullConsumer*)mqPullConsumer;
 
-    CMessageQueue *cMessageQueue;
-    cMessageQueue = (CMessageQueue *) malloc(sizeof(CMessageQueue));
-    strncpy(cMessageQueue->topic, "testTopic", 8);
-    strncpy(cMessageQueue->brokerName, "testBroker", 9);
-    cMessageQueue->queueId = 1;
+  CMessageQueue* cMessageQueue;
+  cMessageQueue = (CMessageQueue*)malloc(sizeof(CMessageQueue));
+  strncpy(cMessageQueue->topic, "testTopic", 8);
+  strncpy(cMessageQueue->brokerName, "testBroker", 9);
+  cMessageQueue->queueId = 1;
 
-    PullResult timeOutPullResult(PullStatus::BROKER_TIMEOUT, 1, 2, 3);
+  PullResult timeOutPullResult(PullStatus::BROKER_TIMEOUT, 1, 2, 3);
 
-    PullResult noNewMsgPullResult(PullStatus::NO_NEW_MSG, 1, 2, 3);
+  PullResult noNewMsgPullResult(PullStatus::NO_NEW_MSG, 1, 2, 3);
 
-    PullResult noMatchedMsgPullResult(PullStatus::NO_MATCHED_MSG, 1, 2, 3);
+  PullResult noMatchedMsgPullResult(PullStatus::NO_MATCHED_MSG, 1, 2, 3);
 
-    PullResult offsetIllegalPullResult(PullStatus::OFFSET_ILLEGAL, 1, 2, 3);
+  PullResult offsetIllegalPullResult(PullStatus::OFFSET_ILLEGAL, 1, 2, 3);
 
-    PullResult defaultPullResult((PullStatus) -1, 1, 2, 3);
+  PullResult defaultPullResult((PullStatus)-1, 1, 2, 3);
 
-    vector<MQMessageExt> src;
-    for (int i = 0; i < 5; i++) {
-        MQMessageExt ext;
-        src.push_back(ext);
-    }
+  vector<MQMessageExt> src;
+  for (int i = 0; i < 5; i++) {
+    MQMessageExt ext;
+    src.push_back(ext);
+  }
 
-    PullResult foundPullResult(PullStatus::FOUND, 1, 2, 3, src);
+  PullResult foundPullResult(PullStatus::FOUND, 1, 2, 3, src);
 
-    EXPECT_CALL(*mqPullConsumer, pull(_, _, _, _))
-        .WillOnce(Return(timeOutPullResult))
-        .WillOnce(Return(noNewMsgPullResult))
-        .WillOnce(Return(noMatchedMsgPullResult))
-        .WillOnce(Return(offsetIllegalPullResult))
-        .WillOnce(Return(defaultPullResult))
-        /*.WillOnce(Return(timeOutPullResult))*/.WillOnce(Return(foundPullResult));
+  EXPECT_CALL(*mqPullConsumer, pull(_, _, _, _))
+      .WillOnce(Return(timeOutPullResult))
+      .WillOnce(Return(noNewMsgPullResult))
+      .WillOnce(Return(noMatchedMsgPullResult))
+      .WillOnce(Return(offsetIllegalPullResult))
+      .WillOnce(Return(defaultPullResult))
+      /*.WillOnce(Return(timeOutPullResult))*/.WillOnce(Return(foundPullResult));
 
-    CPullResult timeOutcPullResult = Pull(pullConsumer, cMessageQueue, "123123", 0, 0);
-    EXPECT_EQ(timeOutcPullResult.pullStatus, E_BROKER_TIMEOUT);
+  CPullResult timeOutcPullResult = Pull(pullConsumer, cMessageQueue, "123123", 0, 0);
+  EXPECT_EQ(timeOutcPullResult.pullStatus, E_BROKER_TIMEOUT);
 
-    CPullResult noNewMsgcPullResult = Pull(pullConsumer, cMessageQueue, "123123", 0, 0);
-    EXPECT_EQ(noNewMsgcPullResult.pullStatus, E_NO_NEW_MSG);
+  CPullResult noNewMsgcPullResult = Pull(pullConsumer, cMessageQueue, "123123", 0, 0);
+  EXPECT_EQ(noNewMsgcPullResult.pullStatus, E_NO_NEW_MSG);
 
-    CPullResult noMatchedMsgcPullResult = Pull(pullConsumer, cMessageQueue, "123123", 0, 0);
-    EXPECT_EQ(noMatchedMsgcPullResult.pullStatus, E_NO_MATCHED_MSG);
+  CPullResult noMatchedMsgcPullResult = Pull(pullConsumer, cMessageQueue, "123123", 0, 0);
+  EXPECT_EQ(noMatchedMsgcPullResult.pullStatus, E_NO_MATCHED_MSG);
 
-    CPullResult offsetIllegalcPullResult = Pull(pullConsumer, cMessageQueue, "123123", 0, 0);
-    EXPECT_EQ(offsetIllegalcPullResult.pullStatus, E_OFFSET_ILLEGAL);
+  CPullResult offsetIllegalcPullResult = Pull(pullConsumer, cMessageQueue, "123123", 0, 0);
+  EXPECT_EQ(offsetIllegalcPullResult.pullStatus, E_OFFSET_ILLEGAL);
 
-    CPullResult defaultcPullResult = Pull(pullConsumer, cMessageQueue, "123123", 0, 0);
-    EXPECT_EQ(defaultcPullResult.pullStatus, E_NO_NEW_MSG);
+  CPullResult defaultcPullResult = Pull(pullConsumer, cMessageQueue, "123123", 0, 0);
+  EXPECT_EQ(defaultcPullResult.pullStatus, E_NO_NEW_MSG);
 
-    CPullResult exceptionPullResult = Pull(pullConsumer, cMessageQueue, NULL, 0, 0);
-    EXPECT_EQ(exceptionPullResult.pullStatus, E_BROKER_TIMEOUT);
+  CPullResult exceptionPullResult = Pull(pullConsumer, cMessageQueue, NULL, 0, 0);
+  EXPECT_EQ(exceptionPullResult.pullStatus, E_BROKER_TIMEOUT);
 
-    CPullResult foundcPullResult = Pull(pullConsumer, cMessageQueue, "123123", 0, 0);
-    EXPECT_EQ(foundcPullResult.pullStatus, E_FOUND);
+  CPullResult foundcPullResult = Pull(pullConsumer, cMessageQueue, "123123", 0, 0);
+  EXPECT_EQ(foundcPullResult.pullStatus, E_FOUND);
 
-    delete mqPullConsumer;
+  delete mqPullConsumer;
 }
 
 TEST(cpullConsumer, infoMock) {
-    MockDefaultMQPullConsumer *mqPullConsumer = new MockDefaultMQPullConsumer("groudId");
-    CPullConsumer *pullConsumer = (CPullConsumer *) mqPullConsumer;
+  MockDefaultMQPullConsumer* mqPullConsumer = new MockDefaultMQPullConsumer("groudId");
+  CPullConsumer* pullConsumer = (CPullConsumer*)mqPullConsumer;
 
-    Expectation exp = EXPECT_CALL(*mqPullConsumer, start()).Times(1);
-    EXPECT_EQ(StartPullConsumer(pullConsumer), OK);
+  Expectation exp = EXPECT_CALL(*mqPullConsumer, start()).Times(1);
+  EXPECT_EQ(StartPullConsumer(pullConsumer), OK);
 
-    EXPECT_CALL(*mqPullConsumer, shutdown()).Times(1);
-    EXPECT_EQ(ShutdownPullConsumer(pullConsumer), OK);
+  EXPECT_CALL(*mqPullConsumer, shutdown()).Times(1);
+  EXPECT_EQ(ShutdownPullConsumer(pullConsumer), OK);
 
-    // EXPECT_CALL(*mqPullConsumer,setLogFileSizeAndNum(_,_)).Times(1);
-    EXPECT_EQ(SetPullConsumerLogFileNumAndSize(pullConsumer, 1, 2), OK);
+  // EXPECT_CALL(*mqPullConsumer,setLogFileSizeAndNum(_,_)).Times(1);
+  EXPECT_EQ(SetPullConsumerLogFileNumAndSize(pullConsumer, 1, 2), OK);
 
-    // EXPECT_CALL(*mqPullConsumer,setLogLevel(_)).Times(1);
-    EXPECT_EQ(SetPullConsumerLogLevel(pullConsumer, E_LOG_LEVEL_INFO), OK);
+  // EXPECT_CALL(*mqPullConsumer,setLogLevel(_)).Times(1);
+  EXPECT_EQ(SetPullConsumerLogLevel(pullConsumer, E_LOG_LEVEL_INFO), OK);
 
-    std::vector<MQMessageQueue> fullMQ;
-    for (int i = 0; i < 5; i++) {
-        MQMessageQueue queue("testTopic", "testsBroker", i);
-        fullMQ.push_back(queue);
-    }
+  std::vector<MQMessageQueue> fullMQ;
+  for (int i = 0; i < 5; i++) {
+    MQMessageQueue queue("testTopic", "testsBroker", i);
+    fullMQ.push_back(queue);
+  }
 
-    EXPECT_CALL(*mqPullConsumer, fetchSubscribeMessageQueues(_, _)).Times(1).WillOnce(SetArgReferee<1>(fullMQ));
-    CMessageQueue *mqs = NULL;
-    int size = 0;
-    FetchSubscriptionMessageQueues(pullConsumer, "testTopic", &mqs, &size);
-    EXPECT_EQ(size, 5);
+  EXPECT_CALL(*mqPullConsumer, fetchSubscribeMessageQueues(_, _)).Times(1).WillOnce(SetArgReferee<1>(fullMQ));
+  CMessageQueue* mqs = NULL;
+  int size = 0;
+  FetchSubscriptionMessageQueues(pullConsumer, "testTopic", &mqs, &size);
+  EXPECT_EQ(size, 5);
 
-    delete mqPullConsumer;
+  delete mqPullConsumer;
 }
 
 TEST(cpullConsumer, init) {
-    CPullConsumer *pullConsumer = CreatePullConsumer("testGroupId");
-    DefaultMQPullConsumer *defaultMQPullConsumer = (DefaultMQPullConsumer *) pullConsumer;
-    EXPECT_FALSE(pullConsumer == NULL);
+  CPullConsumer* pullConsumer = CreatePullConsumer("testGroupId");
+  DefaultMQPullConsumer* defaultMQPullConsumer = (DefaultMQPullConsumer*)pullConsumer;
+  EXPECT_FALSE(pullConsumer == NULL);
 
-    EXPECT_EQ(SetPullConsumerGroupID(pullConsumer, "groupId"), OK);
-    EXPECT_EQ(GetPullConsumerGroupID(pullConsumer), defaultMQPullConsumer->getGroupName().c_str());
+  EXPECT_EQ(SetPullConsumerGroupID(pullConsumer, "groupId"), OK);
+  EXPECT_EQ(GetPullConsumerGroupID(pullConsumer), defaultMQPullConsumer->getGroupName().c_str());
 
-    EXPECT_EQ(SetPullConsumerNameServerAddress(pullConsumer, "127.0.0.1:10091"), OK);
-    EXPECT_EQ(defaultMQPullConsumer->getNamesrvAddr(), "127.0.0.1:10091");
+  EXPECT_EQ(SetPullConsumerNameServerAddress(pullConsumer, "127.0.0.1:10091"), OK);
+  EXPECT_EQ(defaultMQPullConsumer->getNamesrvAddr(), "127.0.0.1:10091");
 
-    EXPECT_EQ(SetPullConsumerNameServerDomain(pullConsumer, "domain"), OK);
-    EXPECT_EQ(defaultMQPullConsumer->getNamesrvDomain(), "domain");
+  EXPECT_EQ(SetPullConsumerNameServerDomain(pullConsumer, "domain"), OK);
+  EXPECT_EQ(defaultMQPullConsumer->getNamesrvDomain(), "domain");
 
-    EXPECT_EQ(SetPullConsumerSessionCredentials(pullConsumer, "accessKey", "secretKey", "channel"), OK);
-    SessionCredentials sessionCredentials = defaultMQPullConsumer->getSessionCredentials();
-    EXPECT_EQ(sessionCredentials.getAccessKey(), "accessKey");
+  EXPECT_EQ(SetPullConsumerSessionCredentials(pullConsumer, "accessKey", "secretKey", "channel"), OK);
+  SessionCredentials sessionCredentials = defaultMQPullConsumer->getSessionCredentials();
+  EXPECT_EQ(sessionCredentials.getAccessKey(), "accessKey");
 
-    EXPECT_EQ(SetPullConsumerLogPath(pullConsumer, NULL), OK);
+  EXPECT_EQ(SetPullConsumerLogPath(pullConsumer, NULL), OK);
 
-    // EXPECT_EQ(SetPullConsumerLogFileNumAndSize(pullConsumer,NULL,NULL),NULL_POINTER);
-    EXPECT_EQ(SetPullConsumerLogLevel(pullConsumer, E_LOG_LEVEL_DEBUG), OK);
+  // EXPECT_EQ(SetPullConsumerLogFileNumAndSize(pullConsumer,NULL,NULL),NULL_POINTER);
+  EXPECT_EQ(SetPullConsumerLogLevel(pullConsumer, E_LOG_LEVEL_DEBUG), OK);
 }
 
 TEST(cpullConsumer, null) {
-    CPullConsumer *pullConsumer = CreatePullConsumer("testGroupId");
-    DefaultMQPullConsumer *defaultMQPullConsumer = (DefaultMQPullConsumer *) pullConsumer;
-    EXPECT_FALSE(pullConsumer == NULL);
+  CPullConsumer* pullConsumer = CreatePullConsumer("testGroupId");
+  DefaultMQPullConsumer* defaultMQPullConsumer = (DefaultMQPullConsumer*)pullConsumer;
+  EXPECT_FALSE(pullConsumer == NULL);
 
-    EXPECT_EQ(SetPullConsumerGroupID(pullConsumer, "groupId"), OK);
-    EXPECT_EQ(GetPullConsumerGroupID(pullConsumer), defaultMQPullConsumer->getGroupName().c_str());
+  EXPECT_EQ(SetPullConsumerGroupID(pullConsumer, "groupId"), OK);
+  EXPECT_EQ(GetPullConsumerGroupID(pullConsumer), defaultMQPullConsumer->getGroupName().c_str());
 
-    EXPECT_EQ(SetPullConsumerNameServerAddress(pullConsumer, "127.0.0.1:10091"), OK);
-    EXPECT_EQ(defaultMQPullConsumer->getNamesrvAddr(), "127.0.0.1:10091");
+  EXPECT_EQ(SetPullConsumerNameServerAddress(pullConsumer, "127.0.0.1:10091"), OK);
+  EXPECT_EQ(defaultMQPullConsumer->getNamesrvAddr(), "127.0.0.1:10091");
 
-    EXPECT_EQ(SetPullConsumerNameServerDomain(pullConsumer, "domain"), OK);
-    EXPECT_EQ(defaultMQPullConsumer->getNamesrvDomain(), "domain");
+  EXPECT_EQ(SetPullConsumerNameServerDomain(pullConsumer, "domain"), OK);
+  EXPECT_EQ(defaultMQPullConsumer->getNamesrvDomain(), "domain");
 
-    EXPECT_EQ(SetPullConsumerSessionCredentials(pullConsumer, "accessKey", "secretKey", "channel"), OK);
-    SessionCredentials sessionCredentials = defaultMQPullConsumer->getSessionCredentials();
-    EXPECT_EQ(sessionCredentials.getAccessKey(), "accessKey");
+  EXPECT_EQ(SetPullConsumerSessionCredentials(pullConsumer, "accessKey", "secretKey", "channel"), OK);
+  SessionCredentials sessionCredentials = defaultMQPullConsumer->getSessionCredentials();
+  EXPECT_EQ(sessionCredentials.getAccessKey(), "accessKey");
 
-    EXPECT_EQ(SetPullConsumerLogPath(pullConsumer, NULL), OK);
-    // EXPECT_EQ(SetPullConsumerLogFileNumAndSize(pullConsumer,NULL,NULL),NULL_POINTER);
-    EXPECT_EQ(SetPullConsumerLogLevel(pullConsumer, E_LOG_LEVEL_DEBUG), OK);
-    EXPECT_EQ(DestroyPullConsumer(pullConsumer), OK);
-    EXPECT_EQ(StartPullConsumer(NULL), NULL_POINTER);
-    EXPECT_EQ(ShutdownPullConsumer(NULL), NULL_POINTER);
+  EXPECT_EQ(SetPullConsumerLogPath(pullConsumer, NULL), OK);
+  // EXPECT_EQ(SetPullConsumerLogFileNumAndSize(pullConsumer,NULL,NULL),NULL_POINTER);
+  EXPECT_EQ(SetPullConsumerLogLevel(pullConsumer, E_LOG_LEVEL_DEBUG), OK);
+  EXPECT_EQ(DestroyPullConsumer(pullConsumer), OK);
+  EXPECT_EQ(StartPullConsumer(NULL), NULL_POINTER);
+  EXPECT_EQ(ShutdownPullConsumer(NULL), NULL_POINTER);
 }
 
-int main(int argc, char *argv[]) {
-    InitGoogleMock(&argc, argv);
-    testing::GTEST_FLAG(throw_on_failure) = true;
-    testing::GTEST_FLAG(filter) = "cpullConsumer.*";
-    int itestts = RUN_ALL_TESTS();
-    return itestts;
+int main(int argc, char* argv[]) {
+  InitGoogleMock(&argc, argv);
+  testing::GTEST_FLAG(throw_on_failure) = true;
+  testing::GTEST_FLAG(filter) = "cpullConsumer.*";
+  int itestts = RUN_ALL_TESTS();
+  return itestts;
 }
diff --git a/test/src/extern/CPushConsumerTest.cpp b/test/src/extern/CPushConsumerTest.cpp
index 281b801..a2d2fc9 100644
--- a/test/src/extern/CPushConsumerTest.cpp
+++ b/test/src/extern/CPushConsumerTest.cpp
@@ -42,112 +42,115 @@
 using rocketmq::SessionCredentials;
 
 class MockDefaultMQPushConsumer : public DefaultMQPushConsumer {
-   public:
-    MockDefaultMQPushConsumer(const string &groupname) : DefaultMQPushConsumer(groupname) {}
+ public:
+  MockDefaultMQPushConsumer(const string& groupname) : DefaultMQPushConsumer(groupname) {}
 
-    MOCK_METHOD0(start, void());
-    MOCK_METHOD0(shutdown, void());
-    MOCK_METHOD2(setLogFileSizeAndNum, void(int, long));
-    MOCK_METHOD1(setLogLevel, void(elogLevel));
+  MOCK_METHOD0(start, void());
+  MOCK_METHOD0(shutdown, void());
+  MOCK_METHOD2(setLogFileSizeAndNum, void(int, long));
+  MOCK_METHOD1(setLogLevel, void(elogLevel));
 };
 
 TEST(cPushComsumer, infomock) {
-    MockDefaultMQPushConsumer *pushComsumer = new MockDefaultMQPushConsumer("testGroup");
-    CPushConsumer *consumer = (CPushConsumer *) pushComsumer;
+  MockDefaultMQPushConsumer* pushComsumer = new MockDefaultMQPushConsumer("testGroup");
+  CPushConsumer* consumer = (CPushConsumer*)pushComsumer;
 
-    EXPECT_CALL(*pushComsumer, start()).Times(1);
-    EXPECT_EQ(StartPushConsumer(consumer), OK);
+  EXPECT_CALL(*pushComsumer, start()).Times(1);
+  EXPECT_EQ(StartPushConsumer(consumer), OK);
 
-    EXPECT_CALL(*pushComsumer, shutdown()).Times(1);
-    EXPECT_EQ(ShutdownPushConsumer(consumer), OK);
+  EXPECT_CALL(*pushComsumer, shutdown()).Times(1);
+  EXPECT_EQ(ShutdownPushConsumer(consumer), OK);
 
-    EXPECT_CALL(*pushComsumer, setLogFileSizeAndNum(1, 1)).Times(1);
-    pushComsumer->setLogFileSizeAndNum(1, 1);
-    EXPECT_EQ(SetPushConsumerLogFileNumAndSize(consumer, 1, 1), OK);
+  EXPECT_CALL(*pushComsumer, setLogFileSizeAndNum(1, 1)).Times(1);
+  pushComsumer->setLogFileSizeAndNum(1, 1);
+  EXPECT_EQ(SetPushConsumerLogFileNumAndSize(consumer, 1, 1), OK);
 
-    // EXPECT_CALL(*pushComsumer,setLogLevel(_)).Times(1);
-    EXPECT_EQ(SetPushConsumerLogLevel(consumer, E_LOG_LEVEL_FATAL), OK);
+  // EXPECT_CALL(*pushComsumer,setLogLevel(_)).Times(1);
+  EXPECT_EQ(SetPushConsumerLogLevel(consumer, E_LOG_LEVEL_FATAL), OK);
 
-    Mock::AllowLeak(pushComsumer);
+  Mock::AllowLeak(pushComsumer);
+}
+
+int MessageCallBackFunc(CPushConsumer* consumer, CMessageExt* msg) {
+  return 0;
 }
 
 TEST(cPushComsumer, info) {
-    CPushConsumer *cpushConsumer = CreatePushConsumer("testGroup");
-    DefaultMQPushConsumer *mqPushConsumer = (DefaultMQPushConsumer *) cpushConsumer;
+  CPushConsumer* cpushConsumer = CreatePushConsumer("testGroup");
+  DefaultMQPushConsumer* mqPushConsumer = (DefaultMQPushConsumer*)cpushConsumer;
 
-    EXPECT_TRUE(cpushConsumer != NULL);
-    EXPECT_EQ(string(GetPushConsumerGroupID(cpushConsumer)), "testGroup");
+  EXPECT_TRUE(cpushConsumer != NULL);
+  EXPECT_EQ(string(GetPushConsumerGroupID(cpushConsumer)), "testGroup");
 
-    EXPECT_EQ(SetPushConsumerGroupID(cpushConsumer, "testGroupTwo"), OK);
-    EXPECT_EQ(string(GetPushConsumerGroupID(cpushConsumer)), "testGroupTwo");
+  EXPECT_EQ(SetPushConsumerGroupID(cpushConsumer, "testGroupTwo"), OK);
+  EXPECT_EQ(string(GetPushConsumerGroupID(cpushConsumer)), "testGroupTwo");
 
-    EXPECT_EQ(SetPushConsumerNameServerAddress(cpushConsumer, "127.0.0.1:9876"), OK);
-    EXPECT_EQ(mqPushConsumer->getNamesrvAddr(), "127.0.0.1:9876");
+  EXPECT_EQ(SetPushConsumerNameServerAddress(cpushConsumer, "127.0.0.1:9876"), OK);
+  EXPECT_EQ(mqPushConsumer->getNamesrvAddr(), "127.0.0.1:9876");
 
-    EXPECT_EQ(SetPushConsumerNameServerDomain(cpushConsumer, "domain"), OK);
-    EXPECT_EQ(mqPushConsumer->getNamesrvDomain(), "domain");
+  EXPECT_EQ(SetPushConsumerNameServerDomain(cpushConsumer, "domain"), OK);
+  EXPECT_EQ(mqPushConsumer->getNamesrvDomain(), "domain");
 
-    EXPECT_EQ(Subscribe(cpushConsumer, "testTopic", "testSub"), OK);
+  EXPECT_EQ(Subscribe(cpushConsumer, "testTopic", "testSub"), OK);
 
-    MessageCallBack pCallback;
-    EXPECT_EQ(RegisterMessageCallbackOrderly(cpushConsumer, pCallback), OK);
-    EXPECT_EQ(mqPushConsumer->getMessageListenerType(), MessageListenerType::messageListenerOrderly);
+  EXPECT_EQ(RegisterMessageCallbackOrderly(cpushConsumer, MessageCallBackFunc), OK);
+  EXPECT_EQ(mqPushConsumer->getMessageListenerType(), MessageListenerType::messageListenerOrderly);
 
-    EXPECT_EQ(RegisterMessageCallback(cpushConsumer, pCallback), OK);
-    EXPECT_EQ(mqPushConsumer->getMessageListenerType(), MessageListenerType::messageListenerConcurrently);
+  EXPECT_EQ(RegisterMessageCallback(cpushConsumer, MessageCallBackFunc), OK);
+  EXPECT_EQ(mqPushConsumer->getMessageListenerType(), MessageListenerType::messageListenerConcurrently);
 
-    EXPECT_EQ(UnregisterMessageCallbackOrderly(cpushConsumer), OK);
-    EXPECT_EQ(UnregisterMessageCallback(cpushConsumer), OK);
+  EXPECT_EQ(UnregisterMessageCallbackOrderly(cpushConsumer), OK);
+  EXPECT_EQ(UnregisterMessageCallback(cpushConsumer), OK);
 
-    EXPECT_EQ(SetPushConsumerThreadCount(cpushConsumer, 10), OK);
-    EXPECT_EQ(mqPushConsumer->getConsumeThreadCount(), 10);
+  EXPECT_EQ(SetPushConsumerThreadCount(cpushConsumer, 10), OK);
+  EXPECT_EQ(mqPushConsumer->getConsumeThreadCount(), 10);
 
-    EXPECT_EQ(SetPushConsumerMessageBatchMaxSize(cpushConsumer, 1024), OK);
-    EXPECT_EQ(mqPushConsumer->getConsumeMessageBatchMaxSize(), 1024);
+  EXPECT_EQ(SetPushConsumerMessageBatchMaxSize(cpushConsumer, 1024), OK);
+  EXPECT_EQ(mqPushConsumer->getConsumeMessageBatchMaxSize(), 1024);
 
-    EXPECT_EQ(SetPushConsumerInstanceName(cpushConsumer, "instance"), OK);
-    EXPECT_EQ(mqPushConsumer->getInstanceName(), "instance");
+  EXPECT_EQ(SetPushConsumerInstanceName(cpushConsumer, "instance"), OK);
+  EXPECT_EQ(mqPushConsumer->getInstanceName(), "instance");
 
-    EXPECT_EQ(SetPushConsumerSessionCredentials(cpushConsumer, "accessKey", "secretKey", "channel"), OK);
-    SessionCredentials sessionCredentials = mqPushConsumer->getSessionCredentials();
-    EXPECT_EQ(sessionCredentials.getAccessKey(), "accessKey");
+  EXPECT_EQ(SetPushConsumerSessionCredentials(cpushConsumer, "accessKey", "secretKey", "channel"), OK);
+  SessionCredentials sessionCredentials = mqPushConsumer->getSessionCredentials();
+  EXPECT_EQ(sessionCredentials.getAccessKey(), "accessKey");
 
-    EXPECT_EQ(SetPushConsumerMessageModel(cpushConsumer, BROADCASTING), OK);
-    EXPECT_EQ(mqPushConsumer->getMessageModel(), MessageModel::BROADCASTING);
+  EXPECT_EQ(SetPushConsumerMessageModel(cpushConsumer, BROADCASTING), OK);
+  EXPECT_EQ(mqPushConsumer->getMessageModel(), MessageModel::BROADCASTING);
 
-    Mock::AllowLeak(mqPushConsumer);
+  Mock::AllowLeak(mqPushConsumer);
 }
 
 TEST(cPushComsumer, null) {
-    CPushConsumer *cpushConsumer = CreatePushConsumer("testGroup");
+  CPushConsumer* cpushConsumer = CreatePushConsumer("testGroup");
 
-    EXPECT_TRUE(CreatePushConsumer(NULL) == NULL);
-    EXPECT_EQ(DestroyPushConsumer(NULL), NULL_POINTER);
-    EXPECT_EQ(StartPushConsumer(NULL), NULL_POINTER);
-    EXPECT_EQ(ShutdownPushConsumer(NULL), NULL_POINTER);
-    EXPECT_EQ(SetPushConsumerGroupID(NULL, "testGroup"), NULL_POINTER);
-    EXPECT_TRUE(GetPushConsumerGroupID(NULL) == NULL);
-    EXPECT_EQ(SetPushConsumerNameServerAddress(NULL, NULL), NULL_POINTER);
-    EXPECT_EQ(SetPushConsumerNameServerDomain(NULL, NULL), NULL_POINTER);
-    EXPECT_EQ(Subscribe(NULL, NULL, NULL), NULL_POINTER);
-    EXPECT_EQ(RegisterMessageCallbackOrderly(NULL, NULL), NULL_POINTER);
-    EXPECT_EQ(RegisterMessageCallbackOrderly(cpushConsumer, NULL), NULL_POINTER);
-    EXPECT_EQ(RegisterMessageCallback(NULL, NULL), NULL_POINTER);
-    EXPECT_EQ(UnregisterMessageCallbackOrderly(NULL), NULL_POINTER);
-    EXPECT_EQ(UnregisterMessageCallback(NULL), NULL_POINTER);
-    EXPECT_EQ(SetPushConsumerThreadCount(NULL, NULL), NULL_POINTER);
-    EXPECT_EQ(SetPushConsumerMessageBatchMaxSize(NULL, NULL), NULL_POINTER);
-    EXPECT_EQ(SetPushConsumerInstanceName(NULL, NULL), NULL_POINTER);
-    EXPECT_EQ(SetPushConsumerSessionCredentials(NULL, NULL, NULL, NULL), NULL_POINTER);
-    EXPECT_EQ(SetPushConsumerLogPath(NULL, NULL), NULL_POINTER);
-    EXPECT_EQ(SetPushConsumerLogFileNumAndSize(NULL, 1, 1), NULL_POINTER);
-    EXPECT_EQ(SetPushConsumerLogLevel(NULL, E_LOG_LEVEL_LEVEL_NUM), NULL_POINTER);
-    EXPECT_EQ(SetPushConsumerMessageModel(NULL, BROADCASTING), NULL_POINTER);
+  EXPECT_TRUE(CreatePushConsumer(NULL) == NULL);
+  EXPECT_EQ(DestroyPushConsumer(NULL), NULL_POINTER);
+  EXPECT_EQ(StartPushConsumer(NULL), NULL_POINTER);
+  EXPECT_EQ(ShutdownPushConsumer(NULL), NULL_POINTER);
+  EXPECT_EQ(SetPushConsumerGroupID(NULL, "testGroup"), NULL_POINTER);
+  EXPECT_TRUE(GetPushConsumerGroupID(NULL) == NULL);
+  EXPECT_EQ(SetPushConsumerNameServerAddress(NULL, NULL), NULL_POINTER);
+  EXPECT_EQ(SetPushConsumerNameServerDomain(NULL, NULL), NULL_POINTER);
+  EXPECT_EQ(Subscribe(NULL, NULL, NULL), NULL_POINTER);
+  EXPECT_EQ(RegisterMessageCallbackOrderly(NULL, NULL), NULL_POINTER);
+  EXPECT_EQ(RegisterMessageCallbackOrderly(cpushConsumer, NULL), NULL_POINTER);
+  EXPECT_EQ(RegisterMessageCallback(NULL, NULL), NULL_POINTER);
+  EXPECT_EQ(UnregisterMessageCallbackOrderly(NULL), NULL_POINTER);
+  EXPECT_EQ(UnregisterMessageCallback(NULL), NULL_POINTER);
+  EXPECT_EQ(SetPushConsumerThreadCount(NULL, 0), NULL_POINTER);
+  EXPECT_EQ(SetPushConsumerMessageBatchMaxSize(NULL, 0), NULL_POINTER);
+  EXPECT_EQ(SetPushConsumerInstanceName(NULL, NULL), NULL_POINTER);
+  EXPECT_EQ(SetPushConsumerSessionCredentials(NULL, NULL, NULL, NULL), NULL_POINTER);
+  EXPECT_EQ(SetPushConsumerLogPath(NULL, NULL), NULL_POINTER);
+  EXPECT_EQ(SetPushConsumerLogFileNumAndSize(NULL, 1, 1), NULL_POINTER);
+  EXPECT_EQ(SetPushConsumerLogLevel(NULL, E_LOG_LEVEL_LEVEL_NUM), NULL_POINTER);
+  EXPECT_EQ(SetPushConsumerMessageModel(NULL, BROADCASTING), NULL_POINTER);
 }
 
-int main(int argc, char *argv[]) {
-    InitGoogleMock(&argc, argv);
-    testing::GTEST_FLAG(filter) = "cPushComsumer.*";
-    int itestts = RUN_ALL_TESTS();
-    return itestts;
+int main(int argc, char* argv[]) {
+  InitGoogleMock(&argc, argv);
+  testing::GTEST_FLAG(filter) = "cPushComsumer.*";
+  int itestts = RUN_ALL_TESTS();
+  return itestts;
 }
diff --git a/test/src/message/MQDecoderTest.cpp b/test/src/message/MQDecoderTest.cpp
index 4893200..748d89c 100644
--- a/test/src/message/MQDecoderTest.cpp
+++ b/test/src/message/MQDecoderTest.cpp
@@ -53,152 +53,152 @@
 
 // TODO
 TEST(decoders, messageId) {
-    int host;
-    int port;
-    string msgIdStr =
-        MQDecoder::createMessageId(rocketmq::IPPort2socketAddress(inet_addr("127.0.0.1"), 10091), (int64) 1024);
-    MQMessageId msgId = MQDecoder::decodeMessageId(msgIdStr);
+  int host;
+  int port;
+  string msgIdStr =
+      MQDecoder::createMessageId(rocketmq::IPPort2socketAddress(inet_addr("127.0.0.1"), 10091), (int64)1024);
+  MQMessageId msgId = MQDecoder::decodeMessageId(msgIdStr);
 
-    EXPECT_EQ(msgId.getOffset(), 1024);
+  EXPECT_EQ(msgId.getOffset(), 1024);
 
-    rocketmq::socketAddress2IPPort(msgId.getAddress(), host, port);
-    EXPECT_EQ(host, inet_addr("127.0.0.1"));
-    EXPECT_EQ(port, 10091);
+  rocketmq::socketAddress2IPPort(msgId.getAddress(), host, port);
+  EXPECT_EQ(host, inet_addr("127.0.0.1"));
+  EXPECT_EQ(port, 10091);
 }
 
 TEST(decoder, decoder) {
-    MQMessageExt mext;
-    MemoryOutputStream *memoryOut = new MemoryOutputStream(1024);
+  MQMessageExt mext;
+  MemoryOutputStream* memoryOut = new MemoryOutputStream(1024);
 
-    // 1 TOTALSIZE 4
-    memoryOut->writeIntBigEndian(107);
-    mext.setStoreSize(107);
+  // 1 TOTALSIZE 4
+  memoryOut->writeIntBigEndian(107);
+  mext.setStoreSize(107);
 
-    // 2 MAGICCODE sizeof(int)  8=4+4
-    memoryOut->writeIntBigEndian(14);
+  // 2 MAGICCODE sizeof(int)  8=4+4
+  memoryOut->writeIntBigEndian(14);
 
-    // 3 BODYCRC  12=8+4
-    memoryOut->writeIntBigEndian(24);
-    mext.setBodyCRC(24);
-    // 4 QUEUEID 16=12+4
-    memoryOut->writeIntBigEndian(4);
-    mext.setQueueId(4);
-    // 5 FLAG    20=16+4
-    memoryOut->writeIntBigEndian(4);
-    mext.setFlag(4);
-    // 6 QUEUEOFFSET  28 = 20+8
-    memoryOut->writeInt64BigEndian((int64) 1024);
-    mext.setQueueOffset(1024);
-    // 7 PHYSICALOFFSET 36=28+8
-    memoryOut->writeInt64BigEndian((int64) 2048);
-    mext.setCommitLogOffset(2048);
-    // 8 SYSFLAG  40=36+4
-    memoryOut->writeIntBigEndian(0);
-    mext.setSysFlag(0);
-    // 9 BORNTIMESTAMP 48 = 40+8
-    memoryOut->writeInt64BigEndian((int64) 4096);
-    mext.setBornTimestamp(4096);
-    // 10 BORNHOST 56= 48+8
-    memoryOut->writeIntBigEndian(inet_addr("127.0.0.1"));
-    memoryOut->writeIntBigEndian(10091);
-    mext.setBornHost(rocketmq::IPPort2socketAddress(inet_addr("127.0.0.1"), 10091));
-    // 11 STORETIMESTAMP 64 =56+8
-    memoryOut->writeInt64BigEndian((int64) 4096);
-    mext.setStoreTimestamp(4096);
-    // 12 STOREHOST 72 = 64+8
-    memoryOut->writeIntBigEndian(inet_addr("127.0.0.2"));
-    memoryOut->writeIntBigEndian(10092);
-    mext.setStoreHost(rocketmq::IPPort2socketAddress(inet_addr("127.0.0.2"), 10092));
-    // 13 RECONSUMETIMES 76 = 72+4
-    mext.setReconsumeTimes(111111);
-    memoryOut->writeIntBigEndian(mext.getReconsumeTimes());
-    // 14 Prepared Transaction Offset 84 = 76+8
-    memoryOut->writeInt64BigEndian((int64) 12);
-    mext.setPreparedTransactionOffset(12);
-    // 15 BODY 88 = 84+4   10
-    string *body = new string("1234567890");
-    mext.setBody(body->c_str());
-    memoryOut->writeIntBigEndian(10);
-    memoryOut->write(body->c_str(), body->size());
+  // 3 BODYCRC  12=8+4
+  memoryOut->writeIntBigEndian(24);
+  mext.setBodyCRC(24);
+  // 4 QUEUEID 16=12+4
+  memoryOut->writeIntBigEndian(4);
+  mext.setQueueId(4);
+  // 5 FLAG    20=16+4
+  memoryOut->writeIntBigEndian(4);
+  mext.setFlag(4);
+  // 6 QUEUEOFFSET  28 = 20+8
+  memoryOut->writeInt64BigEndian((int64)1024);
+  mext.setQueueOffset(1024);
+  // 7 PHYSICALOFFSET 36=28+8
+  memoryOut->writeInt64BigEndian((int64)2048);
+  mext.setCommitLogOffset(2048);
+  // 8 SYSFLAG  40=36+4
+  memoryOut->writeIntBigEndian(0);
+  mext.setSysFlag(0);
+  // 9 BORNTIMESTAMP 48 = 40+8
+  memoryOut->writeInt64BigEndian((int64)4096);
+  mext.setBornTimestamp(4096);
+  // 10 BORNHOST 56= 48+8
+  memoryOut->writeIntBigEndian(inet_addr("127.0.0.1"));
+  memoryOut->writeIntBigEndian(10091);
+  mext.setBornHost(rocketmq::IPPort2socketAddress(inet_addr("127.0.0.1"), 10091));
+  // 11 STORETIMESTAMP 64 =56+8
+  memoryOut->writeInt64BigEndian((int64)4096);
+  mext.setStoreTimestamp(4096);
+  // 12 STOREHOST 72 = 64+8
+  memoryOut->writeIntBigEndian(inet_addr("127.0.0.2"));
+  memoryOut->writeIntBigEndian(10092);
+  mext.setStoreHost(rocketmq::IPPort2socketAddress(inet_addr("127.0.0.2"), 10092));
+  // 13 RECONSUMETIMES 76 = 72+4
+  mext.setReconsumeTimes(111111);
+  memoryOut->writeIntBigEndian(mext.getReconsumeTimes());
+  // 14 Prepared Transaction Offset 84 = 76+8
+  memoryOut->writeInt64BigEndian((int64)12);
+  mext.setPreparedTransactionOffset(12);
+  // 15 BODY 88 = 84+4   10
+  string* body = new string("1234567890");
+  mext.setBody(body->c_str());
+  memoryOut->writeIntBigEndian(10);
+  memoryOut->write(body->c_str(), body->size());
 
-    // 16 TOPIC
-    memoryOut->writeByte(10);
-    memoryOut->write(body->c_str(), body->size());
-    mext.setTopic(body->c_str());
+  // 16 TOPIC
+  memoryOut->writeByte(10);
+  memoryOut->write(body->c_str(), body->size());
+  mext.setTopic(body->c_str());
 
-    // 17 PROPERTIES
-    memoryOut->writeShortBigEndian(0);
+  // 17 PROPERTIES
+  memoryOut->writeShortBigEndian(0);
 
-    mext.setMsgId(MQDecoder::createMessageId(mext.getStoreHost(), (int64) mext.getCommitLogOffset()));
+  mext.setMsgId(MQDecoder::createMessageId(mext.getStoreHost(), (int64)mext.getCommitLogOffset()));
 
-    vector<MQMessageExt> mqvec;
-    MemoryBlock block = memoryOut->getMemoryBlock();
-    MQDecoder::decodes(&block, mqvec);
-    EXPECT_EQ(mqvec.size(), 1);
-    std::cout << mext.toString() << "\n";
-    std::cout << mqvec[0].toString() << "\n";
-    EXPECT_EQ(mqvec[0].toString(), mext.toString());
+  vector<MQMessageExt> mqvec;
+  MemoryBlock block = memoryOut->getMemoryBlock();
+  MQDecoder::decodes(&block, mqvec);
+  EXPECT_EQ(mqvec.size(), 1);
+  std::cout << mext.toString() << "\n";
+  std::cout << mqvec[0].toString() << "\n";
+  EXPECT_EQ(mqvec[0].toString(), mext.toString());
 
-    mqvec.clear();
-    MQDecoder::decodes(&block, mqvec, false);
-    EXPECT_FALSE(mqvec[0].getBody().size());
+  mqvec.clear();
+  MQDecoder::decodes(&block, mqvec, false);
+  EXPECT_FALSE(mqvec[0].getBody().size());
 
-    //===============================================================
-    // 8 SYSFLAG  40=36+4
-    mext.setSysFlag(0 | MessageSysFlag::CompressedFlag);
-    memoryOut->setPosition(36);
-    memoryOut->writeIntBigEndian(mext.getSysFlag());
+  //===============================================================
+  // 8 SYSFLAG  40=36+4
+  mext.setSysFlag(0 | MessageSysFlag::CompressedFlag);
+  memoryOut->setPosition(36);
+  memoryOut->writeIntBigEndian(mext.getSysFlag());
 
-    // 15 Body 84
-    string outBody;
-    string boody("123123123");
-    UtilAll::deflate(boody, outBody, 5);
-    mext.setBody(outBody);
+  // 15 Body 84
+  string outBody;
+  string boody("123123123");
+  UtilAll::deflate(boody, outBody, 5);
+  mext.setBody(outBody);
 
-    memoryOut->setPosition(84);
-    memoryOut->writeIntBigEndian(outBody.size());
-    memoryOut->write(outBody.c_str(), outBody.size());
+  memoryOut->setPosition(84);
+  memoryOut->writeIntBigEndian(outBody.size());
+  memoryOut->write(outBody.c_str(), outBody.size());
 
-    // 16 TOPIC
-    memoryOut->writeByte(10);
-    memoryOut->write(body->c_str(), body->size());
-    mext.setTopic(body->c_str());
+  // 16 TOPIC
+  memoryOut->writeByte(10);
+  memoryOut->write(body->c_str(), body->size());
+  mext.setTopic(body->c_str());
 
-    // 17 PROPERTIES
-    map<string, string> properties;
-    properties["RocketMQ"] = "cpp-client";
-    properties[MQMessage::PROPERTY_UNIQ_CLIENT_MESSAGE_ID_KEYIDX] = "123456";
-    mext.setProperties(properties);
-    mext.setMsgId("123456");
+  // 17 PROPERTIES
+  map<string, string> properties;
+  properties["RocketMQ"] = "cpp-client";
+  properties[MQMessage::PROPERTY_UNIQ_CLIENT_MESSAGE_ID_KEYIDX] = "123456";
+  mext.setProperties(properties);
+  mext.setMsgId("123456");
 
-    string proString = MQDecoder::messageProperties2String(properties);
+  string proString = MQDecoder::messageProperties2String(properties);
 
-    memoryOut->writeShortBigEndian(proString.size());
-    memoryOut->write(proString.c_str(), proString.size());
+  memoryOut->writeShortBigEndian(proString.size());
+  memoryOut->write(proString.c_str(), proString.size());
 
-    mext.setStoreSize(memoryOut->getDataSize());
-    memoryOut->setPosition(0);
-    memoryOut->writeIntBigEndian(mext.getStoreSize());
+  mext.setStoreSize(memoryOut->getDataSize());
+  memoryOut->setPosition(0);
+  memoryOut->writeIntBigEndian(mext.getStoreSize());
 
-    block = memoryOut->getMemoryBlock();
-    MQDecoder::decodes(&block, mqvec);
-    EXPECT_EQ(mqvec[0].toString(), mext.toString());
+  block = memoryOut->getMemoryBlock();
+  MQDecoder::decodes(&block, mqvec);
+  EXPECT_EQ(mqvec[0].toString(), mext.toString());
 }
 
 TEST(decoder, messagePropertiesAndToString) {
-    map<string, string> properties;
-    properties["RocketMQ"] = "cpp-client";
-    string proString = MQDecoder::messageProperties2String(properties);
+  map<string, string> properties;
+  properties["RocketMQ"] = "cpp-client";
+  string proString = MQDecoder::messageProperties2String(properties);
 
-    map<string, string> newProperties;
-    MQDecoder::string2messageProperties(proString, newProperties);
-    EXPECT_EQ(properties, newProperties);
+  map<string, string> newProperties;
+  MQDecoder::string2messageProperties(proString, newProperties);
+  EXPECT_EQ(properties, newProperties);
 }
 
-int main(int argc, char *argv[]) {
-    InitGoogleMock(&argc, argv);
+int main(int argc, char* argv[]) {
+  InitGoogleMock(&argc, argv);
 
-    testing::GTEST_FLAG(filter) = "decoder.*";
-    int itestts = RUN_ALL_TESTS();
-    return itestts;
+  testing::GTEST_FLAG(filter) = "decoder.*";
+  int itestts = RUN_ALL_TESTS();
+  return itestts;
 }
diff --git a/test/src/message/MQMessageExtTest.cpp b/test/src/message/MQMessageExtTest.cpp
index 3772a03..df8303d 100644
--- a/test/src/message/MQMessageExtTest.cpp
+++ b/test/src/message/MQMessageExtTest.cpp
@@ -32,107 +32,107 @@
 using rocketmq::TopicFilterType;
 
 TEST(messageExt, init) {
-    MQMessageExt messageExt;
-    EXPECT_EQ(messageExt.getQueueOffset(), 0);
-    EXPECT_EQ(messageExt.getCommitLogOffset(), 0);
-    EXPECT_EQ(messageExt.getBornTimestamp(), 0);
-    EXPECT_EQ(messageExt.getStoreTimestamp(), 0);
-    EXPECT_EQ(messageExt.getPreparedTransactionOffset(), 0);
-    EXPECT_EQ(messageExt.getQueueId(), 0);
-    EXPECT_EQ(messageExt.getStoreSize(), 0);
-    EXPECT_EQ(messageExt.getReconsumeTimes(), 3);
-    EXPECT_EQ(messageExt.getBodyCRC(), 0);
-    EXPECT_EQ(messageExt.getMsgId(), "");
-    EXPECT_EQ(messageExt.getOffsetMsgId(), "");
+  MQMessageExt messageExt;
+  EXPECT_EQ(messageExt.getQueueOffset(), 0);
+  EXPECT_EQ(messageExt.getCommitLogOffset(), 0);
+  EXPECT_EQ(messageExt.getBornTimestamp(), 0);
+  EXPECT_EQ(messageExt.getStoreTimestamp(), 0);
+  EXPECT_EQ(messageExt.getPreparedTransactionOffset(), 0);
+  EXPECT_EQ(messageExt.getQueueId(), 0);
+  EXPECT_EQ(messageExt.getStoreSize(), 0);
+  EXPECT_EQ(messageExt.getReconsumeTimes(), 3);
+  EXPECT_EQ(messageExt.getBodyCRC(), 0);
+  EXPECT_EQ(messageExt.getMsgId(), "");
+  EXPECT_EQ(messageExt.getOffsetMsgId(), "");
 
-    messageExt.setQueueOffset(1);
-    EXPECT_EQ(messageExt.getQueueOffset(), 1);
+  messageExt.setQueueOffset(1);
+  EXPECT_EQ(messageExt.getQueueOffset(), 1);
 
-    messageExt.setCommitLogOffset(1024);
-    EXPECT_EQ(messageExt.getCommitLogOffset(), 1024);
+  messageExt.setCommitLogOffset(1024);
+  EXPECT_EQ(messageExt.getCommitLogOffset(), 1024);
 
-    messageExt.setBornTimestamp(1024);
-    EXPECT_EQ(messageExt.getBornTimestamp(), 1024);
+  messageExt.setBornTimestamp(1024);
+  EXPECT_EQ(messageExt.getBornTimestamp(), 1024);
 
-    messageExt.setStoreTimestamp(2048);
-    EXPECT_EQ(messageExt.getStoreTimestamp(), 2048);
+  messageExt.setStoreTimestamp(2048);
+  EXPECT_EQ(messageExt.getStoreTimestamp(), 2048);
 
-    messageExt.setPreparedTransactionOffset(4096);
-    EXPECT_EQ(messageExt.getPreparedTransactionOffset(), 4096);
+  messageExt.setPreparedTransactionOffset(4096);
+  EXPECT_EQ(messageExt.getPreparedTransactionOffset(), 4096);
 
-    messageExt.setQueueId(2);
-    EXPECT_EQ(messageExt.getQueueId(), 2);
+  messageExt.setQueueId(2);
+  EXPECT_EQ(messageExt.getQueueId(), 2);
 
-    messageExt.setStoreSize(12);
-    EXPECT_EQ(messageExt.getStoreSize(), 12);
+  messageExt.setStoreSize(12);
+  EXPECT_EQ(messageExt.getStoreSize(), 12);
 
-    messageExt.setReconsumeTimes(48);
-    EXPECT_EQ(messageExt.getReconsumeTimes(), 48);
+  messageExt.setReconsumeTimes(48);
+  EXPECT_EQ(messageExt.getReconsumeTimes(), 48);
 
-    messageExt.setBodyCRC(32);
-    EXPECT_EQ(messageExt.getBodyCRC(), 32);
+  messageExt.setBodyCRC(32);
+  EXPECT_EQ(messageExt.getBodyCRC(), 32);
 
-    messageExt.setMsgId("MsgId");
-    EXPECT_EQ(messageExt.getMsgId(), "MsgId");
+  messageExt.setMsgId("MsgId");
+  EXPECT_EQ(messageExt.getMsgId(), "MsgId");
 
-    messageExt.setOffsetMsgId("offsetMsgId");
-    EXPECT_EQ(messageExt.getOffsetMsgId(), "offsetMsgId");
+  messageExt.setOffsetMsgId("offsetMsgId");
+  EXPECT_EQ(messageExt.getOffsetMsgId(), "offsetMsgId");
 
-    messageExt.setBornTimestamp(1111);
-    EXPECT_EQ(messageExt.getBornTimestamp(), 1111);
+  messageExt.setBornTimestamp(1111);
+  EXPECT_EQ(messageExt.getBornTimestamp(), 1111);
 
-    messageExt.setStoreTimestamp(2222);
-    EXPECT_EQ(messageExt.getStoreTimestamp(), 2222);
+  messageExt.setStoreTimestamp(2222);
+  EXPECT_EQ(messageExt.getStoreTimestamp(), 2222);
 
-    struct sockaddr_in sa;
-    sa.sin_family = AF_INET;
-    sa.sin_port = htons(10091);
-    sa.sin_addr.s_addr = inet_addr("127.0.0.1");
+  struct sockaddr_in sa;
+  sa.sin_family = AF_INET;
+  sa.sin_port = htons(10091);
+  sa.sin_addr.s_addr = inet_addr("127.0.0.1");
 
-    sockaddr bornHost;
-    memcpy(&bornHost, &sa, sizeof(sockaddr));
+  sockaddr bornHost;
+  memcpy(&bornHost, &sa, sizeof(sockaddr));
 
-    messageExt.setBornHost(bornHost);
-    EXPECT_EQ(messageExt.getBornHostNameString(), rocketmq::getHostName(bornHost));
-    EXPECT_EQ(messageExt.getBornHostString(), rocketmq::socketAddress2String(bornHost));
+  messageExt.setBornHost(bornHost);
+  EXPECT_EQ(messageExt.getBornHostNameString(), rocketmq::getHostName(bornHost));
+  EXPECT_EQ(messageExt.getBornHostString(), rocketmq::socketAddress2String(bornHost));
 
-    struct sockaddr_in storeSa;
-    storeSa.sin_family = AF_INET;
-    storeSa.sin_port = htons(10092);
-    storeSa.sin_addr.s_addr = inet_addr("127.0.0.2");
+  struct sockaddr_in storeSa;
+  storeSa.sin_family = AF_INET;
+  storeSa.sin_port = htons(10092);
+  storeSa.sin_addr.s_addr = inet_addr("127.0.0.2");
 
-    sockaddr storeHost;
-    memcpy(&storeHost, &storeSa, sizeof(sockaddr));
-    messageExt.setStoreHost(storeHost);
-    EXPECT_EQ(messageExt.getStoreHostString(), rocketmq::socketAddress2String(storeHost));
+  sockaddr storeHost;
+  memcpy(&storeHost, &storeSa, sizeof(sockaddr));
+  messageExt.setStoreHost(storeHost);
+  EXPECT_EQ(messageExt.getStoreHostString(), rocketmq::socketAddress2String(storeHost));
 
-    MQMessageExt twoMessageExt(2, 1024, bornHost, 2048, storeHost, "msgId");
-    EXPECT_EQ(twoMessageExt.getQueueOffset(), 0);
-    EXPECT_EQ(twoMessageExt.getCommitLogOffset(), 0);
-    EXPECT_EQ(twoMessageExt.getBornTimestamp(), 1024);
-    EXPECT_EQ(twoMessageExt.getStoreTimestamp(), 2048);
-    EXPECT_EQ(twoMessageExt.getPreparedTransactionOffset(), 0);
-    EXPECT_EQ(twoMessageExt.getQueueId(), 2);
-    EXPECT_EQ(twoMessageExt.getStoreSize(), 0);
-    EXPECT_EQ(twoMessageExt.getReconsumeTimes(), 3);
-    EXPECT_EQ(twoMessageExt.getBodyCRC(), 0);
-    EXPECT_EQ(twoMessageExt.getMsgId(), "msgId");
-    EXPECT_EQ(twoMessageExt.getOffsetMsgId(), "");
+  MQMessageExt twoMessageExt(2, 1024, bornHost, 2048, storeHost, "msgId");
+  EXPECT_EQ(twoMessageExt.getQueueOffset(), 0);
+  EXPECT_EQ(twoMessageExt.getCommitLogOffset(), 0);
+  EXPECT_EQ(twoMessageExt.getBornTimestamp(), 1024);
+  EXPECT_EQ(twoMessageExt.getStoreTimestamp(), 2048);
+  EXPECT_EQ(twoMessageExt.getPreparedTransactionOffset(), 0);
+  EXPECT_EQ(twoMessageExt.getQueueId(), 2);
+  EXPECT_EQ(twoMessageExt.getStoreSize(), 0);
+  EXPECT_EQ(twoMessageExt.getReconsumeTimes(), 3);
+  EXPECT_EQ(twoMessageExt.getBodyCRC(), 0);
+  EXPECT_EQ(twoMessageExt.getMsgId(), "msgId");
+  EXPECT_EQ(twoMessageExt.getOffsetMsgId(), "");
 
-    EXPECT_EQ(twoMessageExt.getBornHostNameString(), rocketmq::getHostName(bornHost));
-    EXPECT_EQ(twoMessageExt.getBornHostString(), rocketmq::socketAddress2String(bornHost));
+  EXPECT_EQ(twoMessageExt.getBornHostNameString(), rocketmq::getHostName(bornHost));
+  EXPECT_EQ(twoMessageExt.getBornHostString(), rocketmq::socketAddress2String(bornHost));
 
-    EXPECT_EQ(twoMessageExt.getStoreHostString(), rocketmq::socketAddress2String(storeHost));
+  EXPECT_EQ(twoMessageExt.getStoreHostString(), rocketmq::socketAddress2String(storeHost));
 
-    EXPECT_EQ(MQMessageExt::parseTopicFilterType(MessageSysFlag::MultiTagsFlag), TopicFilterType::MULTI_TAG);
+  EXPECT_EQ(MQMessageExt::parseTopicFilterType(MessageSysFlag::MultiTagsFlag), TopicFilterType::MULTI_TAG);
 
-    EXPECT_EQ(MQMessageExt::parseTopicFilterType(0), TopicFilterType::SINGLE_TAG);
+  EXPECT_EQ(MQMessageExt::parseTopicFilterType(0), TopicFilterType::SINGLE_TAG);
 }
 
-int main(int argc, char *argv[]) {
-    InitGoogleMock(&argc, argv);
+int main(int argc, char* argv[]) {
+  InitGoogleMock(&argc, argv);
 
-    testing::GTEST_FLAG(filter) = "messageExt.init";
-    int itestts = RUN_ALL_TESTS();
-    return itestts;
+  testing::GTEST_FLAG(filter) = "messageExt.init";
+  int itestts = RUN_ALL_TESTS();
+  return itestts;
 }
diff --git a/test/src/message/MQMessageIdTest.cpp b/test/src/message/MQMessageIdTest.cpp
index 191438d..d83de2f 100644
--- a/test/src/message/MQMessageIdTest.cpp
+++ b/test/src/message/MQMessageIdTest.cpp
@@ -28,29 +28,29 @@
 using rocketmq::MQMessageId;
 
 TEST(messageId, id) {
-    int host;
-    int port;
-    sockaddr addr = rocketmq::IPPort2socketAddress(inet_addr("127.0.0.1"), 10091);
-    MQMessageId id(addr, 1024);
+  int host;
+  int port;
+  sockaddr addr = rocketmq::IPPort2socketAddress(inet_addr("127.0.0.1"), 10091);
+  MQMessageId id(addr, 1024);
 
-    rocketmq::socketAddress2IPPort(id.getAddress(), host, port);
-    EXPECT_EQ(host, inet_addr("127.0.0.1"));
-    EXPECT_EQ(port, 10091);
-    EXPECT_EQ(id.getOffset(), 1024);
+  rocketmq::socketAddress2IPPort(id.getAddress(), host, port);
+  EXPECT_EQ(host, inet_addr("127.0.0.1"));
+  EXPECT_EQ(port, 10091);
+  EXPECT_EQ(id.getOffset(), 1024);
 
-    id.setAddress(rocketmq::IPPort2socketAddress(inet_addr("127.0.0.2"), 10092));
-    id.setOffset(2048);
+  id.setAddress(rocketmq::IPPort2socketAddress(inet_addr("127.0.0.2"), 10092));
+  id.setOffset(2048);
 
-    rocketmq::socketAddress2IPPort(id.getAddress(), host, port);
-    EXPECT_EQ(host, inet_addr("127.0.0.2"));
-    EXPECT_EQ(port, 10092);
-    EXPECT_EQ(id.getOffset(), 2048);
+  rocketmq::socketAddress2IPPort(id.getAddress(), host, port);
+  EXPECT_EQ(host, inet_addr("127.0.0.2"));
+  EXPECT_EQ(port, 10092);
+  EXPECT_EQ(id.getOffset(), 2048);
 }
 
-int main(int argc, char *argv[]) {
-    InitGoogleMock(&argc, argv);
+int main(int argc, char* argv[]) {
+  InitGoogleMock(&argc, argv);
 
-    testing::GTEST_FLAG(filter) = "messageId.id";
-    int itestts = RUN_ALL_TESTS();
-    return itestts;
+  testing::GTEST_FLAG(filter) = "messageId.id";
+  int itestts = RUN_ALL_TESTS();
+  return itestts;
 }
diff --git a/test/src/message/MQMessageQueueTest.cpp b/test/src/message/MQMessageQueueTest.cpp
index 4522349..c1c542d 100644
--- a/test/src/message/MQMessageQueueTest.cpp
+++ b/test/src/message/MQMessageQueueTest.cpp
@@ -26,61 +26,61 @@
 using rocketmq::MQMessageQueue;
 
 TEST(messageQueue, init) {
-    MQMessageQueue messageQueue;
-    EXPECT_EQ(messageQueue.getBrokerName(), "");
-    EXPECT_EQ(messageQueue.getTopic(), "");
-    EXPECT_EQ(messageQueue.getQueueId(), -1);
+  MQMessageQueue messageQueue;
+  EXPECT_EQ(messageQueue.getBrokerName(), "");
+  EXPECT_EQ(messageQueue.getTopic(), "");
+  EXPECT_EQ(messageQueue.getQueueId(), -1);
 
-    MQMessageQueue twoMessageQueue("testTopic", "testBroker", 1);
-    EXPECT_EQ(twoMessageQueue.getBrokerName(), "testBroker");
-    EXPECT_EQ(twoMessageQueue.getTopic(), "testTopic");
-    EXPECT_EQ(twoMessageQueue.getQueueId(), 1);
+  MQMessageQueue twoMessageQueue("testTopic", "testBroker", 1);
+  EXPECT_EQ(twoMessageQueue.getBrokerName(), "testBroker");
+  EXPECT_EQ(twoMessageQueue.getTopic(), "testTopic");
+  EXPECT_EQ(twoMessageQueue.getQueueId(), 1);
 
-    MQMessageQueue threeMessageQueue("threeTestTopic", "threeTestBroker", 2);
-    MQMessageQueue frouMessageQueue(threeMessageQueue);
-    EXPECT_EQ(frouMessageQueue.getBrokerName(), "threeTestBroker");
-    EXPECT_EQ(frouMessageQueue.getTopic(), "threeTestTopic");
-    EXPECT_EQ(frouMessageQueue.getQueueId(), 2);
+  MQMessageQueue threeMessageQueue("threeTestTopic", "threeTestBroker", 2);
+  MQMessageQueue frouMessageQueue(threeMessageQueue);
+  EXPECT_EQ(frouMessageQueue.getBrokerName(), "threeTestBroker");
+  EXPECT_EQ(frouMessageQueue.getTopic(), "threeTestTopic");
+  EXPECT_EQ(frouMessageQueue.getQueueId(), 2);
 
-    frouMessageQueue = twoMessageQueue;
-    EXPECT_EQ(frouMessageQueue.getBrokerName(), "testBroker");
-    EXPECT_EQ(frouMessageQueue.getTopic(), "testTopic");
-    EXPECT_EQ(frouMessageQueue.getQueueId(), 1);
+  frouMessageQueue = twoMessageQueue;
+  EXPECT_EQ(frouMessageQueue.getBrokerName(), "testBroker");
+  EXPECT_EQ(frouMessageQueue.getTopic(), "testTopic");
+  EXPECT_EQ(frouMessageQueue.getQueueId(), 1);
 
-    frouMessageQueue.setBrokerName("frouTestBroker");
-    frouMessageQueue.setTopic("frouTestTopic");
-    frouMessageQueue.setQueueId(4);
-    EXPECT_EQ(frouMessageQueue.getBrokerName(), "frouTestBroker");
-    EXPECT_EQ(frouMessageQueue.getTopic(), "frouTestTopic");
-    EXPECT_EQ(frouMessageQueue.getQueueId(), 4);
+  frouMessageQueue.setBrokerName("frouTestBroker");
+  frouMessageQueue.setTopic("frouTestTopic");
+  frouMessageQueue.setQueueId(4);
+  EXPECT_EQ(frouMessageQueue.getBrokerName(), "frouTestBroker");
+  EXPECT_EQ(frouMessageQueue.getTopic(), "frouTestTopic");
+  EXPECT_EQ(frouMessageQueue.getQueueId(), 4);
 }
 
 TEST(messageQueue, operators) {
-    MQMessageQueue messageQueue;
-    EXPECT_EQ(messageQueue, messageQueue);
-    EXPECT_EQ(messageQueue.compareTo(messageQueue), 0);
+  MQMessageQueue messageQueue;
+  EXPECT_EQ(messageQueue, messageQueue);
+  EXPECT_EQ(messageQueue.compareTo(messageQueue), 0);
 
-    MQMessageQueue twoMessageQueue;
-    EXPECT_EQ(messageQueue, twoMessageQueue);
-    EXPECT_EQ(messageQueue.compareTo(twoMessageQueue), 0);
+  MQMessageQueue twoMessageQueue;
+  EXPECT_EQ(messageQueue, twoMessageQueue);
+  EXPECT_EQ(messageQueue.compareTo(twoMessageQueue), 0);
 
-    twoMessageQueue.setTopic("testTopic");
-    EXPECT_FALSE(messageQueue == twoMessageQueue);
-    EXPECT_FALSE(messageQueue.compareTo(twoMessageQueue) == 0);
+  twoMessageQueue.setTopic("testTopic");
+  EXPECT_FALSE(messageQueue == twoMessageQueue);
+  EXPECT_FALSE(messageQueue.compareTo(twoMessageQueue) == 0);
 
-    twoMessageQueue.setQueueId(1);
-    EXPECT_FALSE(messageQueue == twoMessageQueue);
-    EXPECT_FALSE(messageQueue.compareTo(twoMessageQueue) == 0);
+  twoMessageQueue.setQueueId(1);
+  EXPECT_FALSE(messageQueue == twoMessageQueue);
+  EXPECT_FALSE(messageQueue.compareTo(twoMessageQueue) == 0);
 
-    twoMessageQueue.setBrokerName("testBroker");
-    EXPECT_FALSE(messageQueue == twoMessageQueue);
-    EXPECT_FALSE(messageQueue.compareTo(twoMessageQueue) == 0);
+  twoMessageQueue.setBrokerName("testBroker");
+  EXPECT_FALSE(messageQueue == twoMessageQueue);
+  EXPECT_FALSE(messageQueue.compareTo(twoMessageQueue) == 0);
 }
 
-int main(int argc, char *argv[]) {
-    InitGoogleMock(&argc, argv);
+int main(int argc, char* argv[]) {
+  InitGoogleMock(&argc, argv);
 
-    testing::GTEST_FLAG(filter) = "messageQueue.*";
-    int itestts = RUN_ALL_TESTS();
-    return itestts;
+  testing::GTEST_FLAG(filter) = "messageQueue.*";
+  int itestts = RUN_ALL_TESTS();
+  return itestts;
 }
diff --git a/test/src/message/MQMessageTest.cpp b/test/src/message/MQMessageTest.cpp
index 2a121f5..6c0165a 100644
--- a/test/src/message/MQMessageTest.cpp
+++ b/test/src/message/MQMessageTest.cpp
@@ -32,121 +32,121 @@
 using rocketmq::MQMessage;
 
 TEST(message, Init) {
-    MQMessage messageOne;
-    EXPECT_EQ(messageOne.getTopic(), "");
-    EXPECT_EQ(messageOne.getBody(), "");
-    EXPECT_EQ(messageOne.getTags(), "");
-    EXPECT_EQ(messageOne.getFlag(), 0);
+  MQMessage messageOne;
+  EXPECT_EQ(messageOne.getTopic(), "");
+  EXPECT_EQ(messageOne.getBody(), "");
+  EXPECT_EQ(messageOne.getTags(), "");
+  EXPECT_EQ(messageOne.getFlag(), 0);
 
-    MQMessage messageTwo("test", "testBody");
-    EXPECT_EQ(messageTwo.getTopic(), "test");
-    EXPECT_EQ(messageTwo.getBody(), "testBody");
-    EXPECT_EQ(messageTwo.getTags(), "");
-    EXPECT_EQ(messageTwo.getFlag(), 0);
+  MQMessage messageTwo("test", "testBody");
+  EXPECT_EQ(messageTwo.getTopic(), "test");
+  EXPECT_EQ(messageTwo.getBody(), "testBody");
+  EXPECT_EQ(messageTwo.getTags(), "");
+  EXPECT_EQ(messageTwo.getFlag(), 0);
 
-    MQMessage messageThree("test", "tagTest", "testBody");
-    EXPECT_EQ(messageThree.getTopic(), "test");
-    EXPECT_EQ(messageThree.getBody(), "testBody");
-    EXPECT_EQ(messageThree.getTags(), "tagTest");
-    EXPECT_EQ(messageThree.getFlag(), 0);
+  MQMessage messageThree("test", "tagTest", "testBody");
+  EXPECT_EQ(messageThree.getTopic(), "test");
+  EXPECT_EQ(messageThree.getBody(), "testBody");
+  EXPECT_EQ(messageThree.getTags(), "tagTest");
+  EXPECT_EQ(messageThree.getFlag(), 0);
 
-    MQMessage messageFour("test", "tagTest", "testKey", "testBody");
-    EXPECT_EQ(messageFour.getTopic(), "test");
-    EXPECT_EQ(messageFour.getBody(), "testBody");
-    EXPECT_EQ(messageFour.getTags(), "tagTest");
-    EXPECT_EQ(messageFour.getKeys(), "testKey");
-    EXPECT_EQ(messageFour.getFlag(), 0);
+  MQMessage messageFour("test", "tagTest", "testKey", "testBody");
+  EXPECT_EQ(messageFour.getTopic(), "test");
+  EXPECT_EQ(messageFour.getBody(), "testBody");
+  EXPECT_EQ(messageFour.getTags(), "tagTest");
+  EXPECT_EQ(messageFour.getKeys(), "testKey");
+  EXPECT_EQ(messageFour.getFlag(), 0);
 
-    MQMessage messageFive("test", "tagTest", "testKey", 1, "testBody", 2);
-    EXPECT_EQ(messageFive.getTopic(), "test");
-    EXPECT_EQ(messageFive.getBody(), "testBody");
-    EXPECT_EQ(messageFive.getTags(), "tagTest");
-    EXPECT_EQ(messageFive.getKeys(), "testKey");
-    EXPECT_EQ(messageFive.getFlag(), 1);
+  MQMessage messageFive("test", "tagTest", "testKey", 1, "testBody", 2);
+  EXPECT_EQ(messageFive.getTopic(), "test");
+  EXPECT_EQ(messageFive.getBody(), "testBody");
+  EXPECT_EQ(messageFive.getTags(), "tagTest");
+  EXPECT_EQ(messageFive.getKeys(), "testKey");
+  EXPECT_EQ(messageFive.getFlag(), 1);
 
-    MQMessage messageSix(messageFive);
-    EXPECT_EQ(messageSix.getTopic(), "test");
-    EXPECT_EQ(messageSix.getBody(), "testBody");
-    EXPECT_EQ(messageSix.getTags(), "tagTest");
-    EXPECT_EQ(messageSix.getKeys(), "testKey");
-    EXPECT_EQ(messageSix.getFlag(), 1);
+  MQMessage messageSix(messageFive);
+  EXPECT_EQ(messageSix.getTopic(), "test");
+  EXPECT_EQ(messageSix.getBody(), "testBody");
+  EXPECT_EQ(messageSix.getTags(), "tagTest");
+  EXPECT_EQ(messageSix.getKeys(), "testKey");
+  EXPECT_EQ(messageSix.getFlag(), 1);
 }
 
 TEST(message, info) {
-    MQMessage message;
+  MQMessage message;
 
-    EXPECT_EQ(message.getTopic(), "");
-    message.setTopic("testTopic");
-    EXPECT_EQ(message.getTopic(), "testTopic");
-    char *topic = "testTopic";
-    message.setTopic(topic, 5);
-    EXPECT_EQ(message.getTopic(), "testT");
+  EXPECT_EQ(message.getTopic(), "");
+  message.setTopic("testTopic");
+  EXPECT_EQ(message.getTopic(), "testTopic");
+  char* topic = "testTopic";
+  message.setTopic(topic, 5);
+  EXPECT_EQ(message.getTopic(), "testT");
 
-    EXPECT_EQ(message.getBody(), "");
-    message.setBody("testBody");
-    EXPECT_EQ(message.getBody(), "testBody");
+  EXPECT_EQ(message.getBody(), "");
+  message.setBody("testBody");
+  EXPECT_EQ(message.getBody(), "testBody");
 
-    char *body = "testBody";
-    message.setBody(body, 5);
-    EXPECT_EQ(message.getBody(), "testB");
+  char* body = "testBody";
+  message.setBody(body, 5);
+  EXPECT_EQ(message.getBody(), "testB");
 
-    string tags(message.getTags());
-    EXPECT_EQ(tags, "");
-    EXPECT_EQ(message.getFlag(), 0);
-    message.setFlag(2);
-    EXPECT_EQ(message.getFlag(), 2);
+  string tags(message.getTags());
+  EXPECT_EQ(tags, "");
+  EXPECT_EQ(message.getFlag(), 0);
+  message.setFlag(2);
+  EXPECT_EQ(message.getFlag(), 2);
 
-    EXPECT_EQ(message.isWaitStoreMsgOK(), true);
-    message.setWaitStoreMsgOK(false);
-    EXPECT_EQ(message.isWaitStoreMsgOK(), false);
-    message.setWaitStoreMsgOK(true);
-    EXPECT_EQ(message.isWaitStoreMsgOK(), true);
+  EXPECT_EQ(message.isWaitStoreMsgOK(), true);
+  message.setWaitStoreMsgOK(false);
+  EXPECT_EQ(message.isWaitStoreMsgOK(), false);
+  message.setWaitStoreMsgOK(true);
+  EXPECT_EQ(message.isWaitStoreMsgOK(), true);
 
-    string keys(message.getTags());
-    EXPECT_EQ(keys, "");
-    message.setKeys("testKeys");
-    EXPECT_EQ(message.getKeys(), "testKeys");
+  string keys(message.getTags());
+  EXPECT_EQ(keys, "");
+  message.setKeys("testKeys");
+  EXPECT_EQ(message.getKeys(), "testKeys");
 
-    EXPECT_EQ(message.getDelayTimeLevel(), 0);
-    message.setDelayTimeLevel(1);
-    EXPECT_EQ(message.getDelayTimeLevel(), 1);
+  EXPECT_EQ(message.getDelayTimeLevel(), 0);
+  message.setDelayTimeLevel(1);
+  EXPECT_EQ(message.getDelayTimeLevel(), 1);
 
-    message.setSysFlag(1);
-    EXPECT_EQ(message.getSysFlag(), 1);
+  message.setSysFlag(1);
+  EXPECT_EQ(message.getSysFlag(), 1);
 }
 
 TEST(message, properties) {
-    MQMessage message;
-    EXPECT_EQ(message.getProperties().size(), 1);
-    EXPECT_STREQ(message.getProperty(MQMessage::PROPERTY_TRANSACTION_PREPARED).c_str(), "");
+  MQMessage message;
+  EXPECT_EQ(message.getProperties().size(), 1);
+  EXPECT_STREQ(message.getProperty(MQMessage::PROPERTY_TRANSACTION_PREPARED).c_str(), "");
 
-    message.setProperty(MQMessage::PROPERTY_TRANSACTION_PREPARED, "true");
-    EXPECT_EQ(message.getProperties().size(), 2);
-    EXPECT_EQ(message.getSysFlag(), 4);
-    EXPECT_EQ(message.getProperty(MQMessage::PROPERTY_TRANSACTION_PREPARED), "true");
+  message.setProperty(MQMessage::PROPERTY_TRANSACTION_PREPARED, "true");
+  EXPECT_EQ(message.getProperties().size(), 2);
+  EXPECT_EQ(message.getSysFlag(), 4);
+  EXPECT_EQ(message.getProperty(MQMessage::PROPERTY_TRANSACTION_PREPARED), "true");
 
-    message.setProperty(MQMessage::PROPERTY_TRANSACTION_PREPARED, "false");
-    EXPECT_EQ(message.getProperties().size(), 2);
-    EXPECT_EQ(message.getSysFlag(), 0);
-    EXPECT_EQ(message.getProperty(MQMessage::PROPERTY_TRANSACTION_PREPARED), "false");
+  message.setProperty(MQMessage::PROPERTY_TRANSACTION_PREPARED, "false");
+  EXPECT_EQ(message.getProperties().size(), 2);
+  EXPECT_EQ(message.getSysFlag(), 0);
+  EXPECT_EQ(message.getProperty(MQMessage::PROPERTY_TRANSACTION_PREPARED), "false");
 
-    map<string, string> newProperties;
+  map<string, string> newProperties;
 
-    newProperties[MQMessage::PROPERTY_TRANSACTION_PREPARED] = "true";
-    message.setProperties(newProperties);
-    EXPECT_EQ(message.getSysFlag(), 4);
-    EXPECT_EQ(message.getProperty(MQMessage::PROPERTY_TRANSACTION_PREPARED), "true");
+  newProperties[MQMessage::PROPERTY_TRANSACTION_PREPARED] = "true";
+  message.setProperties(newProperties);
+  EXPECT_EQ(message.getSysFlag(), 4);
+  EXPECT_EQ(message.getProperty(MQMessage::PROPERTY_TRANSACTION_PREPARED), "true");
 
-    newProperties[MQMessage::PROPERTY_TRANSACTION_PREPARED] = "false";
-    message.setProperties(newProperties);
-    EXPECT_EQ(message.getSysFlag(), 0);
-    EXPECT_EQ(message.getProperty(MQMessage::PROPERTY_TRANSACTION_PREPARED), "false");
+  newProperties[MQMessage::PROPERTY_TRANSACTION_PREPARED] = "false";
+  message.setProperties(newProperties);
+  EXPECT_EQ(message.getSysFlag(), 0);
+  EXPECT_EQ(message.getProperty(MQMessage::PROPERTY_TRANSACTION_PREPARED), "false");
 }
 
-int main(int argc, char *argv[]) {
-    InitGoogleMock(&argc, argv);
+int main(int argc, char* argv[]) {
+  InitGoogleMock(&argc, argv);
 
-    testing::GTEST_FLAG(filter) = "message.info";
-    int itestts = RUN_ALL_TESTS();
-    return itestts;
+  testing::GTEST_FLAG(filter) = "message.info";
+  int itestts = RUN_ALL_TESTS();
+  return itestts;
 }
diff --git a/test/src/protocol/CommandHeaderTest.cpp b/test/src/protocol/CommandHeaderTest.cpp
index 7439c45..ee19e0e 100644
--- a/test/src/protocol/CommandHeaderTest.cpp
+++ b/test/src/protocol/CommandHeaderTest.cpp
@@ -72,124 +72,123 @@
 TEST(commandHeader, ConsumerSendMsgBackRequestHeader) {}
 
 TEST(commandHeader, GetConsumerListByGroupResponseBody) {
-    Value value;
-    value[0] = "body";
-    value[1] = 1;
+  Value value;
+  value[0] = "body";
+  value[1] = 1;
 
-    Value root;
-    root["consumerIdList"] = value;
+  Value root;
+  root["consumerIdList"] = value;
 
-    FastWriter writer;
-    string data = writer.write(root);
+  FastWriter writer;
+  string data = writer.write(root);
 
-    MemoryBlock *mem = new MemoryBlock(data.c_str(), data.size());
-    vector<string> cids;
-    GetConsumerListByGroupResponseBody::Decode(mem, cids);
+  MemoryBlock* mem = new MemoryBlock(data.c_str(), data.size());
+  vector<string> cids;
+  GetConsumerListByGroupResponseBody::Decode(mem, cids);
 
-    EXPECT_EQ(cids.size(), 1);
+  EXPECT_EQ(cids.size(), 1);
 
-    delete mem;
+  delete mem;
 }
 
 TEST(commandHeader, ResetOffsetRequestHeader) {
-    ResetOffsetRequestHeader header;
+  ResetOffsetRequestHeader header;
 
-    header.setTopic("testTopic");
-    EXPECT_EQ(header.getTopic(), "testTopic");
+  header.setTopic("testTopic");
+  EXPECT_EQ(header.getTopic(), "testTopic");
 
-    header.setGroup("testGroup");
-    EXPECT_EQ(header.getGroup(), "testGroup");
+  header.setGroup("testGroup");
+  EXPECT_EQ(header.getGroup(), "testGroup");
 
-    header.setTimeStamp(123);
-    EXPECT_EQ(header.getTimeStamp(), 123);
+  header.setTimeStamp(123);
+  EXPECT_EQ(header.getTimeStamp(), 123);
 
-    header.setForceFlag(true);
-    EXPECT_TRUE(header.getForceFlag());
+  header.setForceFlag(true);
+  EXPECT_TRUE(header.getForceFlag());
 
-    Value value;
-    value["isForce"] = "false";
-    shared_ptr<ResetOffsetRequestHeader> headersh(
-        static_cast<ResetOffsetRequestHeader *>(ResetOffsetRequestHeader::Decode(value)));
-    EXPECT_EQ(headersh->getTopic(), "");
-    EXPECT_EQ(headersh->getGroup(), "");
-    // EXPECT_EQ(headersh->getTimeStamp(), 0);
-    EXPECT_FALSE(headersh->getForceFlag());
-    value["topic"] = "testTopic";
-    headersh.reset(static_cast<ResetOffsetRequestHeader *>(ResetOffsetRequestHeader::Decode(value)));
-    EXPECT_EQ(headersh->getTopic(), "testTopic");
-    EXPECT_EQ(headersh->getGroup(), "");
-    // EXPECT_EQ(headersh->getTimeStamp(), 0);
-    EXPECT_FALSE(headersh->getForceFlag());
+  Value value;
+  value["isForce"] = "false";
+  shared_ptr<ResetOffsetRequestHeader> headersh(
+      static_cast<ResetOffsetRequestHeader*>(ResetOffsetRequestHeader::Decode(value)));
+  EXPECT_EQ(headersh->getTopic(), "");
+  EXPECT_EQ(headersh->getGroup(), "");
+  // EXPECT_EQ(headersh->getTimeStamp(), 0);
+  EXPECT_FALSE(headersh->getForceFlag());
+  value["topic"] = "testTopic";
+  headersh.reset(static_cast<ResetOffsetRequestHeader*>(ResetOffsetRequestHeader::Decode(value)));
+  EXPECT_EQ(headersh->getTopic(), "testTopic");
+  EXPECT_EQ(headersh->getGroup(), "");
+  // EXPECT_EQ(headersh->getTimeStamp(), 0);
+  EXPECT_FALSE(headersh->getForceFlag());
 
-    value["topic"] = "testTopic";
-    value["group"] = "testGroup";
-    headersh.reset(static_cast<ResetOffsetRequestHeader *>(ResetOffsetRequestHeader::Decode(value)));
-    EXPECT_EQ(headersh->getTopic(), "testTopic");
-    EXPECT_EQ(headersh->getGroup(), "testGroup");
-    // EXPECT_EQ(headersh->getTimeStamp(), 0);
-    EXPECT_FALSE(headersh->getForceFlag());
+  value["topic"] = "testTopic";
+  value["group"] = "testGroup";
+  headersh.reset(static_cast<ResetOffsetRequestHeader*>(ResetOffsetRequestHeader::Decode(value)));
+  EXPECT_EQ(headersh->getTopic(), "testTopic");
+  EXPECT_EQ(headersh->getGroup(), "testGroup");
+  // EXPECT_EQ(headersh->getTimeStamp(), 0);
+  EXPECT_FALSE(headersh->getForceFlag());
 
-    value["topic"] = "testTopic";
-    value["group"] = "testGroup";
-    value["timestamp"] = "123";
-    headersh.reset(static_cast<ResetOffsetRequestHeader *>(ResetOffsetRequestHeader::Decode(value)));
-    EXPECT_EQ(headersh->getTopic(), "testTopic");
-    EXPECT_EQ(headersh->getGroup(), "testGroup");
-    EXPECT_EQ(headersh->getTimeStamp(), 123);
-    EXPECT_FALSE(headersh->getForceFlag());
+  value["topic"] = "testTopic";
+  value["group"] = "testGroup";
+  value["timestamp"] = "123";
+  headersh.reset(static_cast<ResetOffsetRequestHeader*>(ResetOffsetRequestHeader::Decode(value)));
+  EXPECT_EQ(headersh->getTopic(), "testTopic");
+  EXPECT_EQ(headersh->getGroup(), "testGroup");
+  EXPECT_EQ(headersh->getTimeStamp(), 123);
+  EXPECT_FALSE(headersh->getForceFlag());
 
-    value["topic"] = "testTopic";
-    value["group"] = "testGroup";
-    value["timestamp"] = "123";
-    value["isForce"] = "1";
-    headersh.reset(static_cast<ResetOffsetRequestHeader *>(ResetOffsetRequestHeader::Decode(value)));
-    EXPECT_EQ(headersh->getTopic(), "testTopic");
-    EXPECT_EQ(headersh->getGroup(), "testGroup");
-    EXPECT_EQ(headersh->getTimeStamp(), 123);
-    EXPECT_TRUE(headersh->getForceFlag());
+  value["topic"] = "testTopic";
+  value["group"] = "testGroup";
+  value["timestamp"] = "123";
+  value["isForce"] = "1";
+  headersh.reset(static_cast<ResetOffsetRequestHeader*>(ResetOffsetRequestHeader::Decode(value)));
+  EXPECT_EQ(headersh->getTopic(), "testTopic");
+  EXPECT_EQ(headersh->getGroup(), "testGroup");
+  EXPECT_EQ(headersh->getTimeStamp(), 123);
+  EXPECT_TRUE(headersh->getForceFlag());
 }
 
 TEST(commandHeader, GetConsumerRunningInfoRequestHeader) {
-    GetConsumerRunningInfoRequestHeader header;
-    header.setClientId("testClientId");
-    header.setConsumerGroup("testConsumer");
-    header.setJstackEnable(true);
+  GetConsumerRunningInfoRequestHeader header;
+  header.setClientId("testClientId");
+  header.setConsumerGroup("testConsumer");
+  header.setJstackEnable(true);
 
-    map<string, string> requestMap;
-    header.SetDeclaredFieldOfCommandHeader(requestMap);
-    EXPECT_EQ(requestMap["clientId"], "testClientId");
-    EXPECT_EQ(requestMap["consumerGroup"], "testConsumer");
-    EXPECT_EQ(requestMap["jstackEnable"], "1");
+  map<string, string> requestMap;
+  header.SetDeclaredFieldOfCommandHeader(requestMap);
+  EXPECT_EQ(requestMap["clientId"], "testClientId");
+  EXPECT_EQ(requestMap["consumerGroup"], "testConsumer");
+  EXPECT_EQ(requestMap["jstackEnable"], "1");
 
-    Value outData;
-    header.Encode(outData);
-    EXPECT_EQ(outData["clientId"], "testClientId");
-    EXPECT_EQ(outData["consumerGroup"], "testConsumer");
-    EXPECT_TRUE(outData["jstackEnable"].asBool());
+  Value outData;
+  header.Encode(outData);
+  EXPECT_EQ(outData["clientId"], "testClientId");
+  EXPECT_EQ(outData["consumerGroup"], "testConsumer");
+  EXPECT_TRUE(outData["jstackEnable"].asBool());
 
-    shared_ptr<GetConsumerRunningInfoRequestHeader> decodeHeader(
-        static_cast<GetConsumerRunningInfoRequestHeader *>(GetConsumerRunningInfoRequestHeader::Decode(outData)));
-    EXPECT_EQ(decodeHeader->getClientId(), "testClientId");
-    EXPECT_EQ(decodeHeader->getConsumerGroup(), "testConsumer");
-    EXPECT_TRUE(decodeHeader->isJstackEnable());
+  shared_ptr<GetConsumerRunningInfoRequestHeader> decodeHeader(
+      static_cast<GetConsumerRunningInfoRequestHeader*>(GetConsumerRunningInfoRequestHeader::Decode(outData)));
+  EXPECT_EQ(decodeHeader->getClientId(), "testClientId");
+  EXPECT_EQ(decodeHeader->getConsumerGroup(), "testConsumer");
+  EXPECT_TRUE(decodeHeader->isJstackEnable());
 }
 
 TEST(commandHeader, NotifyConsumerIdsChangedRequestHeader) {
-    Json::Value ext;
-    shared_ptr<NotifyConsumerIdsChangedRequestHeader> header(
-        static_cast<NotifyConsumerIdsChangedRequestHeader *>(NotifyConsumerIdsChangedRequestHeader::Decode(ext)));
-    EXPECT_EQ(header->getGroup(), "");
+  Json::Value ext;
+  shared_ptr<NotifyConsumerIdsChangedRequestHeader> header(
+      static_cast<NotifyConsumerIdsChangedRequestHeader*>(NotifyConsumerIdsChangedRequestHeader::Decode(ext)));
+  EXPECT_EQ(header->getGroup(), "");
 
-    ext["consumerGroup"] = "testGroup";
-    header.reset(
-        static_cast<NotifyConsumerIdsChangedRequestHeader *>(NotifyConsumerIdsChangedRequestHeader::Decode(ext)));
-    EXPECT_EQ(header->getGroup(), "testGroup");
+  ext["consumerGroup"] = "testGroup";
+  header.reset(static_cast<NotifyConsumerIdsChangedRequestHeader*>(NotifyConsumerIdsChangedRequestHeader::Decode(ext)));
+  EXPECT_EQ(header->getGroup(), "testGroup");
 }
 
-int main(int argc, char *argv[]) {
-    InitGoogleMock(&argc, argv);
-    testing::GTEST_FLAG(throw_on_failure) = true;
-    testing::GTEST_FLAG(filter) = "commandHeader.*";
-    int itestts = RUN_ALL_TESTS();
-    return itestts;
+int main(int argc, char* argv[]) {
+  InitGoogleMock(&argc, argv);
+  testing::GTEST_FLAG(throw_on_failure) = true;
+  testing::GTEST_FLAG(filter) = "commandHeader.*";
+  int itestts = RUN_ALL_TESTS();
+  return itestts;
 }
diff --git a/test/src/protocol/ConsumerRunningInfoTest.cpp b/test/src/protocol/ConsumerRunningInfoTest.cpp
index ef46eb1..fbea4b2 100644
--- a/test/src/protocol/ConsumerRunningInfoTest.cpp
+++ b/test/src/protocol/ConsumerRunningInfoTest.cpp
@@ -45,80 +45,80 @@
 using rocketmq::SubscriptionData;
 
 TEST(consumerRunningInfo, init) {
-    ConsumerRunningInfo consumerRunningInfo;
-    consumerRunningInfo.setJstack("jstack");
-    EXPECT_EQ(consumerRunningInfo.getJstack(), "jstack");
+  ConsumerRunningInfo consumerRunningInfo;
+  consumerRunningInfo.setJstack("jstack");
+  EXPECT_EQ(consumerRunningInfo.getJstack(), "jstack");
 
-    EXPECT_TRUE(consumerRunningInfo.getProperties().empty());
+  EXPECT_TRUE(consumerRunningInfo.getProperties().empty());
 
-    consumerRunningInfo.setProperty("testKey", "testValue");
-    map<string, string> properties = consumerRunningInfo.getProperties();
-    EXPECT_EQ(properties["testKey"], "testValue");
+  consumerRunningInfo.setProperty("testKey", "testValue");
+  map<string, string> properties = consumerRunningInfo.getProperties();
+  EXPECT_EQ(properties["testKey"], "testValue");
 
-    consumerRunningInfo.setProperties(map<string, string>());
-    EXPECT_TRUE(consumerRunningInfo.getProperties().empty());
+  consumerRunningInfo.setProperties(map<string, string>());
+  EXPECT_TRUE(consumerRunningInfo.getProperties().empty());
 
-    EXPECT_TRUE(consumerRunningInfo.getSubscriptionSet().empty());
+  EXPECT_TRUE(consumerRunningInfo.getSubscriptionSet().empty());
 
-    vector<SubscriptionData> subscriptionSet;
-    subscriptionSet.push_back(SubscriptionData());
+  vector<SubscriptionData> subscriptionSet;
+  subscriptionSet.push_back(SubscriptionData());
 
-    consumerRunningInfo.setSubscriptionSet(subscriptionSet);
-    EXPECT_EQ(consumerRunningInfo.getSubscriptionSet().size(), 1);
+  consumerRunningInfo.setSubscriptionSet(subscriptionSet);
+  EXPECT_EQ(consumerRunningInfo.getSubscriptionSet().size(), 1);
 
-    EXPECT_TRUE(consumerRunningInfo.getMqTable().empty());
+  EXPECT_TRUE(consumerRunningInfo.getMqTable().empty());
 
-    MessageQueue messageQueue("testTopic", "testBroker", 3);
-    ProcessQueueInfo processQueueInfo;
-    processQueueInfo.commitOffset = 1024;
-    consumerRunningInfo.setMqTable(messageQueue, processQueueInfo);
-    map<MessageQueue, ProcessQueueInfo> mqTable = consumerRunningInfo.getMqTable();
-    EXPECT_EQ(mqTable[messageQueue].commitOffset, processQueueInfo.commitOffset);
+  MessageQueue messageQueue("testTopic", "testBroker", 3);
+  ProcessQueueInfo processQueueInfo;
+  processQueueInfo.commitOffset = 1024;
+  consumerRunningInfo.setMqTable(messageQueue, processQueueInfo);
+  map<MessageQueue, ProcessQueueInfo> mqTable = consumerRunningInfo.getMqTable();
+  EXPECT_EQ(mqTable[messageQueue].commitOffset, processQueueInfo.commitOffset);
 
-    // encode start
-    consumerRunningInfo.setProperty(ConsumerRunningInfo::PROP_NAMESERVER_ADDR, "127.0.0.1:9876");
-    consumerRunningInfo.setProperty(ConsumerRunningInfo::PROP_THREADPOOL_CORE_SIZE, "core_size");
-    consumerRunningInfo.setProperty(ConsumerRunningInfo::PROP_CONSUME_ORDERLY, "consume_orderly");
-    consumerRunningInfo.setProperty(ConsumerRunningInfo::PROP_CONSUME_TYPE, "consume_type");
-    consumerRunningInfo.setProperty(ConsumerRunningInfo::PROP_CLIENT_VERSION, "client_version");
-    consumerRunningInfo.setProperty(ConsumerRunningInfo::PROP_CONSUMER_START_TIMESTAMP, "127");
-    // TODO
-    /* string outstr = consumerRunningInfo.encode();
-     std::cout<< outstr;
-     Value root;
-     Reader reader;
-     reader.parse(outstr.c_str(), root);
+  // encode start
+  consumerRunningInfo.setProperty(ConsumerRunningInfo::PROP_NAMESERVER_ADDR, "127.0.0.1:9876");
+  consumerRunningInfo.setProperty(ConsumerRunningInfo::PROP_THREADPOOL_CORE_SIZE, "core_size");
+  consumerRunningInfo.setProperty(ConsumerRunningInfo::PROP_CONSUME_ORDERLY, "consume_orderly");
+  consumerRunningInfo.setProperty(ConsumerRunningInfo::PROP_CONSUME_TYPE, "consume_type");
+  consumerRunningInfo.setProperty(ConsumerRunningInfo::PROP_CLIENT_VERSION, "client_version");
+  consumerRunningInfo.setProperty(ConsumerRunningInfo::PROP_CONSUMER_START_TIMESTAMP, "127");
+  // TODO
+  /* string outstr = consumerRunningInfo.encode();
+   std::cout<< outstr;
+   Value root;
+   Reader reader;
+   reader.parse(outstr.c_str(), root);
 
-     EXPECT_EQ(root["jstack"].asString() , "jstack");
+   EXPECT_EQ(root["jstack"].asString() , "jstack");
 
-     Json::Value outData = root["properties"];
-     EXPECT_EQ(outData[ConsumerRunningInfo::PROP_NAMESERVER_ADDR].asString(),"127.0.0.1:9876");
-     EXPECT_EQ(
-             outData[ConsumerRunningInfo::PROP_THREADPOOL_CORE_SIZE].asString(),
-             "core_size");
-     EXPECT_EQ(outData[ConsumerRunningInfo::PROP_CONSUME_ORDERLY].asString(),
-               "consume_orderly");
-     EXPECT_EQ(outData[ConsumerRunningInfo::PROP_CONSUME_TYPE].asString(),
-               "consume_type");
-     EXPECT_EQ(outData[ConsumerRunningInfo::PROP_CLIENT_VERSION].asString(),
-               "client_version");
-     EXPECT_EQ(
-             outData[ConsumerRunningInfo::PROP_CONSUMER_START_TIMESTAMP].asString(),
-             "127");
+   Json::Value outData = root["properties"];
+   EXPECT_EQ(outData[ConsumerRunningInfo::PROP_NAMESERVER_ADDR].asString(),"127.0.0.1:9876");
+   EXPECT_EQ(
+           outData[ConsumerRunningInfo::PROP_THREADPOOL_CORE_SIZE].asString(),
+           "core_size");
+   EXPECT_EQ(outData[ConsumerRunningInfo::PROP_CONSUME_ORDERLY].asString(),
+             "consume_orderly");
+   EXPECT_EQ(outData[ConsumerRunningInfo::PROP_CONSUME_TYPE].asString(),
+             "consume_type");
+   EXPECT_EQ(outData[ConsumerRunningInfo::PROP_CLIENT_VERSION].asString(),
+             "client_version");
+   EXPECT_EQ(
+           outData[ConsumerRunningInfo::PROP_CONSUMER_START_TIMESTAMP].asString(),
+           "127");
 
-     Json::Value subscriptionSetJson = root["subscriptionSet"];
-     EXPECT_EQ(subscriptionSetJson[0], subscriptionSet[0].toJson());
+   Json::Value subscriptionSetJson = root["subscriptionSet"];
+   EXPECT_EQ(subscriptionSetJson[0], subscriptionSet[0].toJson());
 
-     Json::Value mqTableJson = root["mqTable"];
-     EXPECT_EQ(mqTableJson[messageQueue.toJson().toStyledString()].asString(),
-               processQueueInfo.toJson().toStyledString());
- */
+   Json::Value mqTableJson = root["mqTable"];
+   EXPECT_EQ(mqTableJson[messageQueue.toJson().toStyledString()].asString(),
+             processQueueInfo.toJson().toStyledString());
+*/
 }
 
-int main(int argc, char *argv[]) {
-    InitGoogleMock(&argc, argv);
-    testing::GTEST_FLAG(throw_on_failure) = true;
-    testing::GTEST_FLAG(filter) = "consumerRunningInfo.*";
-    int itestts = RUN_ALL_TESTS();
-    return itestts;
+int main(int argc, char* argv[]) {
+  InitGoogleMock(&argc, argv);
+  testing::GTEST_FLAG(throw_on_failure) = true;
+  testing::GTEST_FLAG(filter) = "consumerRunningInfo.*";
+  int itestts = RUN_ALL_TESTS();
+  return itestts;
 }
diff --git a/test/src/protocol/HeartbeatDataTest.cpp b/test/src/protocol/HeartbeatDataTest.cpp
index 21feae1..c153ed5 100644
--- a/test/src/protocol/HeartbeatDataTest.cpp
+++ b/test/src/protocol/HeartbeatDataTest.cpp
@@ -39,77 +39,77 @@
 using rocketmq::SubscriptionData;
 
 TEST(heartbeatData, ProducerData) {
-    ProducerData producerData;
-    producerData.groupName = "testGroup";
+  ProducerData producerData;
+  producerData.groupName = "testGroup";
 
-    Json::Value outJson = producerData.toJson();
-    EXPECT_EQ(outJson["groupName"], "testGroup");
+  Json::Value outJson = producerData.toJson();
+  EXPECT_EQ(outJson["groupName"], "testGroup");
 }
 
 TEST(heartbeatData, ConsumerData) {
-    ConsumerData consumerData;
-    consumerData.groupName = "testGroup";
-    consumerData.consumeType = ConsumeType::CONSUME_ACTIVELY;
-    consumerData.messageModel = MessageModel::BROADCASTING;
-    consumerData.consumeFromWhere = ConsumeFromWhere::CONSUME_FROM_TIMESTAMP;
+  ConsumerData consumerData;
+  consumerData.groupName = "testGroup";
+  consumerData.consumeType = ConsumeType::CONSUME_ACTIVELY;
+  consumerData.messageModel = MessageModel::BROADCASTING;
+  consumerData.consumeFromWhere = ConsumeFromWhere::CONSUME_FROM_TIMESTAMP;
 
-    vector<SubscriptionData> subs;
-    subs.push_back(SubscriptionData("testTopic", "sub"));
+  vector<SubscriptionData> subs;
+  subs.push_back(SubscriptionData("testTopic", "sub"));
 
-    consumerData.subscriptionDataSet = subs;
+  consumerData.subscriptionDataSet = subs;
 
-    Json::Value outJson = consumerData.toJson();
+  Json::Value outJson = consumerData.toJson();
 
-    EXPECT_EQ(outJson["groupName"], "testGroup");
+  EXPECT_EQ(outJson["groupName"], "testGroup");
 
-    EXPECT_EQ(outJson["consumeType"].asInt(), ConsumeType::CONSUME_ACTIVELY);
-    EXPECT_EQ(outJson["messageModel"].asInt(), MessageModel::BROADCASTING);
-    EXPECT_EQ(outJson["consumeFromWhere"].asInt(), ConsumeFromWhere::CONSUME_FROM_TIMESTAMP);
+  EXPECT_EQ(outJson["consumeType"].asInt(), ConsumeType::CONSUME_ACTIVELY);
+  EXPECT_EQ(outJson["messageModel"].asInt(), MessageModel::BROADCASTING);
+  EXPECT_EQ(outJson["consumeFromWhere"].asInt(), ConsumeFromWhere::CONSUME_FROM_TIMESTAMP);
 
-    Json::Value subsValue = outJson["subscriptionDataSet"];
-    EXPECT_EQ(subsValue[0]["topic"], "testTopic");
-    EXPECT_EQ(subsValue[0]["subString"], "sub");
+  Json::Value subsValue = outJson["subscriptionDataSet"];
+  EXPECT_EQ(subsValue[0]["topic"], "testTopic");
+  EXPECT_EQ(subsValue[0]["subString"], "sub");
 }
 
 TEST(heartbeatData, HeartbeatData) {
-    HeartbeatData heartbeatData;
-    heartbeatData.setClientID("testClientId");
+  HeartbeatData heartbeatData;
+  heartbeatData.setClientID("testClientId");
 
-    ProducerData producerData;
-    producerData.groupName = "testGroup";
+  ProducerData producerData;
+  producerData.groupName = "testGroup";
 
-    EXPECT_TRUE(heartbeatData.isProducerDataSetEmpty());
-    heartbeatData.insertDataToProducerDataSet(producerData);
-    EXPECT_FALSE(heartbeatData.isProducerDataSetEmpty());
+  EXPECT_TRUE(heartbeatData.isProducerDataSetEmpty());
+  heartbeatData.insertDataToProducerDataSet(producerData);
+  EXPECT_FALSE(heartbeatData.isProducerDataSetEmpty());
 
-    ConsumerData consumerData;
-    consumerData.groupName = "testGroup";
-    consumerData.consumeType = ConsumeType::CONSUME_ACTIVELY;
-    consumerData.messageModel = MessageModel::BROADCASTING;
-    consumerData.consumeFromWhere = ConsumeFromWhere::CONSUME_FROM_TIMESTAMP;
+  ConsumerData consumerData;
+  consumerData.groupName = "testGroup";
+  consumerData.consumeType = ConsumeType::CONSUME_ACTIVELY;
+  consumerData.messageModel = MessageModel::BROADCASTING;
+  consumerData.consumeFromWhere = ConsumeFromWhere::CONSUME_FROM_TIMESTAMP;
 
-    vector<SubscriptionData> subs;
-    subs.push_back(SubscriptionData("testTopic", "sub"));
+  vector<SubscriptionData> subs;
+  subs.push_back(SubscriptionData("testTopic", "sub"));
 
-    consumerData.subscriptionDataSet = subs;
-    EXPECT_TRUE(heartbeatData.isConsumerDataSetEmpty());
-    heartbeatData.insertDataToConsumerDataSet(consumerData);
-    EXPECT_FALSE(heartbeatData.isConsumerDataSetEmpty());
+  consumerData.subscriptionDataSet = subs;
+  EXPECT_TRUE(heartbeatData.isConsumerDataSetEmpty());
+  heartbeatData.insertDataToConsumerDataSet(consumerData);
+  EXPECT_FALSE(heartbeatData.isConsumerDataSetEmpty());
 
-    string outData;
-    heartbeatData.Encode(outData);
+  string outData;
+  heartbeatData.Encode(outData);
 
-    Json::Value root;
-    Json::Reader reader;
-    reader.parse(outData, root);
+  Json::Value root;
+  Json::Reader reader;
+  reader.parse(outData, root);
 
-    EXPECT_EQ(root["clientID"], "testClientId");
+  EXPECT_EQ(root["clientID"], "testClientId");
 }
 
-int main(int argc, char *argv[]) {
-    InitGoogleMock(&argc, argv);
-    testing::GTEST_FLAG(throw_on_failure) = true;
-    testing::GTEST_FLAG(filter) = "heartbeatData.*";
-    int itestts = RUN_ALL_TESTS();
-    return itestts;
+int main(int argc, char* argv[]) {
+  InitGoogleMock(&argc, argv);
+  testing::GTEST_FLAG(throw_on_failure) = true;
+  testing::GTEST_FLAG(filter) = "heartbeatData.*";
+  int itestts = RUN_ALL_TESTS();
+  return itestts;
 }
diff --git a/test/src/protocol/KVTableTest.cpp b/test/src/protocol/KVTableTest.cpp
index 312d35c..b6fd504 100644
--- a/test/src/protocol/KVTableTest.cpp
+++ b/test/src/protocol/KVTableTest.cpp
@@ -32,20 +32,20 @@
 using rocketmq::KVTable;
 
 TEST(KVTable, init) {
-    KVTable table;
+  KVTable table;
 
-    EXPECT_EQ(table.getTable().size(), 0);
+  EXPECT_EQ(table.getTable().size(), 0);
 
-    map<string, string> maps;
-    maps["string"] = "string";
-    table.setTable(maps);
-    EXPECT_EQ(table.getTable().size(), 1);
+  map<string, string> maps;
+  maps["string"] = "string";
+  table.setTable(maps);
+  EXPECT_EQ(table.getTable().size(), 1);
 }
 
-int main(int argc, char *argv[]) {
-    InitGoogleMock(&argc, argv);
-    testing::GTEST_FLAG(throw_on_failure) = true;
-    testing::GTEST_FLAG(filter) = "KVTable.*";
-    int itestts = RUN_ALL_TESTS();
-    return itestts;
+int main(int argc, char* argv[]) {
+  InitGoogleMock(&argc, argv);
+  testing::GTEST_FLAG(throw_on_failure) = true;
+  testing::GTEST_FLAG(filter) = "KVTable.*";
+  int itestts = RUN_ALL_TESTS();
+  return itestts;
 }
diff --git a/test/src/protocol/LockBatchBodyTest.cpp b/test/src/protocol/LockBatchBodyTest.cpp
index fec3b27..9f8f300 100644
--- a/test/src/protocol/LockBatchBodyTest.cpp
+++ b/test/src/protocol/LockBatchBodyTest.cpp
@@ -37,67 +37,67 @@
 using rocketmq::UnlockBatchRequestBody;
 
 TEST(lockBatchBody, LockBatchRequestBody) {
-    LockBatchRequestBody lockBatchRequestBody;
+  LockBatchRequestBody lockBatchRequestBody;
 
-    lockBatchRequestBody.setClientId("testClientId");
-    EXPECT_EQ(lockBatchRequestBody.getClientId(), "testClientId");
+  lockBatchRequestBody.setClientId("testClientId");
+  EXPECT_EQ(lockBatchRequestBody.getClientId(), "testClientId");
 
-    lockBatchRequestBody.setConsumerGroup("testGroup");
-    EXPECT_EQ(lockBatchRequestBody.getConsumerGroup(), "testGroup");
+  lockBatchRequestBody.setConsumerGroup("testGroup");
+  EXPECT_EQ(lockBatchRequestBody.getConsumerGroup(), "testGroup");
 
-    vector<MQMessageQueue> vectorMessageQueue;
-    vectorMessageQueue.push_back(MQMessageQueue());
-    vectorMessageQueue.push_back(MQMessageQueue());
+  vector<MQMessageQueue> vectorMessageQueue;
+  vectorMessageQueue.push_back(MQMessageQueue());
+  vectorMessageQueue.push_back(MQMessageQueue());
 
-    lockBatchRequestBody.setMqSet(vectorMessageQueue);
-    EXPECT_EQ(lockBatchRequestBody.getMqSet(), vectorMessageQueue);
+  lockBatchRequestBody.setMqSet(vectorMessageQueue);
+  EXPECT_EQ(lockBatchRequestBody.getMqSet(), vectorMessageQueue);
 
-    Json::Value outJson = lockBatchRequestBody.toJson(MQMessageQueue("topicTest", "testBroker", 10));
-    EXPECT_EQ(outJson["topic"], "topicTest");
-    EXPECT_EQ(outJson["brokerName"], "testBroker");
-    EXPECT_EQ(outJson["queueId"], 10);
+  Json::Value outJson = lockBatchRequestBody.toJson(MQMessageQueue("topicTest", "testBroker", 10));
+  EXPECT_EQ(outJson["topic"], "topicTest");
+  EXPECT_EQ(outJson["brokerName"], "testBroker");
+  EXPECT_EQ(outJson["queueId"], 10);
 
-    string outData;
-    lockBatchRequestBody.Encode(outData);
+  string outData;
+  lockBatchRequestBody.Encode(outData);
 
-    Json::Value root;
-    Json::Reader reader;
-    reader.parse(outData, root);
-    EXPECT_EQ(root["clientId"], "testClientId");
-    EXPECT_EQ(root["consumerGroup"], "testGroup");
+  Json::Value root;
+  Json::Reader reader;
+  reader.parse(outData, root);
+  EXPECT_EQ(root["clientId"], "testClientId");
+  EXPECT_EQ(root["consumerGroup"], "testGroup");
 }
 
 TEST(lockBatchBody, UnlockBatchRequestBody) {}
 
 TEST(lockBatchBody, LockBatchResponseBody) {
-    Json::Value root;
-    Json::Value mqs;
+  Json::Value root;
+  Json::Value mqs;
 
-    Json::Value mq;
-    mq["topic"] = "testTopic";
-    mq["brokerName"] = "testBroker";
-    mq["queueId"] = 1;
-    mqs[0] = mq;
-    root["lockOKMQSet"] = mqs;
+  Json::Value mq;
+  mq["topic"] = "testTopic";
+  mq["brokerName"] = "testBroker";
+  mq["queueId"] = 1;
+  mqs[0] = mq;
+  root["lockOKMQSet"] = mqs;
 
-    Json::FastWriter fastwrite;
-    string outData = fastwrite.write(root);
+  Json::FastWriter fastwrite;
+  string outData = fastwrite.write(root);
 
-    MemoryBlock *mem = new MemoryBlock(outData.c_str(), outData.size());
+  MemoryBlock* mem = new MemoryBlock(outData.c_str(), outData.size());
 
-    LockBatchResponseBody lockBatchResponseBody;
+  LockBatchResponseBody lockBatchResponseBody;
 
-    vector<MQMessageQueue> messageQueues;
-    LockBatchResponseBody::Decode(mem, messageQueues);
+  vector<MQMessageQueue> messageQueues;
+  LockBatchResponseBody::Decode(mem, messageQueues);
 
-    MQMessageQueue messageQueue("testTopic", "testBroker", 1);
-    EXPECT_EQ(messageQueue, messageQueues[0]);
+  MQMessageQueue messageQueue("testTopic", "testBroker", 1);
+  EXPECT_EQ(messageQueue, messageQueues[0]);
 }
 
-int main(int argc, char *argv[]) {
-    InitGoogleMock(&argc, argv);
-    testing::GTEST_FLAG(throw_on_failure) = true;
-    testing::GTEST_FLAG(filter) = "lockBatchBody.*";
-    int itestts = RUN_ALL_TESTS();
-    return itestts;
+int main(int argc, char* argv[]) {
+  InitGoogleMock(&argc, argv);
+  testing::GTEST_FLAG(throw_on_failure) = true;
+  testing::GTEST_FLAG(filter) = "lockBatchBody.*";
+  int itestts = RUN_ALL_TESTS();
+  return itestts;
 }
diff --git a/test/src/protocol/MessageQueueTest.cpp b/test/src/protocol/MessageQueueTest.cpp
index 68d137e..eb943d2 100644
--- a/test/src/protocol/MessageQueueTest.cpp
+++ b/test/src/protocol/MessageQueueTest.cpp
@@ -26,64 +26,64 @@
 using rocketmq::MessageQueue;
 
 TEST(messageExt, init) {
-    MessageQueue messageQueue;
-    EXPECT_EQ(messageQueue.getQueueId(), -1);
+  MessageQueue messageQueue;
+  EXPECT_EQ(messageQueue.getQueueId(), -1);
 
-    MessageQueue twoMessageQueue("testTopic", "testBroker", 1);
-    EXPECT_EQ(twoMessageQueue.getQueueId(), 1);
-    EXPECT_EQ(twoMessageQueue.getTopic(), "testTopic");
-    EXPECT_EQ(twoMessageQueue.getBrokerName(), "testBroker");
+  MessageQueue twoMessageQueue("testTopic", "testBroker", 1);
+  EXPECT_EQ(twoMessageQueue.getQueueId(), 1);
+  EXPECT_EQ(twoMessageQueue.getTopic(), "testTopic");
+  EXPECT_EQ(twoMessageQueue.getBrokerName(), "testBroker");
 
-    MessageQueue threeMessageQueue(twoMessageQueue);
-    EXPECT_EQ(threeMessageQueue.getQueueId(), 1);
-    EXPECT_EQ(threeMessageQueue.getTopic(), "testTopic");
-    EXPECT_EQ(threeMessageQueue.getBrokerName(), "testBroker");
+  MessageQueue threeMessageQueue(twoMessageQueue);
+  EXPECT_EQ(threeMessageQueue.getQueueId(), 1);
+  EXPECT_EQ(threeMessageQueue.getTopic(), "testTopic");
+  EXPECT_EQ(threeMessageQueue.getBrokerName(), "testBroker");
 
-    Json::Value outJson = twoMessageQueue.toJson();
-    EXPECT_EQ(outJson["queueId"], 1);
-    EXPECT_EQ(outJson["topic"], "testTopic");
-    EXPECT_EQ(outJson["brokerName"], "testBroker");
+  Json::Value outJson = twoMessageQueue.toJson();
+  EXPECT_EQ(outJson["queueId"], 1);
+  EXPECT_EQ(outJson["topic"], "testTopic");
+  EXPECT_EQ(outJson["brokerName"], "testBroker");
 
-    MessageQueue fiveMessageQueue = threeMessageQueue;
-    EXPECT_EQ(fiveMessageQueue.getQueueId(), 1);
-    EXPECT_EQ(fiveMessageQueue.getTopic(), "testTopic");
-    EXPECT_EQ(fiveMessageQueue.getBrokerName(), "testBroker");
+  MessageQueue fiveMessageQueue = threeMessageQueue;
+  EXPECT_EQ(fiveMessageQueue.getQueueId(), 1);
+  EXPECT_EQ(fiveMessageQueue.getTopic(), "testTopic");
+  EXPECT_EQ(fiveMessageQueue.getBrokerName(), "testBroker");
 }
 
 TEST(messageExt, info) {
-    MessageQueue messageQueue;
+  MessageQueue messageQueue;
 
-    messageQueue.setQueueId(11);
-    EXPECT_EQ(messageQueue.getQueueId(), 11);
+  messageQueue.setQueueId(11);
+  EXPECT_EQ(messageQueue.getQueueId(), 11);
 
-    messageQueue.setTopic("testTopic");
-    EXPECT_EQ(messageQueue.getTopic(), "testTopic");
+  messageQueue.setTopic("testTopic");
+  EXPECT_EQ(messageQueue.getTopic(), "testTopic");
 
-    messageQueue.setBrokerName("testBroker");
-    EXPECT_EQ(messageQueue.getBrokerName(), "testBroker");
+  messageQueue.setBrokerName("testBroker");
+  EXPECT_EQ(messageQueue.getBrokerName(), "testBroker");
 }
 
 TEST(messageExt, operators) {
-    MessageQueue messageQueue;
-    EXPECT_TRUE(messageQueue == messageQueue);
+  MessageQueue messageQueue;
+  EXPECT_TRUE(messageQueue == messageQueue);
 
-    MessageQueue twoMessageQueue;
-    EXPECT_TRUE(messageQueue == twoMessageQueue);
+  MessageQueue twoMessageQueue;
+  EXPECT_TRUE(messageQueue == twoMessageQueue);
 
-    twoMessageQueue.setTopic("testTopic");
-    EXPECT_FALSE(messageQueue == twoMessageQueue);
+  twoMessageQueue.setTopic("testTopic");
+  EXPECT_FALSE(messageQueue == twoMessageQueue);
 
-    messageQueue.setQueueId(11);
-    EXPECT_FALSE(messageQueue == twoMessageQueue);
+  messageQueue.setQueueId(11);
+  EXPECT_FALSE(messageQueue == twoMessageQueue);
 
-    messageQueue.setBrokerName("testBroker");
-    EXPECT_FALSE(messageQueue == twoMessageQueue);
+  messageQueue.setBrokerName("testBroker");
+  EXPECT_FALSE(messageQueue == twoMessageQueue);
 }
 
-int main(int argc, char *argv[]) {
-    InitGoogleMock(&argc, argv);
-    testing::GTEST_FLAG(throw_on_failure) = true;
-    testing::GTEST_FLAG(filter) = "messageExt.*";
-    int itestts = RUN_ALL_TESTS();
-    return itestts;
+int main(int argc, char* argv[]) {
+  InitGoogleMock(&argc, argv);
+  testing::GTEST_FLAG(throw_on_failure) = true;
+  testing::GTEST_FLAG(filter) = "messageExt.*";
+  int itestts = RUN_ALL_TESTS();
+  return itestts;
 }
diff --git a/test/src/protocol/ProcessQueueInfoTest.cpp b/test/src/protocol/ProcessQueueInfoTest.cpp
index 9f00d51..bb5e714 100644
--- a/test/src/protocol/ProcessQueueInfoTest.cpp
+++ b/test/src/protocol/ProcessQueueInfoTest.cpp
@@ -28,51 +28,51 @@
 using rocketmq::ProcessQueueInfo;
 
 TEST(processQueueInfo, init) {
-    ProcessQueueInfo processQueueInfo;
-    EXPECT_EQ(processQueueInfo.commitOffset, 0);
-    EXPECT_EQ(processQueueInfo.cachedMsgMinOffset, 0);
-    EXPECT_EQ(processQueueInfo.cachedMsgMaxOffset, 0);
-    EXPECT_EQ(processQueueInfo.cachedMsgCount, 0);
-    EXPECT_EQ(processQueueInfo.transactionMsgMinOffset, 0);
-    EXPECT_EQ(processQueueInfo.transactionMsgMaxOffset, 0);
-    EXPECT_EQ(processQueueInfo.transactionMsgCount, 0);
-    EXPECT_EQ(processQueueInfo.locked, false);
-    EXPECT_EQ(processQueueInfo.tryUnlockTimes, 0);
-    EXPECT_EQ(processQueueInfo.lastLockTimestamp, 123);
-    EXPECT_EQ(processQueueInfo.droped, false);
-    EXPECT_EQ(processQueueInfo.lastPullTimestamp, 0);
-    EXPECT_EQ(processQueueInfo.lastConsumeTimestamp, 0);
+  ProcessQueueInfo processQueueInfo;
+  EXPECT_EQ(processQueueInfo.commitOffset, 0);
+  EXPECT_EQ(processQueueInfo.cachedMsgMinOffset, 0);
+  EXPECT_EQ(processQueueInfo.cachedMsgMaxOffset, 0);
+  EXPECT_EQ(processQueueInfo.cachedMsgCount, 0);
+  EXPECT_EQ(processQueueInfo.transactionMsgMinOffset, 0);
+  EXPECT_EQ(processQueueInfo.transactionMsgMaxOffset, 0);
+  EXPECT_EQ(processQueueInfo.transactionMsgCount, 0);
+  EXPECT_EQ(processQueueInfo.locked, false);
+  EXPECT_EQ(processQueueInfo.tryUnlockTimes, 0);
+  EXPECT_EQ(processQueueInfo.lastLockTimestamp, 123);
+  EXPECT_EQ(processQueueInfo.droped, false);
+  EXPECT_EQ(processQueueInfo.lastPullTimestamp, 0);
+  EXPECT_EQ(processQueueInfo.lastConsumeTimestamp, 0);
 
-    processQueueInfo.setLocked(true);
-    EXPECT_EQ(processQueueInfo.isLocked(), true);
+  processQueueInfo.setLocked(true);
+  EXPECT_EQ(processQueueInfo.isLocked(), true);
 
-    processQueueInfo.setDroped(true);
-    EXPECT_EQ(processQueueInfo.isDroped(), true);
+  processQueueInfo.setDroped(true);
+  EXPECT_EQ(processQueueInfo.isDroped(), true);
 
-    processQueueInfo.setCommitOffset(456);
-    EXPECT_EQ(processQueueInfo.getCommitOffset(), 456);
+  processQueueInfo.setCommitOffset(456);
+  EXPECT_EQ(processQueueInfo.getCommitOffset(), 456);
 
-    Json::Value outJson = processQueueInfo.toJson();
+  Json::Value outJson = processQueueInfo.toJson();
 
-    EXPECT_EQ(outJson["commitOffset"], "456");
-    EXPECT_EQ(outJson["cachedMsgMinOffset"], "0");
-    EXPECT_EQ(outJson["cachedMsgMaxOffset"], "0");
-    EXPECT_EQ(outJson["cachedMsgCount"].asInt(), 0);
-    EXPECT_EQ(outJson["transactionMsgMinOffset"], "0");
-    EXPECT_EQ(outJson["transactionMsgMaxOffset"], "0");
-    EXPECT_EQ(outJson["transactionMsgCount"].asInt(), 0);
-    EXPECT_EQ(outJson["locked"].asBool(), true);
-    EXPECT_EQ(outJson["tryUnlockTimes"].asInt(), 0);
-    EXPECT_EQ(outJson["lastLockTimestamp"], "123");
-    EXPECT_EQ(outJson["droped"].asBool(), true);
-    EXPECT_EQ(outJson["lastPullTimestamp"], "0");
-    EXPECT_EQ(outJson["lastConsumeTimestamp"], "0");
+  EXPECT_EQ(outJson["commitOffset"], "456");
+  EXPECT_EQ(outJson["cachedMsgMinOffset"], "0");
+  EXPECT_EQ(outJson["cachedMsgMaxOffset"], "0");
+  EXPECT_EQ(outJson["cachedMsgCount"].asInt(), 0);
+  EXPECT_EQ(outJson["transactionMsgMinOffset"], "0");
+  EXPECT_EQ(outJson["transactionMsgMaxOffset"], "0");
+  EXPECT_EQ(outJson["transactionMsgCount"].asInt(), 0);
+  EXPECT_EQ(outJson["locked"].asBool(), true);
+  EXPECT_EQ(outJson["tryUnlockTimes"].asInt(), 0);
+  EXPECT_EQ(outJson["lastLockTimestamp"], "123");
+  EXPECT_EQ(outJson["droped"].asBool(), true);
+  EXPECT_EQ(outJson["lastPullTimestamp"], "0");
+  EXPECT_EQ(outJson["lastConsumeTimestamp"], "0");
 }
 
-int main(int argc, char *argv[]) {
-    InitGoogleMock(&argc, argv);
-    testing::GTEST_FLAG(throw_on_failure) = true;
-    testing::GTEST_FLAG(filter) = "processQueueInfo.init";
-    int itestts = RUN_ALL_TESTS();
-    return itestts;
+int main(int argc, char* argv[]) {
+  InitGoogleMock(&argc, argv);
+  testing::GTEST_FLAG(throw_on_failure) = true;
+  testing::GTEST_FLAG(filter) = "processQueueInfo.init";
+  int itestts = RUN_ALL_TESTS();
+  return itestts;
 }
diff --git a/test/src/protocol/RemotingCommandTest.cpp b/test/src/protocol/RemotingCommandTest.cpp
index 1da4c14..ca28aa3 100644
--- a/test/src/protocol/RemotingCommandTest.cpp
+++ b/test/src/protocol/RemotingCommandTest.cpp
@@ -54,232 +54,205 @@
 using rocketmq::SendMessageResponseHeader;
 
 TEST(remotingCommand, init) {
-    RemotingCommand remotingCommand;
-    EXPECT_EQ(remotingCommand.getCode(), 0);
-    EXPECT_EQ(remotingCommand.getOpaque(), 0);
-    EXPECT_EQ(remotingCommand.getRemark(), "");
-    EXPECT_EQ(remotingCommand.getVersion(), 0);
-    //  EXPECT_EQ(remotingCommand.getFlag() , 0);
-    EXPECT_EQ(remotingCommand.getMsgBody(), "");
-    EXPECT_TRUE(remotingCommand.getCommandHeader() == nullptr);
+  RemotingCommand remotingCommand;
+  EXPECT_EQ(remotingCommand.getCode(), 0);
 
-    RemotingCommand twoRemotingCommand(13);
-    EXPECT_EQ(twoRemotingCommand.getCode(), 13);
-    EXPECT_EQ(twoRemotingCommand.getOpaque(), 0);
-    EXPECT_EQ(twoRemotingCommand.getRemark(), "");
-    EXPECT_EQ(twoRemotingCommand.getVersion(), MQVersion::s_CurrentVersion);
-    // EXPECT_EQ(twoRemotingCommand.getFlag() , 0);
-    EXPECT_EQ(twoRemotingCommand.getMsgBody(), "");
-    EXPECT_TRUE(twoRemotingCommand.getCommandHeader() == nullptr);
+  RemotingCommand twoRemotingCommand(13);
+  EXPECT_EQ(twoRemotingCommand.getCode(), 13);
+  EXPECT_EQ(twoRemotingCommand.getOpaque(), 0);
+  EXPECT_EQ(twoRemotingCommand.getRemark(), "");
+  EXPECT_EQ(twoRemotingCommand.getVersion(), MQVersion::s_CurrentVersion);
+  // EXPECT_EQ(twoRemotingCommand.getFlag() , 0);
+  EXPECT_EQ(twoRemotingCommand.getMsgBody(), "");
+  EXPECT_TRUE(twoRemotingCommand.getCommandHeader() == nullptr);
 
-    RemotingCommand threeRemotingCommand(13, new GetRouteInfoRequestHeader("topic"));
-    EXPECT_FALSE(threeRemotingCommand.getCommandHeader() == nullptr);
+  RemotingCommand threeRemotingCommand(13, new GetRouteInfoRequestHeader("topic"));
+  EXPECT_FALSE(threeRemotingCommand.getCommandHeader() == nullptr);
 
-    RemotingCommand frouRemotingCommand(13, "CPP", MQVersion::s_CurrentVersion, 12, 3, "remark",
-                                        new GetRouteInfoRequestHeader("topic"));
-    EXPECT_EQ(frouRemotingCommand.getCode(), 13);
-    EXPECT_EQ(frouRemotingCommand.getOpaque(), 12);
-    EXPECT_EQ(frouRemotingCommand.getRemark(), "remark");
-    EXPECT_EQ(frouRemotingCommand.getVersion(), MQVersion::s_CurrentVersion);
-    EXPECT_EQ(frouRemotingCommand.getFlag(), 3);
-    EXPECT_EQ(frouRemotingCommand.getMsgBody(), "");
-    EXPECT_FALSE(frouRemotingCommand.getCommandHeader() == nullptr);
+  RemotingCommand frouRemotingCommand(13, "CPP", MQVersion::s_CurrentVersion, 12, 3, "remark",
+                                      new GetRouteInfoRequestHeader("topic"));
+  EXPECT_EQ(frouRemotingCommand.getCode(), 13);
+  EXPECT_EQ(frouRemotingCommand.getOpaque(), 12);
+  EXPECT_EQ(frouRemotingCommand.getRemark(), "remark");
+  EXPECT_EQ(frouRemotingCommand.getVersion(), MQVersion::s_CurrentVersion);
+  EXPECT_EQ(frouRemotingCommand.getFlag(), 3);
+  EXPECT_EQ(frouRemotingCommand.getMsgBody(), "");
+  EXPECT_FALSE(frouRemotingCommand.getCommandHeader() == nullptr);
 
-    RemotingCommand sixRemotingCommand(frouRemotingCommand);
-    EXPECT_EQ(sixRemotingCommand.getCode(), 13);
-    EXPECT_EQ(sixRemotingCommand.getOpaque(), 12);
-    EXPECT_EQ(sixRemotingCommand.getRemark(), "remark");
-    EXPECT_EQ(sixRemotingCommand.getVersion(), MQVersion::s_CurrentVersion);
-    EXPECT_EQ(sixRemotingCommand.getFlag(), 3);
-    EXPECT_EQ(sixRemotingCommand.getMsgBody(), "");
-    EXPECT_TRUE(sixRemotingCommand.getCommandHeader() == nullptr);
+  RemotingCommand sixRemotingCommand(frouRemotingCommand);
+  EXPECT_EQ(sixRemotingCommand.getCode(), 13);
+  EXPECT_EQ(sixRemotingCommand.getOpaque(), 12);
+  EXPECT_EQ(sixRemotingCommand.getRemark(), "remark");
+  EXPECT_EQ(sixRemotingCommand.getVersion(), MQVersion::s_CurrentVersion);
+  EXPECT_EQ(sixRemotingCommand.getFlag(), 3);
+  EXPECT_EQ(sixRemotingCommand.getMsgBody(), "");
+  EXPECT_TRUE(sixRemotingCommand.getCommandHeader() == nullptr);
 
-    RemotingCommand *sevenRemotingCommand = new RemotingCommand();
-    EXPECT_EQ(sevenRemotingCommand->getCode(), 0);
-    EXPECT_EQ(sevenRemotingCommand->getOpaque(), 0);
-    EXPECT_EQ(sevenRemotingCommand->getRemark(), "");
-    EXPECT_EQ(sevenRemotingCommand->getVersion(), 0);
-    EXPECT_EQ(sevenRemotingCommand->getFlag(), 0);
-    EXPECT_EQ(sevenRemotingCommand->getMsgBody(), "");
-    EXPECT_TRUE(sevenRemotingCommand->getCommandHeader() == nullptr);
-
-    RemotingCommand *egthRemotingCommand = sevenRemotingCommand;
-    EXPECT_EQ(egthRemotingCommand->getCode(), 0);
-    EXPECT_EQ(egthRemotingCommand->getOpaque(), 0);
-    EXPECT_EQ(egthRemotingCommand->getRemark(), "");
-    EXPECT_EQ(egthRemotingCommand->getVersion(), 0);
-    EXPECT_EQ(egthRemotingCommand->getFlag(), 0);
-    EXPECT_EQ(egthRemotingCommand->getMsgBody(), "");
-    EXPECT_TRUE(egthRemotingCommand->getCommandHeader() == nullptr);
-
-    sevenRemotingCommand = &sixRemotingCommand;
-    EXPECT_EQ(sevenRemotingCommand->getCode(), 13);
-    EXPECT_EQ(sevenRemotingCommand->getOpaque(), 12);
-    EXPECT_EQ(sevenRemotingCommand->getRemark(), "remark");
-    EXPECT_EQ(sevenRemotingCommand->getVersion(), MQVersion::s_CurrentVersion);
-    EXPECT_EQ(sevenRemotingCommand->getFlag(), 3);
-    EXPECT_EQ(sevenRemotingCommand->getMsgBody(), "");
-    EXPECT_TRUE(sevenRemotingCommand->getCommandHeader() == nullptr);
-
-    // Assign
-    delete egthRemotingCommand;
+  RemotingCommand* sevenRemotingCommand = &sixRemotingCommand;
+  EXPECT_EQ(sevenRemotingCommand->getCode(), 13);
+  EXPECT_EQ(sevenRemotingCommand->getOpaque(), 12);
+  EXPECT_EQ(sevenRemotingCommand->getRemark(), "remark");
+  EXPECT_EQ(sevenRemotingCommand->getVersion(), MQVersion::s_CurrentVersion);
+  EXPECT_EQ(sevenRemotingCommand->getFlag(), 3);
+  EXPECT_EQ(sevenRemotingCommand->getMsgBody(), "");
+  EXPECT_TRUE(sevenRemotingCommand->getCommandHeader() == nullptr);
 }
 
 TEST(remotingCommand, info) {
-    RemotingCommand remotingCommand;
+  RemotingCommand remotingCommand;
 
-    remotingCommand.setCode(13);
-    EXPECT_EQ(remotingCommand.getCode(), 13);
+  remotingCommand.setCode(13);
+  EXPECT_EQ(remotingCommand.getCode(), 13);
 
-    remotingCommand.setOpaque(12);
-    EXPECT_EQ(remotingCommand.getOpaque(), 12);
+  remotingCommand.setOpaque(12);
+  EXPECT_EQ(remotingCommand.getOpaque(), 12);
 
-    remotingCommand.setRemark("123");
-    EXPECT_EQ(remotingCommand.getRemark(), "123");
+  remotingCommand.setRemark("123");
+  EXPECT_EQ(remotingCommand.getRemark(), "123");
 
-    remotingCommand.setMsgBody("msgBody");
-    EXPECT_EQ(remotingCommand.getMsgBody(), "msgBody");
+  remotingCommand.setMsgBody("msgBody");
+  EXPECT_EQ(remotingCommand.getMsgBody(), "msgBody");
 
-    remotingCommand.addExtField("key", "value");
+  remotingCommand.addExtField("key", "value");
 }
 
 TEST(remotingCommand, flag) {
-    RemotingCommand remotingCommand(13, "CPP", MQVersion::s_CurrentVersion, 12, 0, "remark",
-                                    new GetRouteInfoRequestHeader("topic"));
-    ;
-    EXPECT_EQ(remotingCommand.getFlag(), 0);
+  RemotingCommand remotingCommand(13, "CPP", MQVersion::s_CurrentVersion, 12, 0, "remark",
+                                  new GetRouteInfoRequestHeader("topic"));
+  ;
+  EXPECT_EQ(remotingCommand.getFlag(), 0);
 
-    remotingCommand.markResponseType();
-    int bits = 1 << 0;
-    int flag = 0;
-    flag |= bits;
-    EXPECT_EQ(remotingCommand.getFlag(), flag);
-    EXPECT_TRUE(remotingCommand.isResponseType());
+  remotingCommand.markResponseType();
+  int bits = 1 << 0;
+  int flag = 0;
+  flag |= bits;
+  EXPECT_EQ(remotingCommand.getFlag(), flag);
+  EXPECT_TRUE(remotingCommand.isResponseType());
 
-    bits = 1 << 1;
-    flag |= bits;
-    remotingCommand.markOnewayRPC();
-    EXPECT_EQ(remotingCommand.getFlag(), flag);
-    EXPECT_TRUE(remotingCommand.isOnewayRPC());
+  bits = 1 << 1;
+  flag |= bits;
+  remotingCommand.markOnewayRPC();
+  EXPECT_EQ(remotingCommand.getFlag(), flag);
+  EXPECT_TRUE(remotingCommand.isOnewayRPC());
 }
 
 TEST(remotingCommand, encodeAndDecode) {
-    RemotingCommand remotingCommand(13, "CPP", MQVersion::s_CurrentVersion, 12, 3, "remark", NULL);
-    remotingCommand.SetBody("123123", 6);
-    remotingCommand.Encode();
-    // no delete
-    const MemoryBlock *head = remotingCommand.GetHead();
-    const MemoryBlock *body = remotingCommand.GetBody();
+  RemotingCommand remotingCommand(13, "CPP", MQVersion::s_CurrentVersion, 12, 3, "remark", NULL);
+  remotingCommand.SetBody("123123", 6);
+  remotingCommand.Encode();
+  // no delete
+  const MemoryBlock* head = remotingCommand.GetHead();
+  const MemoryBlock* body = remotingCommand.GetBody();
 
-    unique_ptr<MemoryOutputStream> result(new MemoryOutputStream(1024));
-    result->write(head->getData() + 4, head->getSize() - 4);
-    result->write(body->getData(), body->getSize());
+  unique_ptr<MemoryOutputStream> result(new MemoryOutputStream(1024));
+  result->write(head->getData() + 4, head->getSize() - 4);
+  result->write(body->getData(), body->getSize());
 
-    shared_ptr<RemotingCommand> decodeRemtingCommand(RemotingCommand::Decode(result->getMemoryBlock()));
-    EXPECT_EQ(remotingCommand.getCode(), decodeRemtingCommand->getCode());
-    EXPECT_EQ(remotingCommand.getOpaque(), decodeRemtingCommand->getOpaque());
-    EXPECT_EQ(remotingCommand.getRemark(), decodeRemtingCommand->getRemark());
-    EXPECT_EQ(remotingCommand.getVersion(), decodeRemtingCommand->getVersion());
-    EXPECT_EQ(remotingCommand.getFlag(), decodeRemtingCommand->getFlag());
-    EXPECT_TRUE(decodeRemtingCommand->getCommandHeader() == NULL);
+  shared_ptr<RemotingCommand> decodeRemtingCommand(RemotingCommand::Decode(result->getMemoryBlock()));
+  EXPECT_EQ(remotingCommand.getCode(), decodeRemtingCommand->getCode());
+  EXPECT_EQ(remotingCommand.getOpaque(), decodeRemtingCommand->getOpaque());
+  EXPECT_EQ(remotingCommand.getRemark(), decodeRemtingCommand->getRemark());
+  EXPECT_EQ(remotingCommand.getVersion(), decodeRemtingCommand->getVersion());
+  EXPECT_EQ(remotingCommand.getFlag(), decodeRemtingCommand->getFlag());
+  EXPECT_TRUE(decodeRemtingCommand->getCommandHeader() == NULL);
 
-    // ~RemotingCommand delete
-    GetConsumerRunningInfoRequestHeader *requestHeader = new GetConsumerRunningInfoRequestHeader();
-    requestHeader->setClientId("client");
-    requestHeader->setConsumerGroup("consumerGroup");
-    requestHeader->setJstackEnable(false);
+  // ~RemotingCommand delete
+  GetConsumerRunningInfoRequestHeader* requestHeader = new GetConsumerRunningInfoRequestHeader();
+  requestHeader->setClientId("client");
+  requestHeader->setConsumerGroup("consumerGroup");
+  requestHeader->setJstackEnable(false);
 
-    RemotingCommand encodeRemotingCommand(307, "CPP", MQVersion::s_CurrentVersion, 12, 3, "remark", requestHeader);
-    encodeRemotingCommand.SetBody("123123", 6);
-    encodeRemotingCommand.Encode();
+  RemotingCommand encodeRemotingCommand(307, "CPP", MQVersion::s_CurrentVersion, 12, 3, "remark", requestHeader);
+  encodeRemotingCommand.SetBody("123123", 6);
+  encodeRemotingCommand.Encode();
 
-    // no delete
-    const MemoryBlock *phead = encodeRemotingCommand.GetHead();
-    const MemoryBlock *pbody = encodeRemotingCommand.GetBody();
+  // no delete
+  const MemoryBlock* phead = encodeRemotingCommand.GetHead();
+  const MemoryBlock* pbody = encodeRemotingCommand.GetBody();
 
-    unique_ptr<MemoryOutputStream> results(new MemoryOutputStream(1024));
-    results->write(phead->getData() + 4, phead->getSize() - 4);
-    results->write(pbody->getData(), pbody->getSize());
+  unique_ptr<MemoryOutputStream> results(new MemoryOutputStream(1024));
+  results->write(phead->getData() + 4, phead->getSize() - 4);
+  results->write(pbody->getData(), pbody->getSize());
 
-    shared_ptr<RemotingCommand> decodeRemtingCommandTwo(RemotingCommand::Decode(results->getMemoryBlock()));
+  shared_ptr<RemotingCommand> decodeRemtingCommandTwo(RemotingCommand::Decode(results->getMemoryBlock()));
 
-    decodeRemtingCommandTwo->SetExtHeader(encodeRemotingCommand.getCode());
-    GetConsumerRunningInfoRequestHeader *header =
-        reinterpret_cast<GetConsumerRunningInfoRequestHeader *>(decodeRemtingCommandTwo->getCommandHeader());
-    EXPECT_EQ(requestHeader->getClientId(), header->getClientId());
-    EXPECT_EQ(requestHeader->getConsumerGroup(), header->getConsumerGroup());
+  decodeRemtingCommandTwo->SetExtHeader(encodeRemotingCommand.getCode());
+  GetConsumerRunningInfoRequestHeader* header =
+      reinterpret_cast<GetConsumerRunningInfoRequestHeader*>(decodeRemtingCommandTwo->getCommandHeader());
+  EXPECT_EQ(requestHeader->getClientId(), header->getClientId());
+  EXPECT_EQ(requestHeader->getConsumerGroup(), header->getConsumerGroup());
 }
 
 TEST(remotingCommand, SetExtHeader) {
-    shared_ptr<RemotingCommand> remotingCommand(new RemotingCommand());
+  shared_ptr<RemotingCommand> remotingCommand(new RemotingCommand());
 
-    remotingCommand->SetExtHeader(-1);
-    EXPECT_TRUE(remotingCommand->getCommandHeader() == NULL);
+  remotingCommand->SetExtHeader(-1);
+  EXPECT_TRUE(remotingCommand->getCommandHeader() == NULL);
 
-    Json::Value object;
-    Json::Value extFields;
-    extFields["id"] = 1;
-    object["extFields"] = extFields;
-    remotingCommand->setParsedJson(object);
+  Json::Value object;
+  Json::Value extFields;
+  extFields["id"] = 1;
+  object["extFields"] = extFields;
+  remotingCommand->setParsedJson(object);
 
-    remotingCommand->SetExtHeader(MQRequestCode::SEND_MESSAGE);
-    SendMessageResponseHeader *sendMessageResponseHeader =
-        reinterpret_cast<SendMessageResponseHeader *>(remotingCommand->getCommandHeader());
-    EXPECT_EQ(sendMessageResponseHeader->msgId, "");
+  remotingCommand->SetExtHeader(MQRequestCode::SEND_MESSAGE);
+  SendMessageResponseHeader* sendMessageResponseHeader =
+      reinterpret_cast<SendMessageResponseHeader*>(remotingCommand->getCommandHeader());
+  EXPECT_EQ(sendMessageResponseHeader->msgId, "");
 
-    remotingCommand->SetExtHeader(MQRequestCode::PULL_MESSAGE);
-    PullMessageResponseHeader *pullMessageResponseHeader =
-        reinterpret_cast<PullMessageResponseHeader *>(remotingCommand->getCommandHeader());
-    EXPECT_EQ(pullMessageResponseHeader->suggestWhichBrokerId, 0);
+  remotingCommand->SetExtHeader(MQRequestCode::PULL_MESSAGE);
+  PullMessageResponseHeader* pullMessageResponseHeader =
+      reinterpret_cast<PullMessageResponseHeader*>(remotingCommand->getCommandHeader());
+  EXPECT_EQ(pullMessageResponseHeader->suggestWhichBrokerId, 0);
 
-    remotingCommand->SetExtHeader(MQRequestCode::GET_MIN_OFFSET);
-    GetMinOffsetResponseHeader *getMinOffsetResponseHeader =
-        reinterpret_cast<GetMinOffsetResponseHeader *>(remotingCommand->getCommandHeader());
-    EXPECT_EQ(getMinOffsetResponseHeader->offset, 0);
+  remotingCommand->SetExtHeader(MQRequestCode::GET_MIN_OFFSET);
+  GetMinOffsetResponseHeader* getMinOffsetResponseHeader =
+      reinterpret_cast<GetMinOffsetResponseHeader*>(remotingCommand->getCommandHeader());
+  EXPECT_EQ(getMinOffsetResponseHeader->offset, 0);
 
-    remotingCommand->SetExtHeader(MQRequestCode::GET_MAX_OFFSET);
-    GetMaxOffsetResponseHeader *getMaxOffsetResponseHeader =
-        reinterpret_cast<GetMaxOffsetResponseHeader *>(remotingCommand->getCommandHeader());
-    EXPECT_EQ(getMaxOffsetResponseHeader->offset, 0);
+  remotingCommand->SetExtHeader(MQRequestCode::GET_MAX_OFFSET);
+  GetMaxOffsetResponseHeader* getMaxOffsetResponseHeader =
+      reinterpret_cast<GetMaxOffsetResponseHeader*>(remotingCommand->getCommandHeader());
+  EXPECT_EQ(getMaxOffsetResponseHeader->offset, 0);
 
-    remotingCommand->SetExtHeader(MQRequestCode::SEARCH_OFFSET_BY_TIMESTAMP);
-    SearchOffsetResponseHeader *searchOffsetResponseHeader =
-        reinterpret_cast<SearchOffsetResponseHeader *>(remotingCommand->getCommandHeader());
-    EXPECT_EQ(searchOffsetResponseHeader->offset, 0);
+  remotingCommand->SetExtHeader(MQRequestCode::SEARCH_OFFSET_BY_TIMESTAMP);
+  SearchOffsetResponseHeader* searchOffsetResponseHeader =
+      reinterpret_cast<SearchOffsetResponseHeader*>(remotingCommand->getCommandHeader());
+  EXPECT_EQ(searchOffsetResponseHeader->offset, 0);
 
-    remotingCommand->SetExtHeader(MQRequestCode::GET_EARLIEST_MSG_STORETIME);
-    GetEarliestMsgStoretimeResponseHeader *getEarliestMsgStoretimeResponseHeader =
-        reinterpret_cast<GetEarliestMsgStoretimeResponseHeader *>(remotingCommand->getCommandHeader());
-    EXPECT_EQ(getEarliestMsgStoretimeResponseHeader->timestamp, 0);
+  remotingCommand->SetExtHeader(MQRequestCode::GET_EARLIEST_MSG_STORETIME);
+  GetEarliestMsgStoretimeResponseHeader* getEarliestMsgStoretimeResponseHeader =
+      reinterpret_cast<GetEarliestMsgStoretimeResponseHeader*>(remotingCommand->getCommandHeader());
+  EXPECT_EQ(getEarliestMsgStoretimeResponseHeader->timestamp, 0);
 
-    remotingCommand->SetExtHeader(MQRequestCode::QUERY_CONSUMER_OFFSET);
-    QueryConsumerOffsetResponseHeader *queryConsumerOffsetResponseHeader =
-        reinterpret_cast<QueryConsumerOffsetResponseHeader *>(remotingCommand->getCommandHeader());
-    EXPECT_EQ(queryConsumerOffsetResponseHeader->offset, 0);
+  remotingCommand->SetExtHeader(MQRequestCode::QUERY_CONSUMER_OFFSET);
+  QueryConsumerOffsetResponseHeader* queryConsumerOffsetResponseHeader =
+      reinterpret_cast<QueryConsumerOffsetResponseHeader*>(remotingCommand->getCommandHeader());
+  EXPECT_EQ(queryConsumerOffsetResponseHeader->offset, 0);
 
-    extFields["isForce"] = "true";
-    object["extFields"] = extFields;
-    remotingCommand->setParsedJson(object);
-    remotingCommand->SetExtHeader(MQRequestCode::RESET_CONSUMER_CLIENT_OFFSET);
-    ResetOffsetRequestHeader *resetOffsetRequestHeader =
-        reinterpret_cast<ResetOffsetRequestHeader *>(remotingCommand->getCommandHeader());
-    resetOffsetRequestHeader->setGroup("group");
+  extFields["isForce"] = "true";
+  object["extFields"] = extFields;
+  remotingCommand->setParsedJson(object);
+  remotingCommand->SetExtHeader(MQRequestCode::RESET_CONSUMER_CLIENT_OFFSET);
+  ResetOffsetRequestHeader* resetOffsetRequestHeader =
+      reinterpret_cast<ResetOffsetRequestHeader*>(remotingCommand->getCommandHeader());
+  resetOffsetRequestHeader->setGroup("group");
 
-    remotingCommand->SetExtHeader(MQRequestCode::GET_CONSUMER_RUNNING_INFO);
-    GetConsumerRunningInfoRequestHeader *getConsumerRunningInfoRequestHeader =
-        reinterpret_cast<GetConsumerRunningInfoRequestHeader *>(remotingCommand->getCommandHeader());
-    getConsumerRunningInfoRequestHeader->setClientId("id");
+  remotingCommand->SetExtHeader(MQRequestCode::GET_CONSUMER_RUNNING_INFO);
+  GetConsumerRunningInfoRequestHeader* getConsumerRunningInfoRequestHeader =
+      reinterpret_cast<GetConsumerRunningInfoRequestHeader*>(remotingCommand->getCommandHeader());
+  getConsumerRunningInfoRequestHeader->setClientId("id");
 
-    remotingCommand->SetExtHeader(MQRequestCode::NOTIFY_CONSUMER_IDS_CHANGED);
-    NotifyConsumerIdsChangedRequestHeader *notifyConsumerIdsChangedRequestHeader =
-        reinterpret_cast<NotifyConsumerIdsChangedRequestHeader *>(remotingCommand->getCommandHeader());
-    notifyConsumerIdsChangedRequestHeader->setGroup("group");
+  remotingCommand->SetExtHeader(MQRequestCode::NOTIFY_CONSUMER_IDS_CHANGED);
+  NotifyConsumerIdsChangedRequestHeader* notifyConsumerIdsChangedRequestHeader =
+      reinterpret_cast<NotifyConsumerIdsChangedRequestHeader*>(remotingCommand->getCommandHeader());
+  notifyConsumerIdsChangedRequestHeader->setGroup("group");
 }
 
-int main(int argc, char *argv[]) {
-    InitGoogleMock(&argc, argv);
-    testing::GTEST_FLAG(throw_on_failure) = true;
-    testing::GTEST_FLAG(filter) = "remotingCommand.*";
-    int itestts = RUN_ALL_TESTS();
-    return itestts;
+int main(int argc, char* argv[]) {
+  InitGoogleMock(&argc, argv);
+  testing::GTEST_FLAG(throw_on_failure) = true;
+  testing::GTEST_FLAG(filter) = "remotingCommand.*";
+  int itestts = RUN_ALL_TESTS();
+  return itestts;
 }
diff --git a/test/src/protocol/TopicRouteDataTest.cpp b/test/src/protocol/TopicRouteDataTest.cpp
index 8ddba9f..cf88ac1 100644
--- a/test/src/protocol/TopicRouteDataTest.cpp
+++ b/test/src/protocol/TopicRouteDataTest.cpp
@@ -30,64 +30,64 @@
 using rocketmq::TopicRouteData;
 
 TEST(topicRouteData, topicRouteData) {
-    Json::Value root;
-    root["orderTopicConf"] = "orderTopicConf";
+  Json::Value root;
+  root["orderTopicConf"] = "orderTopicConf";
 
-    Json::Value queueDatas;
-    Json::Value queueData;
+  Json::Value queueDatas;
+  Json::Value queueData;
 
-    queueData["brokerName"] = "brokerTest";
-    queueData["readQueueNums"] = 8;
-    queueData["writeQueueNums"] = 8;
-    queueData["perm"] = 7;
-    queueDatas[0] = queueData;
+  queueData["brokerName"] = "brokerTest";
+  queueData["readQueueNums"] = 8;
+  queueData["writeQueueNums"] = 8;
+  queueData["perm"] = 7;
+  queueDatas[0] = queueData;
 
-    root["queueDatas"] = queueDatas;
+  root["queueDatas"] = queueDatas;
 
-    Json::Value brokerDatas;
-    Json::Value brokerData;
-    brokerData["brokerName"] = "testBroker";
+  Json::Value brokerDatas;
+  Json::Value brokerData;
+  brokerData["brokerName"] = "testBroker";
 
-    Json::Value brokerAddrs;
-    brokerAddrs["0"] = "127.0.0.1:10091";
-    brokerAddrs["1"] = "127.0.0.2:10092";
-    brokerData["brokerAddrs"] = brokerAddrs;
+  Json::Value brokerAddrs;
+  brokerAddrs["0"] = "127.0.0.1:10091";
+  brokerAddrs["1"] = "127.0.0.2:10092";
+  brokerData["brokerAddrs"] = brokerAddrs;
 
-    brokerDatas[0] = brokerData;
+  brokerDatas[0] = brokerData;
 
-    root["brokerDatas"] = brokerDatas;
-    string out = root.toStyledString();
+  root["brokerDatas"] = brokerDatas;
+  string out = root.toStyledString();
 
-    MemoryBlock *block = new MemoryBlock(out.c_str(), out.size());
-    TopicRouteData *topicRouteData = TopicRouteData::Decode(block);
-    EXPECT_EQ(root["orderTopicConf"], topicRouteData->getOrderTopicConf());
+  MemoryBlock* block = new MemoryBlock(out.c_str(), out.size());
+  TopicRouteData* topicRouteData = TopicRouteData::Decode(block);
+  EXPECT_EQ(root["orderTopicConf"], topicRouteData->getOrderTopicConf());
 
-    BrokerData broker;
-    broker.brokerName = "testBroker";
-    broker.brokerAddrs[0] = "127.0.0.1:10091";
-    broker.brokerAddrs[1] = "127.0.0.2:10092";
+  BrokerData broker;
+  broker.brokerName = "testBroker";
+  broker.brokerAddrs[0] = "127.0.0.1:10091";
+  broker.brokerAddrs[1] = "127.0.0.2:10092";
 
-    vector<BrokerData> brokerDataSt = topicRouteData->getBrokerDatas();
-    EXPECT_EQ(broker, brokerDataSt[0]);
+  vector<BrokerData> brokerDataSt = topicRouteData->getBrokerDatas();
+  EXPECT_EQ(broker, brokerDataSt[0]);
 
-    QueueData queue;
-    queue.brokerName = "brokerTest";
-    queue.readQueueNums = 8;
-    queue.writeQueueNums = 8;
-    queue.perm = 7;
-    vector<QueueData> queueDataSt = topicRouteData->getQueueDatas();
-    EXPECT_EQ(queue, queueDataSt[0]);
+  QueueData queue;
+  queue.brokerName = "brokerTest";
+  queue.readQueueNums = 8;
+  queue.writeQueueNums = 8;
+  queue.perm = 7;
+  vector<QueueData> queueDataSt = topicRouteData->getQueueDatas();
+  EXPECT_EQ(queue, queueDataSt[0]);
 
-    EXPECT_EQ(topicRouteData->selectBrokerAddr(), "127.0.0.1:10091");
+  EXPECT_EQ(topicRouteData->selectBrokerAddr(), "127.0.0.1:10091");
 
-    delete block;
-    delete topicRouteData;
+  delete block;
+  delete topicRouteData;
 }
 
-int main(int argc, char *argv[]) {
-    InitGoogleMock(&argc, argv);
-    testing::GTEST_FLAG(throw_on_failure) = true;
-    testing::GTEST_FLAG(filter) = "topicRouteData.topicRouteData";
-    int itestts = RUN_ALL_TESTS();
-    return itestts;
+int main(int argc, char* argv[]) {
+  InitGoogleMock(&argc, argv);
+  testing::GTEST_FLAG(throw_on_failure) = true;
+  testing::GTEST_FLAG(filter) = "topicRouteData.topicRouteData";
+  int itestts = RUN_ALL_TESTS();
+  return itestts;
 }
diff --git a/test/src/transport/ClientRemotingProcessorTest.cpp b/test/src/transport/ClientRemotingProcessorTest.cpp
index 80348b0..5c906eb 100644
--- a/test/src/transport/ClientRemotingProcessorTest.cpp
+++ b/test/src/transport/ClientRemotingProcessorTest.cpp
@@ -66,170 +66,172 @@
 using rocketmq::UtilAll;
 
 class MockClientRemotingProcessor : public ClientRemotingProcessor {
-   public:
-    MockClientRemotingProcessor(MQClientFactory *factrory) : ClientRemotingProcessor(factrory) {}
-    MOCK_METHOD1(resetOffset, RemotingCommand *(RemotingCommand *request));
-    MOCK_METHOD1(getConsumerRunningInfo, RemotingCommand *(RemotingCommand *request));
-    MOCK_METHOD1(notifyConsumerIdsChanged, RemotingCommand *(RemotingCommand *request));
+ public:
+  MockClientRemotingProcessor(MQClientFactory* factrory) : ClientRemotingProcessor(factrory) {}
+  MOCK_METHOD1(resetOffset, RemotingCommand*(RemotingCommand* request));
+  MOCK_METHOD1(getConsumerRunningInfo, RemotingCommand*(RemotingCommand* request));
+  MOCK_METHOD1(notifyConsumerIdsChanged, RemotingCommand*(RemotingCommand* request));
 };
 
 class MockMQClientFactory : public MQClientFactory {
-   public:
-    MockMQClientFactory(const string &clientID,
-                        int pullThreadNum,
-                        uint64_t tcpConnectTimeout,
-                        uint64_t tcpTransportTryLockTimeout,
-                        string unitName)
-        : MQClientFactory(clientID, pullThreadNum, tcpConnectTimeout, tcpTransportTryLockTimeout, unitName) {}
+ public:
+  MockMQClientFactory(const string& clientID,
+                      int pullThreadNum,
+                      uint64_t tcpConnectTimeout,
+                      uint64_t tcpTransportTryLockTimeout,
+                      string unitName)
+      : MQClientFactory(clientID, pullThreadNum, tcpConnectTimeout, tcpTransportTryLockTimeout, unitName) {}
 
-    MOCK_METHOD3(resetOffset,
-                 void(const string &group, const string &topic, const map<MQMessageQueue, int64> &offsetTable));
-    MOCK_METHOD1(consumerRunningInfo, ConsumerRunningInfo *(const string &consumerGroup));
-    MOCK_METHOD2(getSessionCredentialFromConsumer,
-                 bool(const string &consumerGroup, SessionCredentials &sessionCredentials));
-    MOCK_METHOD1(doRebalanceByConsumerGroup, void(const string &consumerGroup));
+  MOCK_METHOD3(resetOffset,
+               void(const string& group, const string& topic, const map<MQMessageQueue, int64>& offsetTable));
+  MOCK_METHOD1(consumerRunningInfo, ConsumerRunningInfo*(const string& consumerGroup));
+  MOCK_METHOD2(getSessionCredentialFromConsumer,
+               bool(const string& consumerGroup, SessionCredentials& sessionCredentials));
+  MOCK_METHOD1(doRebalanceByConsumerGroup, void(const string& consumerGroup));
 };
 
 TEST(clientRemotingProcessor, processRequest) {
-    MockMQClientFactory *factory = new MockMQClientFactory("testClientId", 4, 3000, 4000, "a");
-    ClientRemotingProcessor clientRemotingProcessor(factory);
+  MockMQClientFactory* factory = new MockMQClientFactory("testClientId", 4, 3000, 4000, "a");
+  ClientRemotingProcessor clientRemotingProcessor(factory);
 
-    string addr = "127.0.0.1:9876";
-    RemotingCommand *command = new RemotingCommand();
-    RemotingCommand *pResponse = new RemotingCommand(13);
+  string addr = "127.0.0.1:9876";
+  RemotingCommand* command = new RemotingCommand();
+  RemotingCommand* pResponse = new RemotingCommand(13);
 
-    pResponse->setCode(MQRequestCode::RESET_CONSUMER_CLIENT_OFFSET);
-    command->setCode(MQRequestCode::RESET_CONSUMER_CLIENT_OFFSET);
-    EXPECT_TRUE(clientRemotingProcessor.processRequest(addr, command) == nullptr);
-    EXPECT_EQ(nullptr, clientRemotingProcessor.processRequest(addr, command));
+  pResponse->setCode(MQRequestCode::RESET_CONSUMER_CLIENT_OFFSET);
+  command->setCode(MQRequestCode::RESET_CONSUMER_CLIENT_OFFSET);
+  EXPECT_TRUE(clientRemotingProcessor.processRequest(addr, command) == nullptr);
+  EXPECT_EQ(nullptr, clientRemotingProcessor.processRequest(addr, command));
 
-    NotifyConsumerIdsChangedRequestHeader *header = new NotifyConsumerIdsChangedRequestHeader();
-    header->setGroup("testGroup");
-    RemotingCommand *twoCommand = new RemotingCommand(MQRequestCode::NOTIFY_CONSUMER_IDS_CHANGED, header);
+  NotifyConsumerIdsChangedRequestHeader* header = new NotifyConsumerIdsChangedRequestHeader();
+  header->setGroup("testGroup");
+  RemotingCommand* twoCommand = new RemotingCommand(MQRequestCode::NOTIFY_CONSUMER_IDS_CHANGED, header);
 
-    EXPECT_EQ(NULL, clientRemotingProcessor.processRequest(addr, twoCommand));
+  EXPECT_EQ(NULL, clientRemotingProcessor.processRequest(addr, twoCommand));
 
-    command->setCode(MQRequestCode::GET_CONSUMER_RUNNING_INFO);
-    // EXPECT_EQ(NULL , clientRemotingProcessor.processRequest(addr, command));
+  command->setCode(MQRequestCode::GET_CONSUMER_RUNNING_INFO);
+  // EXPECT_EQ(NULL , clientRemotingProcessor.processRequest(addr, command));
 
-    command->setCode(MQRequestCode::CHECK_TRANSACTION_STATE);
-    EXPECT_TRUE(clientRemotingProcessor.processRequest(addr, command) == nullptr);
+  command->setCode(MQRequestCode::CHECK_TRANSACTION_STATE);
+  EXPECT_TRUE(clientRemotingProcessor.processRequest(addr, command) == nullptr);
 
-    command->setCode(MQRequestCode::GET_CONSUMER_STATUS_FROM_CLIENT);
-    EXPECT_TRUE(clientRemotingProcessor.processRequest(addr, command) == nullptr);
+  command->setCode(MQRequestCode::GET_CONSUMER_STATUS_FROM_CLIENT);
+  EXPECT_TRUE(clientRemotingProcessor.processRequest(addr, command) == nullptr);
 
-    command->setCode(MQRequestCode::CONSUME_MESSAGE_DIRECTLY);
-    EXPECT_TRUE(clientRemotingProcessor.processRequest(addr, command) == nullptr);
+  command->setCode(MQRequestCode::CONSUME_MESSAGE_DIRECTLY);
+  EXPECT_TRUE(clientRemotingProcessor.processRequest(addr, command) == nullptr);
 
-    command->setCode(1);
-    EXPECT_TRUE(clientRemotingProcessor.processRequest(addr, command) == nullptr);
+  command->setCode(1);
+  EXPECT_TRUE(clientRemotingProcessor.processRequest(addr, command) == nullptr);
 
-    delete command;
-    delete pResponse;
+  delete twoCommand;
+  delete command;
+  delete pResponse;
 }
 
 TEST(clientRemotingProcessor, resetOffset) {
-    MockMQClientFactory *factory = new MockMQClientFactory("testClientId", 4, 3000, 4000, "a");
-    Mock::AllowLeak(factory);
-    ClientRemotingProcessor clientRemotingProcessor(factory);
-    Value root;
-    Value messageQueues;
-    Value messageQueue;
-    messageQueue["brokerName"] = "testBroker";
-    messageQueue["queueId"] = 4;
-    messageQueue["topic"] = "testTopic";
-    messageQueue["offset"] = 1024;
+  MockMQClientFactory* factory = new MockMQClientFactory("testClientId", 4, 3000, 4000, "a");
+  Mock::AllowLeak(factory);
+  ClientRemotingProcessor clientRemotingProcessor(factory);
+  Value root;
+  Value messageQueues;
+  Value messageQueue;
+  messageQueue["brokerName"] = "testBroker";
+  messageQueue["queueId"] = 4;
+  messageQueue["topic"] = "testTopic";
+  messageQueue["offset"] = 1024;
 
-    messageQueues.append(messageQueue);
-    root["offsetTable"] = messageQueues;
+  messageQueues.append(messageQueue);
+  root["offsetTable"] = messageQueues;
 
-    FastWriter wrtier;
-    string strData = wrtier.write(root);
+  FastWriter wrtier;
+  string strData = wrtier.write(root);
 
-    ResetOffsetRequestHeader *header = new ResetOffsetRequestHeader();
-    RemotingCommand *request = new RemotingCommand(13, header);
+  ResetOffsetRequestHeader* header = new ResetOffsetRequestHeader();
+  RemotingCommand* request = new RemotingCommand(13, header);
 
-    EXPECT_CALL(*factory, resetOffset(_, _, _)).Times(1);
-    clientRemotingProcessor.resetOffset(request);
+  EXPECT_CALL(*factory, resetOffset(_, _, _)).Times(1);
+  clientRemotingProcessor.resetOffset(request);
 
-    request->SetBody(strData.c_str(), strData.size() - 2);
-    clientRemotingProcessor.resetOffset(request);
+  request->SetBody(strData.c_str(), strData.size() - 2);
+  clientRemotingProcessor.resetOffset(request);
 
-    request->SetBody(strData.c_str(), strData.size());
-    clientRemotingProcessor.resetOffset(request);
+  request->SetBody(strData.c_str(), strData.size());
+  clientRemotingProcessor.resetOffset(request);
 
-    delete header;
-    delete request;
+  // here header no need delete, it will managered by RemotingCommand
+  // delete header;
+  delete request;
 }
 
 TEST(clientRemotingProcessorS, getConsumerRunningInfo) {
-    MockMQClientFactory *factory = new MockMQClientFactory("testClientId", 4, 3000, 4000, "a");
-    ConsumerRunningInfo *info = new ConsumerRunningInfo();
-    EXPECT_CALL(*factory, consumerRunningInfo(_)).Times(2).WillOnce(Return(info)).WillOnce(Return(info));
-    EXPECT_CALL(*factory, getSessionCredentialFromConsumer(_, _))
-        .Times(2);  //.WillRepeatedly(SetArgReferee<1>(sessionCredentials));
-    ClientRemotingProcessor clientRemotingProcessor(factory);
+  MockMQClientFactory* factory = new MockMQClientFactory("testClientId", 4, 3000, 4000, "a");
+  ConsumerRunningInfo* info = new ConsumerRunningInfo();
+  EXPECT_CALL(*factory, consumerRunningInfo(_)).Times(2).WillOnce(Return(info)).WillOnce(Return(info));
+  EXPECT_CALL(*factory, getSessionCredentialFromConsumer(_, _))
+      .Times(2);  //.WillRepeatedly(SetArgReferee<1>(sessionCredentials));
+  ClientRemotingProcessor clientRemotingProcessor(factory);
 
-    GetConsumerRunningInfoRequestHeader *header = new GetConsumerRunningInfoRequestHeader();
-    header->setConsumerGroup("testGroup");
+  GetConsumerRunningInfoRequestHeader* header = new GetConsumerRunningInfoRequestHeader();
+  header->setConsumerGroup("testGroup");
 
-    RemotingCommand *request = new RemotingCommand(14, header);
+  RemotingCommand* request = new RemotingCommand(14, header);
 
-    RemotingCommand *command = clientRemotingProcessor.getConsumerRunningInfo("127.0.0.1:9876", request);
-    EXPECT_EQ(command->getCode(), MQResponseCode::SYSTEM_ERROR);
-    EXPECT_EQ(command->getRemark(), "The Consumer Group not exist in this consumer");
-    delete command;
-    delete request;
+  RemotingCommand* command = clientRemotingProcessor.getConsumerRunningInfo("127.0.0.1:9876", request);
+  EXPECT_EQ(command->getCode(), MQResponseCode::SYSTEM_ERROR);
+  EXPECT_EQ(command->getRemark(), "The Consumer Group not exist in this consumer");
+  delete command;
+  delete request;
 }
 
 TEST(clientRemotingProcessor, notifyConsumerIdsChanged) {
-    MockMQClientFactory *factory = new MockMQClientFactory("testClientId", 4, 3000, 4000, "a");
-    Mock::AllowLeak(factory);
-    ClientRemotingProcessor clientRemotingProcessor(factory);
-    NotifyConsumerIdsChangedRequestHeader *header = new NotifyConsumerIdsChangedRequestHeader();
-    header->setGroup("testGroup");
-    RemotingCommand *request = new RemotingCommand(14, header);
+  MockMQClientFactory* factory = new MockMQClientFactory("testClientId", 4, 3000, 4000, "a");
+  Mock::AllowLeak(factory);
+  ClientRemotingProcessor clientRemotingProcessor(factory);
+  NotifyConsumerIdsChangedRequestHeader* header = new NotifyConsumerIdsChangedRequestHeader();
+  header->setGroup("testGroup");
+  RemotingCommand* request = new RemotingCommand(14, header);
 
-    EXPECT_CALL(*factory, doRebalanceByConsumerGroup(_)).Times(1);
-    clientRemotingProcessor.notifyConsumerIdsChanged(request);
+  EXPECT_CALL(*factory, doRebalanceByConsumerGroup(_)).Times(1);
+  clientRemotingProcessor.notifyConsumerIdsChanged(request);
 
-    delete request;
+  delete request;
 }
 
 TEST(clientRemotingProcessor, resetOffsetBody) {
-    MockMQClientFactory *factory = new MockMQClientFactory("testClientId", 4, 3000, 4000, "a");
-    ClientRemotingProcessor clientRemotingProcessor(factory);
+  MockMQClientFactory* factory = new MockMQClientFactory("testClientId", 4, 3000, 4000, "a");
+  ClientRemotingProcessor clientRemotingProcessor(factory);
 
-    Value root;
-    Value messageQueues;
-    Value messageQueue;
-    messageQueue["brokerName"] = "testBroker";
-    messageQueue["queueId"] = 4;
-    messageQueue["topic"] = "testTopic";
-    messageQueue["offset"] = 1024;
+  Value root;
+  Value messageQueues;
+  Value messageQueue;
+  messageQueue["brokerName"] = "testBroker";
+  messageQueue["queueId"] = 4;
+  messageQueue["topic"] = "testTopic";
+  messageQueue["offset"] = 1024;
 
-    messageQueues.append(messageQueue);
-    root["offsetTable"] = messageQueues;
+  messageQueues.append(messageQueue);
+  root["offsetTable"] = messageQueues;
 
-    FastWriter wrtier;
-    string strData = wrtier.write(root);
+  FastWriter wrtier;
+  string strData = wrtier.write(root);
 
-    MemoryBlock *mem = new MemoryBlock(strData.c_str(), strData.size());
+  MemoryBlock* mem = new MemoryBlock(strData.c_str(), strData.size());
 
-    ResetOffsetBody *resetOffset = ResetOffsetBody::Decode(mem);
+  ResetOffsetBody* resetOffset = ResetOffsetBody::Decode(mem);
 
-    map<MQMessageQueue, int64> map = resetOffset->getOffsetTable();
-    MQMessageQueue mqmq("testTopic", "testBroker", 4);
-    EXPECT_EQ(map[mqmq], 1024);
-    Mock::AllowLeak(factory);
-    delete resetOffset;
-    delete mem;
+  map<MQMessageQueue, int64> map = resetOffset->getOffsetTable();
+  MQMessageQueue mqmq("testTopic", "testBroker", 4);
+  EXPECT_EQ(map[mqmq], 1024);
+  Mock::AllowLeak(factory);
+  delete resetOffset;
+  delete mem;
 }
 
-int main(int argc, char *argv[]) {
-    InitGoogleMock(&argc, argv);
-    testing::GTEST_FLAG(throw_on_failure) = true;
-    testing::GTEST_FLAG(filter) = "clientRemotingProcessor.*";
-    int itestts = RUN_ALL_TESTS();
-    return itestts;
+int main(int argc, char* argv[]) {
+  InitGoogleMock(&argc, argv);
+  testing::GTEST_FLAG(throw_on_failure) = true;
+  testing::GTEST_FLAG(filter) = "clientRemotingProcessor.*";
+  int itestts = RUN_ALL_TESTS();
+  return itestts;
 }
diff --git a/test/src/transport/ResponseFutureTest.cpp b/test/src/transport/ResponseFutureTest.cpp
index 483fced..9c23ed8 100644
--- a/test/src/transport/ResponseFutureTest.cpp
+++ b/test/src/transport/ResponseFutureTest.cpp
@@ -32,7 +32,7 @@
 using testing::Return;
 
 using rocketmq::AsyncCallback;
-using rocketmq::asyncCallBackStatus;
+using rocketmq::AsyncCallbackStatus;
 using rocketmq::asyncCallBackType;
 using rocketmq::AsyncCallbackWrap;
 using rocketmq::MQClientAPIImpl;
@@ -44,137 +44,80 @@
 using rocketmq::UtilAll;
 
 class MockAsyncCallbackWrap : public SendCallbackWrap {
-   public:
-    MockAsyncCallbackWrap(AsyncCallback *pAsyncCallback, MQClientAPIImpl *pclientAPI)
-        : SendCallbackWrap("", MQMessage(), pAsyncCallback, pclientAPI) {}
+ public:
+  MockAsyncCallbackWrap(AsyncCallback* pAsyncCallback, MQClientAPIImpl* pclientAPI)
+      : SendCallbackWrap("", MQMessage(), pAsyncCallback, pclientAPI) {}
 
-    MOCK_METHOD2(operationComplete, void(ResponseFuture *, bool));
-    MOCK_METHOD0(onException, void());
-    asyncCallBackType getCallbackType() { return asyncCallBackType::sendCallbackWrap; }
+  MOCK_METHOD2(operationComplete, void(ResponseFuture*, bool));
+  MOCK_METHOD0(onException, void());
+  asyncCallBackType getCallbackType() { return asyncCallBackType::sendCallbackWrap; }
 };
 
 TEST(responseFuture, init) {
-    ResponseFuture responseFuture(13, 4, NULL, 1000);
-    EXPECT_EQ(responseFuture.getRequestCode(), 13);
-    EXPECT_EQ(responseFuture.getOpaque(), 4);
+  ResponseFuture responseFuture(13, 4, NULL, 1000);
+  EXPECT_EQ(responseFuture.getRequestCode(), 13);
+  EXPECT_EQ(responseFuture.getOpaque(), 4);
 
-    EXPECT_EQ(responseFuture.getRequestCommand().getCode(), 0);
-    EXPECT_FALSE(responseFuture.isSendRequestOK());
-    EXPECT_EQ(responseFuture.getMaxRetrySendTimes(), 1);
-    EXPECT_EQ(responseFuture.getRetrySendTimes(), 1);
-    EXPECT_EQ(responseFuture.getBrokerAddr(), "");
+  EXPECT_EQ(responseFuture.getRequestCommand().getCode(), 0);
+  EXPECT_FALSE(responseFuture.isSendRequestOK());
+  EXPECT_EQ(responseFuture.getMaxRetrySendTimes(), 1);
+  EXPECT_EQ(responseFuture.getRetrySendTimes(), 1);
+  EXPECT_EQ(responseFuture.getBrokerAddr(), "");
 
-    EXPECT_FALSE(responseFuture.getASyncFlag());
-    EXPECT_TRUE(responseFuture.getAsyncResponseFlag());
-    EXPECT_FALSE(responseFuture.getSyncResponseFlag());
-    EXPECT_TRUE(responseFuture.getAsyncCallbackWrap() == nullptr);
+  EXPECT_FALSE(responseFuture.getAsyncFlag());
+  EXPECT_TRUE(responseFuture.getAsyncCallbackWrap() == nullptr);
 
-    // ~ResponseFuture  delete pcall
-    SendCallbackWrap *pcall = new SendCallbackWrap("", MQMessage(), nullptr, nullptr);
-    ResponseFuture twoResponseFuture(13, 4, nullptr, 1000, true, pcall);
-    EXPECT_TRUE(twoResponseFuture.getASyncFlag());
-    EXPECT_FALSE(twoResponseFuture.getAsyncResponseFlag());
-    EXPECT_TRUE(twoResponseFuture.getSyncResponseFlag());
-    EXPECT_FALSE(twoResponseFuture.getAsyncCallbackWrap() == nullptr);
+  // ~ResponseFuture  delete pcall
+  SendCallbackWrap* pcall = new SendCallbackWrap("", MQMessage(), nullptr, nullptr);
+  ResponseFuture twoResponseFuture(13, 4, nullptr, 1000, true, pcall);
+  EXPECT_TRUE(twoResponseFuture.getAsyncFlag());
+  EXPECT_FALSE(twoResponseFuture.getAsyncCallbackWrap() == nullptr);
 }
 
 TEST(responseFuture, info) {
-    ResponseFuture responseFuture(13, 4, NULL, 1000);
+  ResponseFuture responseFuture(13, 4, NULL, 1000);
 
-    responseFuture.setAsyncResponseFlag();
-    EXPECT_TRUE(responseFuture.getAsyncResponseFlag());
+  responseFuture.setBrokerAddr("127.0.0.1:9876");
+  EXPECT_EQ(responseFuture.getBrokerAddr(), "127.0.0.1:9876");
 
-    responseFuture.setBrokerAddr("127.0.0.1:9876");
-    EXPECT_EQ(responseFuture.getBrokerAddr(), "127.0.0.1:9876");
+  responseFuture.setMaxRetrySendTimes(3000);
+  EXPECT_EQ(responseFuture.getMaxRetrySendTimes(), 3000);
 
-    responseFuture.setMaxRetrySendTimes(3000);
-    EXPECT_EQ(responseFuture.getMaxRetrySendTimes(), 3000);
+  responseFuture.setRetrySendTimes(3000);
+  EXPECT_EQ(responseFuture.getRetrySendTimes(), 3000);
 
-    responseFuture.setRetrySendTimes(3000);
-    EXPECT_EQ(responseFuture.getRetrySendTimes(), 3000);
-
-    responseFuture.setSendRequestOK(true);
-    EXPECT_TRUE(responseFuture.isSendRequestOK());
+  responseFuture.setSendRequestOK(true);
+  EXPECT_TRUE(responseFuture.isSendRequestOK());
 }
 
 TEST(responseFuture, response) {
-    // m_bAsync = false  m_syncResponse
-    ResponseFuture responseFuture(13, 4, NULL, 1000);
+  // m_bAsync = false  m_syncResponse
+  ResponseFuture responseFuture(13, 4, NULL, 1000);
 
-    EXPECT_FALSE(responseFuture.getASyncFlag());
-    EXPECT_FALSE(responseFuture.getSyncResponseFlag());
-    EXPECT_TRUE(responseFuture.getAsyncResponseFlag());
+  EXPECT_FALSE(responseFuture.getAsyncFlag());
 
-    RemotingCommand *pResponseCommand = NULL;
-    responseFuture.setResponse(pResponseCommand);
-    EXPECT_EQ(responseFuture.getRequestCommand().getCode(), 0);
+  RemotingCommand* pResponseCommand = NULL;
+  responseFuture.setResponse(pResponseCommand);
+  EXPECT_EQ(responseFuture.getRequestCommand().getCode(), 0);
 
-    EXPECT_TRUE(responseFuture.getSyncResponseFlag());
+  // m_bAsync = true  m_syncResponse
+  ResponseFuture twoResponseFuture(13, 4, NULL, 1000, true);
+  EXPECT_TRUE(twoResponseFuture.getAsyncFlag());
 
-    // m_bAsync = true  m_syncResponse
-    ResponseFuture twoResponseFuture(13, 4, NULL, 1000, true);
+  ResponseFuture threeSesponseFuture(13, 4, NULL, 1000);
 
-    EXPECT_TRUE(twoResponseFuture.getASyncFlag());
-    EXPECT_TRUE(twoResponseFuture.getSyncResponseFlag());
-    EXPECT_FALSE(twoResponseFuture.getAsyncResponseFlag());
+  uint64_t millis = UtilAll::currentTimeMillis();
+  RemotingCommand* remotingCommand = threeSesponseFuture.waitResponse(10);
+  uint64_t useTime = UtilAll::currentTimeMillis() - millis;
+  EXPECT_LT(useTime, 30);
 
-    twoResponseFuture.setResponse(pResponseCommand);
-    EXPECT_TRUE(twoResponseFuture.getSyncResponseFlag());
-
-    ResponseFuture threeSesponseFuture(13, 4, NULL, 1000);
-
-    uint64_t millis = UtilAll::currentTimeMillis();
-    RemotingCommand *remotingCommand = threeSesponseFuture.waitResponse(10);
-    uint64_t useTime = UtilAll::currentTimeMillis() - millis;
-    EXPECT_LT(useTime, 30);
-
-    EXPECT_TRUE(responseFuture.getSyncResponseFlag());
-    EXPECT_EQ(NULL, remotingCommand);
+  EXPECT_EQ(NULL, remotingCommand);
 }
 
-TEST(responseFuture, executeInvokeCallback) {
-    //  executeInvokeCallback delete wrap
-    MockAsyncCallbackWrap *wrap = new MockAsyncCallbackWrap(nullptr, nullptr);
-    ResponseFuture responseFuture(13, 4, nullptr, 1000, false, wrap);
-
-    RemotingCommand *pResponseCommand = new RemotingCommand();
-    responseFuture.setResponse(pResponseCommand);
-    responseFuture.executeInvokeCallback();
-    EXPECT_EQ(NULL, responseFuture.getCommand());
-
-    EXPECT_CALL(*wrap, operationComplete(_, _)).Times(1);
-    pResponseCommand = new RemotingCommand();
-    responseFuture.setResponse(pResponseCommand);
-    responseFuture.setAsyncCallBackStatus(asyncCallBackStatus::asyncCallBackStatus_response);
-    responseFuture.executeInvokeCallback();
-    EXPECT_EQ(pResponseCommand->getCode(), 0);
-
-    ResponseFuture twoResponseFuture(13, 4, nullptr, 1000, false, NULL);
-    pResponseCommand = new RemotingCommand();
-    twoResponseFuture.executeInvokeCallback();
-    EXPECT_EQ(NULL, twoResponseFuture.getCommand());
-}
-
-TEST(responseFuture, executeInvokeCallbackException) {
-    //  executeInvokeCallbackException delete wrap
-    MockAsyncCallbackWrap *wrap = new MockAsyncCallbackWrap(nullptr, nullptr);
-
-    ResponseFuture responseFuture(13, 4, nullptr, 1000, false, wrap);
-
-    EXPECT_CALL(*wrap, onException()).Times(1);
-    responseFuture.executeInvokeCallbackException();
-
-    responseFuture.setAsyncCallBackStatus(asyncCallBackStatus::asyncCallBackStatus_timeout);
-    responseFuture.executeInvokeCallbackException();
-
-    ResponseFuture twoRresponseFuture(13, 4, nullptr, 1000, false, NULL);
-    twoRresponseFuture.executeInvokeCallbackException();
-}
-
-int main(int argc, char *argv[]) {
-    InitGoogleMock(&argc, argv);
-    testing::GTEST_FLAG(throw_on_failure) = true;
-    testing::GTEST_FLAG(filter) = "responseFuture.*";
-    int itestts = RUN_ALL_TESTS();
-    return itestts;
+int main(int argc, char* argv[]) {
+  InitGoogleMock(&argc, argv);
+  testing::GTEST_FLAG(throw_on_failure) = true;
+  testing::GTEST_FLAG(filter) = "responseFuture.*";
+  int itestts = RUN_ALL_TESTS();
+  return itestts;
 }
diff --git a/test/src/transport/SocketUtilTest.cpp b/test/src/transport/SocketUtilTest.cpp
index 875f2e7..09560b2 100644
--- a/test/src/transport/SocketUtilTest.cpp
+++ b/test/src/transport/SocketUtilTest.cpp
@@ -24,24 +24,24 @@
 using testing::Return;
 
 TEST(socketUtil, init) {
-    sockaddr addr = rocketmq::IPPort2socketAddress(inet_addr("127.0.0.1"), 10091);
+  sockaddr addr = rocketmq::IPPort2socketAddress(inet_addr("127.0.0.1"), 10091);
 
-    EXPECT_EQ(rocketmq::socketAddress2IPPort(addr), "1.0.0.127:10091");
+  EXPECT_EQ(rocketmq::socketAddress2IPPort(addr), "1.0.0.127:10091");
 
-    int host;
-    int port;
+  int host;
+  int port;
 
-    rocketmq::socketAddress2IPPort(addr, host, port);
-    EXPECT_EQ(host, inet_addr("127.0.0.1"));
-    EXPECT_EQ(port, 10091);
+  rocketmq::socketAddress2IPPort(addr, host, port);
+  EXPECT_EQ(host, inet_addr("127.0.0.1"));
+  EXPECT_EQ(port, 10091);
 
-    EXPECT_EQ(rocketmq::socketAddress2String(addr), "1.0.0.127");
+  EXPECT_EQ(rocketmq::socketAddress2String(addr), "1.0.0.127");
 }
 
-int main(int argc, char *argv[]) {
-    InitGoogleMock(&argc, argv);
-    testing::GTEST_FLAG(throw_on_failure) = true;
-    testing::GTEST_FLAG(filter) = "socketUtil.init";
-    int itestts = RUN_ALL_TESTS();
-    return itestts;
+int main(int argc, char* argv[]) {
+  InitGoogleMock(&argc, argv);
+  testing::GTEST_FLAG(throw_on_failure) = true;
+  testing::GTEST_FLAG(filter) = "socketUtil.init";
+  int itestts = RUN_ALL_TESTS();
+  return itestts;
 }