userver: components::Redis Class Reference
Loading...
Searching...
No Matches
components::Redis Class Reference

#include <userver/storages/redis/component.hpp>

Detailed Description

Valkey and Redis client component.

Provides access to a valkey or redis cluster. Set enable_subscriptions: true on a groups entry to use both components::Redis::GetClient and components::Redis::GetSubscribeClient with the same database name and topology. Commands and subscriptions use separate connections to the Redis nodes. Alternatively, entries in groups and subscribe_groups with the same db and config_name share topology automatically when their sharding_strategy, topology_update_method and max_disconnect_time match. For Redis Cluster, both entries must also agree on whether required is no_wait. Subscription settings come from subscribe_groups, including allow_reads_from_master, per_channel_statistics and health checks.

Dynamic options:

Static options of components::Redis :

Name Description Default value
thread_pools Thread pools options. –
thread_pools.redis_thread_pool_size Thread count to serve Redis requests. –
thread_pools.sentinel_thread_pool_size Thread count to serve sentinel requests. –
groups.[] Redis cluster to work with. –
groups.[].config_name Key name in secdist with options for this cluster. –
groups.[].db Name to refer to the cluster in components::Redis::GetClient(). –
groups.[].sharding_strategy One of RedisStandalone, RedisCluster, KeyShardCrc32, KeyShardTaximeterCrc32 or KeyShardGpsStorageDriver. Possible values: RedisCluster, KeyShardCrc32, KeyShardTaximeterCrc32, KeyShardGpsStorageDriver, RedisStandalone. KeyShardTaximeterCrc32
groups.[].allow_reads_from_master Allows read requests and subscriptions to master instances. false
groups.[].subscription_balancing Configure load sampling for Redis subscription nodes. –
groups.[].subscription_balancing.strategy Redis node load metric to sample. Possible values: none, by_cpu_load, by_net_load. none
groups.[].subscription_balancing.metrics_level Full exports load and poll diagnostics. With basic or off, sampling continues without exporting these metrics. Possible values: off, basic, full. basic
groups.[].subscription_balancing.load_poll_interval Positive interval between INFO requests. 5s
groups.[].subscription_balancing.load_max_age Maximum sample age; at least twice load_poll_interval. 15s
groups.[].enable_subscriptions Enable subscriptions for this group using separate subscription connections. false
groups.[].per_channel_statistics Enables statistics for each redis pub/sub channel. true
groups.[].topology_update_method Topology update method for cluster databases. cluster_slots - use CLUSTER SLOTS command (default). cluster_shards - use CLUSTER SHARDS command. Possible values: cluster_slots, cluster_shards. cluster_slots
groups.[].required Required connection mode for the client. Possible values: no_wait, master, slave, master_or_slave, master_and_slave. –
groups.[].max_disconnect_time The maximum allowed time in seconds for a database host to be disconnected before it is considered unhealthy. Supported for Redis Cluster and Sentinel connections. For Redis Cluster, it should be greater than 2x cluster-node-timeout plus some additional time. 35
groups.[].refresh_topology_on_primary_unavailable In Sentinel mode, request a rate-limited topology refresh when a primary-targeted command gets READONLY or cannot be sent to the primary. false
groups.[].max_failed_shards Maximum number or percent of failed shards allowed in GetComponentHealth check. 0 means all shards must be ready (default behavior). This only affects health checks, not WaitConnectedOnce. –
groups.[].max_failed_shards.amount Maximum number of failed shards allowed. 0
groups.[].max_failed_shards.percent Maximum percent of failed shards allowed. 0
metrics_level Set metrics detail level. Possible values: cluster, shard, instance. instance
subscribe_groups.[] Redis cluster to work with in subscribe mode. –
subscribe_groups.[].config_name Key name in secdist with options for this cluster. –
subscribe_groups.[].db Name to refer to the cluster in components::Redis::GetSubscribeClient(). –
subscribe_groups.[].sharding_strategy Either RedisCluster or KeyShardTaximeterCrc32. Possible values: RedisCluster, KeyShardTaximeterCrc32, RedisStandalone. KeyShardTaximeterCrc32
subscribe_groups.[].allow_reads_from_master Allows subscriptions to master instance to distribute load. false
subscribe_groups.[].topology_update_method Topology update method for cluster databases. cluster_slots - use CLUSTER SLOTS command (default). cluster_shards - use CLUSTER SHARDS command. Possible values: cluster_slots, cluster_shards. cluster_slots
subscribe_groups.[].subscription_balancing Configure load sampling for Redis subscription nodes. –
subscribe_groups.[].subscription_balancing.strategy Redis node load metric to sample. Possible values: none, by_cpu_load, by_net_load. none
subscribe_groups.[].subscription_balancing.metrics_level Full exports load and poll diagnostics. With basic or off, sampling continues without exporting these metrics. Possible values: off, basic, full. basic
subscribe_groups.[].subscription_balancing.load_poll_interval Positive interval between INFO requests. 5s
subscribe_groups.[].subscription_balancing.load_max_age Maximum sample age; at least twice load_poll_interval. 15s
subscribe_groups.[].per_channel_statistics Enables statistics for each redis pub/sub channel. true
subscribe_groups.[].required Required connection mode for the subscription client. Possible values: no_wait, master, slave, master_or_slave, master_and_slave. –
subscribe_groups.[].max_disconnect_time The maximum allowed time in seconds for a database host to be disconnected before it is considered unhealthy. It depends on the cluster-node-timeout setting in the Redis/Valkey config and should be greater than 2x that value plus some additional time. 35
subscribe_groups.[].max_failed_shards Maximum number or percent of failed shards allowed in GetComponentHealth check. 0 means all shards must be ready (default behavior). This only affects health checks, not WaitConnectedOnce. –
subscribe_groups.[].max_failed_shards.amount Maximum number of failed shards allowed. 0
subscribe_groups.[].max_failed_shards.percent Maximum percent of failed shards allowed. 0

