Redis windows redis conf

*Redis configuration

Redis is able to start without a configuration file using a built-in default configuration, however this setup is only recommended for testing and development purposes.

The proper way to configure Redis is by providing a Redis configuration file, usually called redis.conf .

The redis.conf file contains a number of directives that have a very simple format:

This is an example of configuration directive:

It is possible to provide strings containing spaces as arguments using (double or single) quotes, as in the following example:

Single-quoted string can contain characters escaped by backslashes, and double-quoted strings can additionally include any ASCII symbols encoded using backslashed hexadecimal notation «\xff».

The list of configuration directives, and their meaning and intended usage is available in the self documented example redis.conf shipped into the Redis distribution.

*Passing arguments via the command line

Since Redis 2.6 it is possible to also pass Redis configuration parameters using the command line directly. This is very useful for testing purposes. The following is an example that starts a new Redis instance using port 6380 as a slave of the instance running at 127.0.0.1 port 6379.

The format of the arguments passed via the command line is exactly the same as the one used in the redis.conf file, with the exception that the keyword is prefixed with — .

Note that internally this generates an in-memory temporary config file (possibly concatenating the config file passed by the user if any) where arguments are translated into the format of redis.conf.

*Changing Redis configuration while the server is running

It is possible to reconfigure Redis on the fly without stopping and restarting the service, or querying the current configuration programmatically using the special commands CONFIG SET and CONFIG GET

Not all the configuration directives are supported in this way, but most are supported as expected. Please refer to the CONFIG SET and CONFIG GET pages for more information.

Note that modifying the configuration on the fly has no effects on the redis.conf file so at the next restart of Redis the old configuration will be used instead.

Make sure to also modify the redis.conf file accordingly to the configuration you set using CONFIG SET. You can do it manually, or starting with Redis 2.8, you can just use CONFIG REWRITE, which will automatically scan your redis.conf file and update the fields which don’t match the current configuration value. Fields non existing but set to the default value are not added. Comments inside your configuration file are retained.

*Configuring Redis as a cache

If you plan to use Redis just as a cache where every key will have an expire set, you may consider using the following configuration instead (assuming a max memory limit of 2 megabytes as an example):

In this configuration there is no need for the application to set a time to live for keys using the EXPIRE command (or equivalent) since all the keys will be evicted using an approximated LRU algorithm as long as we hit the 2 megabyte memory limit.

Basically in this configuration Redis acts in a similar way to memcached. We have more extensive documentation about using Redis as an LRU cache.

Как установить Redis в ОС Windows без использования Docker

Пошаговое руководство по работе с популярной NoSQL базой данных.

Просто и быстро установить Redis в ОС Windows позволяет Chocolatey. Это менеджер пакетов в среде Windows, аналогичный apt-get в мире Linux. С его помощью можно устанавливать множество программ и обновлять их, не скачивая каждый раз дистрибутив с сайта.

Установка Chocolatey

Действуем по инструкции с официального сайта проекта Chocolatey.

Требования к системе

  • Windows 7+ / Windows Server 2003+;
  • PowerShell v2+. Для установки с сайта требуется как минимум v3 (из-за требований TLS 1.2);
  • .NET Framework 4+. Программа попытается установить .NET 4.0, если он не установлен. Минимальная необходимая версия для установки с этого веб-сайта — 4.5 (из-за требований TLS 1.2).
Читайте также:  Планшет айпад или windows

Преподаватель Skillbox. Пишет про Java, учит Go. Помнит рассвет PHP и как «грабить корованы».

Проверяем версию системы

Запустите консоль запуска команд, нажав WIN + R, и введите команду cmd. Если вверху выведена версия Windows, как на скриншоте, этого достаточно.

Если нет, введите команду systeminfo. В начале вывода должна появиться версия Windows.

Если у вас установлена версия 7 или выше — переходим к следующему шагу.

Проверяем версию PowerShell

Для этого открываем PowerShell, вводим команду $PSVersionTable.PSVersion и получаем ответ:

На нашем скриншоте версия PowerShell 5.1. Если у вас версия ниже 3, необходимо установить PowerShell версии 3 (или выше). Инструкция есть по этой ссылке.

Проверяем версию.NET Framework

Запускаем редактор реестра: нажимаем WIN + R и выполняем команду regedit.

Переходим в раздел

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP и смотрим, какие папки там присутствуют:

Если нет такой ветки или отсутствует версия 4.0 и выше, то необходимо её установить. Подробная инструкция находится по этой ссылке.

Установка Chocolatey

После всех подготовительных действий устанавливаем Chocolatey. Это делается одной командой PowerShell.

Важно! До начала установки необходимо проверить, есть ли на это права. Если прав недостаточно, их нужно добавить.

В PowerShell необходимо убедиться, что Get-ExecutionPolicy не является Restricted. Рекомендуется использовать Bypass для снятия ограничений или AllSigned для более безопасного использования.

Выполните команду Get-ExecutionPolicy. Если она вернёт Restricted, запустите Set-ExecutionPolicy AllSigned (рекомендуется) или Set-ExecutionPolicy Bypass -Scope Process.

