Skip to content

Add Caffeine-Based In-Memory Cache Store (Singleton, Auto-Wired Service)#3

Merged
Abhay2133 merged 2 commits intomainfrom
copilot/fix-9b2bb2bf-a6f2-44b8-bfd7-0c45cca9d794
Sep 27, 2025
Merged

Add Caffeine-Based In-Memory Cache Store (Singleton, Auto-Wired Service)#3
Abhay2133 merged 2 commits intomainfrom
copilot/fix-9b2bb2bf-a6f2-44b8-bfd7-0c45cca9d794

Conversation

Copy link
Contributor

Copilot AI commented Sep 27, 2025

This PR introduces a comprehensive Caffeine-based in-memory cache service that provides a simple key-value store interface for the Spring Boot application.

Overview

The new CacheService is implemented as a Spring singleton service that can be auto-wired into any controller, service, or component. It leverages Caffeine's high-performance caching capabilities with sensible defaults for production use.

Key Features

  • Simple Interface: Provides intuitive put(key, value), get(key), and delete(key) methods
  • Spring Integration: Annotated with @Service for automatic dependency injection
  • Sensible Defaults:
    • 10-minute TTL (Time To Live) for automatic expiration
    • Maximum size of 1000 entries with size-based eviction
  • Type Safety: Supports any object type while maintaining proper validation
  • Error Handling: Validates null keys and values with clear exception messages

Usage Example

@RestController
public class MyController {
    
    @Autowired
    private CacheService cacheService;
    
    @GetMapping("/user/{id}")
    public User getUser(@PathVariable String id) {
        // Try cache first
        User cached = (User) cacheService.get("user:" + id);
        if (cached != null) {
            return cached;
        }
        
        // Fetch from database and cache
        User user = userService.findById(id);
        cacheService.put("user:" + id, user);
        return user;
    }
}

Implementation Details

  • Dependency: Added com.github.ben-manes.caffeine:caffeine to the project
  • Location: src/main/java/com/example/hello_spring/services/CacheService.java
  • Configuration: Uses Caffeine's builder pattern with expireAfterWrite(10, MINUTES) and maximumSize(1000)
  • Thread Safety: Caffeine provides thread-safe operations out of the box

Testing

Added comprehensive unit tests (CacheServiceTest.java) covering:

  • Basic cache operations (put, get, delete)
  • Different data types (String, Integer, Boolean, custom objects)
  • Edge cases (null handling, non-existent keys)
  • Cache management (size tracking, clearing)
  • Error conditions and exception handling

Demo Endpoints

For easy testing and demonstration, added two new endpoints:

  • GET /cache/stats - Shows current cache size and status
  • GET /cache/demo - Interactive demo showing cache hit/miss behavior

Verification

All existing tests continue to pass, and the new cache service integrates seamlessly with the existing Spring Boot application. The implementation follows Spring best practices and maintains the application's existing architecture patterns.

Original prompt

This section details on the original issue you should resolve

<issue_title>Add Caffeine-Based In-Memory Cache Store (Singleton, Auto-Wired Service)</issue_title>
<issue_description>We don’t have any cache mechanism in the project right now. I want to introduce a Caffeine-based in-memory cache service that can be used across the Spring Boot application.

The cache should:

  • Be implemented as a Singleton Spring service.
  • Provide a simple key-value store interface with methods like put, get, and delete.
  • Be auto-wired so that it can be injected into any controller, service, or model.
  • Use Caffeine internally to support advanced features like TTL, eviction policies, and size limits.

Acceptance Criteria:

  • Add Caffeine dependency to the project.
  • Create a CacheService class with put(String key, Object value), get(String key), and delete(String key) methods.
  • Ensure the service follows the Singleton design pattern.
  • Annotate it with Spring’s @Service so it can be auto-wired into other components.
  • Configure sensible defaults for TTL (e.g., 10 minutes) and maximum cache size.
  • Add unit tests to verify correct behavior of the cache.

Example usage:

@Autowired
private CacheService cacheService;

cacheService.put("username", "abhay");
String user = cacheService.get("username"); // returns "abhay"
cacheService.delete("username");

</issue_description>

Comments on the Issue (you are @copilot in this section)

Fixes #2

💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.

Co-authored-by: Abhay2133 <63441094+Abhay2133@users.noreply.github.com>
Copilot AI changed the title [WIP] Add Caffeine-Based In-Memory Cache Store (Singleton, Auto-Wired Service) Add Caffeine-Based In-Memory Cache Store (Singleton, Auto-Wired Service) Sep 27, 2025
Copilot AI requested a review from Abhay2133 September 27, 2025 07:01
Copy link
Owner

@Abhay2133 Abhay2133 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@Abhay2133 Abhay2133 marked this pull request as ready for review September 27, 2025 15:11
@Abhay2133 Abhay2133 merged commit 0e26112 into main Sep 27, 2025
6 checks passed
@coderabbitai
Copy link

coderabbitai bot commented Sep 27, 2025

Important

Review skipped

Bot user detected.

To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Please see the documentation for more information.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.


Comment @coderabbitai help to get the list of available commands and usage tips.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add Caffeine-Based In-Memory Cache Store (Singleton, Auto-Wired Service)

2 participants