Options inherited from components::ComponentBase :

Name Description Default value
load-enabled Set to false to disable loading of the component. true

Static configuration example:

# yaml
redis:
groups:
- config_name: cats
db: hello_service_cats_catalogue
sharding_strategy: RedisCluster
- config_name: dogs
db: hello_service_dogs_catalogue
subscribe_groups:
- config_name: food
db: hello_service_pet_food_orders
thread_pools:
redis_thread_pool_size: 8
sentinel_thread_pool_size: 1

Secdist format

If a config_name option is provided, for example groups.some.config_name: some_name_of_your_database, then the Secdist entry for that alias should look like following:

{
"redis_settings": {
"some_name_of_your_database": {
"password": "the_password_of_your_database",
"sentinel_password": "the_password_for_sentinels_if_any",
"secure_connection": false,
"sentinels": [
{"host": "the_host1_of_your_database", "port": 11564}
],
"shards": [
{"name": "test_master0"}
]
}
}
}

For an example of Secdist setup for standalone, sentinel and cluster testsuite configurations see the snippet:

@pytest.fixture(scope='session')
def service_env(redis_sentinels, redis_cluster_nodes, redis_cluster_replicas, redis_standalone_node):
cluster_shards = [
{'name': f'shard{idx}'}
for idx in range(
len(redis_cluster_nodes) // (redis_cluster_replicas + 1),
)
]
# All the `sentinels` accept host and port. For example `'sentinels': [{'host': '192.168.1.7','port': 6379}]`
secdist_config = {
'redis_settings': {
'redis-cluster': {
'password': '',
'sentinels': redis_cluster_nodes,
'shards': cluster_shards, # For example, it can be [{"name": "shard0"}, {"name": "shard1"}]
},
'redis-sentinel': {
'password': '',
'sentinels': redis_sentinels,
'database_index': 5, # database index to use, 0 by default
'shards': [{'name': 'test_master1'}],
},
'redis-standalone': {
'password': '',
'sentinels': [redis_standalone_node],
'shards': [{'name': 'test_standalone_master0'}],
},
},
}
return {'SECDIST_CONFIG': json.dumps(secdist_config)}
@pytest.fixture
@pytest_userver.service.dependency
def _redis_extra_deps(redis_cluster_store, redis_standalone_store):
# `redis_store` is autodetected by pytest_userver.plugins.service.auto_client_deps fixture
pass

Note that if the components::Secdist component has update-period other than 0, then new connections are created or gracefully closed as the secdist configuration change to new value.

Cluster Valkey or Cluster Redis setup