Установка и настройка Redis

Redis (REmote DIctionary Server) — это нереляционная высокопроизводительная СУБД, сетевое хранилище данных типа «ключ — значение».

Отличие Redis от других хранилищ состоит в том, что значения ключей не ограничиваются строками; есть поддержка таких абстрактных типов данных, как строки, списки, множества, хэш-таблицы и другие.

Также, рассказывая о Redis, часто выделяют ее высокую производительность: причина заключается в том, что все данные хранятся в оперативной памяти. Поэтому есть смысл использовать Redis для работы с быстроменяющимися и активно запрашиваемыми данными.

Redis может стать более чем полноценной заменой Memcached, дав возможность использовать репликацию, более длинные ключи и значения и многое другое.

Изначально установку Redis сервера рекомендуется проводить из репозиториев используемой операционной системы. Предполагается, что последующие команды будут выполняться от имени пользователя root или при использование sudo (если Вы авторизованы не от пользователя root, рекомендуем выполнить sudo su).

Установка на DEB дистрибутивы (Ubuntu/Debian)

Сначала выполним обновление пакетов:

После чего непосредственно выполнив установку Redis сервера:

После завершения установки проверим работу установленного сервиса:

В случае успешной установки в ответ придет текст — PONG, если сервис не установился или не запустился, на экран будет выведена ошибка, о невозможности подключится к сервису или отсутствии команды redis-cli .

Если Redis сервер установлен и запустился, то он будет ожидать подключение на локальном интерфейсе 127.0.0.1 (localhost), порт стандартный — 6379.

Установка на RHEL (CentOS/BitrixOS)

Процесс установки почти не отличается от установки на Debian дистрибутивы. Сначала обновляем пакеты:

Выполняем установку Redis сервера:

Запускаем сервис и добавляем его в автозагрузку:

После чего проверим его работу:

В независимости от используемого дистрибутива Вы всегда можете установить последнюю версию Redis сервера, собрав её из исходных кодов по инструкции с официального сайта проекта Redis:

Настройка Redis

Для Ubuntu и Debian основной конфигурационный файл Redis сервера Вы найдете по пути /etc/redis/redis.conf, в CentOS (а также BitrixOS) конфигурация располагается в файле /etc/redis.conf.

Наиболее интересным будет параметр maxmemory , он задает ограничение использования оперативной памяти для хранения данных в Redis. По умолчанию Redis может использовать всю доступную память сервера, поэтому если сервер не обладает достаточным количеством постоянно свободной памяти (Вы можете просмотреть информацию о используемой памяти командой free -m ), то стоит задать этот параметр. Самым простым решением для выбора максимального объема памяти будет разделить среднее значение нескольких показаний свободной памяти ( free -m ) пополам.

Например, в течение часа показатели free -m были следующими:

Средним показателем для свободной памяти (столбец free) будет 187 ((204+188+169)/3=187), поэтому ограничим maxmemory в 180 Мб. Для этого откроем файл redis.conf, найдем строку “ # maxmemory ”: и заменим её указав нужное значение:

Также в данном файле стоит обратить внимание на следующие параметры:

  • maxclients — количество разрешенных клиентов;
  • tcp-backlog — количество соединений которые могут находится в очереди, если все возможные соединения заняты;
  • save условия, при которых данные будут записываться на диск. Данные Redis хранятся в оперативной памяти и в зависимости от значений save сохраняются на диск, что замедляет производительность, но повышает надежность хранения данных. Условию save передается два значение: количество секунд и количество изменений, если за указанное количество происходит указанное количество изменений, то данные будут сохранены на диск. По умолчанию параметры выглядят так:
Читайте также:  Yandex download linux ubuntu

save 900 1 — сохранить, если за 900 секунд будет хотя бы одно изменение;

save 300 10 — сохранить, если за 300 секунд будет хотя бы 10 изменений;

save 60 10000 — сохранить, если за 60 секунд будет 10000 и более изменений.

Вы можете редактировать текущие правила или удалять их. Вы можете просто закомментировать их (поставить в начале строки #), в этом случае будет достигнута максимальная производительность, т. к. данные не будут записываться на диск, но в случае перезагрузки сервера или Redis все данные будут утеряны.

После внесения каких-либо изменений в конфигурационный файл Redis необходимо перезапустить.

Заключение

Теперь Вы знаете, как правильно устанавливать и настраивать Redis. Больше информации о конфигурации Redis сервера Вы можете получить из его документации:

Redis windows redis conf

Redis on Windows

This project contains the binary releases of MS Open Tech redis port of windows as well as a vagrant configuration for redis letting you run the native version of Redis in a Virtual Box VM.

Whilst it’s recommended to use Redis on Linux in production, it is often useful for developers on Windows platforms to have their own local version of redis running to develop with.

The 3 most popular ways of running redis on windows is to use the binary releases of Microsoft’s native port of redis, but as this is an unofficial port it always lags behind the latest official development of redis on Linux/OSX.

Thanks to Vagrant you can choose to run the latest linux version inside a Virtual Box Linux VM where you’ll be able to run the official native version of redis.

Or if you have the latest version of Windows 10 you can install Bash on Ubuntu on Windows which will let you run the official version of Redis on Ubuntu on Windows 🙂 This is our preferred approach as it lets you run native Ubuntu binaries on Windows more efficiently than running Linux in a VM:

Option 1) Install Redis on Ubuntu on Windows

  1. From Start, search for Turn Windows features on or off (type turn )
  2. Select Windows Subsystem for Linux (beta)

Once installed you can run bash on Ubuntu by typing bash from a Windows Command Prompt. To install the latest version of Redis we first need to install some prerequisites:

Then follow the official installation guide to download, build and install the latest stable version. NOTE: Installing the binaries using make install will not work. You need to copy them manually to /usr/bin (just like described in the guide, except that they use /usr/local/bin — which is the problem).

You’ll then be able to launch redis with:

Which will run redis in the background freeing your shell so you can play with it using the redis client:

Which you can connect to from within bash or from your Windows desktop using the redis-cli native Windows binary from MSOpenTech.

Option 2) Running the latest version of Redis with Vagrant

2. Download the vagrant-redis.zip vagrant configuration

3. Extract vagrant-redis.zip in any folder, e.g. in c:\vagrant-redis

4. Launch the Virtual Box VM with vagrant up

This will launch a new Ubuntu VM instance inside Virtual Box that will automatically install and start the latest stable version of redis.

The vagrant configuration was originally from JasonPunyon/redishobo and has been modified to use the latest stable release of Redis.

Option 3) Running Microsoft’s native port of Redis

These 64-bit binary releases are created by building the Microsoft’s native port of redis which have also been published on NuGet, but as it’s more convenient we provide a zip of the 64-bit binaries here.

Читайте также:  Служба активации windows kms

MS Open Announcements

Current Version: 3.0.503 (June 28, 2016)

1. Download the redis-latest.zip native 64bit Windows port of redis

2. Extract redis64-latest.zip in any folder, e.g. in c:\redis

3. Run the redis-server.exe using the local configuration

4. Run redis-cli.exe to connect to your redis instance

5. Start playing with redis 🙂

The MSOpenTech of Redis adds some useful extensions for better integration with Windows:

Running Redis as a Service

If you installed Redis using the MSI package, then Redis was already installed as a Windows service. Nothing further to do. If you would like to change its settings, you can update the redis.windows-service.conf file and then restart the Redis service (Run -> services.msc -> Redis -> Restart).

During installation of the MSI you can either use the installer’s user interface to update the port that Redis listens to and the firewall exception or run it silently without a UI. The following examples show how to install from the command line:

default install (port 6379 and firewall exception ON):

set port and turn OFF firewall exception:

set port and turn ON firewall exception:

install with no user interface:

If you did not install Redis using the MSI package, then you still run Redis as a Windows service by following these instructions:

In order to better integrate with the Windows Services model, new command line arguments have been introduced to Redis. These service arguments require an elevated user context in order to connect to the service control manager. If these commands are invoked from a non-elevated context, Redis will attempt to create an elevated context in which to execute these commands. This will cause a User Account Control dialog to be displayed by Windows and may require Administrative user credentials in order to proceed.

Installing the Service

This must be the first argument on the redis-server command line. Arguments after this are passed in the order they occur to Redis when the service is launched. The service will be configured as Autostart and will be launched as «NT AUTHORITY\NetworkService». Upon successful installation, a success message will be displayed and Redis will exit.

This command does not start the service.

Uninstalling the Service

This will remove the Redis service configuration information from the registry. Upon successful uninstallation, a success message will be displayed and Redis will exit. This does command not to stop the service.

Starting the Service

This will start the Redis service. Upon successful startup, a success message will be displayed and Redis service will be started.

Stopping the Service

This will stop the Redis service. Upon successful termination, a success message will be displayed and Redis will exit.

Naming the Service

This optional argument may be used with any of the preceding commands to set the name of the installed service. This argument should follow the service-install, service-start, service-stop or service-uninstall commands, and precede any arguments to be passed to Redis via the service-install command. The following would install and start three separate instances of Redis as a service:

Redis Vue is a simple, lightweight, versatile Redis Admin UI developed using Vue and ServiceStack .NET Core Web Apps. It supports Redis’s core Strings, Lists, Sets, Sorted Sets and Hash data structures and custom Redis commands with its entire functionality contained in a single /app/index.html using the dynamic ServiceStack Templates language, making it easy to customize and further enhance.

Redis React is a simple user-friendly UI for browsing data in Redis servers which takes advantages of the complex type conventions built in the ServiceStack.Redis Client to provide a rich, human-friendly UI for navigating related datasets, enabling a fast and fluid browsing experience for your Redis servers.

Windows, OSX and Linux downloads available from Redis React Home Page

See the redis config project for a quick way to setup up the minimal highly available Redis Sentinel configuration including start/stop scripts for instantly running multiple redis instances on a single (or multiple) Windows, OSX or Linux servers.

About

Vagrant redis configuration and the binary releases of MS Open Tech redis port of windows

Оцените статью