This project implements a gateway system that manages client connections, processes requests, and enforces rate limiting using a token bucket algorithm. The system is designed to handle multiple clients concurrently while ensuring that each client adheres to a specified request rate limit.
The system works as follows:
-
Client Connection:
- A client connects to the gateway using the
connectmethod. - The gateway tracks the client's connection state and sets a refresh time.
- A client connects to the gateway using the
-
Request Submission:
- A client submits a request using the
submitmethod. - The gateway checks if the client is connected, if the request is within the rate limit, and if the connection has expired.
- If all checks pass, the request is processed, and the status is logged.
- A client submits a request using the
-
Rate Limiting:
- The
RateLimiterenforces a limit on the number of requests a client can make within a specified time window. - If a client exceeds the limit, the request is throttled (
Status.THROTTLED).
- The
-
Client Disconnection:
- A client disconnects using the
disconnectmethod. - The gateway updates the client's connection state.
- A client disconnects using the
- Interface:
Gateway.java - Implementation:
GatewayImpl.java - Description: Defines the contract for the gateway system, including methods for connecting clients, submitting requests, and disconnecting clients.
- Methods:
connect(String client): Establishes a connection for a client.submit(String client, Object request): Submits a request from a client and returns the status (OK,ERROR, orTHROTTLED).disconnect(String client): Disconnects a client.
- Class:
RateLimiter.java - Description: Implements a token bucket rate-limiting algorithm to control the rate of requests per client.
- Key Components:
TokenBucket: Represents the token bucket for each client.canConsume(String key): Checks if a client can make a request based on available tokens.
- Class:
ClientState.java - Description: Tracks the state of a client connection, including connection status and the last refresh time.
- Key Methods:
isConnectionExpired(): Checks if the client's connection has expired based on the configured timeout.
- Interface:
RequestProcessor.java - Implementation:
RequestProcessorImpl.java - Description: Defines the contract for processing client requests.
- Method:
onRequest(String client, Object request, Status status): Processes a request and logs its status.
- Class:
App.java - Description: A simple application to demonstrate the gateway system. Connects a client, submits requests, and logs the results.
- Java Development Kit (JDK) 8 or higher.
- Maven (for building and testing).
Using Maven:
mvn clean installThe App class demonstrates the functionality of the gateway system. Run it using the following command:
Using Maven:
mvn exec:java -Dexec.mainClass="org.galaxy.App"