放入消息
/** * 获取beanstalk实例 * * @staticvar resource|bool $beanstalk * @return resource */ function get_beanstalk() { static $beanstalk = FALSE; if ($beanstalk) { return $beanstalk; } include_once APPPATH . 'libraries/beanstalkd/pheanstalk_init.php'; //加载配置文件 $CI =& get_instance(); $CI->config->load('beanstalkd'); $bean_config = $CI->config->item('beanstalk_server'); $beanstalk = new Pheanstalk_Pheanstalk($bean_config['host'], $bean_config['port']); return $beanstalk; } /** * 发送到队列函数 * * @param string $tube 队列名称 * @param string $info 写入到队列的信息 * @param int $priority 队列优先级 * @param int $delay 迁移到正式发送队列的延迟时间 * @param int $ttr 队列reserve后的过期时间 * @return bool */ function send2queue($tube, $info, $priority = 1024, $delay = 0, $ttr = 60) { $pheanstalk = get_beanstalk(); $res = $pheanstalk->useTube($tube)->put( $info, $priority, $delay, $ttr ); return $res; }
自动脚本读取队列,发送消息
/** * 發送邮件 */ public function send_email() { $pheanstalk = get_beanstalk(); while ( $job = $pheanstalk->watch(Queue::SEND_EMAIL)->ignore("default")->reserve() ) { $res = $job->getData(); $res = json_decode($res, TRUE); $email_cc = ''; $email_bcc = ''; if(isset($res['email_addr'],$res['email_title'],$res['email_content'])) { if (isset($res['email_cc'])) $email_cc = $res['email_cc']; if (isset($res['email_bcc'])) $email_bcc = $res['email_bcc']; $ret = send_email($res['email_addr'],$res['email_title'],$res['email_content'],$email_cc,$email_bcc); if(!$ret) { log_msg('queue_send_email_error.log','email_addr:'.$res['email_addr'].' email_title:'.$res['email_title'].' email_cc:'.$email_cc.' email_bcc:'.$email_bcc.' email_content:'.$res['email_content']); } } $pheanstalk->delete($job); } } function send_email($to, $subject, $content, $cc='', $bcc='') { include_once APPPATH . 'libraries/swiftmailer/swift_required.php'; $transport = Swift_SmtpTransport::newInstance('mail.fastweb.com.cn', 25) ->setUsername('11@qq.com') ->setPassword('safasfafa'); $mailer =Swift_Mailer::newInstance($transport); $message = Swift_Message::newInstance() ->setSubject($subject) ->setFrom(array('11@qq.com' =>'qq管理员')) ->setTo($to) ->setContentType('text/html') ->setCharset('utf-8') ->setBody($content); $cc != '' && $message->setCc($cc); $bcc != '' && $message->setBcc($bcc); return $mailer->send($message); }