Start with Redis cache from scratch
This article mainly introduces how to start Redis cache from scratch. It has certain reference value. Now I share it with you. Friends in need can refer to it
Redis introduction
Redis is an open source language using ANSI C #Write, support network, log-type, memory-based and persistent, Key-Valuedatabase, and provide multiple languagesAPI. From 2010#3月15,## The development of #Redis is hosted by VMware. Starting from 5 in #2013, Redis has been developed by PivotalSponsored. redis is a key-value
storage system. Similar to Memcached, it supports storing relatively more value types, including string( String)、list(Linked list)、set(SET)、zset(sorted set --ordered set) and hash (hash type). These data types support push/pop, add/remove and fetch Intersection, union and difference and richer operations, and these operations are all atomic. On this basis, redis supports various sorting methods. Like memcached, in order to ensure efficiency, data is cached in memory. The difference is that redis will periodically write updated data to disk or write modification operations to additional record files, and on this basis, master-slave(Master-slave) Synchronization.
Redis — это высокопроизводительная база данных ключ-значение. Появление redis во многом компенсировало memcached этого типаkey/valueНедостаточное хранилище может сыграть очень хорошую дополнительную роль для реляционной базы данных в некоторых ситуациях. Он предоставляет Java, C/C , C#, PHP,JavaScript,Perl,Object-C , Python, Ruby, Erlang и другие клиенты, используйте очень удобный. [1]
##Redis поддерживает синхронизацию master-slave. Данные могут быть синхронизированы с главного сервера на любое количество подчиненных серверов, а подчиненный сервер может быть главным сервером, связанным с другими подчиненными серверами. Это позволяет Redis выполнять одноуровневую репликацию дерева. Сохранение может записывать данные намеренно или непреднамеренно. Поскольку механизм подписки на публикацию / полностью реализован, когда подчиненная база данных синхронизирует дерево где угодно, она может подписаться на канал и получить полную запись публикации сообщения главного сервера. Синхронизация полезна для масштабируемости и избыточности данных операций чтения. Адрес официального сайта
redis очень легко запомнить: это redis.io. (Я специально проверил и обнаружил, что суффикс доменного имени io принадлежит национальному доменному имени, которое британская территория в Индийском океане, то есть Британская территория в Индийском океане)
В настоящее время Vmware финансирует разработку и поддержание проект redis.
2. Установка RedisИзвлечение установочного файла#После распаковки
Выполните команду make для компиляции
Компилируйте OK,
Введите каталог src
Работа терминала Redis-cli
Файл Redis-сервера для запуска службы Redis
Тестовый файл давления Redis-benchmark
Redis-check-xx Сценарий резервного файла проверки автомобиля
Создайте рабочий каталог Redis и скопируйте два запущенных файла в прошлое
Копируем файл конфигурации в прошлое
#3. Запускаем сервис Redis
Признаки успешного фронтенда запуск службы redis
./redis-server
В настоящее время возникла проблема. Текущую службу невозможно отключить. После выключения она исчезнет, поэтому ее необходимо изменить.
Остановить службу Ctrl z
Сначала остановите службу redis
Используйте фон для запуска службы redis
vim redis.conf
Измените значение на «Да», чтобы сохранить и установить Запустить Redis в фоновом режиме
Начать снова
Я обнаружил, что он все еще запускается в интерфейс
#Включите его при запуске. Запустите файл конфигурации вместе
Проверьте процесс redis
Обнаружено, что Redis запущен
4. Простое использование
Три переменные установлены, и эти три переменные хранятся в памяти.
Как читать?
Получать!
5. Конкретные операции
1. Операция с ключами
В redis нельзя использовать «\n» и пробелы как дополнительно к содержимому компонента имени, другой контент может использоваться как часть имени ключа. Длина имени не требуется
Код | Функция |
##Существует ключ | Существует ли он |
Del key1 key2…. | Удалить указанный ключ |
Тип ключа | #Возвращает тип значения данного ключа |
Шаблон ключа | Вернуть все ключи, соответствующие указанному шаблону |
##Переименовать старый ключ newkey |
Изменить имя |
#Dbsize | ##Вернуть количество ключей в текущая база данных
|
Укажите срок действия ключа | |
#Возвращает время действия ключа в секундах | |
Выбрать базу данных | |
Переместить ключ из текущей базы данных в указанную базу данных | |
#Удалить все ключи в текущей базе данных | |
Удалить все ключи во всех базах данных |
Вот пример использования
Code | Функция | ||||||||||||||||||||||||||||||||||||||||||||||||||||
##Установить значение, соответствующее ключ к значению строкового типа | |||||||||||||||||||||||||||||||||||||||||||||||||||||
##Задайте значения нескольких ключей в Once |
Mget key1 key2 … keyN | ||||||||||||||||||||||||||||||||||||||||||||||||||||
##Получение значений нескольких ключей одновременно
|
Incr key | ||||||||||||||||||||||||||||||||||||||||||||||||||||
Операция над значением ключа | ## Ключ Decr |
||||||||||||||||||||||||||||||||||||||||||||||||||||
##Incrby целое число ключа | |||||||||||||||||||||||||||||||||||||||||||||||||||||
Decrby ключевое целое число | |||||||||||||||||||||||||||||||||||||||||||||||||||||
Добавить значение ключа | |||||||||||||||||||||||||||||||||||||||||||||||||||||
##Substr key start end | Возвращает строковое значение перехваченного ключа | ||||||||||||||||||||||||||||||||||||||||||||||||||||
##
3.Введение и использование типа связанного списка «Список»Тип списка на самом деле представляет собой двусвязный список If вы хотите запросить 10 последних последних пользователей, необходимо проверять по одному, что требует слишком много ресурсов Пример списка связанных списков: Сквозной список В связанном списке хранится информация о 5 последних пользователях, вошедших в систему Новые пользователи приходят, а старые удаляются Как работать со связанным список?
Есть ключ с пятью элементами Затем добавьте ссылку 5.SortSet операция типа сортированного набораКак и набор, отсортированный набор также представляет собой набор строковых элементов Разница в том, что каждому элементу присвоен вес Элементы в наборе можно получить по порядку по значению веса Случай: Используйте набор сортировки, чтобы получить 5 самых популярных постов для обучения Каждый элемент в отсортированном наборе представляет собой комбинацию значения и веса
|
The above is the detailed content of Start with Redis cache from scratch. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

