Total Pageviews

Showing posts with label redis. Show all posts
Showing posts with label redis. Show all posts

Thursday, 16 July 2026

Using Redis as a primary database

 

When we think of a structured databases, we think about rows, columns, tables, and the relationships between different tables. And we are correct about this. Most applications we use/develop use some sort of relational database, such as PostgreSQL, MySQL, and MariaDB. Then, we have applications that use NoSQL databases, like MongoDB.

Redis is popularly known for being used as a cache store alongside Relational Database Management System (RDBMS). As it is an in-memory data store, the read/write speed is higher than traditional RDBMS, which stores data on the disk. However, there are downsides to this database as well. For instance, there are memory limitations as all the data is stored in memory (or RAM), and a large amount of RAM can significantly increase the cost of the server on the cloud.

Using Redis as a Cache

Image credit: backendless.com

Redis can be viewed as an intermediate data store or cache that temporarily stores frequently requested data from the database so that database operations are reduced. When the data is not present in the cache, it is retrieved from the persistent database and cached to Redis for further retrieval.

Redis as a Primary database

When we think of using Redis as a primary database, we need to figure out how to store all of our application’s data on Redis, i.e., user data, login credentials, relationships, indexes, etc. Redis has grown from simply storing key-value pairs to storing multiple data structures like Sets, Bitmaps, Hyperloglogs, and others.

Database design of Shortomega

As key-value stores like Redis don’t have rows, columns, tables, or relationships, I need to devise a solution.

Let’s start with a simple data — user’s email and password:

Each user has a unique email and corresponding password to log in. We typically store the hashed value of the password using a hashing algorithm like SHA-1 or SHA-256 to protect the plain password from attackers.

We can store email ID with the corresponding user ID by adding the prefix “email” to the key:

email:<userid> -> <email address>

        
        
      

And the hashed password using:

password:<password> -> password

        
        
      

However, there are some issues with this approach. Whenever we need to add new attributes to the same user, we must add a new hash with a new prefix every time. This will significantly increase the memory space needed to store each user's attributes. Moreover, we usually need to set and retrieve email and password together and for that, we have to perform 2 database operations.

Redis has a built-in structure called hashes which is a collection of field-value pairs. We use the HSET command to add fields to the hash. HSET syntax looks something like this:

HSET key field value [field value ...]

        
        
      

Now we have only one hash for each user data and can store data in this way:

HSET user:<userid> email mail@test.com password <hashed-password> [...other fields and value]

        
        
      

We can easily retrieve all fields using HGETALL command:

Now that we have successfully stored user data efficiently, I will explain how I am building a URL shortener application — Shortomega using Redis as the primary database. I am storing the user login credentials similarly as explained before.

To store short URLs and their corresponding long URL, I am simply storing them in key-value pairs to query them in O(1) time.

short:<short-url> -> <long-url>

        
        
      

In order to associate a short URL to a user, I created a set of short URLs for each user as shown below so that I can retrieve all the created short URLs in a single Redis query.

user:<userid>:urls -> [set]

        
        
      

Challenges

Using sets to store short URLs created by a particular user, I need to perform additional N queries to retrieve corresponding long URLs. This is similar to the N+1 query problem in databases. To address this, I needed to choose between these 2 options:

  1. Store the long URL along with the short URL for a particular user. This will result in redundancy. Managing and updating the URLs at the two places would be cumbersome.

  2. Another option is to write a custom Lua script that runs on the Redis instance and returns the pairs of short and corresponding long URLs. This solves the N+1 query problem and gives the result in a single query. I chose to use this method. The script looks something like this:

local urls = redis.call('SMEMBERS', KEYS[1])
local result = {}
for i, url in ipairs(urls) do
    local longUrl = redis.call('GET', 'short:'..url)
    if longUrl then
        table.insert(result, url)
        table.insert(result, longUrl)
    end
end
return result

        
        
      

In the above Lua script, I am fetching all the short URLs based on the user ID passed from the NestJS backend. By looping over each URL, I get the corresponding long URL that is simply stored in a key-value pair. Lastly, I insert the pair in a table which I return to the back-end for further processing.

To benchmark the performance of retrieving the data in a single database query, I ran a Python script where I first stored and retrieved the data using N+1 queries and I executed Lua script on the Redis instance to retrieve the data in one single query. I plotted the graph as shown below:

In the above plot diagram, we can see the execution time difference between N+1 queries and the Lua script. A user with around 5000 URLs can fetch all the URLs in under 50 ms instead of 300 ms.

Analytics

Analytics include counting of total and unique visitors for each short URLs. This helps the user to track the engagements of created short links across different regions.

The count of total visits can easily be stored in a key-value pair. The value is incremented each time someone clicks on the link. But what about unique visitors? I can store unique IP addresses of visitors in a set and then count the elements in the set to get the unique visitors. However, it will take O(N*M) space in the database to store all the N IP addresses of M links, consuming the memory of the server. As mentioned before, increasing the RAM of a server instance on the cloud is more expensive than adding more disk space. It turns out that there is one special built-in data structure in Redis that can solve this problem. I am talking about HyperLogLog.

