### DynamicPool Usage Example Source: https://docs.rs/fred/latest/fred/clients/struct.DynamicPool.html?search= Demonstrates how to configure, initialize, and interact with a DynamicPool instance. ```rust use fred::{ clients::DynamicPool, prelude::*, types::config::{DynamicPoolConfig, PoolScale, RemoveIdle}, }; use std::{sync::Arc, time::Duration}; async fn example() -> Result<(), Error> { let config = Config::from_url("redis://localhost:6379")?; let pool_config = DynamicPoolConfig { min_clients: 2, max_clients: 15, max_idle_time: Duration::from_secs(60 * 5), // use a scale policy that only removes idle connections scale: Arc::new(RemoveIdle), }; let pool = Builder::from_config(config) .set_pool_config(pool_config) .build_dynamic_pool()?; pool.init().await?; pool.start_scale_task(Duration::from_secs(10)); // use `next()` to interact with individual clients for idx in 0..100 { let _: () = pool.next().incr_by(format!("foo-{idx}"), idx).await?; } // scale the pool manually, or use the `PoolScale` trait to check metrics and scale on an interval pool.scale(1).await; pool.scale(-1).await; // reset the pool to its initial state pool.reset().await; // close all clients in the pool pool.quit().await?; Ok(()) } ``` -------------------------------- ### Initialize a DynamicPool Source: https://docs.rs/fred/latest/fred/clients/struct.DynamicPool.html?search=u32+-%3E+bool Example showing how to initialize a centralized pool and wait for connections to be established. ```rust use fred::prelude::*;\n\n#[tokio::main]\nasync fn main() -> Result<(), Error> {\n let pool = Builder::default_centralized().build_pool(5)?;\n let connection_task = pool.init().await?;\n\n // ...\n\n pool.quit().await?;\n connection_task.await?\n} ``` -------------------------------- ### Library Usage Example Source: https://docs.rs/fred/latest/fred/types/scripts/struct.Library.html Demonstrates creating a library from Lua code and conditionally executing functions based on their flags. ```rust let code = "#!lua name=mylib \n redis.register_function('myfunc', function(keys, args) return \ args[1] end)"; let library = Library::from_code(client, code).await?; assert_eq!(library.name(), "mylib"); if let Some(func) = library.functions().get("myfunc") { if func.flags().contains(&FunctionFlag::NoWrites) { let _: () = func.fcall_ro(client, "key", "arg").await?; } else { let _: () = func.fcall(client, "key", "arg").await?; } } ``` -------------------------------- ### SubscriberClient Usage Example Source: https://docs.rs/fred/latest/fred/clients/struct.SubscriberClient.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates initializing a subscriber client, managing subscriptions, and handling incoming messages. ```rust use fred::clients::SubscriberClient; use fred::prelude::*; async fn example() -> Result<(), Error> { let subscriber = Builder::default_centralized().build_subscriber_client()?; subscriber.init().await?; // spawn a task that will re-subscribe to channels and patterns after reconnecting let _ = subscriber.manage_subscriptions(); let mut message_rx = subscriber.message_rx(); let jh = tokio::spawn(async move { while let Ok(message) = message_rx.recv().await { println!("Recv message {:?} on channel {}", message.value, message.channel); } }); let _ = subscriber.subscribe("foo").await?; let _ = subscriber.psubscribe("bar*").await?; println!("Tracking channels: {:?}", subscriber.tracked_channels()); // foo println!("Tracking patterns: {:?}", subscriber.tracked_patterns()); // bar* // force a re-subscription subscriber.resubscribe_all().await?; // clear all the local state and unsubscribe subscriber.unsubscribe_all().await?; subscriber.quit().await?; Ok(()) } ``` -------------------------------- ### Builder Usage Example Source: https://docs.rs/fred/latest/fred/types/struct.Builder.html?search= Demonstrates initializing a client or pool using default settings, custom configurations, or policy modifications. ```rust fn example() -> Result<(), Error> { // use default values let client = Builder::default_centralized().build()?; // or initialize from a URL or config let config = Config::from_url("redis://localhost:6379/1")?; let mut builder = Builder::from_config(config); // or modify values in place (creating defaults if needed) builder .with_config(|config| { config.version = RespVersion::RESP3; config.fail_fast = true; }) .with_connection_config(|config| { config.tcp = TcpConfig { nodelay: Some(true), ..Default::default() }; config.internal_command_timeout = Duration::from_secs(10); }); // or overwrite configuration structs in place builder.set_policy(ReconnectPolicy::new_exponential(0, 100, 30_000, 2)); builder.set_performance_config(PerformanceConfig::default()); // reuse the builder as needed to create any kind of client let client = builder.build()?; let pool = builder.build_pool(3)?; let subscriber = builder.build_subscriber_client()?; // ... Ok(()) } ``` -------------------------------- ### Library Usage Example Source: https://docs.rs/fred/latest/fred/types/scripts/struct.Library.html?search=u32+-%3E+bool Demonstrates creating a library from Lua code and conditionally executing functions based on their flags. ```rust let code = "#!lua name=mylib \n redis.register_function('myfunc', function(keys, args) return \ args[1] end)"; let library = Library::from_code(client, code).await?; assert_eq!(library.name(), "mylib"); if let Some(func) = library.functions().get("myfunc") { if func.flags().contains(&FunctionFlag::NoWrites) { let _: () = func.fcall_ro(client, "key", "arg").await?; } else { let _: () = func.fcall(client, "key", "arg").await?; } } ``` -------------------------------- ### Initialize a DynamicPool Source: https://docs.rs/fred/latest/fred/clients/struct.DynamicPool.html?search= Example demonstrating how to initialize a centralized pool and manage its connection lifecycle. ```rust use fred::prelude::*; #[tokio::main] async fn main() -> Result<(), Error> { let pool = Builder::default_centralized().build_pool(5)?; let connection_task = pool.init().await?; // ... pool.quit().await?; connection_task.await? } ``` -------------------------------- ### Initialize TlsConfig Source: https://docs.rs/fred/latest/fred/types/config/struct.TlsConfig.html?search= Examples of initializing TlsConfig manually or using shorthand conversion methods. ```rust let config = TlsConfig { // or use `TlsConnector::default_rustls()` connector: TlsConnector::default_native_tls().unwrap(), hostnames: TlsHostMapping::None }; // or use the shorthand let config: TlsConfig = TlsConnector::default_native_tls()?.into(); let config: TlsConfig = TlsConnector::default_rustls()?.into(); ``` -------------------------------- ### Create Centralized Config from URL Source: https://docs.rs/fred/latest/fred/types/config/struct.Config.html Examples of URL strings used to initialize a centralized Redis configuration. ```text redis://username:password@foo.com:6379/1 rediss://username:password@foo.com:6379/1 redis://foo.com:6379/1 redis://foo.com // ... etc ``` -------------------------------- ### monitor Source: https://docs.rs/fred/latest/fred/clients/struct.SentinelClient.html?search=u32+-%3E+bool Start Sentinel’s monitoring. ```APIDOC ## fn monitor( &self, name: N, ip: IpAddr, port: u16, quorum: u32, ) -> impl Future> + Send ### Description Start Sentinel’s monitoring. ``` -------------------------------- ### Using Buffer for mocking Source: https://docs.rs/fred/latest/fred/mocks/struct.Buffer.html?search= Example demonstrating how to use the Buffer mock to capture and verify commands sent to a client. ```rust #[tokio::test] async fn should_use_buffer_mock() { let buffer = Arc::new(Buffer::new()); let config = Config { mocks: Some(buffer.clone()), ..Default::default() }; let client = Builder::from_config(config).build().unwrap(); client.init().await.expect("Failed to connect"); let actual: String = client .set("foo", "bar", None, None, false) .await .expect("Failed to call SET"); assert_eq!(actual, "QUEUED"); let actual: String = client.get("foo").await.expect("Failed to call GET"); assert_eq!(actual, "QUEUED"); // note: values that act as keys use the `Value::Bytes` variant internally let expected = vec![ MockCommand { cmd: "SET".into(), subcommand: None, args: vec!["foo".as_bytes().into(), "bar".into()], }, MockCommand { cmd: "GET".into(), subcommand: None, args: vec!["foo".as_bytes().into()], }, ]; assert_eq!(buffer.take(), expected); } ``` -------------------------------- ### Initialize a Redis client connection Source: https://docs.rs/fred/latest/fred/interfaces/trait.ClientLike.html?search=std%3A%3Avec Demonstrates using the init method to start a connection task and waiting for it to complete. ```rust use fred::prelude::*; #[tokio::main] async fn main() -> Result<(), Error> { let client = Client::default(); let connection_task = client.init().await?; // ... client.quit().await?; connection_task.await? } ``` -------------------------------- ### Execute a Redis transaction Source: https://docs.rs/fred/latest/fred/clients/struct.Transaction.html?search= Example demonstrating how to queue commands and execute them using the exec method. ```rust async fn example(client: &Client) -> Result<(), Error> { let _ = client.mset(vec![("foo", 1), ("bar", 2)]).await?; let trx = client.multi(); let _: () = trx.get("foo").await?; // returns QUEUED let _: () = trx.get("bar").await?; // returns QUEUED let (foo, bar): (i64, i64) = trx.exec(false).await?; assert_eq!((foo, bar), (1, 2)); Ok(()) } ``` -------------------------------- ### cmd Macro Usage Examples Source: https://docs.rs/fred/latest/fred/macro.cmd.html Demonstrates various ways to invoke the cmd macro compared to the explicit CustomCommand constructor. ```rust let _cmd = cmd!("FOO.BAR"); let _cmd = cmd!("FOO.BAR", blocking: true); let _cmd = cmd!("FOO.BAR", hash: ClusterHash::FirstKey); let _cmd = cmd!("FOO.BAR", hash: ClusterHash::FirstKey, blocking: true); // which is shorthand for let _cmd = CustomCommand::new("FOO.BAR", ClusterHash::FirstKey, true); ``` -------------------------------- ### pub fn get(&self, k: &Q) -> Option<&V> Source: https://docs.rs/fred/latest/fred/types/struct.Map.html?search= Returns a reference to the value corresponding to the key. ```APIDOC ## pub fn get(&self, k: &Q) -> Option<&V> ### Description Returns a reference to the value corresponding to the key. The key may be any borrowed form of the map’s key type. ### Parameters - **k** (&Q) - The key to look up. ### Requirements - Available on crate feature `i-streams` only. ``` -------------------------------- ### Initialize and Connect Client Source: https://docs.rs/fred/latest/fred/interfaces/trait.ClientLike.html?search= Demonstrates initializing a client and awaiting the connection task. ```rust use fred::prelude::*;\n\n#[tokio::main]\nasync fn main() -> Result<(), Error> {\n let client = Client::default();\n let connection_task = client.init().await?;\n\n // ...\n\n client.quit().await?;\n connection_task.await?\n} ``` -------------------------------- ### Redis Transaction Example Source: https://docs.rs/fred/latest/fred/clients/struct.ExclusivePool.html?search= A conceptual example of a Redis transaction using WATCH and MULTI/EXEC. ```text WATCH foo foo = GET foo if foo > 1: MULTI INCR foo INCR bar INCR baz EXEC ``` -------------------------------- ### failover Source: https://docs.rs/fred/latest/fred/clients/struct.Pipeline.html?search=std%3A%3Avec Starts a coordinated failover. ```APIDOC ## fn failover(to: Option<(String, u16)>, force: bool, abort: bool, timeout: Option) ### Description Starts a coordinated failover between the currently-connected-to master and one of its replicas. ### Parameters - **to** (Option<(String, u16)>) - Optional - Target server address. - **force** (bool) - Required - Whether to force the failover. - **abort** (bool) - Required - Whether to abort an existing failover. - **timeout** (Option) - Optional - Timeout in milliseconds. ``` -------------------------------- ### pub async fn init Source: https://docs.rs/fred/latest/fred/clients/struct.DynamicPool.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Initializes the pool connections. ```APIDOC ## pub async fn init(&self) -> FredResult ### Description Initialize a new routing and connection task for each client and wait for them to connect successfully. ``` -------------------------------- ### config_get Source: https://docs.rs/fred/latest/fred/clients/struct.SubscriberClient.html?search=std%3A%3Avec Gets configuration parameters. ```APIDOC ## fn config_get( &self, parameter: S, ) -> impl Future> + Send ### Description Used to read the configuration parameters of a running Redis server. ``` -------------------------------- ### Use SimpleMap in a test Source: https://docs.rs/fred/latest/fred/mocks/struct.SimpleMap.html Example of configuring a client with SimpleMap to mock Redis operations in a test environment. ```rust #[tokio::test] async fn should_use_echo_mock() { let config = Config { mocks: Some(Arc::new(SimpleMap::new())), ..Default::default() }; let client = Builder::from_config(config).build().unwrap(); client.init().await.expect("Failed to connect"); let actual: String = client .set("foo", "bar", None, None, false) .await .expect("Failed to call SET"); assert_eq!(actual, "OK"); let actual: String = client.get("foo").await.expect("Failed to call GET"); assert_eq!(actual, "bar"); } ``` -------------------------------- ### get Source: https://docs.rs/fred/latest/fred/clients/struct.Client.html?search=std%3A%3Avec Reads a value from the server. ```APIDOC ## fn get(key: K) ### Description Retrieves the value associated with the specified key from the Redis server. ``` -------------------------------- ### ft_sugget Source: https://docs.rs/fred/latest/fred/clients/struct.Client.html?search= Get completion suggestions for a prefix. ```APIDOC ## fn ft_sugget( &self, key: K, prefix: P, fuzzy: bool, withscores: bool, withpayloads: bool, max: Option, ) -> impl Future> + Send ### Description Get completion suggestions for a prefix. ``` -------------------------------- ### fn init(&self) Source: https://docs.rs/fred/latest/fred/clients/struct.Pool.html?search= Initialize a new routing and connection task for each client and wait for them to connect successfully. ```APIDOC ## fn init(&self) ### Description Initialize a new routing and connection task for each client and wait for them to connect successfully. The returned ConnectHandle refers to the task that drives the routing and connection layer for each client via join. ``` -------------------------------- ### get Source: https://docs.rs/fred/latest/fred/clients/struct.Pipeline.html?search= Reads a value from the Redis server. ```APIDOC ## fn get(key: K) ### Description Read a value from the server. ``` -------------------------------- ### failover Source: https://docs.rs/fred/latest/fred/clients/struct.Client.html?search= Starts a coordinated failover between the master and a replica. ```APIDOC ## failover(to: Option<(String, u16)>, force: bool, abort: bool, timeout: Option) ### Description This command will start a coordinated failover between the currently-connected-to master and one of its replicas. ### Parameters - **to** (Option<(String, u16)>) - Optional - Target address. - **force** (bool) - Required - Force the failover. - **abort** (bool) - Required - Abort the failover. - **timeout** (Option) - Optional - Timeout in seconds. ``` -------------------------------- ### fn with_options(&self, options: &Options) -> WithOptions Source: https://docs.rs/fred/latest/fred/clients/struct.SentinelClient.html Configures command options for the client. ```APIDOC ## fn with_options(&self, options: &Options) ### Description Customize various configuration options on commands. ### Parameters - **options** (&Options) - Required - The configuration options to apply. ``` -------------------------------- ### Initialize and use a Fred Redis client Source: https://docs.rs/fred/latest/fred/index.html?search= Demonstrates creating a client from a URL, configuring connection settings, handling errors, and performing basic GET/SET operations. ```rust use fred::prelude::*; #[tokio::main] async fn main() -> Result<(), Error> { let config = Config::from_url("redis://localhost:6379/1")?; let client = Builder::from_config(config) .with_connection_config(|config| { config.connection_timeout = Duration::from_secs(5); config.tcp = TcpConfig { nodelay: Some(true), ..Default::default() }; }) .build()?; client.init().await?; client.on_error(|(error, server)| async move { println!("{:?}: Connection error: {:?}", server, error); Ok(()) }); // convert responses to many common Rust types let foo: Option = client.get("foo").await?; assert!(foo.is_none()); client.set("foo", "bar", None, None, false).await?; // or use turbofish to declare response types println!("Foo: {:?}", client.get::("foo").await?); client.quit().await?; Ok(()) } ``` -------------------------------- ### failover Source: https://docs.rs/fred/latest/fred/clients/struct.Pipeline.html?search= Starts a coordinated failover between the master and a replica. ```APIDOC ## fn failover(to: Option<(String, u16)>, force: bool, abort: bool, timeout: Option) ### Description This command will start a coordinated failover between the currently-connected-to master and one of its replicas. ### Parameters - **to** (Option<(String, u16)>) - Optional - Target server. - **force** (bool) - Required - Force the failover. - **abort** (bool) - Required - Abort the failover. - **timeout** (Option) - Optional - Timeout in milliseconds. ``` -------------------------------- ### get Source: https://docs.rs/fred/latest/fred/types/struct.Map.html?search=u32+-%3E+bool Returns a reference to the value corresponding to the key. ```APIDOC ## pub fn get(&self, k: &Q) -> Option<&V> ### Description Returns a reference to the value corresponding to the key. The key may be any borrowed form of the map’s key type, but Hash and Eq on the borrowed form must match those for the key type. ``` -------------------------------- ### Apply Options to a command Source: https://docs.rs/fred/latest/fred/types/config/struct.Options.html Demonstrates how to initialize an Options struct and apply it to a client command using with_options. ```rust async fn example() -> Result<(), Error> { let options = Options { max_attempts: Some(10), max_redirections: Some(2), ..Default::default() }; let client = Client::default(); client.init().await?; let _: () = client.with_options(&options).get("foo").await?; Ok(()) } ``` -------------------------------- ### ft_suglen Source: https://docs.rs/fred/latest/fred/interfaces/trait.RediSearchInterface.html?search=u32+-%3E+bool Gets the number of entries in a suggestion dictionary. ```APIDOC ## fn ft_suglen(&self, key: K) -> impl Future> ### Description Returns the number of entries in the suggestion dictionary stored at the specified key. ### Parameters - **key** (K: Into + Send) - The key of the suggestion dictionary. ``` -------------------------------- ### getdel Source: https://docs.rs/fred/latest/fred/clients/struct.Client.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Get the value of key and delete the key. ```APIDOC ## fn getdel(&self, key: K) -> impl Future> + Send ### Description Get the value of key and delete the key. This command is similar to GET, except for the fact that it also deletes the key on success (if and only if the key’s value type is a string). ``` -------------------------------- ### get Source: https://docs.rs/fred/latest/fred/clients/struct.Pool.html?search=std%3A%3Avec Reads a value from the server for a given key. ```APIDOC ## fn get(key: K) ### Description Reads a value from the server. ### Parameters - **key** (K) - Required - The key to retrieve. ``` -------------------------------- ### ft_suglen Source: https://docs.rs/fred/latest/fred/clients/struct.Client.html?search= Get the size of an auto-complete suggestion dictionary. ```APIDOC ## fn ft_suglen(&self, key: K) -> impl Future> + Send ### Description Get the size of an auto-complete suggestion dictionary. ``` -------------------------------- ### hello(version: RespVersion, auth: Option<(Str, Str)>, setname: Option) Source: https://docs.rs/fred/latest/fred/interfaces/trait.AuthInterface.html Switches the client to a different protocol, optionally authenticating in the process. Issues the HELLO command to all servers in a cluster concurrently. ```APIDOC ## hello(version: RespVersion, auth: Option<(Str, Str)>, setname: Option) ### Description Switch to a different protocol, optionally authenticating in the process. ### Parameters - **version** (RespVersion) - Required - The RESP protocol version to switch to. - **auth** (Option<(Str, Str)>) - Optional - Tuple containing username and password for authentication. - **setname** (Option) - Optional - The client name to set. ### Returns - **Future>** - A future that resolves when the protocol switch is complete. ``` -------------------------------- ### hello Source: https://docs.rs/fred/latest/fred/clients/struct.Client.html?search=std%3A%3Avec Switch to a different protocol, optionally authenticating. ```APIDOC ## fn hello( &self, version: RespVersion, auth: Option<(Str, Str)>, setname: Option, ) -> impl Future> + Send ### Description Switch to a different protocol, optionally authenticating in the process. ``` -------------------------------- ### SimpleMap::get Source: https://docs.rs/fred/latest/fred/mocks/struct.SimpleMap.html?search=std%3A%3Avec Performs a GET operation on the internal map. ```APIDOC ## pub fn get(&self, args: Vec) -> Result ### Description Perform a `GET` operation using the provided arguments. ``` -------------------------------- ### Using WithOptions for Command Configuration Source: https://docs.rs/fred/latest/fred/clients/struct.WithOptions.html Demonstrates applying custom options to a client and reusing those options across multiple commands and pipelines. ```rust async fn example() -> Result<(), Error> { let client = Client::default(); client.init().await?; let options = Options { max_redirections: Some(3), max_attempts: Some(1), timeout: Some(Duration::from_secs(10)), ..Default::default() }; let foo: Option = client.with_options(&options).get("foo").await?; // reuse the options bindings let with_options = client.with_options(&options); let foo: () = with_options.get("foo").await?; let bar: () = with_options.get("bar").await?; // combine with other client types let pipeline = client.pipeline().with_options(&options); let _: () = pipeline.get("foo").await?; let _: () = pipeline.get("bar").await?; // custom options will be applied to each command println!("results: {:?}", pipeline.all::().await?); Ok(()) } ``` -------------------------------- ### Get List Range Source: https://docs.rs/fred/latest/fred/clients/struct.Pipeline.html Returns the specified elements of the list. ```rust fn lrange( &self, key: K, start: i64, stop: i64, ) -> impl Future> + Send where R: FromValue, K: Into + Send, ``` -------------------------------- ### Get pool size Source: https://docs.rs/fred/latest/fred/clients/struct.Pool.html?search=std%3A%3Avec Returns the number of clients in the pool. ```rust pub fn size(&self) -> usize ``` -------------------------------- ### Client Initialization and Management Source: https://docs.rs/fred/latest/fred/clients/struct.Client.html?search=std%3A%3Avec Methods for creating new client instances and managing cluster connections. ```rust pub fn new( config: Config, perf: Option, connection: Option, policy: Option, ) -> Client ``` ```rust pub fn clone_new(&self) -> Self ``` ```rust pub fn split_cluster(&self) -> Result, Error> ``` -------------------------------- ### Example Search Queries Source: https://docs.rs/fred/latest/fred/index.html?search= Common search patterns for the library documentation. ```text std::vec ``` ```text u32 -> bool ``` ```text Option, (T -> U) -> Option ``` -------------------------------- ### bgrewriteaof Source: https://docs.rs/fred/latest/fred/clients/struct.Client.html?search= Instructs Redis to start an Append Only File rewrite process. ```APIDOC ## bgrewriteaof() ### Description Instruct Redis to start an Append Only File rewrite process. ``` -------------------------------- ### bgrewriteaof Source: https://docs.rs/fred/latest/fred/clients/struct.Pipeline.html?search= Instructs Redis to start an Append Only File rewrite process. ```APIDOC ## fn bgrewriteaof() ### Description Instruct Redis to start an Append Only File rewrite process. ``` -------------------------------- ### Server::new Source: https://docs.rs/fred/latest/fred/types/config/struct.Server.html Creates a new Server instance with the specified host and port. ```APIDOC ## pub fn new>(host: S, port: u16) -> Self ### Description Creates a new `Server` instance from the provided host and port. ### Parameters - **host** (S: Into) - Required - The hostname or IP address for the server. - **port** (u16) - Required - The port for the server. ``` -------------------------------- ### Get Value by Key Source: https://docs.rs/fred/latest/fred/types/streams/type.XReadResponse.html?search= Retrieves a reference to the value associated with a key. ```rust use std::collections::HashMap; let mut map = HashMap::new(); map.insert(1, "a"); assert_eq!(map.get(&1), Some(&"a")); assert_eq!(map.get(&2), None); ``` -------------------------------- ### Get HashMap Hasher Source: https://docs.rs/fred/latest/fred/types/streams/type.XReadResponse.html?search= Retrieves a reference to the map's BuildHasher. ```rust use std::collections::HashMap; use std::hash::RandomState; let hasher = RandomState::new(); let map: HashMap = HashMap::with_hasher(hasher); let hasher: &RandomState = map.hasher(); ``` -------------------------------- ### ServerConfig Initialization Methods Source: https://docs.rs/fred/latest/fred/types/config/enum.ServerConfig.html Methods for creating different types of server configurations. ```APIDOC ## new_centralized(host: S, port: u16) -> ServerConfig ### Description Creates a new centralized configuration with the provided host and port. ## new_clustered(hosts: Vec<(S, u16)>) -> ServerConfig ### Description Creates a new clustered configuration with the provided set of hosts and ports. The client will use CLUSTER NODES to discover other nodes. ## new_sentinel(hosts: Vec<(H, u16)>, service_name: N) -> ServerConfig ### Description Creates a new sentinel configuration with the provided set of hosts and the service name. ## new_unix_socket