How to clear Redis data: Use the FLUSHALL command to clear all key values. Use the FLUSHDB command to clear the key value of the currently selected database. Use SELECT to switch databases, and then use FLUSHDB to clear multiple databases. Use the DEL command to delete a specific key. Use the redis-cli tool to clear the data.

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

On CentOS systems, you can limit the execution time of Lua scripts by modifying Redis configuration files or using Redis commands to prevent malicious scripts from consuming too much resources. Method 1: Modify the Redis configuration file and locate the Redis configuration file: The Redis configuration file is usually located in /etc/redis/redis.conf. Edit configuration file: Open the configuration file using a text editor (such as vi or nano): sudovi/etc/redis/redis.conf Set the Lua script execution time limit: Add or modify the following lines in the configuration file to set the maximum execution time of the Lua script (unit: milliseconds)

Use the Redis command line tool (redis-cli) to manage and operate Redis through the following steps: Connect to the server, specify the address and port. Send commands to the server using the command name and parameters. Use the HELP command to view help information for a specific command. Use the QUIT command to exit the command line tool.

Redis counter is a mechanism that uses Redis key-value pair storage to implement counting operations, including the following steps: creating counter keys, increasing counts, decreasing counts, resetting counts, and obtaining counts. The advantages of Redis counters include fast speed, high concurrency, durability and simplicity and ease of use. It can be used in scenarios such as user access counting, real-time metric tracking, game scores and rankings, and order processing counting.

There are two types of Redis data expiration strategies: periodic deletion: periodic scan to delete the expired key, which can be set through expired-time-cap-remove-count and expired-time-cap-remove-delay parameters. Lazy Deletion: Check for deletion expired keys only when keys are read or written. They can be set through lazyfree-lazy-eviction, lazyfree-lazy-expire, lazyfree-lazy-user-del parameters.

In Debian systems, readdir system calls are used to read directory contents. If its performance is not good, try the following optimization strategy: Simplify the number of directory files: Split large directories into multiple small directories as much as possible, reducing the number of items processed per readdir call. Enable directory content caching: build a cache mechanism, update the cache regularly or when directory content changes, and reduce frequent calls to readdir. Memory caches (such as Memcached or Redis) or local caches (such as files or databases) can be considered. Adopt efficient data structure: If you implement directory traversal by yourself, select more efficient data structures (such as hash tables instead of linear search) to store and access directory information