HyperLogLog is a probabilistic data structure that estimates the cardinality of a set. Basically, it estimates the number of unique elements in a set without the need for actual storage of elements in a set. It uses up to 12 KB of memory irrespective of count of elements in the set and provides a standard error of 0.81%.

We can add and count elements using following syntax:

PFADD key [element [element ...]]
PFCOUNT key [key ...]

        
        
      

I can now add the IP addresses to the HyperLogLog and count the unique IP addresses.

PFADD short:<hash>:ips [IP addresses ...]
PFCOUNT short:<hash>:ips

        
        
      

Lastly

There are endless possibilities of how we can use Redis as a cache and even as a primary database. The fast operations and in-memory operations of Redis make it an ideal choice for high-performance and real-time applications.

The URL shortener application — Shortomega is work in progress and I will add further development and details here or in another blog.

Enjoy Building!

from  https://tech.ninadnaik.me/using-redis-as-a-primary-database

Saturday, 6 June 2026

Redis-for-beginners

 

Part 1: Redis for Beginners (Part 1 of 2)

Introduction

Redis has come a long way through an evolution and, by now, it can be placed as your primary database—not just a cache layer. It features added data persistence and replication for durability and availability. Additional modules for JSON support and search make it easier to store and query more complex data. Now, Redis has an Object mapping library, Redis OM, which simplifies things.

In this two-part series, the focus is on the core of Redis. This is the first part, which will guide you through setting up a Redis database and using some basic commands.

Setting Up a Redis Database

On a Macbook, use Homebrew

First, make sure you have Homebrew installed. From the terminal, run:

brew --version

If this command fails, you'll need to follow the Homebrew installation instructions.

Installation

From the terminal, run:

brew install redis

This will install Redis on your system.

On a Windows, use WSL

Microsoft provides detailed instructions for installing WSL. Once you're running Ubuntu on Windows, you can follow the steps detailed at Redis Site Installation Steps which are the same steps for installing Redis on Linux to install recent stable versions of Redis from the official packages.

Using Redis Cloud

The last option for installing Redis is called Redis Cloud, and that's what you’ll be using here. It allows you to set up a Redis database online. It also comes with Redis insights that can be used to test different commands and visualize your stored data.

