Example Application of Memcache

Source: Internet
Author: User

First, the most common memcache application 1, cache data from the database query results;
2, save the session control information.
Second, Case 1,cache data results from a database query
The results of querying the database are cached using the memcached server to reduce the frequent database connections and the pressure on the database caused by a large number of queries.
Design principles:
(1), as long as the records in the database have not changed, there is no need to reconnect the database and repeatedly execute repeated query statements, (2), the same query results should be obtained from the cache server.
  
 
  1. <?php
  2. /** 该函数用于执行有结果集的SQL语句,并将结果缓存到memcached服务器中
  3. @paramstring$sql 有结果集的查询语句SQL
  4. @paramobject$memcacheMemcache类的对象
  5. @return$data返回结果集的数据 */
  6. function select($sql, Memcache $memcache){
  7. /* md5 SQL命令 作为 memcache的唯一标识符*/
  8. $key = md5($sql);
  9. /* 先从memcached服务器中获取数据 */
  10. $data = $memcache->get($key);
  11. /* 如果$data为false那么就是没有数据, 那么就需要从数据库中获取 */
  12. if(!$data) {
  13. try{ //很有必要将连接数据库的过程单独处理
  14. $pdo = new PDO("mysql:host=localhost;dbname=dbtest", "mysql_user", "mysql_pass");
  15. }catch(PDOException $e){
  16. die("连接失败:".$e->getMessage());
  17. }
  18. $stmt = $pdo->prepare($sql);
  19. $stmt->execute();
  20. /* 从数据库中获取数据,返回二维数组$data */
  21. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  22. /* 这里向memcached服务器写入从数据库中获取的数据*/
  23. $memcache -> add($key, $data, MEMCACHE_COMPRESSED, 0);
  24. }
  25. return $data;
  26. }
  27. $memcache = new Memcache;
  28. /* 可以使用addServer()方法添加多台memcached服务器 */
  29. $memcache -> connect(‘localhost‘, 11211);
  30. /* 第一次运行还没有缓存数据, 会读取一次数据库, 当再次访问程序时, 就直接从memcache获取*/
  31. $data = select("SELECT * FROM user", $memcache);
  32. var_dump($data); //输出数据



From for notes (Wiz)

Example Application of Memcache

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.