int main(int argc, char **argv) { if(argc != 2) { fprintf(stderr, "Usage: %s /dev/<ssp-port>\n", argv[0]); return 1; } signal(SIGPIPE, SIG_IGN); signal(SIGINT, interrupt); fprintf(stderr, "eSSP starting up (port %s)...\n", argv[1]); if(!sspConnectToValidator(argv[1])) { return 3; } eventBase = event_base_new(); atexit(cleanup); setupDatabase(); redisLibeventAttach(db, eventBase); redisAsyncSetConnectCallback(db, connectCallback); redisAsyncSetDisconnectCallback(db, disconnectCallback); event_base_dispatch(eventBase); return 0; }
int RedisAsyncConn::DoConnect() { m_state = CONNECTING; int retry = 0; while (true) { m_async_context = redisAsyncConnect(m_server_ip.c_str(), m_server_port); if (m_async_context->err) { LOG(ERROR) << "RedisAsyncConn::DoConnect() error=" << m_async_context->errstr << ", retry=" << retry; redisAsyncDisconnect(m_async_context); if (++retry > m_max_retry_times) { return REDIS_ASYNC_CONN_ERR; } } else { break; } } g_async_conn_map.insert(make_pair(m_async_context, this)); RedisNetlibAttach(m_async_context, NetEventLoop::GetInstance()); redisAsyncSetConnectCallback(m_async_context, ConnectCallback); redisAsyncSetDisconnectCallback(m_async_context, DisconnectCallback); LOG(DEBUG) << "RedisAsyncConn::DoConnect() server_ip=" << m_server_ip << ", server_port=" << m_server_port << ", handle=" << m_async_context->c.fd; return REDIS_ASYNC_CONN_OK; }
int rxs_signal_init(rxs_signal* s, const char* ip, uint16_t port) { if (!s) { return -1; } if (!ip) { return -2; } if (!port) { return -3; } s->connected = 0; s->loop = (uv_loop_t*)uv_default_loop(); if (!s->loop) { printf("Error: cannot get default uv loop for signaling.\n"); return -4; } s->redis = redisAsyncConnect(ip, port); if (!s->redis) { printf("Error: cannot create hiredis context for signaling.\n"); return -5; } if (s->redis->err) { printf("Error: something went wrong when trying to connect to redis: %s\n", s->redis->errstr); return -6; } /* @todo - add error checks */ redisLibuvAttach(s->redis, s->loop); redisAsyncSetConnectCallback(s->redis, connect_callback); redisAsyncSetDisconnectCallback(s->redis, disconnect_callback); return 0; }
void connect() { if(redisContext_) { throw IllegalStateException("Error redisContext already created"); } state_ = REDISREQUEST_CONNECTING; ScopedMutexLock(lockRedis_); redisContext_ = redisAsyncConnect(host_.c_str(), port_); if (redisContext_->err) { _LOG_DEBUG("REDIS CONNECT FAILED (CREATE ERROR): %s:%d, err = %x, this = %p" , host_.c_str(), port_, redisContext_->err, this); state_ = REDISREQUEST_CONNECTFAILED; //fire_onRedisRequest_Error(redisContext_->err, "connect error", NULL); // disconnectCallback() is called later soon.. // error process will be executed by that function. } redisContext_->data = this; redisLibeventAttach(redisContext_, (struct event_base *)ioService_->coreHandle()); redisAsyncSetConnectCallback(redisContext_, connectCallback); redisAsyncSetDisconnectCallback(redisContext_, disconnectCallback); timerObj_->setTimer(TIMER_ID_CONNECTION_TIMEOUT, DEFAULT_CONNECT_TIMEOUT, false); _LOG_DEBUG("redis connect start : %s:%d, flag = 0x%x, fd = %d, context = %p, this = %p" , host_.c_str(), port_, redisContext_->c.flags, redisContext_->c.fd, redisContext_, this); }
void uq_redis_connect(EV_P) { pubContext = redisAsyncConnect("127.0.0.1", 6379); if (pubContext->err) { fprintf(stderr, "Redis Error %s\n", pubContext->errstr); exit(1); } redisLibevAttach(EV_A_ pubContext); redisAsyncSetConnectCallback(pubContext, connectCallback); }
void connectAsyncRedis(redisAsyncContext *ctx, EventLoop *loop) { if(redisSayanAttach(ctx, loop)!=REDIS_OK) die("Error: %s\n", ctx->errstr); redisAsyncSetConnectCallback(ctx, connectCallback); redisAsyncSetDisconnectCallback(ctx, disconnectCallback); char *test="bonjour"; redisAsyncCommand(ctx, getCallback, NULL, "SET key %b", test, strlen(test)); redisAsyncCommand(ctx, getCallback, (char*)"end-1", "GET key"); }
int main (int argc, char **argv) { signal(SIGPIPE, SIG_IGN); struct event_base *base = event_base_new(); const char *hostname = (argc > 1) ? argv[1] : "127.0.0.1"; int port = (argc > 2) ? atoi(argv[2]) : 6379; const char *subname = (argc > 3) ? argv[3] : "test"; redisAsyncContext *c = redisAsyncConnect(hostname, port); if (c->err) { /* Let *c leak for now... */ printf("Error: %s\n", c->errstr); return 1; } g_yuv_size = 1920*1080*3/2; g_yuv = malloc(g_yuv_size); start_time = time((time_t*)NULL); now_time = time((time_t*)NULL); // init pipe if(pipe(pipe_fd)){ printf("pipe error\n"); return -1; } // create thread pthread_attr_t attr; struct sched_param param; pthread_t tsk_id; pthread_attr_init(&attr); pthread_attr_setschedpolicy(&attr, SCHED_FIFO); pthread_attr_getschedparam(&attr, ¶m); pthread_create(&tsk_id, &attr, (void *)thread_function, NULL); // event redisLibeventAttach(c,base); redisAsyncSetConnectCallback(c,connectCallback); redisAsyncSetDisconnectCallback(c,disconnectCallback); redisAsyncCommand(c, subCallback, (char*) "sub", "SMEMSUBSCRIBE %s", subname); event_base_dispatch(base); return 0; }
void RedisProxy::connect() { if(_connected) { return; } SLOG(DEBUG) << "redis connect begin..."; _context = redisAsyncConnect(_ip.c_str(), _port); if(!_context) { SLOG(WARNING) << "allocate redis async connection fail!"; return; } if(_context->err != 0) { SLOG(WARNING) << "connect fail[" << _context->err << "]"; redisAsyncFree(_context); _context = nullptr; return; } _context->data = this; _context->ev.data = this; _context->ev.addRead = RedisProxy::redis_add_read; _context->ev.delRead = RedisProxy::redis_del_read; _context->ev.addWrite = RedisProxy::redis_add_write; _context->ev.delWrite = RedisProxy::redis_del_write; _context->ev.cleanup = RedisProxy::redis_cleanup; _read_io = std::make_shared<IO>(_context->c.fd, EV_READ, false);//FIXME:add EV_ET in future _read_io->on_read([this]() { LOG(INFO) << "on read"; redisAsyncHandleRead(_context); }); _write_io = std::make_shared<IO>(_context->c.fd, EV_WRITE, false);//FIXME:add EV_ET in future LOG(INFO) << "redis fd:" << _context->c.fd; _write_io->on_write([this]() { LOG(INFO) << "on write"; redisAsyncHandleWrite(_context); }); _connected = get_local_loop()->add_io(_read_io, false) && get_local_loop()->add_io(_write_io, false); redisAsyncSetConnectCallback(_context, RedisProxy::handle_connect); redisAsyncSetDisconnectCallback(_context, RedisProxy::handle_disconnect); }
bool Redox::initHiredis() { ctx_->data = (void *)this; // Back-reference if (ctx_->err) { logger_.fatal() << "Could not create a hiredis context: " << ctx_->errstr; { unique_lock<mutex> lk(connect_lock_); connect_state_ = INIT_ERROR; } connect_waiter_.notify_all(); return false; } // Attach event loop to hiredis if (redisLibevAttach(evloop_, ctx_) != REDIS_OK) { logger_.fatal() << "Could not attach libev event loop to hiredis."; { unique_lock<mutex> lk(connect_lock_); connect_state_ = INIT_ERROR; } connect_waiter_.notify_all(); return false; } // Set the callbacks to be invoked on server connection/disconnection if (redisAsyncSetConnectCallback(ctx_, Redox::connectedCallback) != REDIS_OK) { logger_.fatal() << "Could not attach connect callback to hiredis."; { unique_lock<mutex> lk(connect_lock_); connect_state_ = INIT_ERROR; } connect_waiter_.notify_all(); return false; } if (redisAsyncSetDisconnectCallback(ctx_, Redox::disconnectedCallback) != REDIS_OK) { logger_.fatal() << "Could not attach disconnect callback to hiredis."; { unique_lock<mutex> lk(connect_lock_); connect_state_ = INIT_ERROR; } connect_waiter_.notify_all(); return false; } return true; }
static int lua_client_on_connect(lua_State *L) { lua_redis_client_t *lua_redis_client = (lua_redis_client_t *) luaL_checkudata(L, 1, LUA_REDIS_CLIENT_MT); if (lua_redis_client->redis_async_context == NULL) { return luaL_error(L, "RedisAsyncContext is null"); } luv_register_event(L, 1, "connect", 2); redisAsyncSetConnectCallback(lua_redis_client->redis_async_context, connectCallback); return 0; }
bool AsyncRedisMgr::redis_connect() { if(redisAsyncSetConnectCallback(m_redis_context,connect_callback) != REDIS_OK) { LOG4CPLUS_ERROR(logger,"when we set connect callback fail."); return false; } if(redisAsyncSetDisconnectCallback(m_redis_context,dis_connect_callback) != REDIS_OK) { LOG4CPLUS_ERROR(logger,"when we set disconnect callback fail."); return false; } return true; }
int main (int argc, char **argv) { signal(SIGPIPE, SIG_IGN); redisAsyncContext *c = redisAsyncConnect("127.0.0.1", 6379); if (c->err) { /* Let *c leak for now... */ printf("Error: %s\n", c->errstr); return 1; } redisLibevAttach(EV_DEFAULT_ c); redisAsyncSetConnectCallback(c,connectCallback); redisAsyncSetDisconnectCallback(c,disconnectCallback); redisAsyncCommand(c, NULL, NULL, "SET key %b", argv[argc-1], strlen(argv[argc-1])); redisAsyncCommand(c, getCallback, (char*)"end-1", "GET key"); ev_loop(EV_DEFAULT_ 0); return 0; }
static int new_connect( struct cnt_pool *pool, uintptr_t **cite, va_list *ap ) { char *host = va_arg(*ap, char *); int port = va_arg(*ap, int); redisAsyncContext *c = redisAsyncConnect (host, port); if (!c || c->err) { /* Let *c leak for now... */ x_printf (E, "Error: %s\n", c->errstr); free (c); *cite = NULL; return -1; } redisLibevAttach(NULL, c); redisAsyncSetConnectCallback(c, _connectCallback); redisAsyncSetDisconnectCallback(c, _disconnectCallback); *cite = (uintptr_t *)c; return 0; }
int main() { signal(SIGPIPE, SIG_IGN); redisAsyncContext *c = redisAsyncConnect("127.0.0.1", 6379); if (c->err) { /* Let *c leak for now... */ printf("Error: %s\n", c->errstr); return 1; } redisLibevAttach(EV_DEFAULT_ c); redisAsyncSetConnectCallback(c,connectCallback); redisAsyncSetDisconnectCallback(c,disconnectCallback); // redisAsyncCommand(c, getCallback, (char*)"sub", "SUBSCRIBE name"); new ChatRoom(c, {"79153060652", "79030072726", "79853672651"}); ev_loop(EV_DEFAULT_ 0); return 0; }
/*Inicia conexao com o Redis e configura as funcoes de callback no libEvent*/ void initRedis( const char * channel, char * id) { signal(SIGPIPE, SIG_IGN); struct event_base *base = event_base_new(); strcpy(globalChannel, channel); setMyID(id); redisAsyncContext * redis = redisAsyncConnect("127.0.0.1", 6379); if ( redis->err ) { printf("Erro conectando no redis %s\n", redis->errstr); exit(EXIT_FAILURE); } initStdin( channel); redisLibeventAttach( redis,base); redisAsyncSetConnectCallback(redis, connectCallback); redisAsyncSetDisconnectCallback( redis,disconnectCallback); event_base_dispatch(base); }
int main (int argc, char **argv) { signal(SIGPIPE, SIG_IGN); struct event_base *base = event_base_new(); redisAsyncContext *c = redisAsyncConnect("127.0.0.1", 6379); if (c->err) { /* Let *c leak for now... */ printf("Error: %s\n", c->errstr); return 1; } redisLibeventAttach(c,base); redisAsyncSetConnectCallback(c,connectCallback); redisAsyncSetDisconnectCallback(c,disconnectCallback); redisAsyncCommand(c, NULL, NULL, "SET key %b", argv[argc-1], strlen(argv[argc-1])); redisAsyncCommand(c, getCallback, (char*)"end-1", "GET key"); event_base_dispatch(base); return 0; }
int main (int argc, char **argv) { signal(SIGPIPE, SIG_IGN); redisAsyncContext *c = redisAsyncConnect("127.0.0.1", 6379); if (c->err) { /* Let *c leak for now... */ printf("Error: %s\n", c->errstr); return 1; } loop = aeCreateEventLoop(); redisAeAttach(loop, c); redisAsyncSetConnectCallback(c,connectCallback); redisAsyncSetDisconnectCallback(c,disconnectCallback); redisAsyncCommand(c, NULL, NULL, "SET key %b", argv[argc-1], strlen(argv[argc-1])); redisAsyncCommand(c, getCallback, (char*)"end-1", "GET key"); aeMain(loop); return 0; }
void func(const std::string& commandStr) { g_SubscribeMutex.lock(); struct event_base *m_base = event_base_new(); redisAsyncContext *m_redis = redisAsyncConnect("127.0.0.1", 6379); if (m_redis->err) { /* Let *c leak for now... */ printf("Error: %s\n", m_redis->errstr); } redisAsyncCommand(m_redis,authCallback, (char*) "auth", "auth %s", "014006"); redisLibeventAttach(m_redis, m_base); redisAsyncSetConnectCallback(m_redis, connectCallback); redisAsyncSetDisconnectCallback(m_redis, disconnectCallback); redisAsyncCommand(m_redis, subscribeCallback, (char*) "sub", commandStr.c_str()); g_SubscribeMutex.unlock(); event_base_dispatch(m_base); }
int AsyncConnection::connect(const string& host, const int port, const int db) { async_context_ = redisAsyncConnect(host.c_str(), port); async_context_->data = this; if (async_context_->err) { cout << "error: " << async_context_->errstr << endl; return -1; } host_ = host; port_ = port; db_ = db; AsyncService::instance().attach(async_context_); redisAsyncSetConnectCallback(async_context_, connect_callback); redisAsyncSetDisconnectCallback(async_context_, disconnect_callback); return 0; }
void build_async_conn() { if (actx) { redisAsyncDisconnect(actx); } actx = redisAsyncConnect(REDIS_SERVER_IP, REDIS_SERVER_PORT); if (actx == NULL || actx->err) { if (actx) { log_error("redisAsyncConnect fails: %s", actx->errstr); //redisFree(actx); } else { log_error("redisAsyncConnect fails: can't allocate redis context"); } return; } redisLibevAttach(EV_DEFAULT_ actx); redisAsyncSetConnectCallback(actx, on_connect); redisAsyncSetDisconnectCallback(actx, on_disconnect); redisAsyncCommand(actx, on_expire, NULL, "SUBSCRIBE __keyevent@0__:expired"); }
static struct redis *__redis_connect_async(struct redis *redis) { redis->eb = event_base_new(); LM_INFO("Connecting (ASYNC) to Redis at %s:%d\n", redis->ip, redis->port); redis->async_ctxt = redisAsyncConnect(redis->ip, redis->port); if(redis->async_ctxt->err) { LM_ERR("%s\n", redis->async_ctxt->errstr); return NULL; } redisLibeventAttach(redis->async_ctxt, redis->eb); redisAsyncSetConnectCallback(redis->async_ctxt, __async_connect_cb); redisAsyncSetDisconnectCallback(redis->async_ctxt, __async_disconnect_cb); redisAsyncCommand(redis->async_ctxt, NULL, NULL, "SELECT %d", redis->db); __redis_subscribe_to_kill_list(redis); event_base_dispatch(redis->eb); return redis; }
int GatewayDataMgr::startRedisCliProcLoop() { int iRet = 0; //init redis script sha1 sha1sumScript(); mPtRedisAC = redisAsyncConnect(mRedisSvrIPAddr.c_str(), mPort); if (mPtRedisAC->err) { /* Let *c leak for now... */ LOG(ERROR)<<"Error: "<<mPtRedisAC->errstr; iRet = -1; return iRet; } mPtEventLoop = aeCreateEventLoop(64); mPtRedisAC->data = mPtEventLoop;//used on connect/disconnect callback redisAeAttach(mPtEventLoop, mPtRedisAC); redisAsyncSetConnectCallback(mPtRedisAC, connectCallback); redisAsyncSetDisconnectCallback(mPtRedisAC,disconnectCallback); std::thread loopThread(std::mem_fn(&GatewayDataMgr::loopThread), this); loopThread.detach(); return iRet; }
int RedisConnectionAsync::asyncConnect() { _ac = redisAsyncConnect(_host.c_str(), _port); if (_ac == nullptr) return -1; _ac->data = (void*)this; if (_ac->err) { redisAsyncFree(_ac); _ac = nullptr; return -1; // throw RedisException((std::string)"RedisAsyncConnect: "+_ac->errstr); } if (redisAsyncSetConnectCallback(_ac, &connected)!=REDIS_OK || redisAsyncSetDisconnectCallback(_ac, &disconnected)!=REDIS_OK) { redisAsyncFree(_ac); _ac = nullptr; return -1; // throw RedisException("RedisAsyncConnect: Can't register callbacks"); } #if HIREDISPP_USE_LIBEVENT if (redisLibeventAttach(_ac, (struct event_base *)_loopbase)!=REDIS_OK) { redisAsyncFree(_ac); _ac = nullptr; return -1; // throw RedisException("redisLibeventAttach: nothing should be attached when something is already attached"); } // Send PING command, so libevent start working redisAsyncCommand(_ac, nullptr, nullptr, "PING"); #else // actually start io proccess ev_io_start(EV_DEFAULT, &((((redisLibevEvents*)(_ac->ev.data)))->rev)); ev_io_start(EV_DEFAULT, &((((redisLibevEvents*)(_ac->ev.data)))->wev)); #endif return 0; }
static PHP_METHOD(swoole_redis, connect) { char *host; zend_size_t host_len; long port; zval *callback; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "slz", &host, &host_len, &port, &callback) == FAILURE) { RETURN_FALSE; } if (host_len <= 0) { swoole_php_error(E_WARNING, "host is empty."); RETURN_FALSE; } if (port <= 1 || port > 65535) { swoole_php_error(E_WARNING, "port is invalid."); RETURN_FALSE; } swRedisClient *redis = emalloc(sizeof(swRedisClient)); bzero(redis, sizeof(swRedisClient)); #if PHP_MAJOR_VERSION < 7 redis->object = getThis(); #else redis->object = &redis->_object; memcpy(redis->object, getThis(), sizeof(zval)); #endif sw_zval_add_ref(&redis->object); swoole_set_object(getThis(), redis); redisAsyncContext *context = redisAsyncConnect(host, (int) port); if (context->err) { swoole_php_error(E_WARNING, "connect to redis-server[%s:%d] failed, Erorr: %s[%d]", host, (int) port, context->errstr, context->err); RETURN_FALSE; } php_swoole_check_reactor(); if (!isset_event_callback) { SwooleG.main_reactor->setHandle(SwooleG.main_reactor, PHP_SWOOLE_FD_REDIS | SW_EVENT_READ, swoole_redis_onRead); SwooleG.main_reactor->setHandle(SwooleG.main_reactor, PHP_SWOOLE_FD_REDIS | SW_EVENT_WRITE, swoole_redis_onWrite); isset_event_callback = 1; } redisAsyncSetConnectCallback(context, swoole_redis_onConnect); redisAsyncSetDisconnectCallback(context, swoole_redis_onClose); #if PHP_MAJOR_VERSION < 7 redis->connect_callback = callback; #else redis->connect_callback = &redis->_connect_callback; memcpy(redis->connect_callback, callback, sizeof(zval)); #endif sw_zval_add_ref(&redis->connect_callback); redis->context = context; context->ev.addRead = swoole_redis_event_AddRead; context->ev.delRead = swoole_redis_event_DelRead; context->ev.addWrite = swoole_redis_event_AddWrite; context->ev.delWrite = swoole_redis_event_DelWrite; context->ev.cleanup = swoole_redis_event_Cleanup; context->ev.data = redis; zend_update_property_string(swoole_redis_class_entry_ptr, getThis(), ZEND_STRL("host"), host TSRMLS_CC); zend_update_property_long(swoole_redis_class_entry_ptr, getThis(), ZEND_STRL("port"), port TSRMLS_CC); if (SwooleG.main_reactor->add(SwooleG.main_reactor, redis->context->c.fd, PHP_SWOOLE_FD_REDIS | SW_EVENT_WRITE) < 0) { swoole_php_fatal_error(E_WARNING, "swoole_event_add failed. Erorr: %s[%d].", redis->context->errstr, redis->context->err); RETURN_FALSE; } swConnection *conn = swReactor_get(SwooleG.main_reactor, redis->context->c.fd); conn->object = redis; }
/*** * @function rspamd_redis.make_request({params}) * Make request to redis server, params is a table of key=value arguments in any order * @param {task} task worker task object * @param {ip} host server address * @param {function} callback callback to be called in form `function (task, err, data)` * @param {string} cmd command to be sent to redis * @param {table} args numeric array of strings used as redis arguments * @param {number} timeout timeout in seconds for request (1.0 by default) * @return {boolean} `true` if a request has been scheduled */ static int lua_redis_make_request (lua_State *L) { struct lua_redis_userdata *ud; struct rspamd_lua_ip *addr = NULL; struct rspamd_task *task = NULL; const gchar *cmd = NULL; gint top, cbref = -1; struct timeval tv; gboolean ret = FALSE; gdouble timeout = REDIS_DEFAULT_TIMEOUT; if (lua_istable (L, 1)) { /* Table version */ lua_pushstring (L, "task"); lua_gettable (L, -2); if (lua_type (L, -1) == LUA_TUSERDATA) { task = lua_check_task (L, -1); } lua_pop (L, 1); lua_pushstring (L, "callback"); lua_gettable (L, -2); if (lua_type (L, -1) == LUA_TFUNCTION) { /* This also pops function from the stack */ cbref = luaL_ref (L, LUA_REGISTRYINDEX); } else { msg_err ("bad callback argument for lua redis"); lua_pop (L, 1); } lua_pushstring (L, "cmd"); lua_gettable (L, -2); cmd = lua_tostring (L, -1); lua_pop (L, 1); lua_pushstring (L, "host"); lua_gettable (L, -2); if (lua_type (L, -1) == LUA_TUSERDATA) { addr = lua_check_ip (L, -1); } lua_pop (L, 1); lua_pushstring (L, "timeout"); lua_gettable (L, -2); timeout = lua_tonumber (L, -1); lua_pop (L, 1); if (task != NULL && addr != NULL && cbref != -1 && cmd != NULL) { ud = rspamd_mempool_alloc (task->task_pool, sizeof (struct lua_redis_userdata)); ud->task = task; ud->L = L; ud->cbref = cbref; lua_pushstring (L, "args"); lua_redis_parse_args (L, -1, cmd, ud); ret = TRUE; } else { if (cbref != -1) { luaL_unref (L, LUA_REGISTRYINDEX, cbref); } msg_err ("incorrect function invocation"); } } else if ((task = lua_check_task (L, 1)) != NULL) { addr = lua_check_ip (L, 2); top = lua_gettop (L); /* Now get callback */ if (lua_isfunction (L, 3) && addr != NULL && addr->addr && top >= 4) { /* Create userdata */ ud = rspamd_mempool_alloc (task->task_pool, sizeof (struct lua_redis_userdata)); ud->task = task; ud->L = L; /* Pop other arguments */ lua_pushvalue (L, 3); /* Get a reference */ ud->cbref = luaL_ref (L, LUA_REGISTRYINDEX); cmd = luaL_checkstring (L, 4); if (top > 4) { lua_redis_parse_args (L, 5, cmd, ud); } else { lua_redis_parse_args (L, 0, cmd, ud); } ret = TRUE; } else { msg_err ("incorrect function invocation"); } } if (ret) { ud->terminated = 0; ud->ctx = redisAsyncConnect (rspamd_inet_address_to_string (addr->addr), rspamd_inet_address_get_port (addr->addr)); redisAsyncSetConnectCallback (ud->ctx, lua_redis_connect_cb); if (ud->ctx == NULL || ud->ctx->err) { ud->terminated = 1; redisAsyncFree (ud->ctx); lua_redis_free_args (ud); luaL_unref (ud->L, LUA_REGISTRYINDEX, ud->cbref); lua_pushboolean (L, FALSE); return 1; } redisLibeventAttach (ud->ctx, ud->task->ev_base); ret = redisAsyncCommandArgv (ud->ctx, lua_redis_callback, ud, ud->nargs, (const gchar **)ud->args, NULL); if (ret == REDIS_OK) { rspamd_session_add_event (ud->task->s, lua_redis_fin, ud, g_quark_from_static_string ("lua redis")); double_to_tv (timeout, &tv); event_set (&ud->timeout, -1, EV_TIMEOUT, lua_redis_timeout, ud); event_base_set (ud->task->ev_base, &ud->timeout); event_add (&ud->timeout, &tv); } else { msg_info ("call to redis failed: %s", ud->ctx->errstr); ud->terminated = 1; lua_redis_free_args (ud); redisAsyncFree (ud->ctx); luaL_unref (ud->L, LUA_REGISTRYINDEX, ud->cbref); } } lua_pushboolean (L, ret); return 1; }
/* Internal host connect - Sync or Async */ static int _host_connect( host_t *h, eredis_reader_t *r ) { redisContext *c; if (r) { /* Sync - not in EV context */ c = (h->port) ? redisConnect( h->target, h->port ) : redisConnectUnix( h->target ); if (! c) { fprintf(stderr, "eredis: error: connect sync %s NULL\n", h->target); return 0; } if (c->err) { #if EREDIS_VERBOSE>0 printf( "eredis: error: connect sync %s %d\n", h->target, c->err); #endif redisFree( c ); return 0; } r->ctx = c; r->host = h; } else { redisAsyncContext *ac; /* ASync - in EV context */ ac = (h->port) ? redisAsyncConnect( h->target, h->port ) : redisAsyncConnectUnix( h->target ); if (! ac) { printf( "eredis: error: connect async %s undef\n", h->target); return 0; } if (ac->err) { #if EREDIS_VERBOSE>0 printf( "eredis: error: connect async %s %d\n", h->target, ac->err); #endif redisAsyncFree( ac ); return 0; } h->async_ctx = ac; /* data for _redis_*_cb */ ac->data = h; /* Order is important here */ /* attach */ redisLibevAttach( h->e->loop, ac ); /* set callbacks */ redisAsyncSetDisconnectCallback( ac, _redis_disconnect_cb ); redisAsyncSetConnectCallback( ac, _redis_connect_cb ); c = (redisContext*) ac; } /* Apply keep-alive */ #ifdef HOST_TCP_KEEPALIVE if (h->port) { redisEnableKeepAlive( c ); if (r && (h->e->sync_to.tv_sec||h->e->sync_to.tv_usec)) { redisSetTimeout( c, h->e->sync_to ); } } #endif /* Override the maxbuf */ c->reader->maxbuf = EREDIS_READER_MAX_BUF; return 1; }
static PHP_METHOD(swoole_redis, connect) { char *host; zend_size_t host_len; long port; zval *callback; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "slz", &host, &host_len, &port, &callback) == FAILURE) { RETURN_FALSE; } if (host_len <= 0) { swoole_php_error(E_WARNING, "redis server host is empty."); RETURN_FALSE; } swRedisClient *redis = swoole_get_object(getThis()); redisAsyncContext *context; if (strncasecmp(host, ZEND_STRL("unix:/")) == 0) { context = redisAsyncConnectUnix(host + 5); } else { if (port <= 1 || port > 65535) { swoole_php_error(E_WARNING, "redis server port is invalid."); RETURN_FALSE; } context = redisAsyncConnect(host, (int) port); } if (context->err) { swoole_php_error(E_WARNING, "failed to connect to the redis-server[%s:%d], Erorr: %s[%d]", host, (int) port, context->errstr, context->err); RETURN_FALSE; } php_swoole_check_reactor(); if (!swReactor_handle_isset(SwooleG.main_reactor, PHP_SWOOLE_FD_REDIS)) { SwooleG.main_reactor->setHandle(SwooleG.main_reactor, PHP_SWOOLE_FD_REDIS | SW_EVENT_READ, swoole_redis_onRead); SwooleG.main_reactor->setHandle(SwooleG.main_reactor, PHP_SWOOLE_FD_REDIS | SW_EVENT_WRITE, swoole_redis_onWrite); SwooleG.main_reactor->setHandle(SwooleG.main_reactor, PHP_SWOOLE_FD_REDIS | SW_EVENT_ERROR, swoole_redis_onError); } redisAsyncSetConnectCallback(context, swoole_redis_onConnect); redisAsyncSetDisconnectCallback(context, swoole_redis_onClose); zend_update_property_long(swoole_redis_class_entry_ptr, getThis(), ZEND_STRL("sock"), context->c.fd TSRMLS_CC); zend_update_property(swoole_redis_class_entry_ptr, getThis(), ZEND_STRL("onConnect"), callback TSRMLS_CC); redis->context = context; context->ev.addRead = swoole_redis_event_AddRead; context->ev.delRead = swoole_redis_event_DelRead; context->ev.addWrite = swoole_redis_event_AddWrite; context->ev.delWrite = swoole_redis_event_DelWrite; context->ev.cleanup = swoole_redis_event_Cleanup; context->ev.data = redis; zend_update_property_string(swoole_redis_class_entry_ptr, getThis(), ZEND_STRL("host"), host TSRMLS_CC); zend_update_property_long(swoole_redis_class_entry_ptr, getThis(), ZEND_STRL("port"), port TSRMLS_CC); if (SwooleG.main_reactor->add(SwooleG.main_reactor, redis->context->c.fd, PHP_SWOOLE_FD_REDIS | SW_EVENT_WRITE) < 0) { swoole_php_fatal_error(E_WARNING, "swoole_event_add failed. Erorr: %s[%d].", redis->context->errstr, redis->context->err); RETURN_FALSE; } if (redis->timeout > 0) { php_swoole_check_timer((int) (redis->timeout * 1000)); redis->timer = SwooleG.timer.add(&SwooleG.timer, (int) (redis->timeout * 1000), 0, redis, swoole_redis_onTimeout); } sw_zval_add_ref(&redis->object); swConnection *conn = swReactor_get(SwooleG.main_reactor, redis->context->c.fd); conn->object = redis; }
static int dispatch_data_thread_init(dispatch_data_thread *ddt, char *test_target_groups, int connections) { int i, j, k; ddt->id = 0; ddt->thread_id = 0; ddt->el = NULL; ddt->hz = 10; ddt->cronloops = 0; ddt->datas = NULL; ddt->rdatas = NULL; ddt->abgs = NULL; ddt->pause = 0; ddt->count_wait_for_reply = 0; ddt->reply_total_count_per_cycle = 0; ddt->reply_type_err_count_per_cycle = 0; ddt->el = aeCreateEventLoop(200); if (ddt->el == NULL) { return VRT_ERROR; } ddt->datas = dmtqueue_create(); if (ddt->datas == NULL) { return VRT_ERROR; } if (dmtqueue_init_with_lockqueue(ddt->datas, NULL) != 0) { return VRT_ERROR; } ddt->rdatas = dlistCreate(); if (ddt->rdatas == NULL) { return VRT_ERROR; } ddt->abgs = abtest_groups_create(test_target_groups); if (ddt->abgs == NULL) { return VRT_ERROR; } /* Init connection context for each server */ for (i = 0; i < darray_n(ddt->abgs); i ++) { abtest_group *abg = darray_get(ddt->abgs, i); for (j = 0; j < darray_n(&abg->abtest_servers); j ++) { abtest_server *abs = darray_get(&abg->abtest_servers, j); abs->conn_contexts = darray_create(connections, sizeof(conn_context)); for (k = 0; k < connections; k ++) { conn_context *cc = darray_push(abs->conn_contexts); if (dispatch_conn_context_init(cc,abs->host,abs->port) != VRT_OK) { return VRT_ERROR; } cc->actx->data = ddt; redisAeAttach(ddt->el, cc->actx); redisAsyncSetConnectCallback(cc->actx,connect_callback); redisAsyncSetDisconnectCallback(cc->actx,disconnect_callback); } } } if (aeCreateTimeEvent(ddt->el, 1, dispatch_data_thread_cron, ddt, NULL) == AE_ERR) { return VRT_ERROR; } return VRT_OK; }