(path: P) -> ServerConfig ### Description Creates a new server configuration for a connected Unix socket. Available only with the `unix-sockets` crate feature. ``` -------------------------------- ### Initialize and Clone Client Source: https://docs.rs/fred/latest/fred/clients/struct.Client.html?search=u32+-%3E+bool Methods for creating new client instances or cloning existing configurations. ```rust pub fn new( config: Config, perf: Option, connection: Option, policy: Option, ) -> Client ``` ```rust pub fn clone_new(&self) -> Self ``` -------------------------------- ### get(key: K) Source: https://docs.rs/fred/latest/fred/interfaces/trait.KeysInterface.html?search=std%3A%3Avec Read a value from the server. ```APIDOC ## get(key) ### Description Read a value from the server. ### Parameters - **key** (K: Into) - Required - The key to retrieve. ``` -------------------------------- ### init Source: https://docs.rs/fred/latest/fred/clients/struct.Replicas.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Initialize a new routing and connection task and wait for it to connect successfully. ```APIDOC ## init ### Description Initialize a new routing and connection task and wait for it to connect successfully. ### Signature `fn init(&self) -> impl Future> + Send` ``` -------------------------------- ### Get List Length Source: https://docs.rs/fred/latest/fred/clients/struct.Pipeline.html Returns the length of the list stored at the key. ```rust fn llen(&self, key: K) -> impl Future> + Send where R: FromValue, K: Into + Send, ``` -------------------------------- ### fn hello(&self, version: RespVersion, auth: Option<(Str, Str)>, setname: Option) Source: https://docs.rs/fred/latest/fred/interfaces/trait.AuthInterface.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Switches the client to a different protocol version, optionally performing authentication and setting a client name in the process. ```APIDOC ## fn hello(&self, version: RespVersion, auth: Option<(Str, Str)>, setname: Option) ### Description Switch to a different protocol, optionally authenticating in the process. If running against clustered servers this function will issue the HELLO command to each server concurrently. ### Parameters - **version** (RespVersion) - Required - The protocol version to switch to. - **auth** (Option<(Str, Str)>) - Optional - Optional tuple containing username and password for authentication. - **setname** (Option) - Optional - Optional name to set for the client connection. ``` -------------------------------- ### set Source: https://docs.rs/fred/latest/fred/clients/struct.Client.html?search=std%3A%3Avec Sets a value with optional NX|XX, EX|PX|EXAT|PXAT|KEEPTTL, and GET arguments. ```APIDOC ## fn set(key: K, value: V, expire: Option, options: Option, get: bool) ### Description Sets a value in Redis with optional expiration, conditional (NX/XX) logic, and GET functionality. ### Parameters - **key** (K) - Required - The key to set. - **value** (V) - Required - The value to associate with the key. - **expire** (Option) - Optional - Expiration settings. - **options** (Option) - Optional - Set options like NX or XX. - **get** (bool) - Required - Whether to return the old value. ``` -------------------------------- ### Get last client Source: https://docs.rs/fred/latest/fred/clients/struct.Pool.html?search=std%3A%3Avec Retrieves the client that executed the most recent command. ```rust pub fn last(&self) -> &Client ``` -------------------------------- ### Get next client Source: https://docs.rs/fred/latest/fred/clients/struct.Pool.html?search=std%3A%3Avec Retrieves the next client in the round-robin sequence. ```rust pub fn next(&self) -> &Client ``` -------------------------------- ### init Source: https://docs.rs/fred/latest/fred/clients/struct.Pool.html?search=u32+-%3E+bool Initialize a new routing and connection task for each client and wait for them to connect successfully. ```APIDOC ## fn init(&self) -> impl Future> + Send ### Description Initialize a new routing and connection task for each client and wait for them to connect successfully. The returned ConnectHandle refers to the task that drives the routing and connection layer for each client via join. ``` -------------------------------- ### start_tracking