To use the Redis database online, follow the steps below:

  1. Sign Up for a Free Redis Account:

    • Visit the Redis website (https://redis.io/) and sign up for a free account.
    • Provide the necessary details and create your account.
  2. Create a Subscription:

    • Once logged in, navigate to the “Subscriptions” section (usually found in the left-hand menu).
    • Click on “New Database” or a similar option.
    • Scroll down and select the free tier, which typically comes with 30MB of storage.
    • Click on “Create Database.”
  3. Download the Redis App:

    • To work with Redis locally, download the Redis app for your system (Windows, macOS, or Linux).
    • Install the app following the instructions provided.
  4. Connect to Your Database:

    • After creating the database, find the “Connect” option and click on it.
    • Click on the "Open with RedisInsights" button. This will launch your installed Redis application.

Basic Commands

When using your RedisInsights application, navigate to your workbench. You can access your workbench by clicking on this icon:

SET: Using the SET Command to Set a Key-Value Pair

To set a key-value pair in Redis, follow these steps:

  1. In your workbench input section, type the following command:
SET key value

Replace key with the name of the key you want to set, and value with the corresponding value you want to assign to that key.

  1. Press CTRL + Enter to execute the command. For example, executing SET name maria will set the value "maria" for the key name.

  2. You should receive the message "OK" in the output section below, confirming that the key-value pair was successfully set.

  3. To verify, go back to the Redis browser, switch to the data view, and refresh the view to see the updated key-value pair.

Error Handling:

If you include a space in your data without quotes, you’ll get a syntax error. To include spaces, enclose the data in quotes.

Example:

SET name "chun li"

GET: Retrieving a Value by Key

To retrieve the value of a specific key, use the GET command. In your workbench, type:

GET key

Replace key with the name of the key you want to retrieve. For example, if you have a key named name with the value "chun li", executing GET name will return "chun li". Press CTRL + Enter to execute the command.

DEL: Deleting Keys

To delete one or more keys and their associated values, use the DEL command. In your workbench, type:

DEL key1 key2 key3 ...

Replace key1, key2, key3, etc., with the names of the keys you want to delete. For example:

DEL name1 name2

Executing this command will delete the keys name1 and name2 along with their respective values. The command will return an integer indicating the number of keys deleted. For instance, a response of 2 indicates that two keys were successfully deleted. Press CTRL + Enter to execute the command.

SET MULTIPLE: Setting Multiple Key-Value Pairs

To set multiple key-value pairs simultaneously, use the MSET command. In your workbench, use:

MSET key1 value1 key2 value2 key3 value3

Replace key1, key2, key3, etc., with the names of the keys you want to set, and value1, value2, value3, etc., with their respective values. For instance:

MSET name1 maria name2 yoshi color green rating 10

This command sets the keys name1, name2, color, and rating with their respective values. Press CTRL + Enter. Ensure the key comes first, followed by the value.

GET MULTIPLE: Retrieving Multiple Values

To retrieve values for multiple keys at once, use the MGET command. In your workbench, use:

MGET key1 key2 key3

Replace key1, key2, key3, etc., with the names of the keys you want to retrieve. For example:

MGET name1 name2 rating

This command will return the values associated with keys name1, name2, and rating. Press CTRL + Enter. The values "maria", "Yoshi", and "10" will be returned in the output section.

GETRANGE: Retrieving Substrings

To retrieve a substring of the value of a key, use the GETRANGE command. In your workbench, use:

GETRANGE key start end

Replace key with the name of the key, start with the starting index, and end with the ending index. For example:

GETRANGE name 0 4

This command will return the substring of the value of name from index 0 to 4. If name has the value "chun li", the command will return "chun ".

Conclusion of Part 1

In this first part of our Redis for Beginners series, you learned how to set up a Redis database and run basic commands such as setting, getting, deleting, and retrieving multiple key-value pairs. These are basic skills that anyone working with Redis should be conversant with.

In the next part of this series, we will explore more advanced commands, command options, and go into the differences between lists and sets in Redis. Stay tuned!

from  https://github.com/topeogunleye/Writing/blob/master/Redis-for-beginners-Part-1.md

--------------- 

 

Part 2: Redis for Beginners (Part 2 of 2)

Introduction

Welcome to the second part of our Redis for Beginners series. In the first part, we covered the basics of setting up a Redis database and executing fundamental commands. In this second part, we will explore advanced command options and delve into the differences between lists and sets in Redis.

Command Options

Not all commands have options, but a few, for example SET, have certain added features that can be essential.

  • EX seconds: Sets an expiration time in seconds (must be a positive integer).
  • PX milliseconds: Sets an expiration time in milliseconds (must be a positive integer).
  • EXAT timestamp-seconds: Sets a specific Unix timestamp for expiration (must be a positive integer).
  • NX: Sets the key only if it does not already exist.
  • XX: Sets the key only if it already exists.

You can't use NX and XX together because they will conflict with each other. Also, you can use only one option for expiration (EX or PX) at a time. To learn more about the SET command visit here to check out the Redis documentation page.

Example: SET Command Using the EX Option

When executing the following at your workbench, you will define a key with an expiration in Redis:

SET key value EX seconds

Replace key with the name of the key that contains the string and value with the new value you would like to store. Replace seconds with the amount of time, in seconds, after which the key should expire.

For example, if you have a key name currently holding the value "Mario", and you want to replace it with "Yoshi" after 7 seconds, run:

SET name Yoshi EX 7

This command updates the value of name to "Yoshi" and sets an expiration of 7 seconds from the time the command is executed.

Example: SET Command with NX and XX Options

You can set the key conditionally with respect to its existence in Redis by using the options NX, which stands for Not eXists, and XX, which stands for eXists, in the SET command:

Using NX (Not eXists) Option:

SET key value NX
  • Replace key with the name of the key you want to set.
  • Replace value with the value you want to store in the key.

This command sets the value of key to value only if key does not already exist. If key already exists, the command will not perform any action.

Example:

If you want to set a new key username to "alice" only if username does not already exist, you would use:

SET username alice NX

**Using `XX

` (eXists) Option:**

SET key value XX

This command sets the value of key to value only if key already exists. If key does not exist, the command will not perform any action.

Example:

If you want to update the value of an existing key username to "bob" only if username already exists, you would use:

SET username bob XX

Lists vs. Sets

Lists

  • An ordered collection of strings.
  • Supports operations like adding elements to the head or tail, trimming based on ranges, etc.
  • Useful for maintaining ordered data structures.
  • Commands: RPUSH, LPUSH, LRANGE, LPOP, RPOP, etc.

Sets

  • An unordered collection of unique strings.
  • Supports operations like adding, removing, and checking membership.
  • Useful for storing unique items and performing set operations.
  • Commands: SADD, SREM, SMEMBERS, SISMEMBER, etc.

When deciding between lists and sets, consider the order requirements and the need for uniqueness in your data.


Conclusion

Redis has come a long way through an evolution and, by now, it can be placed as your primary database—not just a cache layer. It features added data persistence and replication for durability and availability. Additional modules for JSON support and search make it easier to store and query more complex data. Now, Redis has an Object mapping library, Redis OM, which simplifies things. In this series, the focus is on the core of Redis.

from  https://github.com/topeogunleye/Writing/blob/master/Redis-for-beginners-Part-2.md

Thursday, 22 January 2026

Redis 8.0回归开源


全球最受欢迎的内存数据库Redis近日宣布,其8.0版本将重新拥抱开源,采用 GNU Affero通用公共许可证(AGPLv3) ,同时保留此前争议性的RSALv2和SSPLv1作为可选许可证。这一决策标志着Redis在经历一年多的”闭源风波”后,试图与开源社区重建信任。

2024 年 3 月Redis 7.4版本突然宣布采用双许可证模式(SSPLv1 + RSALv2),不再符合开放源代码促进会(OSI)的开源定义 。官方解释称此举是为防止云厂商”白嫖”,但社区批评声浪高涨。开发者认为这是对开源精神的背叛,并迅速分叉出Valkey(由Linux基金会支持)和Redict等替代项目。

创始人Antirez于2024年底重返Redis开发,推动了许可证改革的进程。最终,Redis 8.0在2025年5月发布时,新增AGPLv3选项,重新获得OSI认可的开源身份。Antirez在声明中表示:”开源是Redis生命力的基石,我们必须与之共存”

尽管Redis重回开源阵营,但部分开发者认为”伤害已无法弥补”。Antirez的回归虽提振了社区信心,但商业公司与开源治理的平衡仍是难题。 Redis CEO在采访中承认:”我们低估了许可证变更对生态的影响,未来将更注重与社区的协作”。分析指出,AGPLv3的”传染性”条款可能限制云厂商的商业化,但能否阻止分叉项目的崛起仍需观察。

Redis官方博客公告:https://redis.io/blog/agplv3/

Saturday, 18 October 2025

redis-commander

 

Redis management tool written in node.js

joeferner.github.io/redis-commander/ 

Redis web management tool written in node.js

GUI image

Install and Run

$ npm install -g redis-commander
$ redis-commander

Installation via yarn is currently not supported. Please use npm as package manager.

Or run Redis Commander as Docker image ghcr.io/joeferner/redis-commander rediscommander/redis-commander (instructions see below).

Multi-Arch images built are available at ghcr.io/joeferner/redis-commander:latest. (https://github.com/joeferner/redis-commander/pkgs/container/redis-commander)

Remark: new version are not published to Dockerhub right now.

Features

Web-UI to display and edit data within multiple different Redis servers. It can connect to Redis standalone server, Sentinel based setups and Redis Cluster.

It has support for the following data types to view, add, update and delete data:

  • Strings
  • Lists
  • Sets
  • Sorted Set
  • Streams (Basic support based on HFXBus project from https://github.com/exocet-engineering/hfx-bus, only view/add/delete data)
  • ReJSON documents (Basic support, only for viewing values of ReJSON type keys)

Usage

$ redis-commander --help
Options:
  --version                            Show version number                                                                                      [boolean]
  --redis-port                         The port to find redis on.                                                                                [number]
  --redis-host                         The host to find redis on.                                                                                [string]
  --redis-socket                       The unix-socket to find redis on.                                                                         [string]
  --redis-username                     The redis username.                                                                                       [string]
  --redis-password                     The redis password.                                                                                       [string]
  --redis-db                           The redis database.                                                                                       [number]
  --redis-optional                     Set to true if no permanent auto-reconnect shall be done if server is down.             [boolean] [default: false]
  --sentinel-port                      The port to find sentinel on.                                                                             [number]
  --sentinel-host                      The host to find sentinel on.                                                                             [string]
  --sentinels                          Comma separated list of sentinels with host:port.                                                         [string]
  --sentinel-name                      The sentinel group name to use.                                                                           [string]
  --sentinel-username                  The sentinel username to use.                                                                             [string]
  --sentinel-password                  The sentinel password to use.                                                                             [string]
  --clusters                           Comma separated list of redis cluster server with host:port.                                              [string]
  --is-cluster                         Flag to use parameter from redis-host and redis-port as Redis cluster member            [boolean] [default: false]
  --cluster-no-tls-validation          Flag to disable tls host name validation within cluster setups (needed for AWS)         [boolean] [default: false]
  --redis-tls                          Use TLS for connection to redis server. Required for TLS connections.                   [boolean] [default: false]
  --redis-tls-ca-cert                  Use PEM-style CA certificate key for connection to redis server. Requires "redis-tls=true"                [string]
  --redis-tls-ca-cert-file             File path to PEM-style CA certificate key for connection to redis server. Requires "redis-tls=true", Overrides
                                       "redis-tls-ca-cert" if set too.                                                                           [string]
  --redis-tls-cert                     Use PEM-style public key for connection to redis server. Requires "redis-tls=true"                        [string]
  --redis-tls-cert-file                File path to PEM-style public key for connection to redis server. Requires "redis-tls=true", Overrides
                                       "redis-tls-cert" if set too.                                                                              [string]
  --redis-tls-key                      Use PEM-style private key for connection to redis server. Requires "redis-tls=true"                       [string]
  --redis-tls-key-file                 File path PEM-style private key for connection to redis server. Requires "redis-tls=true", Overrides
                                       "redis-tls-key" if set too.                                                                               [string]
  --redis-tls-server-name              Server name to confirm client connection. Server name for the SNI (Server Name Indication) TLS extension. Requires
                                       "redis-tls=true"                                                                                          [string]
  --sentinel-tls                       Enable TLS for sentinel mode. If no special "sentinel-tls-*" option is defined the redis TLS settings are
                                       reused ("redis-tls-*"). Required for TLS sentinel connections.                          [boolean] [default: false]
  --sentinel-tls-ca-cert               Use PEM-style CA certificate key for connection to sentinel. Requires "sentinel-tls=true"                 [string]
  --sentinel-tls-ca-cert-file          File path to PEM-style CA certificate key for connection to sentinel. Requires "sentinel-tls=true", Overrides
                                       "sentinel-tls-ca-cert" if set too.                                                                        [string]
  --sentinel-tls-cert                  Use PEM-style public key for connection to sentinel. Requires "sentinel-tls=true"                         [string]
  --sentinel-tls-cert-file             File path to PEM-style public key for connection to sentinel. Requires "sentinel-tls=true", Overrides
                                       "sentinel-tls-cert" if set too.                                                                           [string]
  --sentinel-tls-key                   Use PEM-style private key for connection to sentinel. Requires "sentinel-tls=true"                        [string]
  --sentinel-tls-key-file              File path to PEM-style private key for connection to sentinel. Requires "sentinel-tls=true", Overrides
                                       "sentinel-tls-key" if set too.                                                                            [string]
  --sentinel-tls-server-name           Server name to confirm client connection. Server name for the SNI (Server Name Indication) TLS extension. Requires
                                       "sentinel-tls=true"                                                                                       [string]
  --insecure-certificate               Disable certificate check for all certificates (Redis, Sentinel, Cluster). Should not be used in
                                       production!                                                                            [boolean] [Standard: false]
  --noload, --nl                       Do not load connections from config.                                                                     [boolean]
  --clear-config, --cc                 Clear configuration file.                                                                                [boolean]
  --migrate-config                     Migrate old configuration file in $HOME to new style.                                                    [boolean]
  --test                               Test final configuration (file, env-vars, command line).                                                 [boolean]
  --open                               Open web-browser with Redis-Commander.                                                  [boolean] [default: false]
  --redis-label                        The label to display for the connection.                                               [string] [default: "local"]
  --read-only                          Start app in read-only mode.                                                            [boolean] [default: false]
  --http-auth-username, --http-u       The http authorisation username.                                                        [string] [default: "test"]
  --http-auth-password, --http-p       The http authorisation password.                                                            [string] [default: ""]
  --http-auth-password-hash, --http-h  The http authorisation password hash.                                                       [string] [default: ""]
  --address                            The address to run the server on.                                                    [string] [default: "0.0.0.0"]
  --port                               The port to run the server on.                                                            [number] [default: 8081]
  --url-prefix                         The url prefix to respond on.                                                               [string] [default: ""]
  --trust-proxy                        App is run behind proxy (enable Express "trust proxy").                                 [boolean] [default: false]
  --max-hash-field-size                The max number of bytes for a hash field before you must click to view it.                   [number] [default: 0]
  --nosave, --ns                       Do not save new connections to config file.                                             [boolean] [default: false]
  --no-log-data                        Do not log data values from redis store.                                                [boolean] [default: false]
  --folding-char, --fc                 Character to fold keys at for tree view.                                                   [string] [default: ":"]
  --root-pattern, --rp                 Default root pattern for redis keys.                                                       [string] [default: "*"]
  --use-scan, --sc                     Use SCAN instead of KEYS.                                                                [boolean] [default: true]
  --scan-count                         The size of each separate scan.                                                            [number] [default: 200]
  -h, -?, --help                       Show help                                                                                                [boolean]

The connection can be established either via direct connection to redis server or indirect via a sentinel instance. Most of this command line parameters map onto configuration params read from the config file - see docs/configuration.md and docs/connections.md.

Configuration

Redis Commander can be configured by configuration files, environment variables or using command line parameters. The different types of config values overwrite each other, only the last (most important) value is used.

For configuration files the node-config module (https://github.com/lorenwest/node-config) is used, with default to json syntax.

The order of precedence for all configuration values (from least to most important) is:

  • Configuration files

    default.json - this file contains all default values and SHOULD NOT be changed

    local.json - optional file, all local overwrites for values inside default.json should be placed here as well as a list of redis connections to use at startup

    local-<NODE_ENV>.json - Do not add anything else than connections to this file! Redis Commander will overwrite this whenever a connection is added or removed via user interface. Inside docker container this file is used to store all connections parsed from REDIS_HOSTS env var. This file overwrites all connections defined inside local.json

    There are some more possible files available to use - please check the node-config Wiki for a complete list of all possible file names (https://github.com/lorenwest/node-config/wiki/Configuration-Files)

  • Environment variables - the full list of env vars possible (except the docker specific ones) can be got from the file config/custom-environment-variables.json together with their mapping to the respective configuration key.

  • Command line parameters - Overwrites everything

To check the final configuration created from files, env-vars set and command line param overwrites start redis commander with additional param "--test". All invalid configuration keys will be listed in the output. The config test does not check if hostnames or ip addresses can be resolved.

More information can be found in the documentation at docs/configuration.md and docs/connections.md.

Remark: Errors on image startup with "permission denied" on config files might be caused due to wrong runtime users running the image. "docker compose" in recent versions does not pick up the user defined inside the Dockerfile and uses some other user, therefor it should be explicit set inside the docker-compose.yml file as shown in the example file.

Environment Variables

These environment variables can be used starting Redis Commander as normal application or inside docker container (defined inside file config/custom-environment-variables.json) and at docs/configuration.md:

HTTP_USER
HTTP_PASSWORD
HTTP_PASSWORD_HASH
ADDRESS
PORT
READ_ONLY
URL_PREFIX
SIGNIN_PATH
ROOT_PATTERN
NOSAVE
NO_LOG_DATA
FOLDING_CHAR
VIEW_JSON_DEFAULT
USE_SCAN
SCAN_COUNT
FLUSH_ON_IMPORT
REDIS_CONNECTION_NAME
REDIS_LABEL
CLIENT_MAX_BODY_SIZE
BINARY_AS_HEX 
 from https://github.com/joeferner/redis-commander 

Sunday, 20 October 2024

redis入门

 (1)---安装、配置、启动 

redis简介

Redis是一个开源、支持网络、基于内存、键值对存储数据库,使用ANSI C编写。从 2015 年 6 月开始,Redis 的开发由RedisLabs赞助,在2013年5月至2015年6月期间,其开发由Pivotal赞助。在2013年5月之前,其开发由VMware赞助。根据月度排行网站DB-Engines.com的数据显示,Redis是最流行的键值对存储数据库。
维基百科)

由于redis基于内存、键值对存储等特点,加上它的5种数据类型,使得redis能够在缓存、消息队列、高并发应用、排行榜相关领域大展身手。

安装(以ubuntu为例)

wget http://download.redis.io/redis-stable.tar.gz
tar xzf redis-stable.tar.gz
cd redis-stable
make
sudo make install

配置redis

开发环境,无须配置。手工启动

redis-server --port 6379

生产环境,设置随系统自动启动(以监听6380端口为例)

1、复制启动脚本
sudo cp utils/redis_init_script /etc/init.d/redis_6380
2、创建配置文件所在目录
sudo mkdir /etc/redis
3、创建PIDFILE文件所在目录

PID FILE的作用,见pid file的作用

sudo mkdir -p /var/redis/6380
4、修改启动脚本

修改第6行的端口号 REDISPORT=6380

sudo vim /etc/init.d/redis_6380
5、复制该实例redis配置文件
sudo cp redis.conf /etc/redis/6380.conf
6、修改配置文件
sudo vim /etc/redis/6380.conf

修改以下参数

daemonize yes #以守护进程运行
PIDFILE /var/run/redis_6380.pid #设置pid文件位置(要跟 /etc/init.d/redis_6380 里的PIDFILE一致)
port 6380
dir /var/redis/6380 # 设置持久化文件存放位置
7、设置开机启动
sudo update-rc.d redis_6380 defaults

提示:centos下使用如下方法

a. 修改/etc/init.d/redis_6380,在首行#!/bin/sh下添加两行

sudo vim /etc/init.d/redis_6380
/*添加这两行:(保留#号)
chkconfig: 2345 10 90
description: redis blabla ....
*/

启动与关闭

(开启,生产环境):

sudo /etc/init.d/redis_6380 start

(开启,开发环境):

redis-server --port 6380

(关闭):

redis-cli -h 127.0.0.1 -p 6380 SHUTDOWN

参考

官方文档

----------------

 (2) 管理与维护 

涉及 持久化_、_主从服务_、_安全_、_监控 等设置或管理。

持久化

redis虽然是基于内存的,但是作为一个比较成熟的数据库,仍然提供了持久化的功能,并且默认是开启的。

redis有两种持久化的方式:RDB 与 AOF

RDB(默认)

在一定时间内改动的键的数量超过则写回到磁盘

配置

默认写到 dump.rdb 文件,可以在配置文件中通过参数 dbfilename 修改
可以在配置文件 redis.conf 中按照如下格式添加自定义规则(默认已有三条规则)

# save time count
save 90 1
save 300 10
文件格式

RDB文件是以二进制形式存储的。

适用场景

由于需要达到一定的改动次数,如果中间出现异常崩溃,最后的那些改动会丢失。如果对可靠性要求不是很高,可以采用。

关闭RDB持久化

删除原有规则,并添加规则:

save ""

AOF (append only file)

每出现一个改动就写回到文件

开启AOF持久化

修改配置文件参数, appendonly yes
默认写到 appendonly.aof 文件中,可以在配置文件中修改 appendfilename 参数
数据格式采用文本文件格式,存储的是每一步的操作,形式如下:

*3 #行数
$3 #字符串长度
set
$3 #字符串长度
foo
$3 #字符串长度
bar

表示的是命令 set foo bar
由于系统默认的写机制存在缓存,延迟回写(30s),如果掉电,缓存中内容会丢失。可以设置自动同步到磁盘,参数 appendfsync,默认时每秒回写一次

适用场景

AOF可靠性更高,但是也更影响性能(好在redis占用资源则不多),适用于对数据可靠性要求很高,对丢失0容忍的应用

注意

可以同时使用RDB和AOF两种持久化方式,不会存在冲突

设置主从服务器

redis-server --port 6380 --slaveof 127.0.0.1 6379

开启6380端口的redis服务器实例A,作为6379实例B的从服务器,随后A会自动向B 报告 ,请求镜像,此后每次B变动,都会通知A更改。A与B的数据交换格式类似于AOF文件,从服务器的数据默认是 只读(readonly),可以通过参数 slave-read-only 参数进行修改,但是从服务器的变化不会影响到主服务器,并且会被下一次的同步覆盖

安全

关闭外部网络访问权限

修改配置文件参数

bind 127.0.0.1

最新版3.2.0 已经默认如此配置了

设置密码

配置文件添加参数

requirepass <password>

以后连接服务器时,都要先输入

AUTH <password>

命令验证,才能正常使用
个人认为没有必要,redis不提供输入次数限制,暴力破解的难度不大,除非是非常高强度的密码。况且已经关闭外部访问,能连上主机的直接看程序代码就知道密码了。

重命名/禁止命令

重命名
rename-command command newCommandName
禁止

禁用某些命令

rename-command command ""

通信协议

redis提供了两种通信协议支持:简单协议 和 统一请求协议

简单协议(SET foo bar)

输入跟在redis-cli 中输入的命令一致

二进制安全的统一请求协议

输入的格式与输出一致,跟AOF文件格式相似
例如 SET foo bar 写为 *3\r\n$3\r\nSET\r\n$3foo\r\n$3bar\r\n

两种协议的输出格式对比

类型 示例数据
错误 -ERR blabla\r\n
状态 +OK\r\n
整数 :3\r\n
字符串 $3\r\nbar\r\n
多行回复 *3\r\n$3\r\nSET\r\n$3foo\r\n$3bar\r\n

管理工具

redis自带工具

在 redis-cli 中输入
slowlog get 慢日志查询,时间阈值在配置文件中修改,默认为10000
monitor 实时显示服务器的每一个请求(所有客户端)

phpRedisAdmin

跟phpmyadmin相似,用网页方式管理 (查看演示)

git clone https://github.com/ErikDubbelboer/phpRedisAdmin.git
cd phpRedisAdmin
//下载predis依赖
git clone https://github.com/nrk/predis.git vendor

cp includes/config.sample.inc.php includes/config.inc.php
//在 config.inc.php 中修改redis服务器连接参数
rdbtools
地址 rdbtools
快照文件解析器,根据快照文件导出json文件,分析redis中每个键的占用空间情况等。

 

Friday, 13 September 2024

类似于Slack/Discord的聊天程序Tailchat

 

Next generation noIM application in your own workspace, not only another Slack/Discord/Rocket.chat

tailchat.msgbyte.com/

Docker Publish Docker Image Version (tag latest semver) Docker Pulls CI Codemagic build status Desktop Build deploy nightly Tailchat Nightly

tailchat

简体中文

Next generation noIM application in your own workspace

Not only another Slack, Discord, Rocket.Chat....

If you are interested in the concept of noIM, welcome to read my blog:

Official Documentation: https://tailchat.msgbyte.com/

Nightly version Try it online: https://nightly.paw.msgbyte.com/

Nightly version is the automatic compile version, that means, every commit code will be automatically compiled. The reliability and stability of the data are not guaranteed, you can deploy with stable version with docker images or github release page

Motivation

At present, the existing IM applications only focus on chatting itself, and IM is naturally a multi-person collaboration method. In my opinion, it should be able to take on more responsibilities, and form its own unique way of forwarding external applications through IM workflow.

Therefore, I bring up the point of noIM, which means Not only IM. Instead, it designed a highly customized application platform for individuals/teams centered on IM, with third-party applications as enhanced functions, and a plugin system as the glue connection layer in the middle.

To this end, the functions were abstracted, and a lot of time was spent designing the underlying mechanism. An instant messaging application such as Tailchat was born for expansion from the beginning of the underlying design. Through Tailchat's plugin system, developers can easily use their favorite applications as part of Tailchat in a very natural way. Different from traditional integration methods such as Slack, the integration of Tailchat is more free, as if it is a native function.

Feature

  • Pay attention to privacy, only invited members can join the group
  • Prevent strangers, add friends only by nickname + a random string of numbers
  • Two-level group space, dividing different topics by panels
  • Highly customized group space, create original group space by grouping with dragging and dropping. At the same time, more plugins can be used to add more capabilities
  • It can be rigorous or fun. Through the combination of plugins, Tailchat can be created for different scenarios. It can be for individuals or for enterprises
  • The backend microservice structure is ready for large-scale deployment. Don't worry about what to do after the number of user growth

Learn more in our website

Performance and Expansion

Tailchat is a modern open source IM application which based on React + Typescript

Front-end microkernel architecture + backend microservice architecture, Tailchat is ready for clustering deployment.

The front end empowers the application through the plugin system, which is very simple and easy to expand for the secondary development of Tailchat.

NOTICE: Although the core functionality of Tailchat is currently in a stable stage, its exposed interface for third-party developers is still being improved. Generally speaking, it is backward compatible, but retains the possibility of Break Change

Visit the official website to learn more: https://tailchat.msgbyte.com/

Quick Deploy

Deploy on Sealos

Deploy on Sealos

Communication

If you are interested in Tailchat, welcome to join Tailchat's seed user exchange group, your feedback can help Tailchat grow better

Tailchat

Tailchat Nightly Group

Producthunt

Tailchat - The next-generation noIM Application in your own workspace | Product Hunt 

from https://github.com/msgbyte/tailchat

------

Manual Deployment

caution

The content of this chapter requires you to have a certain degree of understanding of nodejs, git, linux. When there are problems such as dependency problems, environmental problems, system problems, etc., you need to have the ability to solve and troubleshoot problems by yourself.

If you do not understand this, it is not recommended that you use the contents of this chapter for deployment. It is recommended to use a unified image for deployment.

Dependencies

  • git
  • nodejs v16.18.0 or above
  • pnpm v8.3.1 or above
  • mongodb
  • redis
  • minio

Download the source code

mkdir msgbyte && cd msgbyte

git clone https://github.com/msgbyte/tailchat.git

Switch to stable code

Because the cloned code is the latest code, it may be unstable for a short period of time, so if you want to switch to the stable code of each version, you can use the tag function of git

For example, if you wanna use v1.7.6, you can use the command:

git checkout v1.7.6

Compile the project

Tailchat is a front-end and back-end separated project. So we have to deal with the front-end code and the back-end code separately

Install dependencies

We assume you have installed nodejs v16.18.0+ or above. And installed pnpm v8.3.1 or above

cd tailchat
pnpm install

This command will take some time to install all the dependencies of Tailchat. When the installation is complete, the internal plug-in will automatically execute the compilation command.

Building the project

NODE_ENV=production pnpm build

This command will execute the commands for compiling the front-end and back-end management terminals in parallel. And move the front-end product to the server/dist/public directory of the server.

When the project is built, our product can run normally.

caution:

Please build in macos / linux environment as much as possible, window does not necessarily fully support shell commands.

Run the project

In order to ensure the horizontal expansion of the project, although the core code of Tailchat is written in the same project, it can be divided into multiple subdivided microservices when it is actually started. Selectively enable different services by passing in a combination of different environment variables.

Create an environment variable file in the server directory using the .env.example directory as an example:

cp server/.env.example server/dist/.env
vim .env

Modify the necessary environment variables to your own, such as MONGO_URL, REDIS_URL, MINIO_URL

then start the service

SERVICEDIR=services,plugins pnpm start:service

SERVICEDIR indicates the directory where the microservice is loaded.

from https://tailchat.msgbyte.com/docs/deployment/other-way/manual

 

聊天程序fiora


An interesting open source chat application. Developed with node.js, mongoDB, socket.io and react.

fiora.suisuijiang.com

Fiora is an interesting open source chat application. It is developed based on node.js, react and socket.io technologies

  • Richness: Fiora contains backend, frontend, Android and iOS apps
  • Cross Platform: Fiora is developed with node.js. Supports Windows / Linux / macOS systems
  • Open Source: Fiora follows the MIT open source license

Online Example: https://fiora.suisuijiang.com/
Documentation: https://yinxin630.github.io/fiora/

Features

  1. Register an account and log in, it can save your data for a long time
  2. Join an existing group or create your own group to communicate with everyone
  3. Chat privately with anyone and add them as friends
  4. Multiple message types, including text / emoticons / pictures / codes / files / commands, you can also search for emoticons
  5. Push notification when you receive a new message, you can customize the notification ringtone, and it can also read the message out
  6. Choose the theme you like, and you can set it as any wallpaper and theme color you like
  7. Set up an administrator to manage users

Install

Fiora provides two ways to install

Change Log

You can find the Fiora changelog on the website

from https://github.com/yinxin630/fiora

--------------------------------------------------

Install

Environmental Preparation#

To run Fiora, you need Node.js(recommend v14 LTS version), MongoDB and redis

Recommended to running on Linux or MacOS systems

How to run#

  1. Clone the project git clone https://github.com/yinxin630/fiora.git -b master
  2. Ensure you have install yarn before, if not please run npm install -g yarn
  3. Install project dependencies yarn install
  4. Build client yarn build:web
  5. Config JwtSecret echo "JwtSecret=<string>" > .env2. Change <string> to a secret text
  6. Start the server yarn start
  7. Open http://[ip]:[port](such as http://127.0.0.1:9200) in browser

Run in the background#

Using yarn start to run the server will stop running after disconnecting the ssh connection, it is recommended to use pm2 to run

# install pm2
npm install -g pm2
# use pm2 to run fiora
pm2 start yarn --name fiora -- start
# view pm2 apps status
pm2 ls
# view pm2 fiora logging
pm2 logs fiora

Run With Develop Mode#

  1. Start the server yarn dev:server
  2. Start the client yarn dev:web
  3. Open http://localhost:8080 in browser

Running on the docker#

First install docker https://docs.docker.com/install/

Run directly from the DockerHub image#

# Pull mongo
docker pull mongo
# Pull redis
docker pull redis
# Pull fiora
docker pull suisuijiang/fiora
# Create a virtual network
docker network create fiora-network
# Run mongodB
docker run --name fioradb -p 27017:27017 --network fiora-network mongo
# Run redis
docker run --name fioraredis -p 6379:6379 --network fiora-network redis
# Run fiora
docker run --name fiora -p 9200:9200 --network fiora-network -e Database=mongodb://fioradb:27017/fiora -e RedisHost=fioraredis suisuijiang/fiora

Local build image and run#

  1. Clone the project to the local git clone https://github.com/yinxin630/fiora.git -b master
  2. Build the image docker-compose build --no-cache --force-rm
  3. Run it docker-compose up

from https://yinxin630.github.io/fiora/docs/install/