« Mettre en cache » : différence entre les versions

De MoodleDocs
Aller à :navigation, rechercher
(Page créée avec « {{Performance}} {{Traduction}} en:Caching »)
 
Aucun résumé des modifications
Ligne 2 : Ligne 2 :
{{Traduction}}
{{Traduction}}


Un cache est un ensemble de données traitées qui sont conservées et réutilisées afin d'éviter des requêtes répétées et coûteuses dans la base de données.
Moodle 2.4 a vu l'implémentation de MUC, le Moodle Universal Cache. Ce nouveau système permet à certaines fonctions de Moodle (par exemple la récupération des chaînes de caractères) de tirer profit des différents services de cache installés (par exemple les fichiers, ram, memcached).
Dans les futures versions de Moodle, nous continuerons à étendre le nombre de fonctions Moodle qui utilisent MUC, ce qui continuera à améliorer les performances, mais vous pouvez déjà commencer à l'utiliser pour améliorer votre site.
==Approche générale des tests de performance==
Voici la stratégie générale que vous devriez adopter :
# Construisez un environnement de test aussi proche que possible de votre instance de production réelle (matériel, logiciel, réseau, etc.)
# Assurez-vous de supprimer autant de variables non contrôlées que possible de cet environnement (par exemple d'autres services)
# Utilisez un outil pour placer une charge réaliste, mais simulée et répétable sur votre serveur. (par exemple jmeter ou selenium).
# Décider d'une façon de mesurer la performance du serveur en capturant les données (RAM, charge, temps pris, etc.)
# Exécutez votre charge et mesurez un résultat de performance de base.
# Changez une variable à la fois et ré-exécutez la charge pour voir si la performance s'améliore ou se détériore. Répéter au besoin.
# Lorsque vous découvrez des paramètres qui se traduisent par une amélioration constante des performances, appliquez-les à votre site de production.
==Configuration du cache dans Moodle==
Depuis Moodle 2.4, Moodle fournit une structure de plugin de mise en cache pour donner aux administrateurs la possibilité de contrôler où Moodle stocke les données en cache. Pour la plupart des sites Moodle, la configuration par défaut devrait être suffisante et il n'est pas nécessaire de changer la configuration. Pour les grands sites Moodle avec plusieurs serveurs, les administrateurs peuvent utiliser memcached, mongodb ou d'autres systèmes pour stocker les données du cache. L'écran du plugin de cache offre aux administrateurs la possibilité de configurer les données du cache qui sont stockées où.<br />.
La mise en cache dans Moodle est contrôlée par ce qui est connu sous le nom de Moodle Universal Cache. Communément appelé MUC.
Ce document explique brièvement ce qu'est MUC avant d'entrer dans le détail des concepts et des options de configuration qu'il offre.
==Les concepts de base du cache dans Moodle==
La mise en cache dans Moodle n'est pas aussi complexe qu'il n'y paraît. Un peu de connaissance de base vous permettra de mieux comprendre le fonctionnement de la configuration du cache.
===Type de caches===
Commençons par les types de cache (parfois appelés mode). Il existe trois types de caches de base dans Moodle.
Le premier est le cache de l'application. C'est de loin le type de cache le plus couramment utilisé dans le code. Ses informations sont partagées par tous les utilisateurs et ses données persistent entre les demandes. L'information stockée ici est généralement mise en cache pour l'une des deux raisons suivantes : soit il s'agit d'une information requise pour la majorité des demandes et nous permet d'économiser une ou plusieurs interactions de base de données, soit il s'agit d'une information qui est consultée moins fréquemment mais qui nécessite des ressources importantes pour générer.<br />
Par défaut, ces informations sont stockées dans une structure organisée dans votre répertoire de données Moodle.
Le deuxième type de cache est le cache de session. C'est exactement comme la session PHP que vous connaissez déjà, en fait elle utilise la session PHP par défaut. Vous vous demandez peut-être pourquoi nous avons ce type de cache, mais la réponse est simple. Le MUC fournit un moyen géré de stocker et de supprimer l'information requise entre les demandes. Il offre aux développeurs un cadre à utiliser plutôt que d'avoir à réinventer la roue et assure que nous avons accès à un moyen contrôlé de gérer le cache comme requis. <br />
Il est important de noter qu'il ne s'agit pas d'un type de cache fréquemment utilisé car par défaut, les données du cache de session sont stockées dans la session PHP et la session PHP est stockée dans la base de données. Les utilisations du type cache de session sont limitées à de petits ensembles de données car nous ne voulons pas gonfler les sessions et donc mettre la base de données à rude épreuve.
Le troisième et dernier type est le cache de requête. Les données stockées dans ce type de cache ne persistent que pendant toute la durée de vie de la requête. Si vous êtes un développeur PHP, pensez-y comme une variable statique gérée.<br />>
C'est de loin le moins utilisé des trois types de cache, les utilisations sont souvent limitées aux informations qui seront consultées plusieurs fois dans une même requête, généralement par plus d'une zone de code.
Les informations mises en cache sont stockées en mémoire par défaut.
==== Types de cache et systèmes à serveurs multiples ====
Si vous avez un système avec plusieurs serveurs Web frontaux, le cache de l'application doit être partagé entre les serveurs. En d'autres termes, vous ne pouvez pas utiliser le stockage local rapide pour le cache de l'application, mais vous devez utiliser le stockage partagé ou une autre forme de cache partagé telle qu'un cache memc partagé.
Il en va de même pour le cache de session, à moins que vous n'utilisiez un mécanisme de "sessions bloquées" pour garantir que, dans une session, les utilisateurs accèdent toujours au même serveur frontal.
===Arrière-plan de mise en cache===
Les arrière-plan de cache sont l'endroit où les données sont réellement stockées. Il s'agit notamment du système de fichiers, de la session php, de Memcached et de la mémoire.<br />
Par défaut, seuls le système de fichiers, la session php et la mémoire sont utilisés dans Moodle.<br />
Nous n'exigeons pas qu'un site ait accès à d'autres systèmes comme Memcached. Au lieu de cela, c'est vous qui êtes responsable de l'installation et de la configuration.<br />
Lorsque les arrière-plans de cache sont mentionnés, pensez à des systèmes en dehors de Moodle qui peuvent être utilisés pour stocker des données. Le serveur MongoDB, le serveur Memcache et les applications "serveur" similaires.
===Mémoires de cache===
Les mémoires de cache sont un type de plugin dans Moodle. Ils facilitent la connexion de Moodle aux arrière-plans du cache dont il a été question plus haut. Le Moodle standard a les trois valeurs par défaut mentionnées ci-dessus ainsi que Memcache, Memcached, MongoDB, [[Cache utilisateur APC (APCu)]] et [[Mémoire cache Redis|Redis]].
Vous pouvez trouver d'autres plugins de cache dans la base de données [https://moodle.org/plugins/browse.php?list=category&id=48 plugins].
Le code de ces derniers se trouve dans le cache/mémoire de votre répertoire racine de Moodle.
Dans Moodle, vous pouvez configurer autant de mémoires cache que votre architecture l'exige. Si vous avez plusieurs serveurs Memcache par exemple, vous pouvez créer une instance de cache pour chacun d'eux. Moodle contient par défaut trois instances de cache qui sont utilisées lorsque vous n'avez effectué aucune autre configuration.
* Une instance de stockage de fichiers est créée qui est utilisée pour tous les caches d'applications. Il stocke ses données dans votre répertoire moodledata.
* Une instance de stockage de session est créée qui est utilisée pour tous les caches de session. Il stocke ses données dans la session PHP, qui par défaut est stockée dans votre base de données.
* Une instance de mémoire statique est créée qui est utilisée pour tous les types de cache de requête. Les données n'existent en mémoire que pour la durée de vie d'une requête.
===Caches : ce qui se passe dans le code===
Les caches sont créés en code et sont utilisés par le développeur pour stocker les données qu'il estime nécessaire de mettre en cache.<br />
Gardons cette section agréable et courte parce que vous n'êtes peut-être pas un développeur. Il y a un point très important que vous devez savoir à propos.<br />
Le développeur n'a pas son mot à dire sur l'endroit où les données sont mises en cache. Ils doivent spécifier les informations suivantes lors de la création d'un cache à utiliser.
# Le type de cache dont ils ont besoin.
# La zone de code à laquelle ce cache appartiendra (l'API si vous voulez).
# Le nom de la cache, quelque chose qu'ils inventent pour décrire en un mot ce que le cache contient.
Il y a plusieurs exigences et paramètres optionnels qu'ils peuvent également spécifier, mais ne vous inquiétez pas de cela à ce stade.<br />
Le point important est qu'ils ne peuvent pas choisir quel arrière-plan de cache utiliser, ils peuvent seulement choisir le type de cache qu'ils veulent parmi les trois détaillés ci-dessus.
===Comment ils se lient entre eux===
La meilleure façon de le décrire est de le faire en relation avec les rôles joués au sein d'une organisation.
# L'administrateur système installe les arrière-plans de cache que vous souhaitez utiliser. Memcache, XCache, APC, etc.<br /> Moodle n'est pas au courant, ils sont en dehors de la portée de Moodle et de la responsabilité purement de votre administrateur système.
# L'administrateur de Moodle crée une instance de mémoire de cache dans Moodle pour chaque arrière-plan que le site utilisera.<br /> Il peut y avoir une ou plusieurs instances de mémoire de cache pour chaque arrière-plan. Certains arrière-plans comme Memcached ont des paramètres pour créer des espaces séparés dans un arrière-plan.
# Le développeur a créé des caches en code et les utilise pour stocker des données. <br /> Il ne sait rien sur la façon dont vous allez utiliser vos caches, il crée juste un "cache" et dit à Moodle quel type est le mieux pour lui.
# L'administrateur Moodle crée un mappage entre une instance de cache et un cache.<br /> Ce mappage indique à Moodle d'utiliser l'arrière-plan que vous spécifiez pour stocker les données que le développeur veut en cache.
De plus, vous pouvez aller encore plus loin.
* Vous pouvez mapper plusieurs caches vers une seule instance de la mémoire cache.
* Vous pouvez mapper plusieurs instances de la mémoire cache vers une seule mémoire cache avec priorité (primaire... final)
* Vous pouvez mapper une instance de mémoire cache comme étant la mémoire par défaut utilisée pour toutes les caches d'un type spécifique qui n'ont pas autrement de mappages spécifiques.
Si c'est la première fois que vous lisez un article sur le cache universel de Moodle, cela semble probablement assez complexe, mais ne vous inquiétez pas, il sera discuté plus en détail au fur et à mesure que nous travaillerons sur la configuration du cache dans Moodle.
==Concepts avancés==
Ces concepts sont des choses que la plupart des sites n'auront pas besoin de connaître ou de se préoccuper.
Vous ne devriez commencer à chercher ici que si vous cherchez à maximiser les performances sur de grands sites fonctionnant sur des services en cluster avec des arrière-plan de cache partagés, ou encore sur une architecture multi-sites où les informations sont partagées entre sites.
===Verrouillage===
L'idée de verrouillage n'est pas nouvelle, c'est le processus de contrôle d'accès afin d'éviter les problèmes de concurrence.
MUC a un deuxième type de plugin, un plugin de verrouillage de cache qui est utilisé lorsque les caches l'exigent. Jusqu'à présent, aucun cache n'en a eu besoin. Une cache par nature est volatile et toute information qui est absolument essentielle à la mission devrait être une base de données plus permanente, probablement la base de données.
Néanmoins, il existe un système de verrouillage que les définitions de cache peuvent exiger dans leurs options et qui sera appliqué lors de l'interaction avec une instance de mémoire cache.
===Partage===
Chaque bit de données qui est stocké dans un cache est associé à une clé unique calculée. <br/>
Par défaut, une partie de cette clé est l'identificateur de site qui rend tout contenu stocké dans le cache spécifique au site qui l'a stocké. Pour la plupart des sites, c'est exactement ce que vous voulez.<br/>
Cependant, dans certaines situations, il est avantageux de permettre à plusieurs sites, ou à des sites liés d'une manière ou d'une autre, de partager des données en cache.
Bien sûr, tous les caches ne peuvent pas être partagés, mais certains le peuvent certainement, et en les partageant, vous pouvez encore réduire la charge et augmenter les performances en maximisant l'utilisation des ressources.
Il s'agit d'une fonctionnalité avancée, si vous choisissez de configurer le partage, veuillez le faire avec précaution.
Pour utiliser le partage, vous devez d'abord configurer des instances de cache identiques dans les sites que vous voulez partager des informations, puis sur chaque site définir le partage pour le cache à la même valeur.
; Sites avec le même identifiant de site : C'est la valeur par défaut, elle permet aux sites avec le même identifiant de site de partager les informations mises en cache. C'est le plus restrictif mais il va fonctionner pour toutes les caches. Toutes les autres options comportent un élément de risque en ce sens que vous devez vous assurer que l'information contenue dans le cache s'applique à tous les sites qui y auront accès.
; Sites exécutant la même version : Tous les sites accédant à l'arrière-plan qui ont la même version de Moodle peuvent partager les informations que ce cache a stockées dans la mémoire cache.
; Touche personnalisée : Pour cela, vous saisissez manuellement une clé à utiliser pour le partage. Vous devez ensuite entrer exactement la même clé dans les autres sites où vous voulez partager l'information.
; Tout le monde : Les données mises en cache sont accessibles à tous les autres sites qui y accèdent. Cette option place la balle entièrement dans le camp des administrateurs Moodle.
Par exemple, si vous aviez plusieurs sites Moodle ayant tous la même version sur le serveur avec APC installé, vous pourriez décider de mapper le cache de langue dans la boutique APC et de configurer le partage pour tous les sites ayant la même version.<br/>.
Le cache de langue pour les sites d'une même version est sûr à partager dans de nombreuses situations, il est utilisé sur pratiquement toutes les pages, et APC est extrêmement rapide. Ces trois points peuvent se traduire par une belle petite amélioration des performances de vos sites.
Il est important de considérer avec le cache de langue qu'en le partageant entre les sites, toute personnalisation de langue sera également partagée.
==L'écran de configuration du cache==
L'écran de configuration du cache est votre guichet unique pour configurer la mise en cache dans Moodle.<br/>
Il vous donne un aperçu de la façon dont la mise en cache est actuellement configurée pour votre site et il fournit des liens vers toutes les actions que vous pouvez effectuer pour configurer la mise en cache selon vos besoins spécifiques.
===Accès à l'écran de configuration du cache===
[[Fichier:.png|vignette|L'écran de configuration du cache]]
L'écran de configuration du cache n'est accessible qu'aux utilisateurs ayant la capacité ''moodle/site:config''. Par défaut, c'est seulement admins.<br/>
Une fois connecté à l'écran de configuration, se trouve dans '''Administration du site > Plugins > Cache > Configuration'''.
===Mémoires de cache installées===
[[Fichier:.png|vignette|Capture d'écran des mémoires cache installées]]
Ceci vous montre une liste des plugins de cache que vous avez installés.<br />.
Pour chaque plugin, vous pouvez rapidement voir s'il est prêt à être utilisé (toutes les conditions php ont été remplies), combien d'instances de mémoires existent déjà sur ce site, les types de cache pour lesquels cette mémoire peut être utilisée, les fonctionnalités qu'il supporte (avancées) et les actions que vous pouvez effectuer concernant cette mémoire.
Souvent, la seule action disponible est de créer une nouvelle instance de mémoire.<br />.
La plupart des mémoires prennent en charge les instances multiples, mais pas toutes car vous verrez que le cache de session et le cache de requête statique ne le font pas. Pour ces deux mémoires, il n'est pas logique d'avoir plusieurs instances.
===Configuration des instances de la mémoire===
[[Fichier:.png|vignette|Capture d'écran des instances de la mémoire configurées]]
Ici vous obtenez une liste des instances de la mémoire cache de ce site.
; '''Nom de mémoire''' : Le nom donné à cette instance de la mémoire cache lorsqu'elle est créée pour que vous puissiez la reconnaître. Il peut être tout ce que vous voulez et n'est utilisé que pour que vous puissiez identifier l'instance du magasin.
; '''Plugin''' : Le plugin de cache dont il s'agit est une instance.
; '''Prêt''' : Une coche s'affiche lorsque toutes les exigences PHP ont été satisfaites ainsi que toutes les exigences de connexion ou de configuration ont été vérifiées.
; '''Mappage des mémoires''' : Le nombre de caches auxquels cette instance de magasin a été mappée explicitement. N'inclut aucune utilisation par le biais de mappages par défaut (voir ci-dessous).
; '''Modes''' : Les modes que cette instance du cache peut servir.
; '''Soutien''' :  Les fonctionnalités prises en charge par cette instance de la mémoire cache.
; '''Verrouillage''' : Le verrouillage est un mécanisme qui limite l'accès aux données mises en cache à un seul processus à la fois pour éviter que les données ne soient écrasées. La méthode de verrouillage détermine la manière dont le verrouillage est acquis et vérifié.
; '''Actions''' : Toutes les actions qui peuvent être effectuées contre cette instance de la mémoire cache.
===Known cache definitions===
[[Image:caching-27-04-known-cache-definitions.png|thumb|500px|Known cache definitions screenshot]]
The idea of a cache definition hasn't been discussed here yet. It is something controlled by the developer. When they create a cache they can do so in two ways, the first is by creating a cache definition. This is essentially telling Moodle about the cache they've created. The second way is to create an Adhoc cache. Developers are always encouraged to use the first method. Only caches with a definition can be mapped and further configured by the admin. Adhoc caches will make use of default settings only.<br />
Typically Adhoc caches are only permitted in situations where the cache is small and configuring it beyond defaults would provide no benefit to administrators. Really its like saying you the administrator doesn't need to concern yourself with it.
For each cache shown here you get the following information:
; '''Definition''' : A concise description of this cache.
; '''Mode''' : The cache type this cache is designed for.
; '''Component''' : The code component the cache is associated with.
; '''Area''' : The area of code this cache is serving within the component.
; '''Store mappings''' : The store or stores that will be used for this cache.
; '''Sharing''' : How is sharing configured for this site.
; '''Actions''' : Any actions that can be performed on the cache. Typically you can edit the cache store instance mappings, edit sharing, and purge the cache.
You'll also find at the bottom of this table a link title "Rescan definitions". Clicking this link will cause Moodle to go off an check all core components, and installed plugins looking for changes in the cache definitions.<br />
This happens by default during upgrade, and if a new cache definition is encountered. However should you find yourself looking for a cache that isn't there this may be worth a try.<br />
It is also handy for developers as it allows them to quickly apply changes when working with caches. It is useful when tweaking cache definitions to find what works best.
Information on specific cache definitions can be found on the [[Cache definitions]] page.
===Summary of cache lock instances===
[[Image:caching-27-05-summary-of-cache-lock-instances.png|thumb|500px|Summary of cache lock instances screenshot]]
As mentioned above cache locking is an advanced concept in MUC.<br />
The table here shows information on the configured locking mechanisms available to MUC. By default just a single locking mechanism is available, file locking.
At present there are no caches that make use of this and as such I won't discuss it further here.
===Stores used when no mapping is present===
[[Image:caching-27-06-stores-used-when-no-mapping-is-present.png|thumb|500px|Mapping of default stores screenshot]]
This table quickly shows which cache store instances are going to be used for cache types if there are no specific mappings in place.<br />
To simplify that, this show the default cache stores for each type.
At the bottom you will notice there is a link "Edit mappings" that takes you to a page where you can configure this.
==Adding cache store instances==
The default configuration is going to work for all sites, however you may be able to improve your sites performance by making use of various caching backends and techniques. The first thing you are going to want to do is add cache store instances configured to connect to/use the cache backends you've set up.
===File cache===
[[Image:caching-27-07-add-file-cache-store.png|thumb|300px|Adding a file cache store screenshot]]
When on the cache configuration screen within the ''Installed cache stores'' table you should be able to see the File cache plugin, click ''`Add instance`'' to start the process of adding a file cache store instance.
When creating a file cache there is in fact only one required param, the store name. The store name is used to identify the file store instance in the configuration interface and must be unique to the site.
It can be anything you want, but we would advice making it something that describes you intended use of the file store.
The following properties can also be specified, customising where the file cache will be located, and how it operates.
; '''Cache path''' : Allows you to specify a directory to use when storing cache data on the file system. Of course the user the webserver is running as must have read/write access to this directory. By default (blank) the Moodledata directory will be used.
; '''Auto create directory''' : If enabled when the cache is initialised if the specified directory does not exist Moodle will create it. If this is specified and the directory does not exist the the cache will be deemed not ready and will not be used.
; '''Single directory store''' : By default the file store will create a subdirectory structure to store data in. The first 3 characters of the data key will be used as a directory. This is useful in avoiding file system limits it the file system has a maximum number of files per directory. By enabling this option the file cache will not use subdirectories for storage of data. This leads to a flat structure but one that is more likely hit file system limits. Use with care.
; '''Prescan directory''' : One of the features the file cache provides is to prescan the storage directory when the cache is first used. This leads to faster checks of files at the expense of an in-depth read.
The file cache store is the default store used for application caches and by default the moodledata directory gets used for the cache.
File access can be a taxing resource in times of increased load and the following are some ideas about configuring alternative file stores in order to improve performance.
First up is there a faster file system available for use on your server.<br />
Perhaps you've an SSD installed but are not using it for your moodledata directory because space is a premium.<br />
You should consider creating a directory or small partition on your SSD and creating a file store to use that instead of your Moodle data directory.
Next you've not got a faster drive available for use, but you do have plenty of free space.<br />
Something that may be worth giving a shot would be to create a small partition on the drive you've got installed that uses a performance orientated file system.<br />
Many linux installations these days for example use EXT4, a nice file system but one that has overheads due to the likes of journalling.<br />
Creating a partition and using a file system that has been optimised for performance may give you that little boost you are looking for. Remember caches are designed to be volatile and choosing a file system for a cache is different decision to choosing a file system for your server.<br />
Finally if you're ready to go to lengths and have an abundance of memory on your server you could consider creating a ramdisk/tmpfs and pointing a file store at that.
Purely based in memory, it is volatile exactly like the cache is, and file system performance just isn't going to get much better than this.<br />
Of course you will be limited in space and you are essentially taking that resource away from your server.
Please remember with all of these ideas that they are just ideas.<br />
What ever you choose - test, test, test, be sure of the decision you make.
===Memcache===
[[Image:caching-27-08-add-memcache-store.png|thumb|300px|Add Memcache store screenshot]]
Before you can add a Memcache store instance you must first have a Memcached server you can access and have the Memcache php extension installed and enabled on your web server.
Like the file store you must provide a the store name. It is used to identify the store instance in the configuration interface and must be unique to the site.<br />
For a Memcache store you must also enter the Memcache server, or servers you wish it to make use of.
Servers should be added one per line and each line can contain 1 to 3 properties separated by colons.
# The URL or IP address of the server (required)
# The port the server is listening on (optional)
# The weight to give this server (optional)
For example, if you had two Memcached instances running on your server, one configured for the default port, and one configured for 11212 you would use the following:
<code>
127.0.0.1
127.0.0.1:11212
</code>
Optionally you can also specify a key prefix to use. What you enter here will prefixed to all keys before accessing the server and can be used to effectively partition the Memcache space in a recognisable way. This can be handy if you have a management tool for you Memcached server that you use to inspect what is stored there.
'''Important implementation notes'''
* The Memcache extension does not provide a means of deleting a set or entries. Either a single entry is deleted, or all entries are deleted.<br />Because of this it is important to note that when you purge a Memcache store within Moodle it deletes ALL entries in the Memcache backend. Not just those relating to Moodle.<br />For that reason it is highly recommended to use dedicated Memcached servers and to '''NOT''' configure any other software to use those servers. Doing so may lead to performance depreciation and adverse affects.
* Likewise if you want to use Memcache for caching and for sessions in Moodle it is essential to use two Memcached servers. One for sessions, and one for caching. Otherwise a cache purge in Moodle will purge your sessions!
===Memcached===
[[Image:caching-27-09-add-memcached-store.png|thumb|300px|Add Memcached store screenshot]]
Like the Memcache store you must first have a Memcached server you can access and have the Memcached php extension installed and enabled on your server.
Also like the Memcache store there are two required parameters in configuring a Memcached store.
; '''Store name''' : It is used to identify the store instance in the configuration interface and must be unique to the site.
; '''Servers''' : The servers you wish this cache store use. See below for details.
Servers should be added one per line and each line can contain 1 to 3 properties separated by colons.
# The URL or IP address of the server (required)
# The port the server is listening on (optional)
# The weight to give this server (optional)
For example, if you had two Memcached instances running on your server, one configured for the default port, and one configured for 11212 you would use the following:
<code>
127.0.0.1
127.0.0.1:11212
</code>
There are also several optional parameters you can set when creating a Memcached store.
; '''Use compression''' : Defaults to true, but can be disabled if you wish.
; '''Use serialiser''' : Allows your to select which serialiser gets used when communicating with the Memcache server. By default the Memcached extension and PHP only provide one serialised, however there is a couple of others available for installation if you go looking for them. One for example is the igbinary found at https://github.com/igbinary/igbinary.
; '''Prefix key''' : Allows you to set some characters that will be prefixed to all keys before interacting with the server.
; '''Hash method''' : The hash method provided by the Memcached extension is used by default here. However you can select to use an alternative if you wish. http://www.php.net/manual/en/memcached.constants.php provides a little information on the options available. Please note if you wish to you can also override the default hash function PHP uses within your php.ini.
; '''Buffer writes''' : Disabled by default, and for good reason. Turning on buffered writes will minimise interaction with the Memcached server by buffering io operations. The downside to this is that on a system with any concurrency there is a good chance multiple requests will end up generating the data because no one had pushed it to the Memcached server when they first requested it. Enabling this can be advantageous for caches that are only accessed in capability controlled areas for example where multiple interaction is taking a toll on network resources or such. But that is definitely on the extreme tweaking end of the scale.
'''Important implementation notes'''
* The Memcached extension does not provide a means of deleting a set or entries. Either a single entry is deleted, or all entries are deleted.<br />
Because of this it is important to note that when you purge a Memcached store within Moodle it deletes ALL entries in the Memcached server. Not just those relating to Moodle.<br />
For that reason it is highly recommended to use dedicated Memcached servers and to '''NOT''' configure any other software to use the same servers. Doing so may lead to performance depreciation and adverse affects.
* Likewise if you want to use Memcached for caching and for sessions in Moodle it is essential to use two Memcached servers. One for sessions, and one for caching. Otherwise a cache purge in Moodle will purge your sessions!
===MongoDB===
[[Image:caching-27-10-add-mongodb-store.png|thumb|300px|Add MongoDB store screenshot]]
MongoDB is an open source document orientated NoSQL database. Check out their website www.mongodb.org for more information.
; '''Store name''' : Used to identify the store instance in the configuration interface and must be unique to the site.
; '''Server''' : This is the connection string for the server you want to use. Multiple servers can be specified using a comma-separated list.
; '''Database''' : The name of the database to make use of.
; '''Username''' : The username to use when making a connection.
; '''Password''' : The password of the user being used for the connection.
; '''Replica set''' : The name of the replica set to connect to. If this is given the master will be determined by using the ismaster database command on the seeds, so the driver may end up connecting to a server that was not even listed.
; '''Use''' : If enabled the usesafe option will be used during insert, get, and remove operations. If you've specified a replica set this will be forced on anyway.
; '''Use safe value''' : You can choose to provide a specific value for use safe. This will determine the number of servers that operations must be completed on before they are deemed to have been completed.
; '''Use extended keys''' : If enabled full key sets will be used when working with the plugin. This isn't used internally yet but would allow you to easily search and investigate the MongoDB plugin manually if you so choose. Turning this on will add an small overhead so should only be done if you require it.
==Mapping a cache to a store instance==
[[Image:caching-27-11-store-mapping.png|thumb|300px|Cache definition store mapping screenshot]]
Mapping a store instance to a cache tells Moodle to use that store instance when the cache is interacted with. This allows the Moodle administrator to control where information gets stored and to most importantly optimise performance of your site by making the most of the resources available to your site.
To set a mapping first browse to the cache configuration screen.<br />
Proceed to find the ''Known cache definitions'' table and within it find the cache you'd like to map.
In the actions column select the link for '''Edit mappings'''.
The screen you are presented allows you to map one or more cache store instances to be used by this cache.<br />
You are presented with several drop-downs that allow you to map one or more cached. All mapped caches get interacted with. The "Primary" store is the store that will be used first when interacting with the cache.
The "Final" mapped store will be the last cache store interacted with.<br />
How this interaction occurs is documented below.
If no stores are mapped for the cache then the default stores are used. Have a look at the section below for information on changing the default stores.
If a single store instance is mapped to the cache the following occurs:
; ''Getting data from the cache'' : Moodle asks the cache to get the data. The cache attempts to get it from the store. If the store has it it gives it to the cache, and the cache gives it to Moodle so that it can use the data. If the store doesn't have it the a fail is returned and Moodle will have to generate the data and will most likely then send it to the cache.
; ''Storing data in the cache'' : Moodle will ask the cache to store some data, and the cache will give it to the cache store.
If multiple store instances are mapped to the cache the following occurs:
; ''Getting data from a store'' : Moodle asks the cache to get the data. The cache attempts to get it from the first store. If the first store has it then it returns the data to the cache and the cache returns it to Moodle. If the first store doesn't have the data then it attempts to get the data from the second store. If the second store has it it returns it to the first store that then stores it itself before returning it to the cache. If it doesn't then the next store is used. This continue until either the data is found or there are no more stores to check.
; ''Storing data in the cache'' : Moodle will ask the cache to store some data, the cache will give it to every mapped cache store for storage.
The main advantage to assigning multiple stores is that you can introduce cache redundancy. Of course this introduces an overhead so it should only be used when actually required.
The following is an example of when mapping multiple stores can provide an advantage:
<pre>
Scenario:
You have have a web server that has a Moodle site as well as other sites.
You also have a Memcache server that is used by several sites including Moodle.
Memcache has a limited size cache, that when full and requested to store more information frees space by dropping the least used cache entries.
You want to use Memcache for your Moodle site because it is fast, however you are aware that it may introduce more cache misses because it is a heavily used Memcache server.
Solution:
To get around this you map two stores to caches you wish to use Memcache.
You make Memcache the primary store, and you make the default file store the final cache store.
Explanation:
By doing this you've created redundancy, when something is requested Moodle first tries to get it from Memcache (the fastest store) and if its not there it proceeds to check the file cache.
</pre>
Just a couple more points of interest:
* Mapping multiple caches will introduce overhead, the more caches mapped the more overhead.
* Consider the cache stores you are mapping to, if data remains there once set then there is no point mapping any further stores after it. This technique is primarily valuable in situations where data is not guaranteed to remain after being set.
* Always test your configuration. Enable the display of performance information and then watch which stores get used when interacting with Moodle in such a way as to trigger the cache.
==Setting the stores that get used when no mapping is present==
[[Image:caching-27-12-default-store-mapping.png|thumb|300px|Setting which stores get used when no mapping is present screenshot]]
This is really setting the default stores that get used for a cache type when there is not a specific mapping that has been made for it.
To set a mapping first browse to the cache configuration screen.<br />
Proceed to find the ''Stores used when no mapping is present'' table.<br />
After the table you will find a link '''Edit mappings''', click this.
On the screen you are presented with you can select one store for each cache type to use when a cache of the corresponding type gets initialised and there is not an explicit mapping for it.
Note that on this interface the drop downs only contain store instances that are suitable for mapping to the type.
Not all instances will necessarily be shown. If you have a store instance you don't see then it is not suitable for '''ALL''' the cache definitions that exist.<br />
You will not be able to make that store instance the default, you will instead need to map it explicitly to each cache you want/can use it for.
==Configuring caching for your site==
This is where it really gets tricky, and unfortunately there is no step-by-step guide to this.
How caching can be best configured for a site comes down entirely to the site in question and the resources available to it.
What can be offered are some tips and tricks to get you thinking about things and to perhaps introduce ideas that will help you along the way.
If you are reading this document and you've learnt a thing or two about configuring caching on your site share your learnings by adding to the points here.
* Plan it. It's a complex thing. Understand your site, understand your system, and really think how users will be using it all.
* If you've got a small site the gains aren't likely to be significant, if you've got a large site getting this right can lead to a substantial boost in performance.
* When looking at cache backends really research the advantages and disadvantages of each. Keep your site in mind when thinking about them. Depending upon your site you may find that no one cache backend is going to meet the entire needs of your site and that you will benefit from having a couple of backends at your disposal.
* Things aren't usually as simple as installing a cache backend and then using it. Pay attention to configuration and try to optimise it for your system. Test it separately and have an understanding of its performance before tell Moodle about it. The cache allows you to shift load off the database and reduce page request processing.<br />If for instance you have Memcache installed but your connection has not been optimised for it you may well find yourself in a losing situation before you even tell Moodle about the Memcache server.
* When considering your default store instances keep in mind that they must operate with data sets of varying sizes and frequency. For a large site really your best bet is to look at each cache definition and map it to a store that is best suited for the data it includes and the frequency of access.<br />Cache definitions have been documented [[Cache definitions]].
* Again when mapping store instances to caches really think about the cache you are mapping and make a decision based upon what you understand of your site and what you know about the cache.<br />Cache definitions have been documented [[Cache definitions]].
* Test your configuration. If you can stress test it even better! If you turn on performance information Moodle will also print cache access information at the bottom of the screen. You can use this to visually check the cache is being used as you expect, and it will give you an indication of where misses etc are occurring.
* Keep an eye on your backend. Moodle doesn't provide a means of monitoring a cache backend and that is certainly something you should keep an eye on. Memcache for instance drops least used data when full to make room for new entries. APC on the other hand stops accepting data when full. Both will impact your performance if full and you're going to encounter misses. However APC when full is horrible, but it is much faster.
===More on performance testing===
Two links that might be useful to anyone considering testing performance on their own servers:
* [http://www.iteachwithmoodle.com/2012/10/12/moodle-performance-testing-how-much-more-horsepower-do-each-new-versions-of-moodle-require/ Moodle performance testing: how much more horsepower do each new versions of Moodle require?]
* [http://www.iteachwithmoodle.com/2012/10/11/how-to-stress-test-your-moodle-server-using-loadstorm/ How to load test your Moodle server using Loadstorm]
===Performance advice for load-balanced web servers===
# In Moodle 2.4 onwards with load-balanced web servers, don't use the default caching option that stores the data in moodledata on a shared network drive.  Use memcached instead.  See Tim Hunt's article on http://tjhunt.blogspot.de/2013/05/performance-testing-moodle.html
# In Moodle 2.6 onwards make sure you set $CFG->localcachedir to some local directory in config.php (for each node).  This will speed up some of the disk caching that happens outside of MUC, such as themes, javascript, libraries etc.
==Troubleshooting==
Have you encountered a problem, or found yourself in a conundrum? Perhaps the answer is in this section. If its not when you find have an answer how about sharing it here.
==More information==
* [[Cache definitions]] Information on the cache definitions found within Moodle.
* [[:dev:Cache API|Cache API]] Details of the Cache API.
* [[:dev:Cache API - Quick reference|Cache API - Quick reference]] A short, code focused page of on the Cache API.
* [[:dev:The Moodle Universal Cache (MUC)|The Moodle Universal Cache (MUC)]] The original cache specification.
Cache related forum discussions that may help in understanding MUC:
* [https://moodle.org/mod/forum/discuss.php?d=217195 MUC is here, now what?]
* [https://moodle.org/mod/forum/discuss.php?d=226123 Status of MUC?]
* [https://moodle.org/mod/forum/discuss.php?d=222250 Putting cachedir on local disks in cluster]
* [https://moodle.org/mod/forum/discuss.php?d=232122 moodle cachestore_file]
Other:
* [http://jfilip.ca/2013/08/20/moodle-2-4-5-vs-2-5-1-performance-and-muc-apc-cache-store/ Moodle 2.4.5 vs. 2.5.1 performance and MUC APC cache store] blog post by Justin Filip
==See also==
* [[MUC FAQ]]
[[de:Caching]]
[[es:Cacheando]]
[[en:Caching]]
[[en:Caching]]

Version du 6 mai 2019 à 15:43

Remarque : la traduction de cette page n'est pas terminée. N'hésitez pas à traduire tout ou partie de cette page ou à la compléter. Vous pouvez aussi utiliser la page de discussion pour vos recommandations et suggestions d'améliorations.


Un cache est un ensemble de données traitées qui sont conservées et réutilisées afin d'éviter des requêtes répétées et coûteuses dans la base de données.

Moodle 2.4 a vu l'implémentation de MUC, le Moodle Universal Cache. Ce nouveau système permet à certaines fonctions de Moodle (par exemple la récupération des chaînes de caractères) de tirer profit des différents services de cache installés (par exemple les fichiers, ram, memcached).

Dans les futures versions de Moodle, nous continuerons à étendre le nombre de fonctions Moodle qui utilisent MUC, ce qui continuera à améliorer les performances, mais vous pouvez déjà commencer à l'utiliser pour améliorer votre site.

Approche générale des tests de performance

Voici la stratégie générale que vous devriez adopter :

  1. Construisez un environnement de test aussi proche que possible de votre instance de production réelle (matériel, logiciel, réseau, etc.)
  2. Assurez-vous de supprimer autant de variables non contrôlées que possible de cet environnement (par exemple d'autres services)
  3. Utilisez un outil pour placer une charge réaliste, mais simulée et répétable sur votre serveur. (par exemple jmeter ou selenium).
  4. Décider d'une façon de mesurer la performance du serveur en capturant les données (RAM, charge, temps pris, etc.)
  5. Exécutez votre charge et mesurez un résultat de performance de base.
  6. Changez une variable à la fois et ré-exécutez la charge pour voir si la performance s'améliore ou se détériore. Répéter au besoin.
  7. Lorsque vous découvrez des paramètres qui se traduisent par une amélioration constante des performances, appliquez-les à votre site de production.

Configuration du cache dans Moodle

Depuis Moodle 2.4, Moodle fournit une structure de plugin de mise en cache pour donner aux administrateurs la possibilité de contrôler où Moodle stocke les données en cache. Pour la plupart des sites Moodle, la configuration par défaut devrait être suffisante et il n'est pas nécessaire de changer la configuration. Pour les grands sites Moodle avec plusieurs serveurs, les administrateurs peuvent utiliser memcached, mongodb ou d'autres systèmes pour stocker les données du cache. L'écran du plugin de cache offre aux administrateurs la possibilité de configurer les données du cache qui sont stockées où.
. La mise en cache dans Moodle est contrôlée par ce qui est connu sous le nom de Moodle Universal Cache. Communément appelé MUC.

Ce document explique brièvement ce qu'est MUC avant d'entrer dans le détail des concepts et des options de configuration qu'il offre.

Les concepts de base du cache dans Moodle

La mise en cache dans Moodle n'est pas aussi complexe qu'il n'y paraît. Un peu de connaissance de base vous permettra de mieux comprendre le fonctionnement de la configuration du cache.

Type de caches

Commençons par les types de cache (parfois appelés mode). Il existe trois types de caches de base dans Moodle.

Le premier est le cache de l'application. C'est de loin le type de cache le plus couramment utilisé dans le code. Ses informations sont partagées par tous les utilisateurs et ses données persistent entre les demandes. L'information stockée ici est généralement mise en cache pour l'une des deux raisons suivantes : soit il s'agit d'une information requise pour la majorité des demandes et nous permet d'économiser une ou plusieurs interactions de base de données, soit il s'agit d'une information qui est consultée moins fréquemment mais qui nécessite des ressources importantes pour générer.
Par défaut, ces informations sont stockées dans une structure organisée dans votre répertoire de données Moodle.

Le deuxième type de cache est le cache de session. C'est exactement comme la session PHP que vous connaissez déjà, en fait elle utilise la session PHP par défaut. Vous vous demandez peut-être pourquoi nous avons ce type de cache, mais la réponse est simple. Le MUC fournit un moyen géré de stocker et de supprimer l'information requise entre les demandes. Il offre aux développeurs un cadre à utiliser plutôt que d'avoir à réinventer la roue et assure que nous avons accès à un moyen contrôlé de gérer le cache comme requis.
Il est important de noter qu'il ne s'agit pas d'un type de cache fréquemment utilisé car par défaut, les données du cache de session sont stockées dans la session PHP et la session PHP est stockée dans la base de données. Les utilisations du type cache de session sont limitées à de petits ensembles de données car nous ne voulons pas gonfler les sessions et donc mettre la base de données à rude épreuve.

Le troisième et dernier type est le cache de requête. Les données stockées dans ce type de cache ne persistent que pendant toute la durée de vie de la requête. Si vous êtes un développeur PHP, pensez-y comme une variable statique gérée.
> C'est de loin le moins utilisé des trois types de cache, les utilisations sont souvent limitées aux informations qui seront consultées plusieurs fois dans une même requête, généralement par plus d'une zone de code. Les informations mises en cache sont stockées en mémoire par défaut.

Types de cache et systèmes à serveurs multiples

Si vous avez un système avec plusieurs serveurs Web frontaux, le cache de l'application doit être partagé entre les serveurs. En d'autres termes, vous ne pouvez pas utiliser le stockage local rapide pour le cache de l'application, mais vous devez utiliser le stockage partagé ou une autre forme de cache partagé telle qu'un cache memc partagé.

Il en va de même pour le cache de session, à moins que vous n'utilisiez un mécanisme de "sessions bloquées" pour garantir que, dans une session, les utilisateurs accèdent toujours au même serveur frontal.

Arrière-plan de mise en cache

Les arrière-plan de cache sont l'endroit où les données sont réellement stockées. Il s'agit notamment du système de fichiers, de la session php, de Memcached et de la mémoire.
Par défaut, seuls le système de fichiers, la session php et la mémoire sont utilisés dans Moodle.
Nous n'exigeons pas qu'un site ait accès à d'autres systèmes comme Memcached. Au lieu de cela, c'est vous qui êtes responsable de l'installation et de la configuration.
Lorsque les arrière-plans de cache sont mentionnés, pensez à des systèmes en dehors de Moodle qui peuvent être utilisés pour stocker des données. Le serveur MongoDB, le serveur Memcache et les applications "serveur" similaires.

Mémoires de cache

Les mémoires de cache sont un type de plugin dans Moodle. Ils facilitent la connexion de Moodle aux arrière-plans du cache dont il a été question plus haut. Le Moodle standard a les trois valeurs par défaut mentionnées ci-dessus ainsi que Memcache, Memcached, MongoDB, Cache utilisateur APC (APCu) et Redis.

Vous pouvez trouver d'autres plugins de cache dans la base de données plugins.

Le code de ces derniers se trouve dans le cache/mémoire de votre répertoire racine de Moodle.

Dans Moodle, vous pouvez configurer autant de mémoires cache que votre architecture l'exige. Si vous avez plusieurs serveurs Memcache par exemple, vous pouvez créer une instance de cache pour chacun d'eux. Moodle contient par défaut trois instances de cache qui sont utilisées lorsque vous n'avez effectué aucune autre configuration.

  • Une instance de stockage de fichiers est créée qui est utilisée pour tous les caches d'applications. Il stocke ses données dans votre répertoire moodledata.
  • Une instance de stockage de session est créée qui est utilisée pour tous les caches de session. Il stocke ses données dans la session PHP, qui par défaut est stockée dans votre base de données.
  • Une instance de mémoire statique est créée qui est utilisée pour tous les types de cache de requête. Les données n'existent en mémoire que pour la durée de vie d'une requête.

Caches : ce qui se passe dans le code

Les caches sont créés en code et sont utilisés par le développeur pour stocker les données qu'il estime nécessaire de mettre en cache.
Gardons cette section agréable et courte parce que vous n'êtes peut-être pas un développeur. Il y a un point très important que vous devez savoir à propos.
Le développeur n'a pas son mot à dire sur l'endroit où les données sont mises en cache. Ils doivent spécifier les informations suivantes lors de la création d'un cache à utiliser.

  1. Le type de cache dont ils ont besoin.
  2. La zone de code à laquelle ce cache appartiendra (l'API si vous voulez).
  3. Le nom de la cache, quelque chose qu'ils inventent pour décrire en un mot ce que le cache contient.

Il y a plusieurs exigences et paramètres optionnels qu'ils peuvent également spécifier, mais ne vous inquiétez pas de cela à ce stade.
Le point important est qu'ils ne peuvent pas choisir quel arrière-plan de cache utiliser, ils peuvent seulement choisir le type de cache qu'ils veulent parmi les trois détaillés ci-dessus.

Comment ils se lient entre eux

La meilleure façon de le décrire est de le faire en relation avec les rôles joués au sein d'une organisation.

  1. L'administrateur système installe les arrière-plans de cache que vous souhaitez utiliser. Memcache, XCache, APC, etc.
    Moodle n'est pas au courant, ils sont en dehors de la portée de Moodle et de la responsabilité purement de votre administrateur système.
  2. L'administrateur de Moodle crée une instance de mémoire de cache dans Moodle pour chaque arrière-plan que le site utilisera.
    Il peut y avoir une ou plusieurs instances de mémoire de cache pour chaque arrière-plan. Certains arrière-plans comme Memcached ont des paramètres pour créer des espaces séparés dans un arrière-plan.
  3. Le développeur a créé des caches en code et les utilise pour stocker des données.
    Il ne sait rien sur la façon dont vous allez utiliser vos caches, il crée juste un "cache" et dit à Moodle quel type est le mieux pour lui.
  4. L'administrateur Moodle crée un mappage entre une instance de cache et un cache.
    Ce mappage indique à Moodle d'utiliser l'arrière-plan que vous spécifiez pour stocker les données que le développeur veut en cache.

De plus, vous pouvez aller encore plus loin.

  • Vous pouvez mapper plusieurs caches vers une seule instance de la mémoire cache.
  • Vous pouvez mapper plusieurs instances de la mémoire cache vers une seule mémoire cache avec priorité (primaire... final)
  • Vous pouvez mapper une instance de mémoire cache comme étant la mémoire par défaut utilisée pour toutes les caches d'un type spécifique qui n'ont pas autrement de mappages spécifiques.

Si c'est la première fois que vous lisez un article sur le cache universel de Moodle, cela semble probablement assez complexe, mais ne vous inquiétez pas, il sera discuté plus en détail au fur et à mesure que nous travaillerons sur la configuration du cache dans Moodle.

Concepts avancés

Ces concepts sont des choses que la plupart des sites n'auront pas besoin de connaître ou de se préoccuper.

Vous ne devriez commencer à chercher ici que si vous cherchez à maximiser les performances sur de grands sites fonctionnant sur des services en cluster avec des arrière-plan de cache partagés, ou encore sur une architecture multi-sites où les informations sont partagées entre sites.

Verrouillage

L'idée de verrouillage n'est pas nouvelle, c'est le processus de contrôle d'accès afin d'éviter les problèmes de concurrence.

MUC a un deuxième type de plugin, un plugin de verrouillage de cache qui est utilisé lorsque les caches l'exigent. Jusqu'à présent, aucun cache n'en a eu besoin. Une cache par nature est volatile et toute information qui est absolument essentielle à la mission devrait être une base de données plus permanente, probablement la base de données.

Néanmoins, il existe un système de verrouillage que les définitions de cache peuvent exiger dans leurs options et qui sera appliqué lors de l'interaction avec une instance de mémoire cache.

Partage

Chaque bit de données qui est stocké dans un cache est associé à une clé unique calculée.
Par défaut, une partie de cette clé est l'identificateur de site qui rend tout contenu stocké dans le cache spécifique au site qui l'a stocké. Pour la plupart des sites, c'est exactement ce que vous voulez.
Cependant, dans certaines situations, il est avantageux de permettre à plusieurs sites, ou à des sites liés d'une manière ou d'une autre, de partager des données en cache. Bien sûr, tous les caches ne peuvent pas être partagés, mais certains le peuvent certainement, et en les partageant, vous pouvez encore réduire la charge et augmenter les performances en maximisant l'utilisation des ressources.

Il s'agit d'une fonctionnalité avancée, si vous choisissez de configurer le partage, veuillez le faire avec précaution.

Pour utiliser le partage, vous devez d'abord configurer des instances de cache identiques dans les sites que vous voulez partager des informations, puis sur chaque site définir le partage pour le cache à la même valeur.

Sites avec le même identifiant de site
C'est la valeur par défaut, elle permet aux sites avec le même identifiant de site de partager les informations mises en cache. C'est le plus restrictif mais il va fonctionner pour toutes les caches. Toutes les autres options comportent un élément de risque en ce sens que vous devez vous assurer que l'information contenue dans le cache s'applique à tous les sites qui y auront accès.
Sites exécutant la même version
Tous les sites accédant à l'arrière-plan qui ont la même version de Moodle peuvent partager les informations que ce cache a stockées dans la mémoire cache.
Touche personnalisée
Pour cela, vous saisissez manuellement une clé à utiliser pour le partage. Vous devez ensuite entrer exactement la même clé dans les autres sites où vous voulez partager l'information.
Tout le monde
Les données mises en cache sont accessibles à tous les autres sites qui y accèdent. Cette option place la balle entièrement dans le camp des administrateurs Moodle.

Par exemple, si vous aviez plusieurs sites Moodle ayant tous la même version sur le serveur avec APC installé, vous pourriez décider de mapper le cache de langue dans la boutique APC et de configurer le partage pour tous les sites ayant la même version.
. Le cache de langue pour les sites d'une même version est sûr à partager dans de nombreuses situations, il est utilisé sur pratiquement toutes les pages, et APC est extrêmement rapide. Ces trois points peuvent se traduire par une belle petite amélioration des performances de vos sites. Il est important de considérer avec le cache de langue qu'en le partageant entre les sites, toute personnalisation de langue sera également partagée.

L'écran de configuration du cache

L'écran de configuration du cache est votre guichet unique pour configurer la mise en cache dans Moodle.
Il vous donne un aperçu de la façon dont la mise en cache est actuellement configurée pour votre site et il fournit des liens vers toutes les actions que vous pouvez effectuer pour configurer la mise en cache selon vos besoins spécifiques.

Accès à l'écran de configuration du cache

Fichier:.png
L'écran de configuration du cache

L'écran de configuration du cache n'est accessible qu'aux utilisateurs ayant la capacité moodle/site:config. Par défaut, c'est seulement admins.
Une fois connecté à l'écran de configuration, se trouve dans Administration du site > Plugins > Cache > Configuration.

Mémoires de cache installées

Fichier:.png
Capture d'écran des mémoires cache installées

Ceci vous montre une liste des plugins de cache que vous avez installés.
. Pour chaque plugin, vous pouvez rapidement voir s'il est prêt à être utilisé (toutes les conditions php ont été remplies), combien d'instances de mémoires existent déjà sur ce site, les types de cache pour lesquels cette mémoire peut être utilisée, les fonctionnalités qu'il supporte (avancées) et les actions que vous pouvez effectuer concernant cette mémoire.

Souvent, la seule action disponible est de créer une nouvelle instance de mémoire.
. La plupart des mémoires prennent en charge les instances multiples, mais pas toutes car vous verrez que le cache de session et le cache de requête statique ne le font pas. Pour ces deux mémoires, il n'est pas logique d'avoir plusieurs instances.

Configuration des instances de la mémoire

Fichier:.png
Capture d'écran des instances de la mémoire configurées

Ici vous obtenez une liste des instances de la mémoire cache de ce site.

Nom de mémoire
Le nom donné à cette instance de la mémoire cache lorsqu'elle est créée pour que vous puissiez la reconnaître. Il peut être tout ce que vous voulez et n'est utilisé que pour que vous puissiez identifier l'instance du magasin.
Plugin
Le plugin de cache dont il s'agit est une instance.
Prêt
Une coche s'affiche lorsque toutes les exigences PHP ont été satisfaites ainsi que toutes les exigences de connexion ou de configuration ont été vérifiées.
Mappage des mémoires
Le nombre de caches auxquels cette instance de magasin a été mappée explicitement. N'inclut aucune utilisation par le biais de mappages par défaut (voir ci-dessous).
Modes
Les modes que cette instance du cache peut servir.
Soutien
Les fonctionnalités prises en charge par cette instance de la mémoire cache.
Verrouillage
Le verrouillage est un mécanisme qui limite l'accès aux données mises en cache à un seul processus à la fois pour éviter que les données ne soient écrasées. La méthode de verrouillage détermine la manière dont le verrouillage est acquis et vérifié.
Actions
Toutes les actions qui peuvent être effectuées contre cette instance de la mémoire cache.



Known cache definitions

Fichier:caching-27-04-known-cache-definitions.png
Known cache definitions screenshot

The idea of a cache definition hasn't been discussed here yet. It is something controlled by the developer. When they create a cache they can do so in two ways, the first is by creating a cache definition. This is essentially telling Moodle about the cache they've created. The second way is to create an Adhoc cache. Developers are always encouraged to use the first method. Only caches with a definition can be mapped and further configured by the admin. Adhoc caches will make use of default settings only.
Typically Adhoc caches are only permitted in situations where the cache is small and configuring it beyond defaults would provide no benefit to administrators. Really its like saying you the administrator doesn't need to concern yourself with it.

For each cache shown here you get the following information:

Definition
A concise description of this cache.
Mode
The cache type this cache is designed for.
Component
The code component the cache is associated with.
Area
The area of code this cache is serving within the component.
Store mappings
The store or stores that will be used for this cache.
Sharing
How is sharing configured for this site.
Actions
Any actions that can be performed on the cache. Typically you can edit the cache store instance mappings, edit sharing, and purge the cache.

You'll also find at the bottom of this table a link title "Rescan definitions". Clicking this link will cause Moodle to go off an check all core components, and installed plugins looking for changes in the cache definitions.
This happens by default during upgrade, and if a new cache definition is encountered. However should you find yourself looking for a cache that isn't there this may be worth a try.
It is also handy for developers as it allows them to quickly apply changes when working with caches. It is useful when tweaking cache definitions to find what works best.

Information on specific cache definitions can be found on the Cache definitions page.

Summary of cache lock instances

Fichier:caching-27-05-summary-of-cache-lock-instances.png
Summary of cache lock instances screenshot

As mentioned above cache locking is an advanced concept in MUC.
The table here shows information on the configured locking mechanisms available to MUC. By default just a single locking mechanism is available, file locking. At present there are no caches that make use of this and as such I won't discuss it further here.

Stores used when no mapping is present

This table quickly shows which cache store instances are going to be used for cache types if there are no specific mappings in place.
To simplify that, this show the default cache stores for each type.

At the bottom you will notice there is a link "Edit mappings" that takes you to a page where you can configure this.

Adding cache store instances

The default configuration is going to work for all sites, however you may be able to improve your sites performance by making use of various caching backends and techniques. The first thing you are going to want to do is add cache store instances configured to connect to/use the cache backends you've set up.

File cache

Fichier:caching-27-07-add-file-cache-store.png
Adding a file cache store screenshot

When on the cache configuration screen within the Installed cache stores table you should be able to see the File cache plugin, click `Add instance` to start the process of adding a file cache store instance.

When creating a file cache there is in fact only one required param, the store name. The store name is used to identify the file store instance in the configuration interface and must be unique to the site. It can be anything you want, but we would advice making it something that describes you intended use of the file store.

The following properties can also be specified, customising where the file cache will be located, and how it operates.

Cache path
Allows you to specify a directory to use when storing cache data on the file system. Of course the user the webserver is running as must have read/write access to this directory. By default (blank) the Moodledata directory will be used.
Auto create directory
If enabled when the cache is initialised if the specified directory does not exist Moodle will create it. If this is specified and the directory does not exist the the cache will be deemed not ready and will not be used.
Single directory store
By default the file store will create a subdirectory structure to store data in. The first 3 characters of the data key will be used as a directory. This is useful in avoiding file system limits it the file system has a maximum number of files per directory. By enabling this option the file cache will not use subdirectories for storage of data. This leads to a flat structure but one that is more likely hit file system limits. Use with care.
Prescan directory
One of the features the file cache provides is to prescan the storage directory when the cache is first used. This leads to faster checks of files at the expense of an in-depth read.

The file cache store is the default store used for application caches and by default the moodledata directory gets used for the cache. File access can be a taxing resource in times of increased load and the following are some ideas about configuring alternative file stores in order to improve performance.

First up is there a faster file system available for use on your server.
Perhaps you've an SSD installed but are not using it for your moodledata directory because space is a premium.
You should consider creating a directory or small partition on your SSD and creating a file store to use that instead of your Moodle data directory.

Next you've not got a faster drive available for use, but you do have plenty of free space.
Something that may be worth giving a shot would be to create a small partition on the drive you've got installed that uses a performance orientated file system.
Many linux installations these days for example use EXT4, a nice file system but one that has overheads due to the likes of journalling.
Creating a partition and using a file system that has been optimised for performance may give you that little boost you are looking for. Remember caches are designed to be volatile and choosing a file system for a cache is different decision to choosing a file system for your server.

Finally if you're ready to go to lengths and have an abundance of memory on your server you could consider creating a ramdisk/tmpfs and pointing a file store at that. Purely based in memory, it is volatile exactly like the cache is, and file system performance just isn't going to get much better than this.
Of course you will be limited in space and you are essentially taking that resource away from your server.

Please remember with all of these ideas that they are just ideas.
What ever you choose - test, test, test, be sure of the decision you make.

Memcache

Fichier:caching-27-08-add-memcache-store.png
Add Memcache store screenshot

Before you can add a Memcache store instance you must first have a Memcached server you can access and have the Memcache php extension installed and enabled on your web server.

Like the file store you must provide a the store name. It is used to identify the store instance in the configuration interface and must be unique to the site.
For a Memcache store you must also enter the Memcache server, or servers you wish it to make use of. Servers should be added one per line and each line can contain 1 to 3 properties separated by colons.

  1. The URL or IP address of the server (required)
  2. The port the server is listening on (optional)
  3. The weight to give this server (optional)

For example, if you had two Memcached instances running on your server, one configured for the default port, and one configured for 11212 you would use the following: 127.0.0.1 127.0.0.1:11212

Optionally you can also specify a key prefix to use. What you enter here will prefixed to all keys before accessing the server and can be used to effectively partition the Memcache space in a recognisable way. This can be handy if you have a management tool for you Memcached server that you use to inspect what is stored there.

Important implementation notes

  • The Memcache extension does not provide a means of deleting a set or entries. Either a single entry is deleted, or all entries are deleted.
    Because of this it is important to note that when you purge a Memcache store within Moodle it deletes ALL entries in the Memcache backend. Not just those relating to Moodle.
    For that reason it is highly recommended to use dedicated Memcached servers and to NOT configure any other software to use those servers. Doing so may lead to performance depreciation and adverse affects.
  • Likewise if you want to use Memcache for caching and for sessions in Moodle it is essential to use two Memcached servers. One for sessions, and one for caching. Otherwise a cache purge in Moodle will purge your sessions!

Memcached

Fichier:caching-27-09-add-memcached-store.png
Add Memcached store screenshot

Like the Memcache store you must first have a Memcached server you can access and have the Memcached php extension installed and enabled on your server.

Also like the Memcache store there are two required parameters in configuring a Memcached store.

Store name
It is used to identify the store instance in the configuration interface and must be unique to the site.
Servers
The servers you wish this cache store use. See below for details.

Servers should be added one per line and each line can contain 1 to 3 properties separated by colons.

  1. The URL or IP address of the server (required)
  2. The port the server is listening on (optional)
  3. The weight to give this server (optional)

For example, if you had two Memcached instances running on your server, one configured for the default port, and one configured for 11212 you would use the following: 127.0.0.1 127.0.0.1:11212

There are also several optional parameters you can set when creating a Memcached store.

Use compression
Defaults to true, but can be disabled if you wish.
Use serialiser
Allows your to select which serialiser gets used when communicating with the Memcache server. By default the Memcached extension and PHP only provide one serialised, however there is a couple of others available for installation if you go looking for them. One for example is the igbinary found at https://github.com/igbinary/igbinary.
Prefix key
Allows you to set some characters that will be prefixed to all keys before interacting with the server.
Hash method
The hash method provided by the Memcached extension is used by default here. However you can select to use an alternative if you wish. http://www.php.net/manual/en/memcached.constants.php provides a little information on the options available. Please note if you wish to you can also override the default hash function PHP uses within your php.ini.
Buffer writes
Disabled by default, and for good reason. Turning on buffered writes will minimise interaction with the Memcached server by buffering io operations. The downside to this is that on a system with any concurrency there is a good chance multiple requests will end up generating the data because no one had pushed it to the Memcached server when they first requested it. Enabling this can be advantageous for caches that are only accessed in capability controlled areas for example where multiple interaction is taking a toll on network resources or such. But that is definitely on the extreme tweaking end of the scale.

Important implementation notes

  • The Memcached extension does not provide a means of deleting a set or entries. Either a single entry is deleted, or all entries are deleted.

Because of this it is important to note that when you purge a Memcached store within Moodle it deletes ALL entries in the Memcached server. Not just those relating to Moodle.
For that reason it is highly recommended to use dedicated Memcached servers and to NOT configure any other software to use the same servers. Doing so may lead to performance depreciation and adverse affects.

  • Likewise if you want to use Memcached for caching and for sessions in Moodle it is essential to use two Memcached servers. One for sessions, and one for caching. Otherwise a cache purge in Moodle will purge your sessions!

MongoDB

Fichier:caching-27-10-add-mongodb-store.png
Add MongoDB store screenshot

MongoDB is an open source document orientated NoSQL database. Check out their website www.mongodb.org for more information.

Store name
Used to identify the store instance in the configuration interface and must be unique to the site.
Server
This is the connection string for the server you want to use. Multiple servers can be specified using a comma-separated list.
Database
The name of the database to make use of.
Username
The username to use when making a connection.
Password
The password of the user being used for the connection.
Replica set
The name of the replica set to connect to. If this is given the master will be determined by using the ismaster database command on the seeds, so the driver may end up connecting to a server that was not even listed.
Use
If enabled the usesafe option will be used during insert, get, and remove operations. If you've specified a replica set this will be forced on anyway.
Use safe value
You can choose to provide a specific value for use safe. This will determine the number of servers that operations must be completed on before they are deemed to have been completed.
Use extended keys
If enabled full key sets will be used when working with the plugin. This isn't used internally yet but would allow you to easily search and investigate the MongoDB plugin manually if you so choose. Turning this on will add an small overhead so should only be done if you require it.

Mapping a cache to a store instance

Fichier:caching-27-11-store-mapping.png
Cache definition store mapping screenshot

Mapping a store instance to a cache tells Moodle to use that store instance when the cache is interacted with. This allows the Moodle administrator to control where information gets stored and to most importantly optimise performance of your site by making the most of the resources available to your site.

To set a mapping first browse to the cache configuration screen.
Proceed to find the Known cache definitions table and within it find the cache you'd like to map. In the actions column select the link for Edit mappings.

The screen you are presented allows you to map one or more cache store instances to be used by this cache.
You are presented with several drop-downs that allow you to map one or more cached. All mapped caches get interacted with. The "Primary" store is the store that will be used first when interacting with the cache. The "Final" mapped store will be the last cache store interacted with.
How this interaction occurs is documented below.

If no stores are mapped for the cache then the default stores are used. Have a look at the section below for information on changing the default stores.

If a single store instance is mapped to the cache the following occurs:

Getting data from the cache
Moodle asks the cache to get the data. The cache attempts to get it from the store. If the store has it it gives it to the cache, and the cache gives it to Moodle so that it can use the data. If the store doesn't have it the a fail is returned and Moodle will have to generate the data and will most likely then send it to the cache.
Storing data in the cache
Moodle will ask the cache to store some data, and the cache will give it to the cache store.

If multiple store instances are mapped to the cache the following occurs:

Getting data from a store
Moodle asks the cache to get the data. The cache attempts to get it from the first store. If the first store has it then it returns the data to the cache and the cache returns it to Moodle. If the first store doesn't have the data then it attempts to get the data from the second store. If the second store has it it returns it to the first store that then stores it itself before returning it to the cache. If it doesn't then the next store is used. This continue until either the data is found or there are no more stores to check.
Storing data in the cache
Moodle will ask the cache to store some data, the cache will give it to every mapped cache store for storage.

The main advantage to assigning multiple stores is that you can introduce cache redundancy. Of course this introduces an overhead so it should only be used when actually required. The following is an example of when mapping multiple stores can provide an advantage:

Scenario:
You have have a web server that has a Moodle site as well as other sites.
You also have a Memcache server that is used by several sites including Moodle.

Memcache has a limited size cache, that when full and requested to store more information frees space by dropping the least used cache entries.

You want to use Memcache for your Moodle site because it is fast, however you are aware that it may introduce more cache misses because it is a heavily used Memcache server.

Solution:
To get around this you map two stores to caches you wish to use Memcache.
You make Memcache the primary store, and you make the default file store the final cache store.

Explanation:
By doing this you've created redundancy, when something is requested Moodle first tries to get it from Memcache (the fastest store) and if its not there it proceeds to check the file cache.

Just a couple more points of interest:

  • Mapping multiple caches will introduce overhead, the more caches mapped the more overhead.
  • Consider the cache stores you are mapping to, if data remains there once set then there is no point mapping any further stores after it. This technique is primarily valuable in situations where data is not guaranteed to remain after being set.
  • Always test your configuration. Enable the display of performance information and then watch which stores get used when interacting with Moodle in such a way as to trigger the cache.

Setting the stores that get used when no mapping is present

Fichier:caching-27-12-default-store-mapping.png
Setting which stores get used when no mapping is present screenshot

This is really setting the default stores that get used for a cache type when there is not a specific mapping that has been made for it.

To set a mapping first browse to the cache configuration screen.
Proceed to find the Stores used when no mapping is present table.
After the table you will find a link Edit mappings, click this.

On the screen you are presented with you can select one store for each cache type to use when a cache of the corresponding type gets initialised and there is not an explicit mapping for it.

Note that on this interface the drop downs only contain store instances that are suitable for mapping to the type. Not all instances will necessarily be shown. If you have a store instance you don't see then it is not suitable for ALL the cache definitions that exist.
You will not be able to make that store instance the default, you will instead need to map it explicitly to each cache you want/can use it for.

Configuring caching for your site

This is where it really gets tricky, and unfortunately there is no step-by-step guide to this.

How caching can be best configured for a site comes down entirely to the site in question and the resources available to it.

What can be offered are some tips and tricks to get you thinking about things and to perhaps introduce ideas that will help you along the way.

If you are reading this document and you've learnt a thing or two about configuring caching on your site share your learnings by adding to the points here.

  • Plan it. It's a complex thing. Understand your site, understand your system, and really think how users will be using it all.
  • If you've got a small site the gains aren't likely to be significant, if you've got a large site getting this right can lead to a substantial boost in performance.
  • When looking at cache backends really research the advantages and disadvantages of each. Keep your site in mind when thinking about them. Depending upon your site you may find that no one cache backend is going to meet the entire needs of your site and that you will benefit from having a couple of backends at your disposal.
  • Things aren't usually as simple as installing a cache backend and then using it. Pay attention to configuration and try to optimise it for your system. Test it separately and have an understanding of its performance before tell Moodle about it. The cache allows you to shift load off the database and reduce page request processing.
    If for instance you have Memcache installed but your connection has not been optimised for it you may well find yourself in a losing situation before you even tell Moodle about the Memcache server.
  • When considering your default store instances keep in mind that they must operate with data sets of varying sizes and frequency. For a large site really your best bet is to look at each cache definition and map it to a store that is best suited for the data it includes and the frequency of access.
    Cache definitions have been documented Cache definitions.
  • Again when mapping store instances to caches really think about the cache you are mapping and make a decision based upon what you understand of your site and what you know about the cache.
    Cache definitions have been documented Cache definitions.
  • Test your configuration. If you can stress test it even better! If you turn on performance information Moodle will also print cache access information at the bottom of the screen. You can use this to visually check the cache is being used as you expect, and it will give you an indication of where misses etc are occurring.
  • Keep an eye on your backend. Moodle doesn't provide a means of monitoring a cache backend and that is certainly something you should keep an eye on. Memcache for instance drops least used data when full to make room for new entries. APC on the other hand stops accepting data when full. Both will impact your performance if full and you're going to encounter misses. However APC when full is horrible, but it is much faster.

More on performance testing

Two links that might be useful to anyone considering testing performance on their own servers:

Performance advice for load-balanced web servers

  1. In Moodle 2.4 onwards with load-balanced web servers, don't use the default caching option that stores the data in moodledata on a shared network drive. Use memcached instead. See Tim Hunt's article on http://tjhunt.blogspot.de/2013/05/performance-testing-moodle.html
  2. In Moodle 2.6 onwards make sure you set $CFG->localcachedir to some local directory in config.php (for each node). This will speed up some of the disk caching that happens outside of MUC, such as themes, javascript, libraries etc.

Troubleshooting

Have you encountered a problem, or found yourself in a conundrum? Perhaps the answer is in this section. If its not when you find have an answer how about sharing it here.

More information


Cache related forum discussions that may help in understanding MUC:


Other:

See also