(&self, prefixes: P, bcast: bool, optin: bool, optout: bool, noloop: bool) Source: https://docs.rs/fred/latest/fred/interfaces/trait.TrackingInterface.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Sends the CLIENT TRACKING command to all connected servers to subscribe to invalidation messages. Requires RESP3 protocol mode. ```APIDOC ## fn start_tracking

(prefixes: P, bcast: bool, optin: bool, optout: bool, noloop: bool) ### Description Sends the CLIENT TRACKING command to all connected servers, subscribing to invalidation messages on the same connection. This interface requires the RESP3 protocol mode and supports all server deployment types. ### Parameters - **prefixes** (P: Into + Send) - Required - The key prefixes to track. - **bcast** (bool) - Required - Whether to enable broadcast mode. - **optin** (bool) - Required - Whether to enable opt-in mode. - **optout** (bool) - Required - Whether to enable opt-out mode. - **noloop** (bool) - Required - Whether to enable no-loop mode. ``` -------------------------------- ### ts_queryindex Source: https://docs.rs/fred/latest/fred/clients/struct.Client.html?search= Get all time series keys matching a filter list. ```APIDOC ## fn ts_queryindex( &self, filters: I, ) -> impl Future> + Send ### Description Get all time series keys matching a filter list. ``` -------------------------------- ### ts_get Source: https://docs.rs/fred/latest/fred/clients/struct.Client.html?search= Get the sample with the highest timestamp from a given time series. ```APIDOC ## fn ts_get( &self, key: K, latest: bool, ) -> impl Future> + Send ### Description Get the sample with the highest timestamp from a given time series. ``` -------------------------------- ### start_tracking