Valkey/Redis cluster is the new recommended way of setting up key-value datastores with improved stability.

To start, set sharding_strategy: RedisCluster in the static config as shown above.

Secdist configuration is simplified:

  1. "shards" field is ignored, you can specify an empty array there;
  2. "sentinels" field should contain some of the cluster nodes. They are only used for topology discovery; it is not necessary to list all nodes.
Examples
samples/redis_service/main.cpp.

Definition at line 135 of file component.hpp.

Inheritance diagram for components::Redis:

Public Member Functions

 Redis (const ComponentConfig &config, const ComponentContext &component_context)
std::shared_ptr< storages::redis::Client > GetClient (const std::string &name, storages::redis::RedisWaitConnected wait_connected={}) const
 Returns the command client for the named database.
std::shared_ptr< storages::redis::impl::Sentinel > Client (const std::string &name) const
std::shared_ptr< storages::redis::SubscribeClient > GetSubscribeClient (const std::string &name, storages::redis::RedisWaitConnected wait_connected={}) const
 Returns the subscription client for the named database.
ComponentHealth GetComponentHealth () const override
void OnLoadingCancelled () override
void OnAllComponentsLoaded () override
void OnGracefulShutdown (engine::Deadline serving_shutdown_deadline) override
void OnAllComponentsAreStopping () override

Static Public Member Functions

static yaml_config::Schema GetStaticConfigSchema ()

Static Public Attributes

static constexpr std::string_view kName = "redis"
 The default name of components::Redis.

Protected Types

using LoggableComponentBase = ComponentBase

Member Typedef Documentation

◆ LoggableComponentBase

using components::ComponentBase::LoggableComponentBase = ComponentBase
protectedinherited
Deprecated
use components::ComponentBase instead.

Definition at line 79 of file component_base.hpp.

Member Function Documentation

◆ GetComponentHealth()

ComponentHealth components::Redis::GetComponentHealth ( ) const
overridevirtual

Override this function to inform the world of the state of your component.

Warning
The function is called concurrently from multiple threads.

Reimplemented from components::ComponentBase.

◆ OnAllComponentsAreStopping()

void components::ComponentBase::OnAllComponentsAreStopping ( )
inlineoverridevirtualinherited

Component may use this function to stop doing work before the stop of the components that depend on it.

Base components may override it and make final to do some work before the derived object constructor is called. Don't use it otherwise.

Reimplemented from components::RawComponentBase.

Reimplemented in components::Server, and urabbitmq::ConsumerComponentBase.

Definition at line 70 of file component_base.hpp.

◆ OnAllComponentsLoaded()

void components::ComponentBase::OnAllComponentsLoaded ( )
inlineoverridevirtualinherited

Component may use this function to finalize registration of other components that depend on it (for example, handler components register in server component, and the latter uses OnAllComponentsLoaded() to start processing requests).

Base components may override it and make final to do some work after the derived object constructor is called. Don't use it otherwise.

Reimplemented from components::RawComponentBase.

Reimplemented in components::Server, server::handlers::Ping, and urabbitmq::ConsumerComponentBase.

Definition at line 51 of file component_base.hpp.

◆ OnGracefulShutdown()

void components::ComponentBase::OnGracefulShutdown ( engine::Deadline serving_shutdown_deadline)
overridevirtualinherited

Serving components like HTTP and gRPC servers may use this function to stop accepting new requests and shutdown serving in the given time interval. Application components likely do not need to override it.

Parameters
[in]serving_shutdown_deadlineThe deadline until already running requests should be allowed to complete. The component is supposed to stop accepting new requests and continue processing of already active requests until this deadline (unless those requests finish earlier). And it might completely shutdown requests processing when the deadline is reached (or when no active requests left).

Reimplemented from components::RawComponentBase.

Reimplemented in components::Server.

◆ OnLoadingCancelled()

void components::ComponentBase::OnLoadingCancelled ( )
inlineoverridevirtualinherited

Called once if the creation of any other component failed. If the current component expects some other component to take any action with the current component, this call is a signal that such action may never happen due to components loading was cancelled. Application components might not want to override it.

Reimplemented from components::RawComponentBase.

Definition at line 42 of file component_base.hpp.


The documentation for this class was generated from the following file: