This document summarizes different caching techniques that can be used with PHP, including caching content, database caching, and memory caching using APCU, Memcached, and Redis. It provides code examples for storing, getting, and deleting values from the cache with each technique. Specifically, it shows how to cache objects in memory and check the cache before querying a database to improve performance.
В связи с ростом трафика и необходимостью объемного анализа данных, большие данные стали одной из самых популярных областей в сфере IT, и многие компании в настоящее время работают над этим вопросом — развертывают кластеры проекта Hadoop, который в настоящее время является самой популярной платформой для обработки больших данных. В докладе в доступной форме будут представлены вопросы обеспечения безопасности Hadoop или, точнее, их принципы, а также продемонстрированы различные векторы атак на кластер.
A brief overview of caching mechanisms in a web application. Taking a look at the different layers of caching and how to utilize them in a PHP code base. We also compare Redis and MemCached discussing their advantages and disadvantages.
We all love Ehcache. But the rise of real-time Big Data means you want to keep larger amounts of data in memory with low, predictable latency. In this webinar,
we explain how BigMemory Go can turbocharge your Ehcache deployment.
Adobe AEM Maintenance - Customer Care Office HoursAndrew Khoury
This presentation covers how to maintain Adobe Experience Manager 6.x (AEM / CQ / Communiqué) environments.
See the presentation video here:
https://helpx.adobe.com/experience-manager/kt/eseminars/ccoo-aem-Aug-recording.html
A common request sent from your web browser to a web server goes quite a long way and it can take a great deal of time until the data your browser can display are fetched back. I will talk about making this great deal of time significantly less great by caching things on different levels, starting with client-side caching for faster display and minimizing transferred data, storing results of already performed operations and computations and finishing with lowering the load of database servers by caching result sets. Cache expiration and invalidation is the hardest part so I will cover that too. Presentation will be focused mainly on PHP, but most of the principles are quite general work elsewhere too.
В связи с ростом трафика и необходимостью объемного анализа данных, большие данные стали одной из самых популярных областей в сфере IT, и многие компании в настоящее время работают над этим вопросом — развертывают кластеры проекта Hadoop, который в настоящее время является самой популярной платформой для обработки больших данных. В докладе в доступной форме будут представлены вопросы обеспечения безопасности Hadoop или, точнее, их принципы, а также продемонстрированы различные векторы атак на кластер.
A brief overview of caching mechanisms in a web application. Taking a look at the different layers of caching and how to utilize them in a PHP code base. We also compare Redis and MemCached discussing their advantages and disadvantages.
We all love Ehcache. But the rise of real-time Big Data means you want to keep larger amounts of data in memory with low, predictable latency. In this webinar,
we explain how BigMemory Go can turbocharge your Ehcache deployment.
Adobe AEM Maintenance - Customer Care Office HoursAndrew Khoury
This presentation covers how to maintain Adobe Experience Manager 6.x (AEM / CQ / Communiqué) environments.
See the presentation video here:
https://helpx.adobe.com/experience-manager/kt/eseminars/ccoo-aem-Aug-recording.html
A common request sent from your web browser to a web server goes quite a long way and it can take a great deal of time until the data your browser can display are fetched back. I will talk about making this great deal of time significantly less great by caching things on different levels, starting with client-side caching for faster display and minimizing transferred data, storing results of already performed operations and computations and finishing with lowering the load of database servers by caching result sets. Cache expiration and invalidation is the hardest part so I will cover that too. Presentation will be focused mainly on PHP, but most of the principles are quite general work elsewhere too.
In today’s systems , the time it takes to bring data to the end-user can be very long, especially under heavy load. An application can often increase performance by using an appropriate caching system. There are many caching level that you can use in our application today : CDN, In-Memory/Local Cache, Distributed Cache, Outut Cache, Browser Cache, Html Cache
In this last years a lot of high traffic web sites have been built in PHP. One of the main problem to design a distributed PHP architecture is how to share session data between multiple servers. In this presentation we showed the most used solutions to scale a PHP application along multiple servers. We presented different solutions to share session data using open source solutions (nfs, databases, memcached, redis, etc). Moreover we talk about Zend Server Cluster Manager, an enterprise ready Web Application Server for running and managing an HA Cluster of PHP servers.
Improving Website Performance with Memecached Webinar | Achieve InternetAchieve Internet
Improving the performance and scalability of your Drupal website with a Memcached implementation.
In this webinar, you will learn about:
• The components of a Memcached system
• Installing a simple Memcached installation
• Complex distributed installations and when to use them
• Verifying the installation
With the advent of Hadoop, there comes the need for professionals skilled in Hadoop Administration making it imperative to be skilled as a Hadoop Admin for better career, salary and job opportunities.
Make WordPress Fly With Virtual Server Hosting - WordCamp Sydney 2014Vlad Lasky
Presentation slides from Vladimir Lasky's talk "Make WordPress Fly With Virtual Server Hosting", presented on Sunday 28th September at WordCamp Sydney 2014.
Achieving Massive Scalability and High Availability for PHP Applications in t...RightScale
RightScale User Conference NYC 2011 -
Joshua Solomin - Senior Product Marketing Manager, Zend Technologies
It's a common pain point among PHP developers: How do you achieve application-level elasticity while never losing a user session when you scale down servers? Now there's a push-button solution from Zend and RightScale that enables persistent sessions and allows you to readily triage problems with your business-critical PHP applications. This session will introduce you to an auto-scaling PaaS solution specifically designed to make it easier for you to deploy and manage cloud-based, highly available PHP server clusters.
Like all frameworks, Drupal comes with a performance cost, but there are many ways to minimise that cost.
This session explores different and complementary ways to improve performance, covering topics such as caching techniques, performance tuning, and Drupal configuration.
We'll touch on benchmarking before presenting the results from applying each of the performance techniques against copies of a number of real-world Drupal sites.
Securing Your WordPress Website - WordCamp Sydney 2012Vlad Lasky
Presentation slides from Vladimir Lasky's talk "Security for WordPress", presented on Sunday 22nd July at WordCamp Sydney 2012.
This talk is the sequel to his WordCamp Gold Coast 2011 presentation “Securing Your WordPress Website” and covers:
*Tackling the biggest Internet and WordPress security threats of 2012
*An updated list of essential plugins to harden your WordPress site
*New WordPress management services that make it easier to back up and update your sites
MySQL Enterprise Backup: Backup & Recovery Performance tests, full and partial restores, comparisons using MySQL Utilities, using transportable tablespaces, etc.
A simple scenario on a small environment, using ubuntu a laptop and an external hd, showing how to use MEB and leave mysqldump to those specific situations, and reduce backup and restore times via MEB and single-image files, extracting specific .ibd or .frm's and recover the lost rows, or a dropped table.
Memcache is a high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load.
In today’s systems , the time it takes to bring data to the end-user can be very long, especially under heavy load. An application can often increase performance by using an appropriate caching system. There are many caching level that you can use in our application today : CDN, In-Memory/Local Cache, Distributed Cache, Outut Cache, Browser Cache, Html Cache
In this last years a lot of high traffic web sites have been built in PHP. One of the main problem to design a distributed PHP architecture is how to share session data between multiple servers. In this presentation we showed the most used solutions to scale a PHP application along multiple servers. We presented different solutions to share session data using open source solutions (nfs, databases, memcached, redis, etc). Moreover we talk about Zend Server Cluster Manager, an enterprise ready Web Application Server for running and managing an HA Cluster of PHP servers.
Improving Website Performance with Memecached Webinar | Achieve InternetAchieve Internet
Improving the performance and scalability of your Drupal website with a Memcached implementation.
In this webinar, you will learn about:
• The components of a Memcached system
• Installing a simple Memcached installation
• Complex distributed installations and when to use them
• Verifying the installation
With the advent of Hadoop, there comes the need for professionals skilled in Hadoop Administration making it imperative to be skilled as a Hadoop Admin for better career, salary and job opportunities.
Make WordPress Fly With Virtual Server Hosting - WordCamp Sydney 2014Vlad Lasky
Presentation slides from Vladimir Lasky's talk "Make WordPress Fly With Virtual Server Hosting", presented on Sunday 28th September at WordCamp Sydney 2014.
Achieving Massive Scalability and High Availability for PHP Applications in t...RightScale
RightScale User Conference NYC 2011 -
Joshua Solomin - Senior Product Marketing Manager, Zend Technologies
It's a common pain point among PHP developers: How do you achieve application-level elasticity while never losing a user session when you scale down servers? Now there's a push-button solution from Zend and RightScale that enables persistent sessions and allows you to readily triage problems with your business-critical PHP applications. This session will introduce you to an auto-scaling PaaS solution specifically designed to make it easier for you to deploy and manage cloud-based, highly available PHP server clusters.
Like all frameworks, Drupal comes with a performance cost, but there are many ways to minimise that cost.
This session explores different and complementary ways to improve performance, covering topics such as caching techniques, performance tuning, and Drupal configuration.
We'll touch on benchmarking before presenting the results from applying each of the performance techniques against copies of a number of real-world Drupal sites.
Securing Your WordPress Website - WordCamp Sydney 2012Vlad Lasky
Presentation slides from Vladimir Lasky's talk "Security for WordPress", presented on Sunday 22nd July at WordCamp Sydney 2012.
This talk is the sequel to his WordCamp Gold Coast 2011 presentation “Securing Your WordPress Website” and covers:
*Tackling the biggest Internet and WordPress security threats of 2012
*An updated list of essential plugins to harden your WordPress site
*New WordPress management services that make it easier to back up and update your sites
MySQL Enterprise Backup: Backup & Recovery Performance tests, full and partial restores, comparisons using MySQL Utilities, using transportable tablespaces, etc.
A simple scenario on a small environment, using ubuntu a laptop and an external hd, showing how to use MEB and leave mysqldump to those specific situations, and reduce backup and restore times via MEB and single-image files, extracting specific .ibd or .frm's and recover the lost rows, or a dropped table.
Memcache is a high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load.
<p>Your Drupal 8 site is fantastic: you've spent hours/weeks/months working on it, the work is flawless and the customer is delighted - what are you going to need to fly this thing? Which PHP tips, tricks and tunings will help your site perform exceptionally at scale. </p>
<p>There are some significant differences in PHP/FPM performance tuning between Drupal 7 and Drupal 8, and this session will help you understand them. The old adage is true: the more things change, the more they stay the same - we'll revisit some of the 'tried and true' tips to keep your sites up and performant in the crush of traffic that occurs when your content goes viral. </p>
<p>Join us to learn about:</p>
<ul>
<li>Brief glance over Best Practices for Performance Tuning</li>
<li>PHP tuning including OPcache and APC User Cache</li>
<li>Varnish, Memcache, and Database tips</li>
<li>The Software Stack, with Drupal 8 integration tips.</li>
</ul>
Complex applications need a persistent database to store, search and join data: till now a dedicated server was needed to do this, and no offline usage of the app was possible. With the introduction of HTML5 and the concept of Web Databases, we don’t need an external server anymore: everything is stored within the user browser and thus the web app can be used offline as well as online.
Building High Performance and Scalable Applications Using AppFabric Cache- Im...Impetus Technologies
For Impetus’ White Papers archive, visit- http://www.impetus.com/whitepaper
Most applications face challenges related to robustness, speed, and scalability. This paper focuses on Windows Server AppFabric, which provides a distributed in‐memory cache for applications data.
Improving Website Performance with Memecached Webinar | Achieve InternetAchieve Internet
Improving the performance and scalability of your Drupal website with a Memcached implementation.
In this webinar, you will learn about:
• The components of a Memcached system
• Installing a simple Memcached installation
• Complex distributed installations and when to use them
• Verifying the installation
Developing High Performance and Scalable ColdFusion Applications Using Terrac...Shailendra Prasad
1. How to scale – options (pros and cons)
2. Caching basics (various options available)
3. Recent updates of Open source Ehcache project.
4. Scaling your existing application with Ehcache, Terracotta OSS
5. Advance caching techniques for scaling using Terracotta BigMemory
6. Customer use cases where caching was mission critical
Complex applications need a persistent database to store, search and join data: till now a dedicated server was needed to do this, and no offline usage of the app was possible. With the introduction of HTML5 and the concept of Web Databases, we don’t need an external server anymore: everything is stored within the user browser and thus the web app can be used offline as well as online.
Scaleable PHP Applications in KubernetesRobert Lemke
Kubernetes is also called the "distributed Linux of the cloud" – which implies that it provides fundamental infrastructure, which can solve a lot of challenges. Let’s see how PHP applications fit into this picture. In this presentation, we are going to explore when Kubernetes is a good fit for operating your PHP application and how it can be done in practice. We’ll look at the whole lifecycle: how to build your application, create or choose the right Docker images, deploy and scale, and how to deal with performance and monitoring. At the end you will have a good understanding about all the different stages and building blocks for running a PHP application with Kubernetes in production.
ER(Entity Relationship) Diagram for online shopping - TAEHimani415946
https://bit.ly/3KACoyV
The ER diagram for the project is the foundation for the building of the database of the project. The properties, datatypes, and attributes are defined by the ER diagram.
This 7-second Brain Wave Ritual Attracts Money To You.!nirahealhty
Discover the power of a simple 7-second brain wave ritual that can attract wealth and abundance into your life. By tapping into specific brain frequencies, this technique helps you manifest financial success effortlessly. Ready to transform your financial future? Try this powerful ritual and start attracting money today!
1.Wireless Communication System_Wireless communication is a broad term that i...JeyaPerumal1
Wireless communication involves the transmission of information over a distance without the help of wires, cables or any other forms of electrical conductors.
Wireless communication is a broad term that incorporates all procedures and forms of connecting and communicating between two or more devices using a wireless signal through wireless communication technologies and devices.
Features of Wireless Communication
The evolution of wireless technology has brought many advancements with its effective features.
The transmitted distance can be anywhere between a few meters (for example, a television's remote control) and thousands of kilometers (for example, radio communication).
Wireless communication can be used for cellular telephony, wireless access to the internet, wireless home networking, and so on.
Multi-cluster Kubernetes Networking- Patterns, Projects and GuidelinesSanjeev Rampal
Talk presented at Kubernetes Community Day, New York, May 2024.
Technical summary of Multi-Cluster Kubernetes Networking architectures with focus on 4 key topics.
1) Key patterns for Multi-cluster architectures
2) Architectural comparison of several OSS/ CNCF projects to address these patterns
3) Evolution trends for the APIs of these projects
4) Some design recommendations & guidelines for adopting/ deploying these solutions.
4. WHAT IS CACHE?
In computing, a cache, is a hardware or software
component that stores data so future requests for
that data can be served faster; the data stored in
a cache might be the result of an earlier computation,
or the duplicate of data stored elsewhere.[1]
“ “
[1] https://en.wikipedia.org/wiki/Cache_(computing)
5. CACHING TECHNIQUES
There are different caching methods that we can use with
PHP:
➤ Caching content
We can cache content in PHP by saving the final output of a specific
script into the filesystem then simply serving it like a static file for a
specific period of time instead of executing the original script.
6. CACHING TECHNIQUES
There are different caching methods that we can use with
PHP:
➤ Caching content
We can cache content in PHP by saving the final output of a specific
script into the filesystem then simply serving it like a static file for a
specific period of time instead of executing the original script.
➤ Database Cache
Caching the caching is done by the database server itself. This works
by caching the results of the query so the query is only parsed the first
time it runs and in the succeeding requests it won’t be parsed since the
results from the specific query is already cached by the database
server.
7. CACHING TECHNIQUES
There are different caching methods that we can use with
PHP:
➤ Caching content
We can cache content in PHP by saving the final output of a specific
script into the filesystem then simply serving it like a static file for a
specific period of time instead of executing the original script.
➤ Database Cache
Caching the caching is done by the database server itself. This works
by caching the results of the query so the query is only parsed the first
time it runs and in the succeeding requests it won’t be parsed since the
results from the specific query is already cached by the database
server.
➤ Memory Cache
Memory caching techniques are widely used; they use the volatile
memory data and are a lot more faster than caching in the file system.
8. MEMORY CACHING
Memory caching techniques are widely used; they use the volatile memory
data and are a lot more faster than caching in the file system.
➤ APCU [2]
Alternative PHP Cache User Cache (APCU) provides a full backwards
compatible API to the shared memory userland cache provided by APC.
[2] http://php.net/manual/en/intro.apcu.php
9. MEMORY CACHING
Memory caching techniques are widely used; they use the volatile memory
data and are a lot more faster than caching in the file system.
➤ APCU [2]
Alternative PHP Cache User Cache (APCU) provides a full backwards
compatible API to the shared memory userland cache provided by APC.
➤ MEMCACHED [3]
Memcached is an in-memory key-value store for small chunks of
arbitrary data (strings, objects) from results of database calls, API calls,
or page rendering.
[2] http://php.net/manual/en/intro.apcu.php
[3] https://memcached.org/
10. MEMORY CACHING
Memory caching techniques are widely used; they use the volatile memory
data and are a lot more faster than caching in the file system.
➤ APCU [2]
Alternative PHP Cache User Cache (APCU) provides a full backwards
compatible API to the shared memory userland cache provided by APC.
➤ MEMCACHED [3]
Memcached is an in-memory key-value store for small chunks of
arbitrary data (strings, objects) from results of database calls, API calls,
or page rendering.
➤ REDIS [4]
Redis is an open source (BSD licensed), in-memory data structure
store, used as a database, cache and message broker.
[2] http://php.net/manual/en/intro.apcu.php
[3] https://memcached.org/
[4] https://redis.io/
11. APCU
APCu (APC User Cache) is APC stripped of opcode caching.
The first APCu codebase was versioned 4.0.0, it was forked from the head
of the APC master branch at the time.
PHP 7 support is available as of APCu 5.0.0.
APCu can provide a compatibility mode, such that it can provide a drop in
replacement for the applicable parts of APC.
12. APCU IN PHP
<?php
// Set a value
apcu_store('foo', 'bar', 7200);
apcu_store('integer', 12345678, 7200);
apcu_store('boolean', true, 7200);
apcu_store('array', ['apple', 'banana', 'pear'], 7200);
apcu_store('object', serialize(new MyAwesomeClass()), 7200);
// Get a value
apcu_fetch(‘foo’);
// Delete a value
apcu_delete(‘foo’);
// Flush the cache
apcu_clear_cache();
13. APCU IN PHP(2)
<?php
// ..
$myCacheKey = 'my_cache_key';
$row = apcu_fetch($myCacheKey);
if (!$row) {
// Issue painful query to mysql
$sql = "SELECT * FROM table WHERE id = :id";
$dbo->prepare($sql);
$stmt->bindValue(':id', $someId, PDO::PARAM_INT);
$row = $stmt->fetch(PDO::FETCH_OBJ);
apcu_store($myCacheKey, serialize($row));
}
// Now I have access to $row, where I can do what I need to
// And for subsequent calls, the data will be pulled from cache and skip
// the query altogether
var_dump(unserialize($row));
14. MEMCACHED
Memcached is a distributed caching system in RAM for objects, and is
widely used in dynamic web applications to relieve the load on the
database, making it possible to serve some of the data to which access is
most frequent, directly from RAM memory .
15. MEMCACHED
Memcached is a distributed caching system in RAM for objects, and is
widely used in dynamic web applications to relieve the load on the
database, making it possible to serve some of the data to which access is
most frequent, directly from RAM memory .
Memcached was created in 2003 by the company operating LiveJournal,
Danga Interactive, which had to handle more than 20 million exponential
dynamic daily requests. The adoption of this innovative caching system
has made it possible to drastically reduce the load on database servers
and significantly improve site performance.
16. MEMCACHED
Memcached is a distributed caching system in RAM for objects, and is
widely used in dynamic web applications to relieve the load on the
database, making it possible to serve some of the data to which access is
most frequent, directly from RAM memory .
Memcached was created in 2003 by the company operating LiveJournal,
Danga Interactive, which had to handle more than 20 million exponential
dynamic daily requests. The adoption of this innovative caching system
has made it possible to drastically reduce the load on database servers
and significantly improve site performance.
The software was then publicly released under the BSD license that
allowed it to be implemented by other web giants and the inevitable
addition of many features and constant performance enhancement.
Among the most famous memcached users we find informatics giants
such as WordPress, Wikipedia, Flickr, Twitter, YouTube, Digg and
Facebook.
17. MEMCACHED IN PHP
<?php
// Get Connection
$memcached = new Memcached();
$memcached->addServer('localhost', 11211);
// Set a value
$memcached->set('foo', 'bar', 7200);
$memcached->set('integer', 12345678, 7200);
$memcached->set('boolean', true, 7200);
$memcached->set('array', ['apple', 'banana', 'pear'], 7200);
$memcached->set('object', serialize(new MyAwesomeClass()), 7200);
// Get a value
$memcached->get(‘foo');
// Update a value
$memcached->replace('foo', 'barbar', 10200);
// Change TTL
$memcached->touch('foo', 29000);
// Delete a value
$memcached->delete('foo');
// Flush the cache
$memcached->flush();
18. MEMCACHED IN PHP(2)
<?php
// ..
$memcached = new Memcached();
$memcached->addServer('localhost', 11211);
$myCacheKey = 'my_cache_key';
$row = $cache->get($myCacheKey);
if (!$row) {
// Issue painful query to mysql
$sql = "SELECT * FROM table WHERE id = :id";
$dbo->prepare($sql);
$stmt->bindValue(':id', $someId, PDO::PARAM_INT);
$row = $stmt->fetch(PDO::FETCH_OBJ);
$memcached->set($myCacheKey, serialize($row));
}
// Now I have access to $row, where I can do what I need to
// And for subsequent calls, the data will be pulled from cache and skip
// the query altogether
var_dump(unserialize($row));
19. REDIS
Redis is an in-memory database open-source software project sponsored
by Redis Labs. It is networked, in-memory, and stores keys with optional
durability.
20. REDIS
Redis is an in-memory database open-source software project sponsored
by Redis Labs. It is networked, in-memory, and stores keys with optional
durability.
The name Redis means REmote DIctionary Server.
Salvatore Sanfilippo, the original developer of Redis, was hired by
VMware in March, 2010. In May, 2013, Redis was sponsored by Pivotal
Software (a VMware spin-off). In June 2015, development became
sponsored by Redis Labs.
21. REDIS
Redis is an in-memory database open-source software project sponsored
by Redis Labs. It is networked, in-memory, and stores keys with optional
durability.
The name Redis means REmote DIctionary Server.
Salvatore Sanfilippo, the original developer of Redis, was hired by
VMware in March, 2010. In May, 2013, Redis was sponsored by Pivotal
Software (a VMware spin-off). In June 2015, development became
sponsored by Redis Labs.
According to monthly rankings by DB-Engines.com, Redis is often ranked
the most popular key-value database. Redis has also been ranked the #4
NoSQL database in user satisfaction and market presence based on
user reviews, the most popular NoSQL database in containers, and the #1
NoSQL database among Top 50 Developer Tools & Services.
22. REDIS
Redis is an in-memory database open-source software project sponsored
by Redis Labs. It is networked, in-memory, and stores keys with optional
durability.
The name Redis means REmote DIctionary Server.
Salvatore Sanfilippo, the original developer of Redis, was hired by
VMware in March, 2010. In May, 2013, Redis was sponsored by Pivotal
Software (a VMware spin-off). In June 2015, development became
sponsored by Redis Labs.
According to monthly rankings by DB-Engines.com, Redis is often ranked
the most popular key-value database. Redis has also been ranked the #4
NoSQL database in user satisfaction and market presence based on
user reviews, the most popular NoSQL database in containers, and the #1
NoSQL database among Top 50 Developer Tools & Services.
Someone defines Redis as “Memcached on Steroids”.
23. REDIS IN PHP
PRedis [5] is flexible and feature-complete Redis client for PHP and
HHVM by Daniele Alessandri.
[5] https://github.com/nrk/predis
24. REDIS DATA TYPES:
STRINGS
The Redis String type is the simplest type of value you can associate with
a Redis key. It is the only data type in Memcached, so it is also very
natural for newcomers to use it in Redis.
25. REDIS DATA TYPES:
STRINGS
The Redis String type is the simplest type of value you can associate with
a Redis key. It is the only data type in Memcached, so it is also very
natural for newcomers to use it in Redis.
If you don’t provide a ttl, the element will be persisted permanenty.
<?php
// Get Connection
$client = new PRedisClient();
// Set a string
$client->set('foo', 'bar', 7200);
$client->set('integer', 12345678, 7200);
$client->set('boolean', true, 7200);
$client->set('array', ['apple', 'banana', 'pear'], 7200);
$client->set('object', serialize(new MyAwesomeClass()), 7200);
// delete a value
$client->del(‘foo’);
// Get a string value
$client->get(‘foo');
26. REDIS DATA TYPES: LISTS
Redis lists are collections of string elements sorted according to the order
of insertion. They are basically linked lists.
27. REDIS DATA TYPES: LISTS
Redis lists are collections of string elements sorted according to the order
of insertion. They are basically linked lists.
<?php
// Set a hash
$client->lpush(’buylist’, ’apple');
$client->lpush(’buylist’, ’pie’);
$client->rpush(’buylist’, ’pineapple’);
// Get a string value
$client->lrange(‘buylist’, 0, -1); // [‘pie’, ‘apple’, ‘pineapple’]
// Remove the last two occurrences of ‘apple’ in the list
$client->lrem,(‘buylist’, -2, ’apple');
28. REDIS DATA TYPES: SETS
Redis Sets are collections of unique, unsorted string elements.
29. REDIS DATA TYPES: SETS
Redis Sets are collections of unique, unsorted string elements.
<?php
// Create ‘tag:user:1’ a set
$client->sadd(’tags:user:1’, ’apple');
$client->sadd(’tags:user:1’, ’pie');
$client->sadd(’tags:user:1’, ’pineapple’);
// Get a set value
$client->smembers(‘tags:user:1’); // [‘apple’, ‘pie’, ’pineapple’]
$client->srem(’tags:user:1’, ’pineapple’); // removes ‘pineapple’ key
30. REDIS DATA TYPES: SETS
Redis Sets are collections of unique, unsorted string elements.
<?php
// Create ‘tag:user:1’ a set
$client->sadd(’tags:user:1’, ’apple');
$client->sadd(’tags:user:1’, ’pie');
$client->sadd(’tags:user:1’, ’pineapple’);
// Get a set value
$client->smembers(‘tags:user:1’); // [‘apple’, ‘pie’, ’pineapple’]
$client->srem(’tags:user:1’, ’pineapple’); // removes ‘pineapple’ key
<?php
// Create some set
$client->sadd(’car:make:ford’, ’fiesta');
$client->sadd(’car:make:ford’, ’focus');
$client->sadd(’car:make:maserati’, ’quattroporte’);
// Retrieve all ford molds
$client->smembers(‘car:make:ford’); // [‘fiesta’, ‘focus’]
CREATE AN INDEX
31. REDIS DATA TYPES:
SORTED SETS
Similar to Sets but where every string element is associated to a floating
number value, called score. The elements are always taken sorted by
their score, so unlike Sets it is possible to retrieve a range of elements
32. REDIS DATA TYPES:
SORTED SETS
Similar to Sets but where every string element is associated to a floating
number value, called score. The elements are always taken sorted by
their score, so unlike Sets it is possible to retrieve a range of elements
<?php // Create fruits sorted set
$client->zadd(’fruits’, 1, ’apple’);
$client->zadd(’fruits’, 2, ’pie’);
$client->zadd(’fruits’, 2.2, ’pineapple’);
// get fruits sorted set
$client->zrange(‘fruits’, 0, 1, [‘withscores’ => true]);
$client->zrem(’fruits’, ’pineapple’); // removes ‘pineapple’ key
33. REDIS DATA TYPES:
SORTED SETS
Similar to Sets but where every string element is associated to a floating
number value, called score. The elements are always taken sorted by
their score, so unlike Sets it is possible to retrieve a range of elements
<?php // Create fruits sorted set
$client->zadd(’fruits’, 1, ’apple’);
$client->zadd(’fruits’, 2, ’pie’);
$client->zadd(’fruits’, 2.2, ’pineapple’);
// get fruits sorted set
$client->zrange(‘fruits’, 0, 1, [‘withscores’ => true]);
$client->zrem(’fruits’, ’pineapple’); // removes ‘pineapple’ key
<?php // Create fruits sorted set
$client->zadd(’fruits’, 0, ’apple’);
$client->zadd(’fruits’, 0, ’pie’);
$client->zadd(’fruits’, 0, ’pineapple’);
// Get all fruits sorted set with scores
$client->zrangebylex(‘fruits’, 0, -1, [‘limit’ => [20, 5]]);
LEXICOGRAPHICAL SORTING
34. REDIS DATA TYPES:
HASHES
Hashes, which are maps composed of fields associated with values.
Both the field and the value are strings
While hashes are handy to represent objects, actually the number of fields
you can put inside a hash has no practical limits (other than available
memory), so you can use hashes in many different ways inside your
application.
35. REDIS DATA TYPES:
HASHES
Hashes, which are maps composed of fields associated with values.
Both the field and the value are strings
While hashes are handy to represent objects, actually the number of fields
you can put inside a hash has no practical limits (other than available
memory), so you can use hashes in many different ways inside your
application.
<?php
// Set a hash
$client->hset(’user:1’, ’name’, ‘Mauro');
$client->hset(’user:1’, ’surname’, ‘Cassani');
$client->hset(’user:1’, ’email’, ‘mauretto1978@yahoo.it’);
// Get a string value
$client->hget(‘user:1’, ’name’); // Mauro
// Delete hash
$client->hdel(‘user:1’, ’name’); // deletes Mauro
// Get a string value
$client->hgetall(‘user:1’); // full array
36. REDIS KEYS AND SCANS
➤ KEYS - returns all keys matching pattern.
37. REDIS KEYS AND SCANS
➤ KEYS - returns all keys matching pattern.
➤ SCAN - iterates the set of keys in the currently selected Redis database.
38. REDIS KEYS AND SCANS
➤ KEYS - returns all keys matching pattern.
➤ SCAN - iterates the set of keys in the currently selected Redis database.
➤ SSCAN - iterates elements of Sets types.
39. REDIS KEYS AND SCANS
➤ KEYS - returns all keys matching pattern.
➤ SCAN - iterates the set of keys in the currently selected Redis database.
➤ SSCAN - iterates elements of Sets types.
➤ HSCAN - iterates fields of Hash types and their associated values.
40. REDIS KEYS AND SCANS
➤ KEYS - returns all keys matching pattern.
➤ SCAN - iterates the set of keys in the currently selected Redis database.
➤ SSCAN - iterates elements of Sets types.
➤ HSCAN - iterates fields of Hash types and their associated values.
➤ ZSCAN - iterates elements of Sorted Set types and their associated scores.
41. REDIS KEYS AND SCANS
<?php
$client->keys(’user:*’) // Search for all keys starting by user
foreach (new IteratorKeyspace($client, 'predis:*') as $key) { // SCAN
}
foreach (new IteratorSetKey($client, 'predis:set') as $member) { //
SSCAN
}
foreach (new IteratorSortedSetKey($client, 'predis:zset') as $member =>
$rank) { // ZSCAN
}
foreach (new IteratorHashKey($client, 'predis:hset') as $field =>
$value) { // HSCAN
}
➤ KEYS - returns all keys matching pattern.
➤ SCAN - iterates the set of keys in the currently selected Redis database.
➤ SSCAN - iterates elements of Sets types.
➤ HSCAN - iterates fields of Hash types and their associated values.
➤ ZSCAN - iterates elements of Sorted Set types and their associated scores.
43. BRIEF COMPARISON (2)
APCU MEMCACHED REDIS
clustering ✓ ✓
multi-threaded ✓
replication ✓
key length 256 bytes 512 Mb
max value size 1 Mb 1 Mb 512 Mb
data volume
max size
3.5 TiB 4.7 TiB+
read/write +++ +++ ++
storage type in memory in memory disk + in memory
cli ✓ ✓
44. REAL WORLD USE CASE
Think on this:
➤ You have some lists coming from your database or your API;
45. REAL WORLD USE CASE
Think on this:
➤ You have some lists coming from your database or your API;
➤ You want to perform some queries on your lists;
46. REAL WORLD USE CASE
Think on this:
➤ You have some lists coming from your database or your API;
➤ You want to perform some queries on your lists;
➤ For example, imagine you want to display hundred of POIs in Google
Maps, and allow the user to make some query via a dropdown
menu, or maybe you want to allow your users to perform a simple
text search on your list;
47. REAL WORLD USE CASE
Think on this:
➤ You have some lists coming from your database or your API;
➤ You want to perform some queries on your lists;
➤ For example, imagine you want to display hundred of POIs in Google
Maps, and allow the user to make some query via a dropdown
menu, or maybe you want to allow your users to perform a simple
text search on your list;
➤ You want your site is super-fast (so you won’t to make more queries on
you db);
48. REAL WORLD USE CASE
Think on this:
➤ You have some lists coming from your database or your API;
➤ You want to perform some queries on your lists;
➤ For example, imagine you want to display hundred of POIs in Google
Maps, and allow the user to make some query via a dropdown
menu, or maybe you want to allow your users to perform a simple
text search on your list;
➤ You want your site is super-fast (so you won’t to make more queries on
you db);
➤ Of course, you need to cache your data!
49. REAL WORLD USE CASE
Think on this:
➤ You have some lists coming from your database or your API;
➤ You want to perform some queries on your lists;
➤ For example, imagine you want to display hundred of POIs in Google
Maps, and allow the user to make some query via a dropdown
menu, or maybe you want to allow your users to perform a simple
text search on your list;
➤ You want your site is super-fast (so you won’t to make more queries on
you db);
➤ Of course, you need to cache your data!
HOW TO ACHIEVE IT?
50. APPROACH “A”
<?php
// With Memcached
if(!$m->get(‘lista')){ // apcu_fetch with APCu
$m->set('lista', $arrayOfElements, $ttl); // apcu_store with APCu
}
foreach ($m->get('lista') as $key => $item){ // apcu_fetch with APCu
$item = unserialize($item); // ...
}
51. APPROACH “A”
<?php
// With Redis
if(!$c->keys('lista')){
foreach ($arrayOfElements as $item){
$c->hset('lista', $item->{id}, serialize($item));
}
}
foreach ($c->hgetall('lista') as $key => $item){
$item = unserialize($item); // ...
}
<?php
// With Memcached
if(!$m->get(‘lista')){ // apcu_fetch with APCu
$m->set('lista', $arrayOfElements, $ttl); // apcu_store with APCu
}
foreach ($m->get('lista') as $key => $item){ // apcu_fetch with APCu
$item = unserialize($item); // ...
}
52. APPROACH “B”
<?php // With Memcached
foreach ($originalArray as $element) {
$m->set('lista:'.$element->id, serialize($element), $ttl); // apcu_store
$arrayOfIdElements[(string) $element->id] = 'lista:'.$element->id;
}
$m->set('lista', $arrayOfIdElements, $ttl);
foreach ($m->get('lista') as $key){ // apcu_fetch with APCu
$item = $m->get($key); // ... // apcu_fetch with APCu
}
53. APPROACH “B”
<?php // With Redis
$list = $c->keys('lista:*');
if(!$list){
foreach ($arrayOfElements as $item){
$c->hset('lista:'.$item->id, 'element', serialize($item));
}
}
foreach ($list as $item) {
$item = unserialize($c->hget($item, 'element'));
}
<?php // With Memcached
foreach ($originalArray as $element) {
$m->set('lista:'.$element->id, serialize($element), $ttl); // apcu_store
$arrayOfIdElements[(string) $element->id] = 'lista:'.$element->id;
}
$m->set('lista', $arrayOfIdElements, $ttl);
foreach ($m->get('lista') as $key){ // apcu_fetch with APCu
$item = $m->get($key); // ... // apcu_fetch with APCu
}
58. IN-MEMORY LIST
In-memory List [6] is a PHP library that allows you to create and store in
memory your lists, and then quickly retrieve and perform queries on it.
[6] https://github.com/mauretto78/in-memory-list
64. BASIC USAGE
<?php
use InMemoryListApplicationClient;
$array = [...];
$client = new Client();
$collection = $client->create($array);
foreach ($collection as $element){
$item = $client->item($element);
// ...
}
Now you can iterate over all elements:
67. DRIVERS
$client = new Client('redis', $redis_params); // Redis
<?php
use InMemoryListApplicationClient;
$client = new Client('apcu'); // Apcu
$client = new Client('memcached', $memcached_params); // Memcached
You can use APCU, Memcached or Redis:
69. PARAMETERS
When use create method to generate a list, you can provide to it a
parameters array. The allowed keys are:
<?php
use InMemoryListApplicationClient;
$array = [...];
$client = new Client();
$collection = $client->create($array, $parameters);
70. PARAMETERS
When use create method to generate a list, you can provide to it a
parameters array. The allowed keys are:
➤ uuid - uuid of list
<?php
use InMemoryListApplicationClient;
$array = [...];
$client = new Client();
$collection = $client->create($array, $parameters);
71. PARAMETERS
When use create method to generate a list, you can provide to it a
parameters array. The allowed keys are:
➤ uuid - uuid of list
➤ element-uuid - uuid for the list elements
<?php
use InMemoryListApplicationClient;
$array = [...];
$client = new Client();
$collection = $client->create($array, $parameters);
72. PARAMETERS
When use create method to generate a list, you can provide to it a
parameters array. The allowed keys are:
➤ uuid - uuid of list
➤ element-uuid - uuid for the list elements
➤ headers - headers array for the list
<?php
use InMemoryListApplicationClient;
$array = [...];
$client = new Client();
$collection = $client->create($array, $parameters);
73. PARAMETERS
When use create method to generate a list, you can provide to it a
parameters array. The allowed keys are:
➤ uuid - uuid of list
➤ element-uuid - uuid for the list elements
➤ headers - headers array for the list
➤ index - add the list elements to cache index or not
<?php
use InMemoryListApplicationClient;
$array = [...];
$client = new Client();
$collection = $client->create($array, $parameters);
74. PARAMETERS
When use create method to generate a list, you can provide to it a
parameters array. The allowed keys are:
➤ uuid - uuid of list
➤ element-uuid - uuid for the list elements
➤ headers - headers array for the list
➤ index - add the list elements to cache index or not
➤ chunk-size - the chunks size in which the array will be splitted
(integer)
<?php
use InMemoryListApplicationClient;
$array = [...];
$client = new Client();
$collection = $client->create($array, $parameters);
75. PARAMETERS
When use create method to generate a list, you can provide to it a
parameters array. The allowed keys are:
➤ uuid - uuid of list
➤ element-uuid - uuid for the list elements
➤ headers - headers array for the list
➤ index - add the list elements to cache index or not
➤ chunk-size - the chunks size in which the array will be splitted
(integer)
➤ ttl - time to live of the list (in seconds)
<?php
use InMemoryListApplicationClient;
$array = [...];
$client = new Client();
$collection = $client->create($array, $parameters);
76. QUERIES
<?php
use InMemoryListApplicationClient;
use InMemoryListApplicationQueryBuilder;
$array = [...];
$client = new Client();
$collection = $client->create($array, [‘uuid' => 'simple-array']);
$qb = new QueryBuilder($collection);
$qb
->addCriteria('title', 'Mario', 'CONTAINS')
->addCriteria('group_id', '45')
->addCriteria('rate', '3', '>')
->orderBy(‘title')
->limit(30);
foreach ($qb->getResults() as $element){
$item = $client->item($element);
// ...
}
79. FINAL RECAP: WHO WINS?
Small Projects No great differences
High traffic websites ✓ Memcached
Real-time applications,
secondary database persist
✓ Redis