libnsq编译、使用记录
官方介绍libnsq是nsq的c库,尼玛还真是c库,如果用g++编译还真编译不过。这篇文章就是说一下怎么在c++中使用libnsq。
为什么用g++编译不过libnsq呢,因为其头文件中默认全是c函数,没有对c++编译器做处理。
为了保持libnsq的完整性,不对libnsq代码作任何修改。
libnsq默认编译输出libnsq.a,个人不太喜欢使用静态库,所以自行编译为动态库:
gcc -o libnsq.so command.c http.c json.c message.c nsqd_connection.c nsqlookupd.c reader.c -fPIC -shared -lev -levbuffsock -lcurl -ljson-c
随后封装了c调研libnsq,代码如下
brd_nsq_consumer.h
#ifndef __BRD_NSQ_CONSUMER_H__
#define __BRD_NSQ_CONSUMER_H__
#ifdef __cplusplus
extern "C" {
#endif
typedef void (*HANDLER)(const char *msg);
HANDLER callback;
void init_nsq_consumer(const char *topic,const char *channel,const char *nsqlookupdDomain,int nsqlookupdPort,HANDLER handle);
#ifdef __cplusplus
}
#endif
#endif
brd_nsq_consumer.c
#include "brd_nsq_consumer.h"
#include "nsq.h"
void message_handler(struct NSQReader *rdr, struct NSQDConnection *conn, struct NSQMessage *msg, void *ctx);
void init_nsq_consumer(const char *topic,const char *channel,const char *nsqlookupdDomain,int nsqlookupdPort,HANDLER handle)
{
callback = handle;
struct NSQReader *rdr;
struct ev_loop *loop;
void *ctx = NULL; //(void *)(new TestNsqMsgContext());
loop = ev_default_loop(0);
rdr = new_nsq_reader(loop, topic, channel, (void *)ctx,
NULL, NULL, NULL, message_handler);
nsq_reader_connect_to_nsqd(rdr, "127.0.0.1", 4150);
//nsq_reader_add_nsqlookupd_endpoint(rdr, nsqlookupdDomain, 4161);
nsq_run(loop);
}
void message_handler(struct NSQReader *rdr, struct NSQDConnection *conn, struct NSQMessage *msg, void *ctx)
{
if(callback!=NULL)
callback(msg->body);
buffer_reset(conn->command_buf);
nsq_finish(conn->command_buf, msg->id);
buffered_socket_write_buffer(conn->bs, conn->command_buf);
buffer_reset(conn->command_buf);
nsq_ready(conn->command_buf, rdr->max_in_flight);
buffered_socket_write_buffer(conn->bs, conn->command_buf);
free_nsq_message(msg);
}
编译:
gcc -shared -fPIC -o libnsqconsumer.so brd_nsq_consumer.c -lnsq
然后在c++中调用,代码如下:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include "brd_nsq_consumer.h"
class CMainModule
{
public:
CMainModule();
~CMainModule();
static void handler(const char *msg);
int procMSg(const char *msg);
};
static CMainModule *g_pModule;
int main()
{
CMainModule *pModule = new CMainModule;
g_pModule=pModule;
init_nsq_consumer("test","ch","127.0.0.1",4161,CMainModule::handler);
sleep(1000);
delete pModule;
}
CMainModule::CMainModule(){
}
CMainModule::~CMainModule(){
}
void CMainModule::handler(const char *msg){
g_pModule->procMSg(msg);
}
int CMainModule::procMSg(const char *msg){
printf("====main=========%s\n",msg );
return 0;
}
编译:
g++ main.cpp -o a.out -lnsqconsumer -L./
posted on 2017-12-21 10:25 angry-baby 阅读(509) 评论(0) 编辑 收藏 举报