### Build Carade from Source Source: https://github.com/codetease/carade/blob/main/docs/getting-started.md Clones the Carade repository and builds the project using Maven. This method is recommended for development purposes. It requires Git and Maven to be installed. ```bash git clone https://github.com/codetease/carade.git cd carade mvn clean package ``` -------------------------------- ### Install Rust Benchmark Tools Source: https://github.com/codetease/carade/blob/main/tools/rust-benchmarks/README.md Instructions for installing Rust and building the benchmark tool in release mode. This is crucial for accurate benchmark results. ```bash # Install Rust (Linux/macOS) curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh # Refresh shell source $HOME/.cargo/env # Verify installation cargo --version cd tools/rust-benchmarks cargo build --release ``` -------------------------------- ### Carade Server Configuration Example (Properties) Source: https://github.com/codetease/carade/blob/main/docs/operations/configuration.md A sample configuration file for the Carade server using the properties format. It demonstrates settings for network, security, memory, and persistence. This format is human-readable and commonly used for configuration. ```properties # Network port 63790 bind 0.0.0.0 # Security requirepass teasertopsecret # User ACL: user user default teasertopsecret admin user viewer viewpass readonly user writer writepass readwrite # Memory maxmemory 256MB maxmemory-policy noeviction # Persistence appendonly yes appendfilename "carade.aof" save 900 1 save 300 10 ``` -------------------------------- ### Carade Configuration Example Source: https://github.com/codetease/carade/blob/main/README.md This is an example of a `carade.conf` file used to configure the Carade server. It sets the port, password, maximum memory, and defines user access levels. This file allows customization of server behavior and security. ```properties port 63790 requirepass teasertopsecret maxmemory 100MB # Users: user user default teasertopsecret admin user viewer viewpass readonly user writer writepass readwrite ``` -------------------------------- ### Check Java Version Source: https://github.com/codetease/carade/blob/main/docs/getting-started.md Verifies if the installed Java version meets Carade's requirement of Java 21 or later. No specific inputs or outputs are defined beyond the standard version check. ```bash java -version ``` -------------------------------- ### Connect to Carade with redis-cli Source: https://github.com/codetease/carade/blob/main/docs/getting-started.md Demonstrates how to connect to a running Carade instance using the redis-cli tool, authenticate with the default password, and perform basic SET and GET operations. Assumes Carade is running on the default port 63790. ```bash # Connect to default port 63790 redis-cli -p 63790 # Authenticate (default password: teasertopsecret) 127.0.0.1:63790> AUTH teasertopsecret OK # Test command 127.0.0.1:63790> SET foo bar OK 127.0.0.1:63790> GET foo "bar" ``` -------------------------------- ### Run Carade Server from Source Source: https://github.com/codetease/carade/blob/main/docs/getting-started.md Executes the Carade server after building it from source. This command assumes the build was successful and the JAR file is located in the target directory. The server defaults to port 63790. ```bash java -jar target/carade-0.3.4.jar ``` -------------------------------- ### Configure Replica Server with REPLICAOF Command Source: https://github.com/codetease/carade/blob/main/docs/architecture/replication.md Configures a Carade replica server to connect to a master at a specified IP address and port. This command initiates the replication process. ```bash # Connect to master at 127.0.0.1:63790 REPLICAOF 127.0.0.1 63790 ``` -------------------------------- ### Manage Carade Systemd Service Source: https://github.com/codetease/carade/blob/main/docs/operations/deployment.md These commands are used to manage the Carade systemd service after its configuration file has been created. 'daemon-reload' applies changes, 'enable' ensures it starts on boot, and 'start' initiates the service. ```bash sudo systemctl daemon-reload sudo systemctl enable carade sudo systemctl start carade ``` -------------------------------- ### Configure Replica Server in carade.conf Source: https://github.com/codetease/carade/blob/main/docs/architecture/replication.md Sets up Carade replication by specifying the master's address and port, and authentication credentials in the carade.conf configuration file. ```properties replicaof 127.0.0.1 63790 masterauth teasertopsecret ``` -------------------------------- ### Connect to Carade and Test Basic Operations Source: https://context7.com/codetease/carade/llms.txt Demonstrates how to connect to a running Carade server using `redis-cli`, authenticate with a password, and perform basic SET and GET operations. ```bash # Using redis-cli redis-cli -p 63790 # Authenticate (default password: teasertopsecret) 127.0.0.1:63790> AUTH teasertopsecret OK # Test basic operations 127.0.0.1:63790> SET foo bar OK 127.0.0.1:63790> GET foo "bar" ``` -------------------------------- ### Carade Redis Pub/Sub: Subscribe and Publish Source: https://context7.com/codetease/carade/llms.txt Provides a Python example of setting up a Redis Pub/Sub system. It includes a subscriber listening on specific channels and patterns, and a publisher sending messages. ```python import redis import threading r = redis.Redis(host='localhost', port=63790, password='teasertopsecret') # Subscriber (run in separate thread or process) def subscriber(): pubsub = r.pubsub() pubsub.subscribe('news:tech', 'news:sports') pubsub.psubscribe('alerts:*') # Pattern subscription for message in pubsub.listen(): if message['type'] == 'message': print(f"Channel: {message['channel']}, Data: {message['data']}") elif message['type'] == 'pmessage': print(f"Pattern: {message['pattern']}, Channel: {message['channel']}, Data: {message['data']}") # Start subscriber in background thread = threading.Thread(target=subscriber, daemon=True) thread.start() # Publisher r.publish('news:tech', 'New Python release!') r.publish('news:sports', 'Game tonight at 8PM') r.publish('alerts:critical', 'Server disk full!') # Matches pattern 'alerts:*' ``` -------------------------------- ### Run Carade using Docker Source: https://github.com/codetease/carade/blob/main/docs/getting-started.md Pulls the latest Carade Docker image and runs it as a detached container. This command maps the default port 63790 and mounts a local 'data' directory for persistence. It requires Docker to be installed and running. ```bash docker pull ghcr.io/codetease/carade:latest docker run -d \ -p 63790:63790 \ -v $(pwd)/data:/data \ --name carade-server \ ghcr.io/codetease/carade:latest ``` -------------------------------- ### Run Carade with Docker and Custom Configuration Source: https://github.com/codetease/carade/blob/main/docs/operations/deployment.md This Docker command deploys Carade with a custom configuration file and persistent data. It mounts both the configuration file (/opt/carade/carade.conf) and the data volume (/opt/carade/data) into the container. ```bash docker run -d \ -p 63790:63790 \ -v /opt/carade/carade.conf:/app/carade.conf \ -v /opt/carade/data:/data \ ghcr.io/codetease/carade:latest ``` -------------------------------- ### Python Example: Session Management with SETEX Source: https://github.com/codetease/carade/blob/main/docs/commands/strings.md Implements session management in Python using the redis-py library. It utilizes the `setex` command to store session data with an expiration time, ensuring sessions are automatically cleaned up. ```python import redis import json r = redis.Redis(host='localhost', port=63790, password='teasertopsecret') def create_session(user_id, role, session_timeout_seconds=3600): session_key = f"session:{user_id}" session_data = json.dumps({"userId": user_id, "role": role}) # Store the session data and set it to expire automatically r.setex(session_key, session_timeout_seconds, session_data) print(f"Session created for user {user_id}. Expires in {session_timeout_seconds}s.") def get_session(user_id): session_key = f"session:{user_id}" session_data = r.get(session_key) if session_data: return json.loads(session_data) return None # Session expired or doesn't exist # Usage create_session("user123", "admin") # ... later ... session = get_session("user123") if session: print(f"Logged in as {session['role']}") else: print("Session expired, please login again.") ``` -------------------------------- ### Build Carade JAR for Bare Metal Deployment Source: https://github.com/codetease/carade/blob/main/docs/operations/deployment.md This Maven command builds the Carade application into a JAR file, skipping tests for faster compilation. This JAR is intended for deployment on a bare metal server. ```bash mvn clean package -DskipTests ``` -------------------------------- ### HTTP API Example: Set Key with Expiration (SETEX) Source: https://github.com/codetease/carade/blob/main/docs/commands/strings.md Demonstrates setting a string value for a key with an automatic expiration time using the HTTP API. This is useful for implementing time-sensitive data like user sessions. ```http POST /command HTTP/1.1 Host: localhost:63790 Content-Type: text/plain SETEX session:user123 3600 "{\"userId\": 123, \"role\": \"admin\"}" ``` -------------------------------- ### Java Example: Managing User Profiles with Carade Hashes Source: https://github.com/codetease/carade/blob/main/docs/commands/hashes.md Demonstrates how to use Carade's Hash commands (HMSET, HSET, HGET, HGETALL) in Java with the Jedis client to store and retrieve user profile data. It includes connecting to Carade via JedisPool and handling potential exceptions. ```java import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.exceptions.JedisException; import java.util.HashMap; import java.util.Map; public class UserProfileExample { public static void main(String[] args) { // Initialize Jedis Pool (connecting to Carade's default port with password) try (JedisPool pool = new JedisPool("localhost", 63790)) { try (Jedis jedis = pool.getResource()) { jedis.auth("teasertopsecret"); String userId = "user:1001"; // 1. Using HMSET to store multiple fields at once (name, email, age) Map userProfile = new HashMap<>(); userProfile.put("name", "Jane Doe"); userProfile.put("email", "jane.doe@example.com"); userProfile.put("age", "28"); jedis.hmset(userId, userProfile); System.out.println("User profile saved."); // 2. Using HSET to update a single field jedis.hset(userId, "status", "active"); // 3. Using HGET to retrieve a specific field String email = jedis.hget(userId, "email"); System.out.println("Retrieved Email: " + email); // 4. Using HGETALL to retrieve the entire profile Map retrievedProfile = jedis.hgetall(userId); System.out.println("Full Profile:"); for (Map.Entry entry : retrievedProfile.entrySet()) { System.out.println(" " + entry.getKey() + ": " + entry.getValue()); } } catch (JedisException e) { System.err.println("Carade connection or command error: " + e.getMessage()); } } } } ``` -------------------------------- ### Carade Redis JSON Commands: Get Document Source: https://context7.com/codetease/carade/llms.txt Shows how to retrieve an entire JSON document or specific paths within it using the JSON.GET command in Redis. ```bash # Using redis-cli redis-cli -p 63790 # Get entire document 127.0.0.1:63790> JSON.GET user:1 "{\"name\":\"John\",\"age\":30,\"address\":{\"city\":\"NYC\",\"zip\":\"10001\"}}" # Get specific path 127.0.0.1:63790> JSON.GET user:1 $.name "[\"John\"]" # Get nested value 127.0.0.1:63790> JSON.GET user:1 $.address.city "[\"NYC\"]" ``` -------------------------------- ### Python Example: Rate Limiting with Lua Script Source: https://github.com/codetease/carade/blob/main/docs/commands/strings.md Demonstrates how to implement rate limiting in Python using the redis-py library and a server-side Lua script. The script is registered with Carade and executed atomically to check and increment request counts. ```python import redis r = redis.Redis(host='localhost', port=63790, password='teasertopsecret') # The lua script as a string lua_script = """ local current = tonumber(redis.call('GET', KEYS[1]) or "0") local limit = tonumber(ARGV[1]) if current >= limit then return -1 end local new_val = redis.call('INCR', KEYS[1]) if new_val == 1 then redis.call('EXPIRE', KEYS[1], ARGV[2]) end return new_val """ # Register the script once with Carade rate_limit_script = r.register_script(lua_script) def check_rate_limit(user_id, limit=5, window_seconds=60): key = f"rate_limit:{user_id}" # Execute the atomic operation result = rate_limit_script(keys=[key], args=[limit, window_seconds]) if result == -1: print(f"User {user_id}: Rate limit exceeded! Please wait.") return False else: print(f"User {user_id}: Request {result}/{limit} allowed.") return True # Simulate multiple requests for i in range(7): check_rate_limit("user456") ``` -------------------------------- ### Build Carade Project with Maven (Bash) Source: https://github.com/codetease/carade/blob/main/docs/development/contributing.md This Maven command cleans the project, compiles the code, runs tests, and packages the application into a JAR file located in the 'target/' directory. It requires Java JDK 21+ and Maven 3.8+ to be installed. ```bash mvn clean package ``` -------------------------------- ### Carade Redis HyperLogLog: Cardinality Estimation Source: https://context7.com/codetease/carade/llms.txt Introduces Redis HyperLogLog commands for probabilistic cardinality estimation. This example shows basic usage with a Redis client in Python, though the specific commands are not detailed in the provided snippet. ```python import redis r = redis.Redis(host='localhost', port=63790, password='teasertopsecret') # Example usage would involve r.pfadd() and r.pfcount() ``` -------------------------------- ### Run Checkstyle for Code Quality (Bash) Source: https://github.com/codetease/carade/blob/main/docs/development/contributing.md This Maven command executes the Checkstyle plugin to verify that the code adheres to the project's coding standards. It helps maintain code quality and consistency across the project. Ensure Maven is installed. ```bash mvn checkstyle:check ``` -------------------------------- ### Python Failover Logic for Carade Replication Source: https://github.com/codetease/carade/blob/main/docs/architecture/replication.md Implements manual failover logic in Python for Carade replication, directing writes to the master and reads to the replica, with fallback mechanisms. Requires the 'redis' library. ```python import redis import time # Define your master and replica nodes master_pool = redis.ConnectionPool(host='10.0.0.1', port=63790, socket_timeout=2) replica_pool = redis.ConnectionPool(host='10.0.0.2', port=63790, socket_timeout=2) def execute_with_failover(command_type, command_func, *args, **kwargs): """ Executes a command with manual failover. Writes MUST go to the master. Reads can go to the replica. """ if command_type == 'write': try: r = redis.Redis(connection_pool=master_pool) return command_func(r, *args, **kwargs) except redis.exceptions.ConnectionError: print("CRITICAL: Master is down! Writes are failing.") # In a real system, you might trigger an alert or a script to promote the replica here raise elif command_type == 'read': try: # Prefer reading from the replica to offload the master r = redis.Redis(connection_pool=replica_pool) return command_func(r, *args, **kwargs) except redis.exceptions.ConnectionError: print("WARNING: Replica is down, falling back to Master for reads.") try: r = redis.Redis(connection_pool=master_pool) return command_func(r, *args, **kwargs) except redis.exceptions.ConnectionError: print("CRITICAL: Both Master and Replica are down!") raise # Usage def do_set(r, key, value): return r.set(key, value) def do_get(r, key): return r.get(key) # Write goes to master execute_with_failover('write', do_set, 'cache_key', 'some_data') # Read preferentially goes to replica data = execute_with_failover('read', do_get, 'cache_key') ``` -------------------------------- ### Run Carade with Docker and Data Persistence Source: https://github.com/codetease/carade/blob/main/docs/operations/deployment.md This command deploys Carade using Docker, ensuring data persistence by mounting a volume for the /data directory. It maps the host port 63790 to the container's port 63790 and names the container 'carade-server'. ```bash docker run -d \ -p 63790:63790 \ -v /opt/carade/data:/data \ --name carade-server \ ghcr.io/codetease/carade:latest ``` -------------------------------- ### JVM Memory Settings for Carade Source: https://github.com/codetease/carade/blob/main/docs/operations/performance.md Configure JVM heap size for Carade. Set initial and maximum heap sizes equal to avoid resizing overhead, and allow for JVM internal overhead. Ensure heap size is larger than maxmemory in carade.conf. ```Bash java -Xms4G -Xmx4G -jar carade.jar ``` -------------------------------- ### Build and Run Carade Server Source: https://context7.com/codetease/carade/llms.txt Instructions to clone the Carade repository, build the project using Maven, and run the server. It also includes Docker commands for pulling and running the Carade image. ```bash # Clone and build git clone https://github.com/codetease/carade.git cd carade mvn clean package # Run the server java -jar target/carade-0.3.4.jar # Or use Docker docker pull ghcr.io/codetease/carade:latest docker run -d -p 63790:63790 -v $(pwd)/data:/data --name carade-server ghcr.io/codetease/carade:latest ``` -------------------------------- ### Run Carade Rust Benchmark Source: https://github.com/codetease/carade/blob/main/tools/rust-benchmarks/README.md Commands to execute the Carade Rust benchmark client. Supports basic usage with defaults and custom configurations for host, port, clients, requests, and scenarios. ```bash # Basic usage (defaults: localhost:63790, 50 clients, 1000 reqs/client) cargo run --release # Custom scenario with more load cargo run --release -- --host 127.0.0.1 --port 63790 --clients 100 --requests 10000 --scenario LuaStress ``` -------------------------------- ### Set Up Master-Replica Replication (Bash) Source: https://context7.com/codetease/carade/llms.txt Provides bash commands to configure a Redis replica to connect to a master server for replication, ensuring high availability and read scaling. ```bash # On replica server, connect to master redis-cli -p 63791 127.0.0.1:63791> AUTH teasertopsecret OK 127.0.0.1:63791> REPLICAOF 127.0.0.1 63790 OK # Or configure in carade.conf on replica: # replicaof 127.0.0.1 63790 # masterauth teasertopsecret ``` -------------------------------- ### Get Current Time - Java Source: https://github.com/codetease/carade/blob/main/src/main/java/core/utils/README.md Retrieves the current time using a deterministic approach. This utility allows for time manipulation in testing environments by swapping the internal clock. ```java long now = Time.now(); ``` -------------------------------- ### Redis Geo Commands: Get Location Coordinates Source: https://context7.com/codetease/carade/llms.txt Shows how to retrieve the latitude and longitude coordinates of a specific location stored in Redis Geo. ```python import redis r = redis.Redis(host='localhost', port=63790, password='teasertopsecret') # Get coordinates of a location pos = r.geopos('stores:locations', 'store:sf') # [(-122.4194, 37.7749)] ``` -------------------------------- ### Carade Hash Commands API Source: https://github.com/codetease/carade/blob/main/docs/commands/hashes.md This section details the supported Redis Hash commands available through Carade, including setting, getting, updating, and deleting hash fields. ```APIDOC ## Carade Hash Commands Carade supports standard Redis Hash commands for managing key-value pairs within a hash. ### HSET #### Description Set the string value of a hash field. #### Method `HSET` #### Endpoint `/hash/set` (Conceptual endpoint for documentation purposes) #### Parameters * **key** (string) - Required - The key of the hash. * **field** (string) - Required - The field within the hash. * **value** (string) - Required - The value to set for the field. ### HGET #### Description Get the value of a hash field. #### Method `HGET` #### Endpoint `/hash/get` (Conceptual endpoint for documentation purposes) #### Parameters * **key** (string) - Required - The key of the hash. * **field** (string) - Required - The field within the hash. ### HMSET #### Description Set multiple hash fields to multiple values. #### Method `HMSET` #### Endpoint `/hash/mset` (Conceptual endpoint for documentation purposes) #### Parameters * **key** (string) - Required - The key of the hash. * **fields** (map) - Required - A map of field-value pairs to set. ### HGETALL #### Description Get all the fields and values in a hash. #### Method `HGETALL` #### Endpoint `/hash/getall` (Conceptual endpoint for documentation purposes) #### Parameters * **key** (string) - Required - The key of the hash. ### HDEL #### Description Delete one or more hash fields. #### Method `HDEL` #### Endpoint `/hash/del` (Conceptual endpoint for documentation purposes) #### Parameters * **key** (string) - Required - The key of the hash. * **field** (string) - Required - The field to delete. ### HINCRBY #### Description Increment the integer value of a hash field by the given number. #### Method `HINCRBY` #### Endpoint `/hash/incrby` (Conceptual endpoint for documentation purposes) #### Parameters * **key** (string) - Required - The key of the hash. * **field** (string) - Required - The field to increment. * **increment** (integer) - Required - The number to increment by. ``` -------------------------------- ### T-Digest Commands Source: https://github.com/codetease/carade/blob/main/docs/commands/probabilistic.md Commands for adding samples, retrieving quantile values, calculating CDF, and getting information about T-Digest sketches. T-Digest is used for accurate on-line accumulation of rank-based statistics. ```redis TD.ADD key value [value ...] TD.QUANTILE key quantile [quantile ...] TD.CDF key value [value ...] TD.INFO key ``` -------------------------------- ### Carade String Commands with Python (redis-py) Source: https://context7.com/codetease/carade/llms.txt Illustrates how to use Carade's string commands via the `redis-py` client in Python. Covers basic SET/GET, setting keys with expiration, atomic counters, multiple key operations, and string manipulation. ```python import redis import json r = redis.Redis(host='localhost', port=63790, password='teasertopsecret') # Basic SET/GET r.set('user:name', 'John Doe') name = r.get('user:name') # b'John Doe' # SET with expiration (session management) def create_session(user_id, role, timeout_seconds=3600): session_key = f"session:{user_id}" session_data = json.dumps({"userId": user_id, "role": role}) r.setex(session_key, timeout_seconds, session_data) return session_key def get_session(user_id): session_key = f"session:{user_id}" data = r.get(session_key) return json.loads(data) if data else None # Atomic counters r.set('page:views', 0) r.incr('page:views') # 1 r.incrby('page:views', 10) # 11 r.decr('page:views') # 10 # Multiple keys at once r.mset({'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}) values = r.mget(['key1', 'key2', 'key3']) # [b'value1', b'value2', b'value3'] # String manipulation r.append('user:name', ' Jr.') # 'John Doe Jr.' length = r.strlen('user:name') # 12 ``` -------------------------------- ### Redis Geo Commands: Get Geohash Source: https://context7.com/codetease/carade/llms.txt Illustrates how to obtain the geohash representation of a location stored in Redis Geo. Geohashes are useful for spatial indexing and querying. ```python import redis r = redis.Redis(host='localhost', port=63790, password='teasertopsecret') # Get geohash geohash = r.geohash('stores:locations', 'store:sf') # [b'9q8yyz'] ``` -------------------------------- ### Netty Worker Threads Configuration for Carade Source: https://github.com/codetease/carade/blob/main/docs/operations/performance.md Customize the number of worker threads used by Netty within Carade. This can be adjusted via system properties if supported by the application's configuration. ```Bash -Dio.netty.eventLoopThreads=8 ``` -------------------------------- ### Implement New Redis Command in Java Source: https://github.com/codetease/carade/blob/main/src/main/java/core/commands/README.md This Java code demonstrates how to implement a new Redis command by creating a class that adheres to the `Command` interface. It includes argument validation and sending responses back to the client. Dependencies include `core.commands.Command` and `core.network.ClientHandler`. ```java package core.commands.string; import core.commands.Command; import core.network.ClientHandler; import java.util.List; public class MyCmdCommand implements Command { @Override public void execute(ClientHandler client, List args) { // Note: args includes the command name at index 0. // e.g., for "MYCMD key val", args.size() is 3. if (args.size() < 3) { client.sendError("ERR wrong number of arguments for 'mycmd' command"); return; } byte[] key = args.get(1); byte[] val = args.get(2); // Execute logic... client.sendSimpleString("OK"); } } ``` -------------------------------- ### Carade List Commands with Python (redis-py) Source: https://context7.com/codetease/carade/llms.txt Demonstrates the usage of Carade's list commands with the `redis-py` library in Python. Covers pushing and popping elements from both ends, retrieving ranges, blocking pops for queue implementations, list length, indexed access, and trimming lists. ```python import redis r = redis.Redis(host='localhost', port=63790, password='teasertopsecret') # Push elements r.lpush('queue:tasks', 'task3', 'task2', 'task1') # Left push: [task1, task2, task3] r.rpush('queue:tasks', 'task4', 'task5') # Right push: [task1, task2, task3, task4, task5] # Pop elements first = r.lpop('queue:tasks') # b'task1' last = r.rpop('queue:tasks') # b'task5' # Get range (0-indexed, inclusive) items = r.lrange('queue:tasks', 0, -1) # All remaining items # Blocking pop (useful for worker queues) # Blocks until an element is available or timeout (0 = wait forever) r.lpush('work:queue', 'job1') result = r.blpop(['work:queue'], timeout=5) # (b'work:queue', b'job1') # List length and indexed access r.rpush('mylist', 'a', 'b', 'c', 'd') length = r.llen('mylist') # 4 element = r.lindex('mylist', 2) # b'c' # Trim list to specific range r.ltrim('mylist', 0, 1) # Keep only first 2 elements ``` -------------------------------- ### Redis Hash Commands in Java Source: https://context7.com/codetease/carade/llms.txt Demonstrates storing and retrieving user profile data using Redis Hashes. It covers HMSET for multiple fields, HSET for single fields, HGET for retrieval, HGETALL for all fields, HINCRBY for numeric increments, HEXISTS for checking existence, and HDEL for deletion. Requires Jedis client library. ```java import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import java.util.HashMap; import java.util.Map; public class HashExample { public static void main(String[] args) { try (JedisPool pool = new JedisPool("localhost", 63790)) { try (Jedis jedis = pool.getResource()) { jedis.auth("teasertopsecret"); String userId = "user:1001"; // Store multiple fields at once with HMSET Map userProfile = new HashMap<>(); userProfile.put("name", "Jane Doe"); userProfile.put("email", "jane.doe@example.com"); userProfile.put("age", "28"); jedis.hmset(userId, userProfile); // Update single field with HSET jedis.hset(userId, "status", "active"); // Get single field String email = jedis.hget(userId, "email"); // "jane.doe@example.com" // Get all fields and values Map profile = jedis.hgetall(userId); // {name=Jane Doe, email=jane.doe@example.com, age=28, status=active} // Increment numeric field jedis.hincrBy(userId, "age", 1); // age becomes "29" // Check field existence and delete boolean exists = jedis.hexists(userId, "status"); // true jedis.hdel(userId, "status"); } } } } ``` -------------------------------- ### HyperLogLog Commands Source: https://context7.com/codetease/carade/llms.txt Probabilistic cardinality estimation using minimal memory (12KB max) with Python client. ```APIDOC ## HyperLogLog Commands Probabilistic cardinality estimation using minimal memory (12KB max). ### Method Python client (`redis-py`) ### Endpoint `localhost:63790` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import redis r = redis.Redis(host='localhost', port=63790, password='teasertopsecret') # Example usage for HyperLogLog commands would go here. # For instance: # r.pfadd('hll_key', 'user1', 'user2', 'user3') # count = r.pfcount('hll_key') # print(f"Estimated cardinality: {count}") ``` ### Response #### Success Response (200) - **Output**: The estimated cardinality of a HyperLogLog set. ``` -------------------------------- ### Carade Redis Lua Scripting: Rate Limiting Source: https://context7.com/codetease/carade/llms.txt Provides a Python example of executing a Lua script on the server-side for rate limiting. This script atomically increments a counter and checks against a limit. ```python import redis r = redis.Redis(host='localhost', port=63790, password='teasertopsecret') # Rate limiting script lua_script = """ local current = tonumber(redis.call('GET', KEYS[1]) or "0") local limit = tonumber(ARGV[1]) if current >= limit then return -1 end local new_val = redis.call('INCR', KEYS[1]) if new_val == 1 then redis.call('EXPIRE', KEYS[1], ARGV[2]) end return new_val """ rate_limit = r.register_script(lua_script) def check_rate_limit(user_id, limit=5, window_seconds=60): key = f"rate_limit:{user_id}" result = rate_limit(keys=[key], args=[limit, window_seconds]) if result == -1: return False, "Rate limit exceeded" return True, f"Request {result}/{limit} allowed" # Test rate limiting for i in range(7): allowed, msg = check_rate_limit("user123") print(msg) # Output: Request 1/5 allowed, Request 2/5 allowed, ..., Rate limit exceeded ```