public function mc() { $mc = new MyMemcache(); $mc->get('abc'); $mc->set('abc', '1'); $mc->increment('abc', 3); $mc->decrement('abc'); }
/** * 请求http地址前先查MC是否缓存了结果 * @param string $req 请求url,必传参数 * @param int $expire MC失效时间,默认10分钟。 * @param array $header 默认为空。示例$header = array('Host: www.dagger.com'); * @param int $timeout 超时设定,默认为5秒 * @param string $cookie 默认为空。示例 $cookie="fruit=apple; colour=red"; * @param int $redo 请求失败后重试次数,默认为0 * @param int $maxredirect 如果遇上跳转,跳转几次后返回。默认为2 * @return string * @author */ public static function getWithMC($req, $expire = '', $header, $timeout = BaseModelHttp::DAGGER_HTTP_TIMEOUT, $cookie = '', $redo = 1, $maxredirect = BaseModelHttp::DAGGER_HTTP_MAXREDIRECT) { self::debugMCInfo(); $mc = new MyMemcache(); $mcResultKey = __FUNCTION__ . '|' . md5(serialize(func_get_args())); $result = $mc->get($mcResultKey); if (empty($result)) { $result = self::get($req, $header, $timeout, $cookie, $redo, $maxredirect); $expire = intval($expire); if (empty($expire)) { $expire = Http::$MC_EXPIRE_TIME; } $mc->set($mcResultKey, $result, $expire); } return $result; }
protected function getConfig() { //配置 if (!self::$config) { self::$config = (include MEMCACHE_PATH . "config/config.php"); } }
function getUserId() { if (isset($_POST['token'])) { $token = $_POST['token']; } else { $token = $_GET['token']; } $memcache = new MyMemcache(); $userId = $memcache->get($token); $memcache->close(); if (!$userId) { $res = ['ok' => 0, 'error' => 'token not valid']; echo json_encode($res); die; } return $userId; }
public static function set($key_footer = null, $data = array()) { if (self::$_redis) { //开启了redis缓存 return MyRedis::set($key_footer, $data); } elseif (self::$_memcache) { //开启了memcache缓存 return MyMemcache::set($key_footer, $data); } else { return false; } }
public function test_mem() { $mem = MyMemcache::connect(); if ($mem) { var_dump(MyMemcache::get('name')); var_dump(MyMemcache::set('news', 'sumshine')); var_dump(MyMemcache::get('news')); var_dump(MyMemcache::del('news')); var_dump(MyMemcache::get('news')); var_dump(MyMemcache::getAllKeysValues()); } else { echo 'not have connect memcache'; } }
protected function getMemcache() { try { //是否已经实例化 if (!self::$_connect) { $memcache = new memcache(); self::$_connect = $memcache; } else { $memcache = self::$_connect; } if ($memcache) { $memcache->connect(self::$_config['host'], self::$_config['port']); return $memcache; } else { return false; } } catch (Exception $e) { Log::write($e->getMessage(), "ERR", 3, "memcache"); return false; } }
/** * getConn * * @Access public * @Return void */ private static function getConn() { global $memServers; if (empty($memServers)) { return FALSE; } if (!extension_loaded('memcache')) { MyException::Exception('请先安装PHP中Memcache模块'); } if (empty(self::$m)) { $m = new Memcache(); //系统默认对象 foreach ($memServers as $key => $value) { $m->addServer($key, $value); } self::$m = $m; } if (empty(self::$prefix)) { self::$prefix = $_SERVER['SINASRV_MEMCACHED_KEY_PREFIX'] ? $_SERVER['SINASRV_MEMCACHED_KEY_PREFIX'] : 'Reluc-'; } return self::$m; }
/** * mtiTheading 多线程单例,双重锁 * * @Access public * @Return void */ public static function mtiTheading($tabName, $UserModel) { if (empty($UserModel)) { if (empty(self::$SingTon)) { self::$SingTon = new Model(); } $singTon = serialize(self::$SingTon); $model = MyMemcache::get('model'); if (empty($model)) { MyMemcache::set('model', $singTon); } return unserialize(MyMemcache::get('model')); } else { if (empty(self::$userModel[$tabName])) { self::$userModel[$tabName] = new $UserModel(); } $singTon = serialize(self::$userModel[$tabName]); $model = MyMemcache::get($tabName); if (empty($model)) { MyMemcache::set($tabName, $singTon); } return unserialize(MyMemcache::get($tabName)); } }
<?php include 'global.php'; $rs = MyRedis::getInstance(); $mc = new MyMemcache(); $mc->set('a', array(1, 2, 3)); $rs->set('a', array(1, 2, 3)); print_r($rs->get('a')); print_r($mc->get('a'));
*/ include "../Visitor.php"; $_GET['userId'] = getUserId(); $KeyList = array('userId', 'footprintId'); foreach ($KeyList as $k => $v) { if (!isset($_GET[$v])) { $res = ['ok' => 0, 'error' => "param invalid "]; echo json_encode($res); die; } } $mysql = new Mysql(); $result = $mysql->select("*", "footprint", "`footId`", "'{$_GET['footprintId']}'"); if ($result) { if ($result['userId'] == $_GET['userId']) { $myMemcache = new MyMemcache(); $footprintId = $result['id']; $removeFootprint = "delete from footprint where id={$footprintId}"; //echo $removeFootprint; $mysql->query($removeFootprint); $myMemcache->delete($_GET['userId'] . "foot" . $result['footId']); if ($myMemcache->get("like" . $result['footId']) && $myMemcache->get("like" . $result['footId']) == 1) { //$removeFoot="delete from foot where id={$result['footId']}"; //$mysql->query($removeFoot); } echo json_encode(['ok' => 1]); } else { echo json_encode(['ok' => 0, 'error' => "no permission"]); die; } } else {
//$_GET['initiative']="http://www.baidu.co"; //$_GET['title']="http://www.baidu.com"; //$_GET['time']=21324; if (!isset($_GET['footId'])) { $KeyList = array('userId', 'url', 'title', 'time'); foreach ($KeyList as $k => $v) { if (!isset($_GET[$v])) { $res = ['ok' => 0, 'error' => "param invalid "]; echo json_encode($res); return; } } } $mysql = new Mysql(); //连接数据库 $myMemcache = new MyMemcache(); if (isset($_GET['footId'])) { $_GET['like'] = $myMemcache->get("like" . $_GET['footId']) ? $myMemcache->get("like" . $_GET['footId']) + 1 : 1; $_GET['id'] = $_GET['footId']; $FootList = array('id', 'like'); $mysql->update("foot", "like", "{$_GET['like']}", "id", "{$_GET['id']}"); } else { $memValue = $myMemcache->get($_GET['url']); if ($memValue) { $_GET['id'] = $memValue; $footprintId = $myMemcache->get($_GET['userId'] . "foot:" . $_GET['id']); if ($footprintId) { echo json_encode(['ok' => 1, 'data' => [id => $footprintId]]); die; } $_GET['like'] = $myMemcache->get("like" . $_GET['id']) ? $myMemcache->get("like" . $_GET['id']) + 1 : 1;
} if (isset($key)) { $key .= ",`" . $v . "`"; $value .= ",'" . mysql_real_escape_string($_POST[$v]) . "'"; } else { $key = "`" . $v . "`"; $value = "'" . mysql_real_escape_string($_POST[$v]) . "'"; } } $mysql = new Mysql(); //连接数据库 $userName = $_POST['userName']; $result = $mysql->select("*", 'user', '`username`', "'{$userName}'"); if (!$result) { $mysql->replace("user", "{$key}", "{$value}"); $userId = mysql_insert_id(); $mysql->close(); } else { $res = ['ok' => 0, 'error' => 'username existed']; echo json_encode($res); die; } $myMemcache = new MyMemcache(); $expireTime = 7 * 24 * 3600; $token = md5(uniqid(rand(), TRUE)); $myMemcache->set("u" . $userId, $token, $expireTime); $myMemcache->set($token, $userId, $expireTime); $myMemcache->close(); $user = [userId => $userId, token => $token, expireTime => $expireTime]; $res = [ok => 1, data => $user]; echo json_encode($res);
$a['key' . $i] = $i; } $mcd->setMulti($a, 10); $t1 = microtime(true) - $starttime; $starttime = microtime(true); $mc = new MyMemcache(); for ($i = 0; $i < 100; $i++) { $a['key' . $i] = $i; $mc->set('key' . $i, $i, 10); } $t2 = microtime(true) - $starttime; var_dump($t1, $t2, $t2 - $t1); exit; var_dump($mc->get('test')); var_dump($mcd->setMulti('test', 1, 5)); var_dump($mc->getMulti(array('test'))); sleep(5); var_dump($mc->get('test')); var_dump($mc->getMulti(array('test'))); exit; Log::sendLog(100, "[{$absDataPath}]看了还看数据推送异常。联系zhixiong1@,6883,15810834486。"); exit; echo 1; sleep(30); $mc = new MyMemcache(); var_dump($mc->add("aa", 1, 10)); var_dump($mc->add("aa", 1, 10)); var_dump($mc->get("aa")); var_dump($mc->delete("aa")); var_dump($mc->get("aa")); var_dump($mc->add("aa", 1, 10));
//打印出所有的 错误信息 ini_set('error_log', dirname(__FILE__) . '/error_log.txt'); include "../Visitor.php"; $userId = getUserId(); $mysql = new Mysql(); //$regular=new Regular(null); //$regular->host="http://www.google.com/"; //$regular->threshold=100; //$regulars[]=$regular; // //$regular=new Regular(null); //$regular->host="http://www.jd.com/"; //$regular->threshold=10000; //$regulars[]=$regular; //var_dump($_POST['data']); $regulars = json_decode($_POST['data']); $myMemcache = new MyMemcache(); foreach ($regulars as $item) { $key = $item->threshold . "_" . $item->host; if ($myMemcache->get($key)) { $id = $myMemcache->get($key); } else { $mysql->insert("regular", "`host`,`threshold`", "'{$item->host}','{$item->threshold}'"); $id = mysql_insert_id(); $myMemcache->set($key, $id); } $time = time(); $mysql->replace("user_regular", "`user_id`,`regular_id`,`time`", "'{$userId}','{$id}','{$time}'"); } $data = json_encode($regulars); echo $data;
protected static function Eexecute($conn, $sql, $executeArray = array(), $isSelect = FALSE) { try { if (defined('MEMCACHE_START')) { $data = MyMemcache::getCache($sql); if (!empty($data)) { return $data; } } $startTime = microtime(TRUE); $STMT = $conn->prepare($sql); $result = empty($executeArray) ? $STMT->execute() : $STMT->execute($executeArray); if ($result) { if (DEBUG) { if (!empty($executeArray)) { $SQL = self::comSQL($sql, $executeArray); } //好方法 $SQL = empty($SQL) ? $sql : $SQL; } if ($isSelect) { while ($row = $STMT->fetch(PDO::FETCH_ASSOC)) { $data[] = $row; } self::StopTime($SQL, $startTime); if (defined('MEMCACHE_START')) { //缓存结果集到Memcache中 MyMemcache::addCache(self::$tabName, $sql, $data); } return empty($data) ? NULL : $data; } else { if (strstr($sql, 'insert')) { self::StopTime($SQL, $startTime); return self::$InsertId = $conn->lastinsertid(); } self::StopTime($SQL, $startTime); return $STMT->rowCount(); //受影响行,这个只针对update,delete } } else { if (DEBUG) { Debug::addmsg('<font color="red">请检查您的SQL: ' . $sql . '</font>', 2); } } } catch (PDOException $e) { if (DEBUG) { MyException::Exceptions('请确认您的SQL语句:<b>' . $sql . '</b><br />' . $e->getMessage(), $e->getTrace()); } } }
<?php /** * Created by PhpStorm. * User: shaoting * Date: 15/7/25 * Time: 下午2:33 */ include "../memcache.php"; $myMemcache = new MyMemcache(); $expireTime = 7 * 24 * 3600; $userId = time() / 10 % 10000; $token = $myMemcache->get("u" . $userId); while ($token) { $userId = $userId * 2; $token = $myMemcache->get($userId); } $token = md5(uniqid(rand(), TRUE)); $myMemcache->set("u" . $userId, $token); $myMemcache->set($token, $userId); $myMemcache->close(); $user = [userId => $userId, token => $token]; $res = [ok => 1, data => $user]; echo json_encode($res); include '../Mysql.php'; $mysql = new Mysql(); //连接数据库 $userName = "******" . $userId; $mysql->insert("user", "`userId`,`userName`", "'{$userId}','{$userName}'"); //插入数据 $mysql->close();
public function mem() { $mem = MyMemcache::connect(); if ($mem) { var_dump(MyMemcache::get('memcache')); var_dump(MyMemcache::set('memcache', 'mymemcache')); var_dump(MyMemcache::get('memcache')); var_dump(MyMemcache::del('memcache')); var_dump(MyMemcache::get('memcache')); var_dump(MyMemcache::getAllKeysValues()); } else { echo 'not have connect memcache'; } }
//__autoload函数 require PATH_ROOT . 'config/DBConfig.php'; //载入数据库配置 //==========取代global.php功能==========// $time = time(); $db = new QueueRuntimeModelDB(); $sql = "SELECT * FROM " . $db->getTableName() . " WHERE `begin_time` < ?"; $data = $db->getData($sql, array($time - 60 * 50)); if (!empty($data)) { $ndb = new ProjectModelDB(); $queueConfigDB = new QueueConfigModelDB(); foreach ($data as $v) { $row = $ndb->getRow("SELECT `id`,`key`,`name` FROM `" . $ndb->getTableName() . "` WHERE `id` = ?", array($v['project_id'])); $task = trim(array_shift(explode(' ', $v['task']))); $runTimeConfig = $queueConfigDB->getFirst("SELECT `time` FROM `" . $queueConfigDB->getTableName() . "` WHERE `project_id` = ? AND `task` = ?", array($v['project_id'], $task)); if (empty($runTimeConfig)) { $runTimeConfig = 50; } $runTime = intval(($time - $v['begin_time']) / 60); if ($runTime >= $runTimeConfig) { $message = "[{$row['name']}]的队列[{$v['task']}]于[" . date("Y-m-d H:i:s", $v['begin_time']) . "]在[{$v['ip']}]开始运行,目前已超过{$runTime}分钟!"; // 多个监控点,同一次错误只提醒一次 $mc = new MyMemcache(); $mcKey = md5($message . $row['key'] . $row['id']); if ($mc->addPlain($mcKey, 1, 50)) { BaseModelHttp::sendRequest(array('http://i.alarm.mix.sina.com.cn/alarm.php', array('pid' => $row['id'], 'key' => $row['key'], 'sys_mid' => 8, 'code' => 1, 'message' => $message, 'name' => '队列超时', 'client_ip' => '127.0.0.1'))); // BaseModelHttp::sendRequest(array('http://i.alarm.mix.sina.com.cn/alarm.php',array('pid'=>1,'key'=>'b662346b2d7da90b8413a5ee095c8ff4','sys_mid'=>8,'code'=>1,'message'=>$message,'name'=>'队列超时','client_ip'=>'127.0.0.1'))); } } } }
/** * 返回结果集的第一条记录的第一个字段。 * 支持MC的数据查询,只查询从库。因为查询主库不应该读取memcache数据 */ public function getFirstWithMC($sql, $data = '', $expire = '') { $expire = intval($expire); if (empty($expire)) { $expire = $this->MC_EXPIRE_TIME; } $mc = new MyMemcache(); $args = func_get_args(); $mcResultKey = __FUNCTION__ . '|' . md5(implode('', array(serialize($args), $this->DBName))); //结果的mckey $result = $mc->get($mcResultKey); $needQueryDB = $result === false; if ($needQueryDB) { $result = $this->getFirst($sql, $data, 'slave'); $result && $mc->set($mcResultKey, $result, $expire); } else { } return $result; }
include './Public/Function/Function.php'; if (defined('MEMCACHE') && MEMCACHE) { if (extension_loaded('memcache')) { if (!MyMemcache::ConnectError()) { Debug::addmsg('<font color="red">连接memcache服务器失败,请确认IP或端口正确!</font>'); } else { Debug::addmsg('开启Memcache'); } } else { Debug::addmsg('<font color="red">PHP没有安装memcache扩展模块,请先安装!</font>'); } } else { Debug::addmsg('<span style="color:red;">[未使用Memcache]</span>'); } if (IS_SESSION_TO_MEMCACHE && MEMCACHE) { SessionToMem::start(MyMemcache::getMemcache()); Debug::addmsg('开启Session==>Memcache'); } else { session_start(); } Debug::addmsg('SessionID: ' . session_id()); if (empty($_SESSION['configMtime'])) { $_SESSION['configMtime'] = filemtime('./Public/Config.inc.php'); } if (filemtime('./Public/Config.inc.php') > $_SESSION['configMtime']) { Struct::init(); //当修改配置文件,同样执行一次框架结构类 //自动根据数据库驱动切换继承关系 $_SESSION['configMtime'] = filemtime('./Public/Config.inc.php'); $String = file_get_contents(RELUC_DIR . 'Kernel/Model.class.php'); $replaceMent = 'extends Base' . ucfirst(strtolower(DB_DRIVER)) . "\n";