(&self, prefixes: P, bcast: bool, optin: bool, optout: bool, noloop: bool) Source: https://docs.rs/fred/latest/fred/interfaces/trait.TrackingInterface.html?search=std%3A%3Avec Sends the CLIENT TRACKING command to all connected servers to subscribe to invalidation messages. Requires RESP3 protocol mode. ```APIDOC ### Method `start_tracking

(prefixes: P, bcast: bool, optin: bool, optout: bool, noloop: bool) -> impl Future> + Send` ### Description Sends the CLIENT TRACKING command to all connected servers, subscribing to invalidation messages on the same connection. This interface requires the RESP3 protocol mode and supports all server deployment types (centralized, clustered, and sentinel). ### Parameters - **prefixes** (P: Into + Send) - Required - The key prefixes to track. - **bcast** (bool) - Required - Whether to enable broadcast mode. - **optin** (bool) - Required - Whether to enable opt-in mode. - **optout** (bool) - Required - Whether to enable opt-out mode. - **noloop** (bool) - Required - Whether to enable no-loop mode. ``` -------------------------------- ### run Source: https://docs.rs/fred/latest/fred/monitor/index.html?search=std%3A%3Avec Executes the MONITOR command against a specified server. ```APIDOC ## Function: run ### Description Runs the MONITOR command against the provided server. ### Signature `pub fn run(server: &Server) -> Result<(), Error>` ### Parameters - **server** (Server) - Required - The server instance to execute the MONITOR command against. ``` -------------------------------- ### setrange Source: https://docs.rs/fred/latest/fred/clients/struct.Client.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Overwrites part of the string stored at key, starting at the specified offset. ```APIDOC ## fn setrange( &self, key: K, offset: u32, value: V, ) -> impl Future> + Send ### Description Overwrites part of the string stored at `key`, starting at the specified `offset`, for the entire length of `value`. ``` -------------------------------- ### run Source: https://docs.rs/fred/latest/fred/monitor/index.html?search= Executes the MONITOR command against the specified server. ```APIDOC ## Function: run ### Description Runs the MONITOR command against the provided server. This function is available when the `monitor` feature is enabled. ### Signature `pub fn run(server: &Server) -> Result` ``` -------------------------------- ### Get Result References with as_ref Source: https://docs.rs/fred/latest/fred/interfaces/type.FredResult.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Converts a Result reference into a Result of references. ```rust let x: Result = Ok(2); assert_eq!(x.as_ref(), Ok(&2)); let x: Result = Err("Error"); assert_eq!(x.as_ref(), Err(&"Error")); ``` -------------------------------- ### run Source: https://docs.rs/fred/latest/fred/monitor/index.html Executes the MONITOR command against the specified server. ```APIDOC ## Function: run ### Description Run the MONITOR command against the provided server. This function is available only when the `monitor` feature is enabled. ### Signature `pub fn run(server: &Server) -> Result` ### Parameters - **server** (&Server) - The server instance to execute the command against. ``` -------------------------------- ### Get List Element by Index Source: https://docs.rs/fred/latest/fred/clients/struct.Pipeline.html Returns the element at the specified index in the list. ```rust fn lindex( &self, key: K, index: i64, ) -> impl Future> + Send where R: FromValue, K: Into + Send, ``` -------------------------------- ### pub async fn run(config: Config) -> Result, Error> Source: https://docs.rs/fred/latest/fred/monitor/fn.run.html Executes the MONITOR command against the server using the provided configuration. This function is available only when the 'monitor' crate feature is enabled. ```APIDOC ## Function: run ### Description Run the MONITOR command against the provided server. Currently only centralized configurations are supported. ### Signature `pub async fn run(config: Config) -> Result, Error>` ### Requirements - **Crate Feature**: `monitor` ### Parameters - **config** (Config) - Required - The configuration object used to connect to the server. ``` -------------------------------- ### Version::new Source: https://docs.rs/fred/latest/fred/types/struct.Version.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates a new Version instance with specified major, minor, and patch numbers, initializing pre-release and build metadata as empty. ```APIDOC ## Version::new(major: u64, minor: u64, patch: u64) -> Version ### Description Creates a new Version instance with the provided major, minor, and patch components. The pre-release and build metadata fields are initialized to empty values. ### Parameters - **major** (u64) - The major version number. - **minor** (u64) - The minor version number. - **patch** (u64) - The patch version number. ``` -------------------------------- ### Version::new Source: https://docs.rs/fred/latest/fred/types/struct.Version.html?search=std%3A%3Avec Creates a new Version instance with specified major, minor, and patch numbers, initializing pre-release and build metadata as empty. ```APIDOC ## Version::new(major: u64, minor: u64, patch: u64) -> Version ### Description Creates a new Version instance with the provided major, minor, and patch components. The pre-release and build metadata fields are initialized to empty values. ### Parameters - **major** (u64) - Required - The major version number. - **minor** (u64) - Required - The minor version number. - **patch** (u64) - Required - The patch version number. ``` -------------------------------- ### Initialize a New Client Source: https://docs.rs/fred/latest/fred/clients/struct.Client.html Create a new client instance without connecting to the server. ```rust pub fn new( config: Config, perf: Option, connection: Option, policy: Option, ) -> Client ``` -------------------------------- ### getrange Source: https://docs.rs/fred/latest/fred/clients/struct.Client.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns the substring of the string value stored at key with offsets start and end. ```APIDOC ## fn getrange( &self, key: K, start: usize, end: usize, ) -> impl Future> + Send ### Description Returns the substring of the string value stored at `key` with offsets `start` and `end` (both inclusive). ``` -------------------------------- ### Server::new_with_tls Source: https://docs.rs/fred/latest/fred/types/config/struct.Server.html Creates a new Server instance with host, port, and an optional TLS server name. Requires specific crate features. ```APIDOC ## pub fn new_with_tls>(host: S, port: u16, tls_server_name: Option) -> Self ### Description Creates a new `Server` from parts with a TLS server name. This method is available only when `enable-rustls`, `enable-native-tls`, or `enable-rustls-ring` features are enabled. ### Parameters - **host** (S: Into) - Required - The hostname or IP address for the server. - **port** (u16) - Required - The port for the server. - **tls_server_name** (Option) - Optional - The server name used during the TLS handshake. ``` -------------------------------- ### entry Source: https://docs.rs/fred/latest/fred/types/struct.Map.html?search=u32+-%3E+bool Gets the given key’s corresponding entry in the map for in-place manipulation. ```APIDOC ## pub fn entry(&mut self, key: K) -> Entry<'_, K, V, A> ### Description Gets the given key’s corresponding entry in the map for in-place manipulation. ``` -------------------------------- ### Get Mutable Reference to Value Source: https://docs.rs/fred/latest/fred/types/streams/type.XReadResponse.html?search= Retrieves a mutable reference to the value associated with a key. ```rust use std::collections::HashMap; let mut map = HashMap::new(); map.insert(1, "a"); if let Some(x) = map.get_mut(&1) { *x = "b"; } assert_eq!(map[&1], "b"); ``` -------------------------------- ### WithOptions::replicas Source: https://docs.rs/fred/latest/fred/clients/struct.WithOptions.html Creates a client interface for interacting with replica nodes. ```APIDOC ## pub fn replicas(&self) -> Replicas> ### Description Creates a client that interacts with replica nodes. This method is only available when the `replicas` feature is enabled. ### Returns - **Replicas>** - A client configured to interact with replicas. ``` -------------------------------- ### ts_mget Source: https://docs.rs/fred/latest/fred/clients/struct.Client.html?search= Get the sample with the highest timestamp from each time series matching a specific filter. ```APIDOC ## fn ts_mget( &self, latest: bool, labels: Option, filters: I, ) -> impl Future> + Send ### Description Get the sample with the highest timestamp from each time series matching a specific filter. ``` -------------------------------- ### fn init(&self) -> impl Future> + Send Source: https://docs.rs/fred/latest/fred/interfaces/trait.ClientLike.html Initializes a new routing and connection task and waits for a successful connection. ```APIDOC ## init ### Description Initialize a new routing and connection task and wait for it to connect successfully. The returned ConnectHandle refers to the task that drives the routing and connection layer. ``` -------------------------------- ### fn connect(&self) -> ConnectHandle Source: https://docs.rs/fred/latest/fred/interfaces/trait.ClientLike.html Initiates a connection to the server. Returns a JoinHandle to the task driving the connection. ```APIDOC ## connect ### Description Connect to the server. This function returns a `JoinHandle` to a task that drives the connection. It will not resolve until the connection closes, or if a reconnection policy with unlimited attempts is provided then it will run until `QUIT` is called. ``` -------------------------------- ### Get next connected client Source: https://docs.rs/fred/latest/fred/clients/struct.Pool.html?search=std%3A%3Avec Retrieves the next client that is connected and ready to execute a command. ```rust pub fn next_connected(&self) -> &Client ``` -------------------------------- ### ConfigInterface Methods Source: https://docs.rs/fred/latest/fred/clients/struct.Replicas.html?search=std%3A%3Avec Methods for managing Redis server configuration settings. ```APIDOC ## config_resetstat Resets the statistics reported by Redis using the INFO command. ## config_rewrite Rewrites the redis.conf file the server was started with, applying minimal changes to reflect current configuration. ## config_get(parameter) Reads the configuration parameters of a running Redis server. ## config_set(parameter, value) Reconfigures the server at run time without restarting Redis. ``` -------------------------------- ### new Source: https://docs.rs/fred/latest/fred/clients/struct.Client.html Create a new client instance without connecting to the server. ```APIDOC ## pub fn new(config: Config, perf: Option, connection: Option, policy: Option) -> Client ### Description Create a new client instance without connecting to the server. See the builder interface for more information. ``` -------------------------------- ### Usage example for Resp3TimeSeriesValues Source: https://docs.rs/fred/latest/fred/types/timeseries/type.Resp3TimeSeriesValues.html?search=u32+-%3E+bool Demonstrates retrieving time series data using ts_mget while in RESP3 mode. ```rust async fn example(client: &Client) -> Result<(), Error> { assert_eq!(client.protocol_version(), RespVersion::RESP3); client .ts_add("foo", "*", 1.1, None, None, None, None, ("a", "b")) .await?; sleep(Duration::from_millis(5)).await; client .ts_add("foo", "*", 2.2, None, None, None, None, ("a", "b")) .await?; sleep(Duration::from_millis(5)).await; client .ts_add("bar", "*", 3.3, None, None, None, None, ("a", "b")) .await?; sleep(Duration::from_millis(5)).await; client .ts_add("bar", "*", 4.4, None, None, None, None, ("a", "b")) .await?; let ranges: Resp3TimeSeriesValues = client .ts_mget(false, Some(GetLabels::WithLabels), ["a=b"]) .await?; for (key, (labels, values)) in ranges.into_iter() { println!("{} [{:?}] {:?}", key.as_str_lossy(), labels, values); } // bar [[("a", "b"))]] [(1705355605517, 4.4)] // foo [[("a", "b"))]] [(1705355605504, 2.2)] Ok(()) } ``` -------------------------------- ### Initialize and Use an ExclusivePool Source: https://docs.rs/fred/latest/fred/clients/struct.ExclusivePool.html?search= Demonstrates creating an exclusive pool with a specified size, initializing connections, and performing a graceful shutdown. ```rust use fred::prelude::*; #[tokio::main] async fn main() -> Result<(), Error> { let pool = Builder::default_centralized().build_exclusive_pool(5)?; let connection_task = pool.init().await?; // ... pool.quit().await?; connection_task.await? } ``` -------------------------------- ### pub fn from_url_unix(url: &str) -> Result Source: https://docs.rs/fred/latest/fred/types/config/struct.Config.html?search=u32+-%3E+bool Creates a Config from a URL that connects via a Unix domain socket. Requires the unix-sockets crate feature. ```APIDOC ## pub fn from_url_unix(url: &str) -> Result ### Description Creates a `Config` from a URL that connects via a Unix domain socket. Note that the path section is used for the socket file, so database selection must be set manually on the returned `Config` object. ### Parameters - **url** (&str) - Required - The connection URL string (e.g., redis+unix:///path/to/redis.sock) ``` -------------------------------- ### ServerConfig Constructors Source: https://docs.rs/fred/latest/fred/types/config/enum.ServerConfig.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Methods to initialize different server configuration types. ```APIDOC ## ServerConfig Constructors ### new_centralized(host: S, port: u16) -> ServerConfig Creates a new centralized configuration. ### new_clustered(hosts: Vec<(S, u16)>) -> ServerConfig Creates a new clustered configuration. The client will use CLUSTER NODES to discover other nodes. ### new_sentinel(hosts: Vec<(H, u16)>, service_name: N) -> ServerConfig Creates a new sentinel configuration for a service. ### new_unix_socket

(path: P) -> ServerConfig Creates a new server configuration for a Unix socket (requires unix-sockets feature). ### default_centralized() -> ServerConfig Creates a centralized configuration with default local settings. ### default_clustered() -> ServerConfig Creates a clustered configuration with default settings. ``` -------------------------------- ### get_disjoint_unchecked_mut Source: https://docs.rs/fred/latest/fred/types/struct.Map.html?search=u32+-%3E+bool Attempts to get mutable references to N values in the map at once, without validating that the values are unique. ```APIDOC ### pub unsafe fn get_disjoint_unchecked_mut( &mut self, ks: [&Q; N], ) -> [Option<&mut V>; N] Attempts to get mutable references to `N` values in the map at once, without validating that the values are unique. Returns an array of length `N` with the results of each query. `None` will be used if the key is missing. Calling this method with overlapping keys is undefined behavior. ``` -------------------------------- ### Pool Initialization Methods Source: https://docs.rs/fred/latest/fred/clients/struct.Pool.html?search= Methods for creating a new Pool instance from existing clients or configuration. ```rust pub fn from_clients(clients: Vec) -> Result ``` ```rust pub fn new( config: Config, perf: Option, connection: Option, policy: Option, size: usize, ) -> Result ``` -------------------------------- ### Pipelining Source: https://docs.rs/fred/latest/fred/clients/struct.Client.html?search=std%3A%3Avec Method to initiate a command pipeline. ```rust pub fn pipeline(&self) -> Pipeline ```