<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[DigitalYogi]]></title><description><![CDATA[I am Kumar Pallav, I love sharing knowledge on Open Source, Java, Spring , Microservices, Quarkus , Micronaut. ]]></description><link>https://digitalyogi.hashnode.dev</link><image><url>https://cdn.hashnode.com/uploads/logos/5f753b6cb48bd01f31660b33/0d84f646-651d-41e3-be47-004e1130a14a.png</url><title>DigitalYogi</title><link>https://digitalyogi.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Sat, 05 Dec 2026 00:02:46 GMT</lastBuildDate><atom:link href="https://digitalyogi.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[12 System Design Failure Modes Every Backend Engineer Gets Grilled On (with Runnable Java 21 Code)]]></title><description><![CDATA[Almost every backend developer with 2–8 years of experience can draw a load balancer, an app server, Redis, and Postgres on a whiteboard. Where senior…]]></description><link>https://digitalyogi.hashnode.dev/12-system-design-failure-modes-every-backend-engineer-gets-grilled-on-with-runnable-java-21-code</link><guid isPermaLink="true">https://digitalyogi.hashnode.dev/12-system-design-failure-modes-every-backend-engineer-gets-grilled-on-with-runnable-java-21-code</guid><category><![CDATA[System Design]]></category><category><![CDATA[Java]]></category><category><![CDATA[spring-boot]]></category><category><![CDATA[software architecture]]></category><dc:creator><![CDATA[DigitalYogi]]></dc:creator><pubDate>Tue, 24 Nov 2026 13:10:06 GMT</pubDate><content:encoded><![CDATA[<p>Almost every backend developer with 2–8 years of experience can draw a load balancer, an app server, Redis, and Postgres on a whiteboard.</p>
<p>Where senior design discussions actually fall apart is minute 30 — when someone changes one constraint and asks what breaks first.</p>
<p>We compressed the 12 core backend architecture decisions — along with three zero-dependency runnable Java 21 reference implementations (Consistent Hash Ring, Thread-Safe Token Bucket, and Sliding-Window Circuit Breaker) — into an open-source repo of single-page reference sheets:</p>
<p>👉 <strong>GitHub Repo (12 Printable A4 Sheets + Runnable Java 21 Code):</strong> <a href="https://github.com/CODINGSAINT/system-design-templates-java">https://github.com/CODINGSAINT/system-design-templates-java</a></p>
<p>Here are the 3 production failure modes that trip up candidates and engineering teams most often:</p>
<h2>1. Adding Redis — and Still Melting Postgres (Cache Stampede)</h2>
<p>Saying "put Redis in front of the database" solves the happy path. Under a 50,000 RPS spike, a single hot key expiring sends thousands of concurrent misses straight into Postgres within 200ms.</p>
<p><strong>Three fixes to defend clearly:</strong></p>
<ul>
<li><strong>Single-flight request coalescing:</strong> Let one thread/worker rebuild the key while concurrent callers wait or read a slightly stale value.</li>
<li><strong>Jittered TTLs:</strong> Add random +/- 10–15% jitter to expiry times so keys created during a batch warm-up don't expire together.</li>
<li><strong>Delete on write, don't overwrite:</strong> In cache-aside writes, update the DB then <code>DEL</code> the cache key to avoid race conditions where an older write overwrites a newer one in Redis.</li>
</ul>
<h2>2. Three Instant Retries = Self-Inflicted DDoS</h2>
<p>When a downstream payment or inventory service slows down from 40ms to 8 seconds, configuring 3 immediate retries multiplies incoming load by 4x at the exact moment the dependency is struggling — exhausting your thread pool and cascading into login/checkout outages.</p>
<p><strong>Production baseline:</strong></p>
<ul>
<li>Pair strict per-call <strong>timeouts</strong> with <strong>bounded retries + exponential backoff + full jitter</strong>.</li>
<li>Put a <strong>Circuit Breaker</strong> (Closed → Open → Half-Open) in front so failing calls fail fast instead of piling up sockets.</li>
<li>You can run and inspect our dependency-free Java 21 sliding-window implementation directly with <code>java java/CircuitBreaker.java</code> from the repo.</li>
</ul>
<h2>3. Picking Kafka by Default for Simple Work Queues</h2>
<p>Kafka shines when you need replayable event logs, multiple independent consumer groups, or high-throughput stream processing. If you just need task distribution with complex per-message routing, instant deletion on ack, and per-item retries, <strong>RabbitMQ</strong> or zero-ops <strong>Amazon SQS</strong> saves months of operational complexity.</p>
<hr />
<h2>All 12 One-Page Sheets Included in the Repo</h2>
<ol>
<li>Design any system in 6 steps (+ a blank <a href="https://github.com/CODINGSAINT/system-design-templates-java/blob/main/templates/45-min-hld-interview-template.md">45-Minute HLD Interview Template</a>)</li>
<li>Numbers for capacity estimates</li>
<li>Caching with Redis</li>
<li>Choosing a database (Postgres vs MongoDB vs Cassandra vs Redis)</li>
<li>Replication &amp; consistency</li>
<li>Sharding &amp; hot keys</li>
<li>Consistent hashing (<code>java/ConsistentHashRing.java</code>)</li>
<li>Message queues: Kafka vs RabbitMQ vs SQS</li>
<li>Rate limiting (<code>java/TokenBucket.java</code>)</li>
<li>Timeouts, retries &amp; circuit breakers (<code>java/CircuitBreaker.java</code>)</li>
<li>Real-time updates (Polling vs SSE vs WebSockets vs Webhooks)</li>
<li>REST vs gRPC vs GraphQL</li>
</ol>
<p>If you want to practice writing out full design answers and testing them against worked senior solutions (HLD, LLD, Visual DSA, and Spring AI), there are free unlocked problems at <a href="https://kb.digitalyogi.tech/?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=system_design_templates">kb.digitalyogi.tech</a>.</p>
<p>What is the one system design failure mode you see teams miss most often in production or interviews? Drop it in the comments.</p>
]]></content:encoded></item><item><title><![CDATA[Spring AI Tool Calling: From Chatbot to AI Agent with @Tool]]></title><description><![CDATA[Your AI is smart. It knows an enormous amount. But it's frozen. It doesn't know what time it is right now. It doesn't know what's on your calendar. It…]]></description><link>https://digitalyogi.hashnode.dev/spring-ai-tool-calling-from-chatbot-to-ai-agent-with-tool</link><guid isPermaLink="true">https://digitalyogi.hashnode.dev/spring-ai-tool-calling-from-chatbot-to-ai-agent-with-tool</guid><category><![CDATA[ai agents]]></category><category><![CDATA[Java]]></category><category><![CDATA[llm]]></category><category><![CDATA[spring ai]]></category><category><![CDATA[spring-boot]]></category><category><![CDATA[tool calling]]></category><dc:creator><![CDATA[DigitalYogi]]></dc:creator><pubDate>Tue, 12 May 2026 03:53:18 GMT</pubDate><content:encoded><![CDATA[<h1>Spring AI Tool Calling: From Chatbot to AI Agent with @Tool</h1>
<p>Your AI is smart. It knows an enormous amount. But it's frozen.</p>
<p>It doesn't know what time it is right now. It doesn't know what's on your calendar. It can't check the weather, place an order, or set an alarm. All it can do is generate text based on what it learned during training.</p>
<p>For demos, that's fine. For production applications, it's a fundamental limitation.</p>
<p><strong>Tool Calling</strong> is how you fix it.</p>
<hr />
<h2>The Core Idea</h2>
<p>Tool Calling (also called Function Calling) is a mechanism that lets the AI model request execution of real Java methods in your application. The model doesn't run the code itself — it asks your app to run it, then synthesizes the result into a natural language response.</p>
<p>Here's the three-step loop:</p>
<ol>
<li>You send the user's message to the model, along with <em>definitions</em> of your tools — name, description, parameter schema. The model never sees your code.</li>
<li>The model decides it needs data. It returns a <code>tool_call</code> response — a structured JSON object saying "call <code>getCurrentDateTime</code> with no parameters."</li>
<li>Your application executes the Java method. Your code. Your security context. You send the result back to the model.</li>
<li>The model synthesizes the tool result into a final answer.</li>
</ol>
<p>The model never executes anything directly. This is by design. Your application is always the gate.</p>
<hr />
<h2>Two Patterns</h2>
<p>Before writing code, it helps to recognize that there are two fundamentally different kinds of tools:</p>
<p><strong>Information Retrieval</strong> — tools that read data and return it. Current time, weather, database records, calendar events. No side effects. Safe to retry.</p>
<p><strong>Taking Action</strong> — tools that change state. Set an alarm, send an email, write to a database, place an order. Side effects. Require careful design.</p>
<p>Both are valid. But you should know which one you're building.</p>
<hr />
<h2>The @Tool Annotation</h2>
<p>Spring AI's simplest tool definition approach is the <code>@Tool</code> annotation. You create a plain Java class — no interface to implement, no special base class — and annotate any method you want to expose.</p>
<pre><code class="language-java">class ShipmentTools {

    @Tool(description = "Track a package and return its current delivery status and estimated arrival. " +
          "Use this whenever the user asks where their order is, when it arrives, or about shipping updates.")
    String trackPackage(
        @ToolParam(description = "The order tracking number provided by the carrier") String trackingNumber) {
        return shippingService.getStatus(trackingNumber);
    }
}
</code></pre>
<p>Then attach it to a ChatClient call:</p>
<pre><code class="language-java">String response = ChatClient.create(chatModel)
    .prompt("Where is my order TRK-88291?")
    .tools(new ShipmentTools())
    .call()
    .content();
</code></pre>
<p>That's it. Spring AI reads your method signature and automatically generates the JSON schema the model needs. The model receives the tool definition, decides it's relevant, and calls <code>trackPackage</code>. Your Java method runs. The model gets the result.</p>
<h3>The description field is the most important field</h3>
<p>The model uses <code>description</code> to decide <em>when</em> to call your tool. If your description is vague, the model won't know when to use it — or worse, it'll use it at the wrong time.</p>
<p>Write descriptions like you're documenting an API endpoint:</p>
<pre><code class="language-java">// Bad
@Tool(description = "gets order info")

// Good
@Tool(description = "Track a package and return its current delivery status and estimated arrival. " +
      "Use this whenever the user asks where their order is, when it arrives, or about shipping updates.")
</code></pre>
<p>Be specific about what the tool returns, what format, and when it should be called.</p>
<hr />
<h2>Taking Action with @ToolParam</h2>
<p>For tools that take parameters, use <code>@ToolParam</code> to give the model descriptions and format hints for each parameter:</p>
<pre><code class="language-java">@Tool(description = "Add a product to the user's shopping cart")
CartConfirmation addToCart(
    @ToolParam(description = "The product SKU from the catalog — alphanumeric, e.g. PRD-1042") String sku,
    @ToolParam(description = "Number of units to add — must be a positive integer") int quantity) {

    return cartService.addItem(sku, quantity);
}
</code></pre>
<p>The <code>@ToolParam</code> descriptions shape how the model formats its tool call. Here, you're telling the model the expected SKU format and that quantity must be positive. It will comply.</p>
<p>You can also use <code>void</code> return types for fire-and-forget actions:</p>
<pre><code class="language-java">@Tool(description = "Save a product to the user's wishlist for later")
void saveForLater(
    @ToolParam(description = "The product SKU to save") String sku) {

    wishlistService.add(sku);
}
</code></pre>
<p>Tool calling works with side-effect-only methods — no return value required.</p>
<hr />
<h2>Full @Tool Reference</h2>
<table>
<thead>
<tr>
<th>Field</th>
<th>Default</th>
<th>Purpose</th>
</tr>
</thead>
<tbody><tr>
<td><code>name</code></td>
<td>method name</td>
<td>Tool identifier sent to the model. Override if method name is unclear.</td>
</tr>
<tr>
<td><code>description</code></td>
<td>empty</td>
<td>How the model decides <em>when</em> to call this tool. Required in practice.</td>
</tr>
<tr>
<td><code>returnDirect</code></td>
<td><code>false</code></td>
<td>When <code>true</code>, result skips model synthesis and goes straight to the user.</td>
</tr>
<tr>
<td><code>resultConverter</code></td>
<td>Jackson</td>
<td>Custom serializer for the return value. Implement <code>ToolCallResultConverter</code>.</td>
</tr>
</tbody></table>
<p><code>returnDirect = true</code> is useful when you want raw data returned directly — no prose wrapping. Good for data lookup tools where formatting should be handled in the UI, not by the model.</p>
<hr />
<h2>Three Ways to Wire Tools</h2>
<h3>Per-call (instance)</h3>
<pre><code class="language-java">chatClient.prompt("Is the blue hoodie TRK-8821 in stock?")
    .tools(new ShipmentTools())
    .call()
    .content();
</code></pre>
<p>Tools are available for that one call only. Good for request-scoped tools.</p>
<h3>Default via builder</h3>
<pre><code class="language-java">ChatClient chatClient = ChatClient.builder(chatModel)
    .defaultTools(new ShipmentTools())
    .build();
</code></pre>
<p>All calls through this ChatClient automatically get these tools. Good for global utilities — tools your assistant always needs, like product lookup or cart access.</p>
<h3>Spring Bean (functional style)</h3>
<pre><code class="language-java">@Bean
@Description("Look up product details and inventory by SKU")
Function&lt;ProductRequest, ProductResponse&gt; productLookup() {
    return productService;
}

// Reference by name
chatClient.prompt("Is the Acme Pro Backpack in stock?")
    .toolNames("productLookup")
    .call()
    .content();
</code></pre>
<p>The functional style is useful when you already have service beans. Spring AI wraps your <code>Function</code> and handles schema generation.</p>
<p>My recommendation: use <code>@Tool</code> for most things. Use the functional style when you're integrating existing service beans.</p>
<hr />
<h2>The Security Model</h2>
<p>This is the most underappreciated aspect of tool calling.</p>
<p>The model never runs your code. It emits a <code>tool_call</code> JSON object. Your application receives it, decides whether to honor it, executes the Java method if appropriate, and returns the result.</p>
<p>This means:</p>
<ul>
<li>Your Spring Security context is fully intact</li>
<li>Your <code>@PreAuthorize</code>, role checks, and tenant isolation all apply</li>
<li>You can add an approval step before executing any tool</li>
</ul>
<p>If you want explicit control over the execution loop, set <code>internalToolExecutionEnabled(false)</code>:</p>
<pre><code class="language-java">ChatOptions options = ToolCallingChatOptions.builder()
    .toolCallbacks(toolCallbacks)
    .internalToolExecutionEnabled(false)
    .build();

ChatResponse response = chatModel.call(new Prompt(userMessage, options));

while (response.hasToolCalls()) {
    ToolExecutionResult result = toolCallingManager.executeToolCalls(prompt, response);
    prompt = new Prompt(result.conversationHistory(), options);
    response = chatModel.call(prompt);
}
</code></pre>
<p>This is the pattern for applications that need a human approval step, rate limiting on actions, or audit logging before any tool executes.</p>
<hr />
<h2>ToolContext: Secure Request-Scoped Data</h2>
<p>Sometimes you need to pass data into a tool that shouldn't be in the prompt — authentication tokens, user IDs, session data.</p>
<p>Use <code>ToolContext</code>:</p>
<pre><code class="language-java">@Tool(description = "Get the logged-in user's recent orders. Use when the user asks about their purchase history, past orders, or order status.")
List&lt;Order&gt; getRecentOrders(ToolContext toolContext) {
    String accountId = (String) toolContext.getContext().get("accountId");
    return orderRepository.findRecent(accountId, 10);
}
</code></pre>
<p>The <code>ToolContext</code> parameter is injected by Spring AI. It never appears in the JSON schema. The model never sees it — so the user's account ID doesn't accidentally leak into the conversation.</p>
<p>Pass context at call time:</p>
<pre><code class="language-java">chatClient.prompt("What did I order last week?")
    .tools(new OrderTools())
    .toolContext(Map.of("accountId", currentUser.getAccountId()))
    .call()
    .content();
</code></pre>
<p>This is the right pattern for authenticated APIs, multi-tenant apps, and any situation where request-scoped identity needs to flow into tool execution without leaking into the prompt.</p>
<hr />
<h2>What Tool Methods Can't Do</h2>
<p>Method-based tools (<code>@Tool</code>) don't support:</p>
<ul>
<li><code>Optional</code> return types</li>
<li><code>CompletableFuture</code> or <code>Future</code></li>
<li>Reactive types: <code>Mono</code>, <code>Flux</code>, <code>Flow</code></li>
</ul>
<p>Keep your tool method signatures simple: String, primitives, records, and POJOs. If you need reactive patterns in your tools, use the functional (<code>FunctionToolCallback</code>) approach instead.</p>
<hr />
<h2>Common Mistakes</h2>
<p><strong>Vague descriptions.</strong> If <code>description = "gets data"</code>, the model won't know when to call your tool. Write it specifically.</p>
<p><strong>Too many tools at once.</strong> Exposing 20+ tools in a single call gives the model too many options. Confusion leads to wrong tool selection or no tool call at all. Scope your tools to the task — 3 to 5 per request is a reasonable upper bound.</p>
<p><strong>Assuming the model is right.</strong> The model chooses tools based on descriptions. If the behavior seems wrong, the description is usually the problem — not the model.</p>
<p><strong>Forgetting the execution loop.</strong> If <code>internalToolExecutionEnabled = false</code>, you're driving the loop. Forgetting means the model's <code>tool_call</code> response is returned raw to your caller.</p>
<hr />
<h2>The Shift</h2>
<p>Before tool calling, your Spring AI application is a sophisticated text engine. It knows what it was trained on — and nothing else.</p>
<p>After tool calling, your application can interact with the world. Current data, live APIs, real databases, real actions.</p>
<p>That's the difference between a chatbot and an agent.</p>
<p>The next lecture goes to the other side of the conversation: Structured Output. Instead of the model returning raw text, you'll map AI responses directly to Java objects — type-safe, validated, production-ready.</p>
<hr />
<h2>Quick Reference</h2>
<pre><code class="language-java">// Minimal retrieval tool
class ShipmentTools {
    @Tool(description = "Track a package — use when user asks about delivery status or estimated arrival")
    String trackPackage(@ToolParam(description = "Carrier tracking number, e.g. TRK-88291") String trackingNumber) {
        return shippingService.getStatus(trackingNumber);
    }
}

// Attach per-call
ChatClient.create(chatModel)
    .prompt("Where is my order TRK-88291?")
    .tools(new ShipmentTools())
    .call()
    .content();

// With ToolContext for authenticated user data
ChatClient.create(chatModel)
    .prompt("What did I order last week?")
    .tools(new OrderTools())
    .toolContext(Map.of("accountId", currentUser.getAccountId()))
    .call()
    .content();
</code></pre>
<hr />
<p><em>Part of the <a href="#">Spring AI Complete Course</a> — a production-focused series for intermediate Spring Boot developers.</em></p>
<p><em>Previous: <a href="#">Advisors API — Middleware for LLM Calls</a> | Next: <a href="#">Structured Output — AI Meets POJOs</a></em></p>
]]></content:encoded></item><item><title><![CDATA[Spring AI Advisors API in Java: Build Middleware for AI Interactions]]></title><description><![CDATA[Series: Spring AI Complete Course — Lecture 4 of 12Reading Time: 8 minutesLevel: Intermediate Most developers stop at ChatClient. That is enough for demos…]]></description><link>https://digitalyogi.hashnode.dev/spring-ai-advisors-api-in-java-build-middleware-for-ai-interactions</link><guid isPermaLink="true">https://digitalyogi.hashnode.dev/spring-ai-advisors-api-in-java-build-middleware-for-ai-interactions</guid><category><![CDATA[Interceptor Pattern]]></category><category><![CDATA[advisors]]></category><category><![CDATA[AI]]></category><category><![CDATA[chatgpt]]></category><category><![CDATA[claude]]></category><category><![CDATA[cross-cutting concerns]]></category><category><![CDATA[Java]]></category><category><![CDATA[llm]]></category><category><![CDATA[Middleware]]></category><category><![CDATA[RAG ]]></category><category><![CDATA[spring ai]]></category><category><![CDATA[spring-boot]]></category><category><![CDATA[vector database]]></category><dc:creator><![CDATA[DigitalYogi]]></dc:creator><pubDate>Wed, 06 May 2026 07:33:39 GMT</pubDate><content:encoded><![CDATA[<h1>Spring AI Advisors API Explained</h1>
<p><strong>Series:</strong> Spring AI Complete Course — Lecture 4 of 12<br /><strong>Reading Time:</strong> 8 minutes<br /><strong>Level:</strong> Intermediate</p>
<hr />
<p>Most developers stop at <code>ChatClient</code>.</p>
<p>That is enough for demos. It is not enough for production.</p>
<p>The moment an AI feature becomes real, you need behavior around the model call. You need logging. You need request filtering. You need latency tracking. You may need to attach tenant context, inject retrieval metadata, sanitize prompts, or block unsafe content before it ever reaches the model.</p>
<p>If you place all of that inside controllers and services, the codebase turns into a junk drawer. Business logic gets mixed with prompt plumbing. The same pre-processing and post-processing logic gets duplicated across every AI flow.</p>
<p>This is exactly where the <strong>Spring AI Advisors API</strong> comes in.</p>
<p>Advisors are Spring AI's middleware layer for LLM calls. If you already understand servlet filters, Spring MVC interceptors, or WebFlux filters, you already understand the core idea. Advisors let you intercept and shape requests before they hit the model, and inspect or transform responses before they return to your application.</p>
<p>In this article, we will break down:</p>
<ul>
<li><code>CallAdvisor</code> vs <code>StreamAdvisor</code></li>
<li><code>ChatClientRequest</code> and <code>ChatClientResponse</code></li>
<li>Advisor ordering with <code>getOrder()</code></li>
<li>Building a custom logging advisor</li>
<li>Building a content filtering advisor</li>
<li>Composing advisors with <code>ChatClient</code> — globally and per-request</li>
<li>Common mistakes to avoid</li>
</ul>
<p>Let's get into it.</p>
<hr />
<h2>Why Advisors Exist</h2>
<p>A simple Spring AI application often starts like this:</p>
<pre><code class="language-java">@RestController
@RequiredArgsConstructor
public class ChatController {

    private final ChatClient chatClient;

    @GetMapping("/ask")
    public String ask(@RequestParam String message) {
        return chatClient.prompt()
                .user(message)
                .call()
                .content();
    }
}
</code></pre>
<p>This works beautifully in the early stage.</p>
<p>Then reality arrives.</p>
<p>Now you need to answer questions like:</p>
<ul>
<li>How do I log prompts and responses for debugging?</li>
<li>How do I block prohibited content before it reaches the model?</li>
<li>How do I inject metadata for observability or multi-tenant routing?</li>
<li>How do I attach retrieval context for RAG?</li>
<li>How do I measure model latency without scattering timers everywhere?</li>
</ul>
<p>You <em>could</em> do all of this manually in service methods.</p>
<p>You shouldn't.</p>
<p>The better pattern is to centralize these cross-cutting concerns in advisors so your application code stays focused on business logic.</p>
<hr />
<h2>Core Types in the Advisors API</h2>
<p>Spring AI defines different advisor types for synchronous and streaming scenarios.</p>
<table>
<thead>
<tr>
<th>Interface</th>
<th>Use Case</th>
</tr>
</thead>
<tbody><tr>
<td><code>CallAdvisor</code></td>
<td>Blocking (synchronous) calls</td>
</tr>
<tr>
<td><code>StreamAdvisor</code></td>
<td>Streaming (reactive) calls</td>
</tr>
</tbody></table>
<h3><code>CallAdvisor</code></h3>
<p>Use this for normal, non-streaming interactions.</p>
<p>A <code>CallAdvisor</code> surrounds a standard <code>ChatClient</code> call, letting you inspect or modify the request, call the next step in the chain, then inspect or modify the response on the way back.</p>
<h3><code>StreamAdvisor</code></h3>
<p>Use this for streaming scenarios.</p>
<p>When your UI is receiving tokens progressively, the execution model changes. <code>StreamAdvisor</code> is designed for that case, but the mental model stays the same: intercept, enrich, observe, or block the flow.</p>
<h3><code>ChatClientRequest</code></h3>
<p>This object represents the request moving through the advisor chain. It carries:</p>
<ul>
<li>The prompt (user message, system instructions)</li>
<li>Model options (temperature, max tokens, etc.)</li>
<li>Metadata and shared advisor context</li>
</ul>
<p>Advisors can inspect it, enrich it, or pass it along unchanged.</p>
<h3><code>ChatClientResponse</code></h3>
<p>This object represents the final model response as it flows back through the advisor chain. It carries:</p>
<ul>
<li>The generated response content</li>
<li>Token usage statistics</li>
<li>Response metadata and shared advisor context</li>
</ul>
<p>The shared context is important. It lets one advisor place data into the chain and another advisor read it later — across the full lifecycle of a single call.</p>
<hr />
<h2>Think of Advisors as a Stack</h2>
<p>This is the most important mental model.</p>
<p>When Spring AI invokes a <code>ChatClient</code>, it builds an advisor chain. Each advisor gets the request in sequence, and each one has the option to:</p>
<ul>
<li>inspect the request</li>
<li>mutate the request</li>
<li>add context</li>
<li>call the next advisor</li>
<li>short-circuit the chain and return a response directly</li>
<li>inspect or mutate the response</li>
<li>throw an exception if processing should fail</li>
</ul>
<p>Eventually, the final framework-provided advisor sends the request to the LLM.</p>
<p>Then the response comes back through the same chain in reverse order.</p>
<pre><code>Request Path:   Advisor A (order 100) → Advisor B (order 200) → Model
                                                              ↓
Response Path:  Advisor A (order 100) ← Advisor B (order 200) ← Response
</code></pre>
<p>That means the first advisor to process the request becomes the last advisor to process the response.</p>
<p>This stack-like behavior is the key to understanding advisor ordering.</p>
<hr />
<h2>Advisor Ordering with <code>getOrder()</code></h2>
<p>Spring AI uses the standard Spring ordering model.</p>
<p>Each advisor exposes <code>getOrder()</code>, and lower values execute first.</p>
<p>But here's the catch: lower values execute first on the request path and last on the response path.</p>
<p>That means:</p>
<ul>
<li><strong>Lower order value</strong> → earlier for request, later for response</li>
<li><strong>Higher order value</strong> → later for request, earlier for response</li>
</ul>
<p>This is why many developers get confused the first time they build more than one advisor.</p>
<h3>Practical interpretation</h3>
<p>If your advisor is doing <strong>request validation</strong> or <strong>security checks</strong>, give it high precedence so it sees the request early.</p>
<p>If your advisor is doing <strong>response formatting</strong> or <strong>final output shaping</strong>, you might want it to run later on the request side so it gets earlier access to the response side.</p>
<p>Also note:</p>
<ul>
<li><code>Ordered.HIGHEST_PRECEDENCE</code> means the smallest possible order value</li>
<li><code>Ordered.LOWEST_PRECEDENCE</code> means the largest possible order value</li>
<li>if two advisors share the same order value, execution order is not guaranteed</li>
</ul>
<p>In production systems, do not leave this vague. Make ordering explicit.</p>
<hr />
<h2>Build a Custom Logging Advisor</h2>
<p>Let's create a simple advisor that logs the incoming prompt and the outgoing model response.</p>
<pre><code class="language-java">package com.example.ai.advisors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.client.ChatClientResponse;
import org.springframework.ai.chat.client.ChatClientRequest;
import org.springframework.ai.chat.client.advisor.api.CallAdvisor;
import org.springframework.ai.chat.client.advisor.api.CallAdvisorChain;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

@Component
public class LoggingAdvisor implements CallAdvisor {

    private static final Logger log = LoggerFactory.getLogger(LoggingAdvisor.class);

    @Override
    public String getName() {
        return "logging-advisor";
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 10;
    }

    @Override
    public ChatClientResponse adviseCall(ChatClientRequest request, CallAdvisorChain chain) {
        log.info("Prompt user text: {}", request.prompt().getUserMessage().getText());

        ChatClientResponse response = chain.nextCall(request);

        log.info("Model response: {}", response.chatResponse().getResult().getOutput().getText());
        return response;
    }
}
</code></pre>
<h3>What this advisor is doing</h3>
<ol>
<li>It reads the user prompt from <code>ChatClientRequest</code></li>
<li>It forwards the request to the next element in the chain using <code>chain.nextCall(request)</code></li>
<li>It receives the <code>ChatClientResponse</code></li>
<li>It logs the final output text before returning the response</li>
</ol>
<p>This is the canonical advisor structure. It looks very similar to a servlet filter or a Spring AOP around advice because conceptually, that is exactly what it is.</p>
<hr />
<h2>Build a Content Filtering Advisor</h2>
<p>Now let's create something more interesting: a policy guardrail.</p>
<p>This advisor checks the user prompt for prohibited phrases and blocks execution if the content is unsafe.</p>
<pre><code class="language-java">package com.example.ai.advisors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.client.ChatClientResponse;
import org.springframework.ai.chat.client.ChatClientRequest;
import org.springframework.ai.chat.client.advisor.api.CallAdvisor;
import org.springframework.ai.chat.client.advisor.api.CallAdvisorChain;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
public class ContentFilterAdvisor implements CallAdvisor {

    private static final Logger log = LoggerFactory.getLogger(ContentFilterAdvisor.class);

    private static final Set&lt;String&gt; BLOCKED_TERMS = Set.of(
            "password dump",
            "credit card scrape"
    );

    @Override
    public String getName() {
        return "content-filter-advisor";
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }

    @Override
    public ChatClientResponse adviseCall(ChatClientRequest request, CallAdvisorChain chain) {
        String userText = request.prompt().getUserMessage().getText().toLowerCase();

        boolean blocked = BLOCKED_TERMS.stream().anyMatch(userText::contains);
        if (blocked) {
            log.warn("Blocked request containing prohibited content");
            throw new IllegalArgumentException("Prompt blocked by content policy");
        }

        return chain.nextCall(request);
    }
}
</code></pre>
<h3>Why this matters</h3>
<p>This keeps policy enforcement out of your controller and service layer.</p>
<p>More importantly, it gives you a reusable place to apply consistent rules across all AI endpoints.</p>
<p>Today it's a simple keyword blocklist. Tomorrow it could be:</p>
<ul>
<li>PII detection</li>
<li>regex-based sanitization</li>
<li>tenant-specific policy controls</li>
<li>prompt risk scoring</li>
<li>role-based access enforcement</li>
</ul>
<p>That is the real value of advisors. They create clean extension points for production concerns.</p>
<hr />
<h2>Composing Advisors with <code>ChatClient</code></h2>
<h3>Global wiring via the builder</h3>
<p>Once the advisors exist, attach them to your <code>ChatClient</code> so every call gets the treatment automatically.</p>
<pre><code class="language-java">package com.example.ai.config;

import com.example.ai.advisors.ContentFilterAdvisor;
import com.example.ai.advisors.LoggingAdvisor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ChatConfig {

    @Bean
    public ChatClient chatClient(ChatModel chatModel,
                                 LoggingAdvisor loggingAdvisor,
                                 ContentFilterAdvisor contentFilterAdvisor) {
        return ChatClient.builder(chatModel)
                .defaultAdvisors(contentFilterAdvisor, loggingAdvisor)
                .build();
    }
}
</code></pre>
<p>Because <code>ContentFilterAdvisor</code> has <code>HIGHEST_PRECEDENCE</code>, it runs first on the request path. The chain works like this:</p>
<ol>
<li>content filter examines the request</li>
<li>logging advisor logs the prompt</li>
<li>framework sends the request to the model</li>
<li>response comes back</li>
<li>logging advisor logs the response</li>
<li>filter advisor sees the final unwind</li>
</ol>
<p>This is why ordering is not just a number. It defines the behavior of your full middleware pipeline.</p>
<h3>Per-request wiring</h3>
<p>You can also attach advisors to individual calls when you need selective behavior:</p>
<pre><code class="language-java">@Service
public class AiService {

    private final ChatClient chatClient;
    private final LoggingAdvisor loggingAdvisor;
    private final ContentFilterAdvisor filterAdvisor;

    public AiService(ChatClient chatClient,
                     LoggingAdvisor loggingAdvisor,
                     ContentFilterAdvisor filterAdvisor) {
        this.chatClient = chatClient;
        this.loggingAdvisor = loggingAdvisor;
        this.filterAdvisor = filterAdvisor;
    }

    public String chatWithGuardrails(String userMessage) {
        return chatClient.prompt()
                .user(userMessage)
                .advisors(loggingAdvisor, filterAdvisor)
                .call()
                .content();
    }
}
</code></pre>
<hr />
<h2>When to Use <code>StreamAdvisor</code></h2>
<p>If you are using synchronous calls with <code>.call()</code>, <code>CallAdvisor</code> is the right abstraction.</p>
<p>If you are returning streamed responses with <code>.stream()</code>, use <code>StreamAdvisor</code>. The pattern is nearly identical but you work with <code>Flux</code> streams.</p>
<pre><code class="language-java">package com.example.ai.advisors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.client.ChatClientResponse;
import org.springframework.ai.chat.client.ChatClientRequest;
import org.springframework.ai.chat.client.advisor.api.StreamAdvisor;
import org.springframework.ai.chat.client.advisor.api.StreamAdvisorChain;
import org.springframework.stereotype.Component;

import reactor.core.publisher.Flux;

@Component
public class StreamingLoggingAdvisor implements StreamAdvisor {

    private static final Logger log = LoggerFactory.getLogger(StreamingLoggingAdvisor.class);

    @Override
    public Flux&lt;ChatClientResponse&gt; adviseStream(ChatClientRequest request, StreamAdvisorChain chain) {
        log.info("Streaming prompt: {}", request.prompt().getUserMessage().getText());

        return chain.nextStream(request)
                .doOnNext(response -&gt; log.debug("Stream chunk received"));
    }

    @Override
    public int getOrder() {
        return 100;
    }

    @Override
    public String getName() {
        return "streaming-logging-advisor";
    }
}
</code></pre>
<p>Streaming advisors are especially useful in scenarios like:</p>
<ul>
<li>live chat interfaces</li>
<li>SSE endpoints</li>
<li>token-by-token observability</li>
<li>real-time content moderation</li>
<li>progressive UI rendering</li>
</ul>
<hr />
<h2>Real Production Use Cases for Advisors</h2>
<p>Once you understand the pattern, a lot of Spring AI features make more sense.</p>
<p>Advisors are the right place for:</p>
<ul>
<li><strong>Prompt logging</strong> for debugging and traceability</li>
<li><strong>Guardrails</strong> for content filtering and safety policies</li>
<li><strong>RAG context injection</strong> before the model call</li>
<li><strong>Caching</strong> — check a cache in your advisor, return early if the result exists</li>
<li><strong>Rate limiting</strong> — throttle requests based on user tiers or global limits</li>
<li><strong>Observability hooks</strong> for metrics and latency tracking</li>
<li><strong>Tenant metadata propagation</strong> in multi-tenant apps</li>
<li><strong>Response post-processing</strong> for cleanup or formatting</li>
</ul>
<p>This is why I describe Advisors as middleware for AI. They sit around the model call and handle the non-business concerns that every serious AI application eventually needs.</p>
<hr />
<h2>Common Mistakes to Avoid</h2>
<h3>1. Putting advisor logic in controllers</h3>
<p>If your controllers are doing policy checks, prompt shaping, and response logging, the design is already drifting.</p>
<h3>2. Ignoring order semantics</h3>
<p>If you have multiple advisors and no explicit ordering strategy, bugs will appear in weird places. Make ordering explicit — always.</p>
<h3>3. Using one advisor for unrelated concerns</h3>
<p>Keep advisors focused. Logging, policy enforcement, retrieval context, and response shaping should usually be separate units.</p>
<h3>4. Forgetting streaming support</h3>
<p>If your app supports both standard and streaming interactions, make sure you are using the correct advisor type for each path.</p>
<hr />
<h2>Key Takeaways</h2>
<ul>
<li><code>CallAdvisor</code> is for normal request-response model calls; <code>StreamAdvisor</code> is for streaming</li>
<li><code>ChatClientRequest</code> and <code>ChatClientResponse</code> carry data — and shared context — through the chain</li>
<li>Advisors can inspect, enrich, mutate, block, or observe the call</li>
<li><code>getOrder()</code> determines execution order, but the response path unwinds in reverse</li>
<li>Attach advisors globally via the <code>ChatClient</code> builder or selectively per request</li>
<li>Custom advisors give you a clean way to add logging, filtering, RAG, observability, and guardrails without polluting your business logic</li>
</ul>
<p>If <code>ChatClient</code> is how you <em>talk</em> to the model, Advisors are how you <em>control the conversation pipeline</em>.</p>
<p>That distinction is what takes you from toy AI integrations to production-ready AI systems.</p>
<hr />
<h2>Resources</h2>
<ul>
<li>Spring AI Advisors API Reference: <a href="https://docs.spring.io/spring-ai/reference/api/advisors.html">https://docs.spring.io/spring-ai/reference/api/advisors.html</a></li>
<li>Spring AI ChatClient Reference: <a href="https://docs.spring.io/spring-ai/reference/api/chatclient.html">https://docs.spring.io/spring-ai/reference/api/chatclient.html</a></li>
<li>Spring AI Project Docs: <a href="https://docs.spring.io/spring-ai/reference/">https://docs.spring.io/spring-ai/reference/</a></li>
</ul>
<hr />
<h2>Final Thought</h2>
<p>A lot of AI tutorials focus on prompting.</p>
<p>Very few focus on architecture.</p>
<p>But production systems are not defined by how cleverly you ask the model a question. They are defined by how cleanly you manage everything around that question.</p>
<p>That is exactly why the Advisors API matters.</p>
<p>If you're building serious Spring AI applications, this is one of the features worth mastering early.</p>
<p>In the next lecture, we move into <strong>Tool Calling</strong>, where the model stops being just a text engine and starts invoking real Java methods.</p>
<p>That is where the fun begins.</p>
]]></content:encoded></item><item><title><![CDATA[Working with Multiple AI Models in Spring AI — @Qualifier, mutate(), and Model Routing]]></title><description><![CDATA[Spring AI Complete Course — Lecture 3 of 12Previous: Lecture 2 — ChatClient API | Next: Lecture 4 — Advisors API In production AI applications, you rarely…]]></description><link>https://digitalyogi.hashnode.dev/working-with-multiple-ai-models-in-spring-ai-qualifier-mutate-and-model-routing</link><guid isPermaLink="true">https://digitalyogi.hashnode.dev/working-with-multiple-ai-models-in-spring-ai-qualifier-mutate-and-model-routing</guid><category><![CDATA[AI]]></category><category><![CDATA[Java]]></category><category><![CDATA[multi-model]]></category><category><![CDATA[spring ai]]></category><category><![CDATA[spring-boot]]></category><dc:creator><![CDATA[DigitalYogi]]></dc:creator><pubDate>Mon, 27 Apr 2026 03:59:25 GMT</pubDate><content:encoded><![CDATA[<h1>Working with Multiple AI Models in Spring AI</h1>
<blockquote>
<p><strong>Spring AI Complete Course — Lecture 3 of 12</strong><br />Previous: <a href="#">Lecture 2 — ChatClient API</a> | Next: <a href="#">Lecture 4 — Advisors API</a></p>
</blockquote>
<p>In production AI applications, you rarely use just one model. GPT-4o handles creative generation, Claude excels at reasoning, and Groq delivers sub-second inference with open-source models. Spring AI makes it straightforward to wire all of them into a single Spring Boot application using patterns you already know.</p>
<p>This article covers the <strong>@Qualifier pattern</strong> for multi-model configuration, the <strong>mutate() pattern</strong> for runtime flexibility, <strong>OpenAI-compatible endpoints</strong> for providers like Groq, and a <strong>model router</strong> strategy for production systems.</p>
<hr />
<h2>The Problem: Bean Conflicts with Multiple Starters</h2>
<p>When you add a single Spring AI starter — say <code>spring-ai-openai-spring-boot-starter</code> — Spring Boot auto-configures an <code>OpenAiChatModel</code> bean that implements the <code>ChatModel</code> interface. A <code>ChatClient</code> is built on top of it. Everything works.</p>
<p>The moment you add a second starter like <code>spring-ai-anthropic-spring-boot-starter</code>, you now have two <code>ChatModel</code> beans in the application context: <code>OpenAiChatModel</code> and <code>AnthropicChatModel</code>. Any injection point that asks for <code>ChatModel</code> by type will fail with:</p>
<pre><code class="language-plaintext">NoUniqueBeanDefinitionException: No qualifying bean of type 'ChatModel':
expected single matching bean but found 2: openAiChatModel, anthropicChatModel
</code></pre>
<p>This is standard Spring behavior — nothing specific to Spring AI. But it means you need explicit configuration.</p>
<hr />
<h2>Solution: The @Qualifier Pattern</h2>
<p>The cleanest approach is to create dedicated <code>ChatClient</code> beans that inject the concrete model types directly.</p>
<h3>Configuration Class</h3>
<pre><code class="language-java">@Configuration
public class AiConfig {

    @Bean
    public ChatClient openAiChatClient(OpenAiChatModel openAiChatModel) {
        return ChatClient.builder(openAiChatModel)
                .defaultSystem("You are a creative writing assistant.")
                .build();
    }

    @Bean
    public ChatClient anthropicChatClient(AnthropicChatModel anthropicChatModel) {
        return ChatClient.builder(anthropicChatModel)
                .defaultSystem("You are a precise summarization engine.")
                .build();
    }
}
</code></pre>
<p>By injecting <code>OpenAiChatModel</code> and <code>AnthropicChatModel</code> directly (concrete types, not the <code>ChatModel</code> interface), there's zero ambiguity. Each <code>ChatClient</code> bean gets its own model and system prompt.</p>
<h3>Using Qualified Beans in Services</h3>
<pre><code class="language-java">@Service
public class AiService {

    private final ChatClient openAiClient;
    private final ChatClient anthropicClient;

    public AiService(
            @Qualifier("openAiChatClient") ChatClient openAiClient,
            @Qualifier("anthropicChatClient") ChatClient anthropicClient) {
        this.openAiClient = openAiClient;
        this.anthropicClient = anthropicClient;
    }

    public String generateCreativeContent(String prompt) {
        return openAiClient.prompt().user(prompt).call().content();
    }

    public String summarize(String text) {
        return anthropicClient.prompt().user(text).call().content();
    }
}
</code></pre>
<p>The <code>@Qualifier</code> value matches the bean method name. Each method delegates to the right model for its task.</p>
<hr />
<h2>The mutate() Pattern: Runtime Flexibility</h2>
<p>Sometimes you need a variation of an existing <code>ChatClient</code> — different system prompt, different temperature — without creating a new bean. The <code>mutate()</code> method returns a new builder pre-filled with the current client's configuration.</p>
<pre><code class="language-java">ChatClient customClient = openAiClient.mutate()
        .defaultSystem("You are a technical documentation writer.")
        .build();

String result = customClient.prompt()
        .user("Explain the Circuit Breaker pattern")
        .call()
        .content();
</code></pre>
<p><strong>Key characteristics:</strong></p>
<ul>
<li><p>The original <code>ChatClient</code> is <strong>not modified</strong> — <code>mutate()</code> creates a copy</p>
</li>
<li><p>The returned builder inherits all defaults (model, system prompt, advisors)</p>
</li>
<li><p>You override only what you need</p>
</li>
<li><p>The mutated client is typically ephemeral — used and discarded</p>
</li>
</ul>
<p>This is particularly useful when you have a base client configured with retry logic, rate limiting, and observability, and you need task-specific variations at runtime.</p>
<hr />
<h2>OpenAI-Compatible Endpoints: One Starter, Many Providers</h2>
<p>Many AI providers expose OpenAI-compatible REST APIs: <strong>Groq</strong>, <strong>Together AI</strong>, <strong>Ollama</strong>, <strong>Perplexity</strong>, and others. Instead of adding a separate starter for each, you can reuse the OpenAI starter and override the base URL.</p>
<h3>Application Properties</h3>
<pre><code class="language-yaml">spring:
  ai:
    openai:
      api-key: ${OPENAI_API_KEY}
      chat:
        options:
          model: gpt-4o
</code></pre>
<h3>Programmatic Groq Client via OpenAI API</h3>
<pre><code class="language-java"> @Bean
 public ChatClient groqChatClient(
            @Value("${spring.ai.openai-groq.api-key}") String apiKey,
            @Value("${spring.ai.openai-groq.base-url}") String baseUrl) {

        var openAiApi = new OpenAiApi.Builder().
                apiKey(apiKey)
                .baseUrl(baseUrl)
                .build();
        var chatOptions = OpenAiChatOptions.builder()
                .model("openai/gpt-oss-20b")
                .build();
        var chatModel =  OpenAiChatModel.builder()
                .openAiApi(openAiApi)
                .defaultOptions(chatOptions)
                .build();

        return ChatClient.builder(chatModel)
                .defaultSystem("You are a fast inference assistant.")
                .build();
    }
</code></pre>
<p>With custom properties in <code>application.yml</code>:</p>
<pre><code class="language-yaml">spring:
  ai:
    openai-groq:
      base-url: https://api.groq.com/openai/v1
      api-key: ${GROQ_API_KEY}
</code></pre>
<p>Now you have OpenAI, Anthropic, and Groq in one application — three models, three ChatClients, one codebase.</p>
<hr />
<h2>Model Router: Production-Grade Selection</h2>
<p>Hardcoding model selection in your service layer doesn't scale. A router pattern decouples the "which model" decision from business logic.</p>
<pre><code class="language-java">@Service
public class ModelRouter {

    private final Map&lt;String, ChatClient&gt; clients;

    public ModelRouter(
            @Qualifier("openAiChatClient") ChatClient openAi,
            @Qualifier("anthropicChatClient") ChatClient anthropic,
            @Qualifier("groqChatClient") ChatClient groq) {
        this.clients = Map.of(
            "creative", openAi,
            "reasoning", anthropic,
            "fast", groq
        );
    }

    public ChatClient route(String taskType) {
        return clients.getOrDefault(taskType, clients.get("fast"));
    }
}
</code></pre>
<p>Usage becomes trivial:</p>
<pre><code class="language-java">ChatClient client = modelRouter.route("creative");
String result = client.prompt().user(prompt).call().content();
</code></pre>
<p>You can extend this pattern with:</p>
<ul>
<li><p><strong>Cost-aware routing</strong> — track token usage per model and route based on budget</p>
</li>
<li><p><strong>Fallback chains</strong> — if the primary model is down, fall back to the next</p>
</li>
<li><p><strong>A/B testing</strong> — randomly route a percentage of traffic to a new model</p>
</li>
<li><p><strong>Latency-based routing</strong> — choose the fastest available model</p>
</li>
</ul>
<hr />
<h2>Production Considerations</h2>
<h3>Dependency Setup</h3>
<pre><code class="language-xml">&lt;!-- OpenAI --&gt;
&lt;dependency&gt;
    &lt;groupId&gt;org.springframework.ai&lt;/groupId&gt;
    &lt;artifactId&gt;spring-ai-openai-spring-boot-starter&lt;/artifactId&gt;
&lt;/dependency&gt;

&lt;!-- Anthropic --&gt;
&lt;dependency&gt;
    &lt;groupId&gt;org.springframework.ai&lt;/groupId&gt;
    &lt;artifactId&gt;spring-ai-anthropic-spring-boot-starter&lt;/artifactId&gt;
&lt;/dependency&gt;
</code></pre>
<h3>API Key Management</h3>
<p>Store keys in environment variables or a secrets manager. Never commit them to source control.</p>
<pre><code class="language-yaml">spring:
  ai:
    openai:
      api-key: ${OPENAI_API_KEY}
    anthropic:
      api-key: ${ANTHROPIC_API_KEY}
</code></pre>
<h3>Error Handling</h3>
<p>Each model can fail independently. Wrap calls in try-catch and consider implementing circuit breakers (Resilience4j) per model to prevent cascading failures.</p>
<h3>Observability</h3>
<p>Spring AI integrates with Micrometer. Each <code>ChatModel</code> emits metrics for token usage, latency, and error rates — critical when running multiple models in production.</p>
<hr />
<h2>Key Takeaways</h2>
<ol>
<li><p><strong>Multiple starters = bean conflicts.</strong> Use <code>@Qualifier</code> with concrete model types to resolve them.</p>
</li>
<li><p><code>mutate()</code> <strong>creates ephemeral ChatClient variations</strong> without polluting the bean context.</p>
</li>
<li><p><strong>OpenAI-compatible endpoints</strong> let you use Groq, Together AI, and others through the OpenAI starter.</p>
</li>
<li><p><strong>A model router</strong> decouples model selection from business logic and enables cost-aware, fallback, and A/B strategies.</p>
</li>
</ol>
<hr />
<h2>Resources</h2>
<ul>
<li><p><a href="https://docs.spring.io/spring-ai/reference/">Spring AI Reference Documentation</a></p>
</li>
<li><p><a href="https://github.com/spring-projects/spring-ai">Spring AI GitHub Repository</a></p>
</li>
<li><p><a href="https://console.groq.com/docs">Groq API Documentation</a></p>
</li>
<li><p><a href="https://docs.anthropic.com/">Anthropic API Documentation</a></p>
</li>
</ul>
<hr />
<blockquote>
<p><strong>Spring AI Complete Course — Lecture 3 of 12</strong><br />Previous: <a href="#">Lecture 2 — ChatClient API</a> | Next: <a href="#">Lecture 4 — Advisors API</a></p>
</blockquote>
<hr />
<p><em>Tags: #spring-ai #java #spring-boot #ai #multi-model</em></p>
]]></content:encoded></item><item><title><![CDATA[Spring AI ChatClient API: The Fluent Heart of AI Integration]]></title><description><![CDATA[If you've ever tried integrating AI models into a Java application, you know the pain. HTTP clients, API keys scattered everywhere, vendor-specific SDKs…]]></description><link>https://digitalyogi.hashnode.dev/spring-ai-chatclient-api-the-fluent-heart-of-ai-integration</link><guid isPermaLink="true">https://digitalyogi.hashnode.dev/spring-ai-chatclient-api-the-fluent-heart-of-ai-integration</guid><category><![CDATA[Artificial Intelligence]]></category><category><![CDATA[Java]]></category><category><![CDATA[llm]]></category><category><![CDATA[spring ai]]></category><category><![CDATA[spring-boot]]></category><dc:creator><![CDATA[DigitalYogi]]></dc:creator><pubDate>Sat, 11 Apr 2026 13:55:02 GMT</pubDate><content:encoded><![CDATA[<h1 id="heading-spring-ai-chatclient-api-the-fluent-heart-of-ai-integration">Spring AI ChatClient API: The Fluent Heart of AI Integration</h1>
<h2 id="heading-introduction">Introduction</h2>
<p>If you've ever tried integrating AI models into a Java application, you know the pain. HTTP clients, API keys scattered everywhere, vendor-specific SDKs that never quite fit. What should take minutes takes days.</p>
<p>Spring AI's <strong>ChatClient API</strong> changes everything. It's a fluent, intuitive interface that makes calling AI models feel as natural as calling any other Spring service. In this post, we'll dive deep into the ChatClient API — the core building block that everything else in Spring AI builds upon.</p>
<hr />
<h2 id="heading-what-is-chatclient">What is ChatClient?</h2>
<p>At its core, ChatClient is Spring AI's abstraction over AI model communication. Think of it as the <code>RestTemplate</code> or <code>WebClient</code> for AI — but designed specifically for the conversational nature of LLMs.</p>
<p>The API follows three principles:</p>
<ol>
<li><strong>Fluent</strong>: Method chaining that reads like English</li>
<li><strong>Flexible</strong>: Sync or streaming, your choice</li>
<li><strong>Portable</strong>: Same code works across OpenAI, Anthropic, Groq, and more</li>
</ol>
<hr />
<h2 id="heading-creating-a-chatclient">Creating a ChatClient</h2>
<h3 id="heading-the-builder-pattern">The Builder Pattern</h3>
<pre><code class="lang-java"><span class="hljs-meta">@Bean</span>
<span class="hljs-function">ChatClient <span class="hljs-title">chatClient</span><span class="hljs-params">(ChatModel chatModel)</span> </span>{
    <span class="hljs-keyword">return</span> ChatClient.builder(chatModel)
        .defaultSystem(<span class="hljs-string">"You are a helpful Spring Boot expert"</span>)
        .build();
}
</code></pre>
<p>Notice something beautiful here? No API keys. No HTTP configuration. Just the ChatModel — which Spring Boot has already autoconfigured from your <code>application.properties</code>.</p>
<h3 id="heading-autoconfiguration-magic">Autoconfiguration Magic</h3>
<p>Spring AI's autoconfiguration creates a prototype <code>ChatClient.Builder</code> bean. Inject it and build:</p>
<pre><code class="lang-java"><span class="hljs-meta">@RestController</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyController</span> </span>{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> ChatClient chatClient;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">MyController</span><span class="hljs-params">(ChatClient.Builder chatClientBuilder)</span> </span>{
        <span class="hljs-keyword">this</span>.chatClient = chatClientBuilder.build();
    }
}
</code></pre>
<hr />
<h2 id="heading-the-prompt-call-content-chain">The Prompt → Call → Content Chain</h2>
<p>Here's where ChatClient shines. The fluent API follows a natural left-to-right flow:</p>
<h3 id="heading-basic-synchronous-call">Basic Synchronous Call</h3>
<pre><code class="lang-java">String response = chatClient.prompt()
    .user(<span class="hljs-string">"Explain Spring Boot in one sentence"</span>)
    .call()
    .content();
</code></pre>
<p>Breaking it down:</p>
<ul>
<li><strong>prompt()</strong> — Starts the conversation. Add system messages, user messages, conversation history</li>
<li><strong>call()</strong> — Executes synchronously, waits for full response</li>
<li><strong>content()</strong> — Extracts just the text content</li>
</ul>
<h3 id="heading-getting-full-response-metadata">Getting Full Response Metadata</h3>
<p>Need more than just text? Use <code>.chatResponse()</code> instead:</p>
<pre><code class="lang-java">ChatResponse response = chatClient.prompt()
    .user(<span class="hljs-string">"Explain Spring Boot"</span>)
    .call()
    .chatResponse();

<span class="hljs-comment">// Access metadata</span>
Generation generation = response.getResult();
String finishReason = generation.getMetadata().getFinishReason();
<span class="hljs-keyword">int</span> tokenCount = generation.getMetadata().getUsage().getTotalTokens();
</code></pre>
<hr />
<h2 id="heading-sync-vs-streaming">Sync vs Streaming</h2>
<h3 id="heading-synchronous-calls">Synchronous Calls</h3>
<p>Best for: Quick operations where you need the complete answer before continuing.</p>
<pre><code class="lang-java">String answer = chatClient.prompt()
    .user(<span class="hljs-string">"What is dependency injection?"</span>)
    .call()
    .content();
</code></pre>
<h3 id="heading-streaming-calls">Streaming Calls</h3>
<p>Best for: Chat interfaces, long-form content, real-time updates.</p>
<pre><code class="lang-java">Flux&lt;String&gt; tokens = chatClient.prompt()
    .user(<span class="hljs-string">"Write a detailed Spring Boot tutorial"</span>)
    .stream()
    .content();

<span class="hljs-comment">// Subscribe and display tokens as they arrive</span>
tokens.subscribe(System.out::println);
</code></pre>
<p>The beauty? Just swap <code>call()</code> for <code>stream()</code> and you get a reactive <code>Flux</code> of tokens. Spring AI handles all the Server-Sent Events (SSE) complexity.</p>
<hr />
<h2 id="heading-entity-mapping-ai-meets-pojos">Entity Mapping: AI Meets POJOs</h2>
<p>This is where ChatClient becomes production-ready. Map AI responses directly to Java objects:</p>
<pre><code class="lang-java"><span class="hljs-function">record <span class="hljs-title">Movie</span><span class="hljs-params">(String title, String director, <span class="hljs-keyword">int</span> year)</span> </span>{}

Movie recommendation = chatClient.prompt()
    .user(<span class="hljs-string">"Recommend a classic programming movie"</span>)
    .call()
    .entity(Movie.class);

System.out.println(recommendation.title()); <span class="hljs-comment">// "The Social Network"</span>
</code></pre>
<p>Behind the scenes, Spring AI:</p>
<ol>
<li>Instructs the model to return structured JSON</li>
<li>Parses the response</li>
<li>Maps to your record/class</li>
<li>Handles type conversion and validation</li>
</ol>
<p>No more regex parsing. No more manual JSON mapping.</p>
<hr />
<h2 id="heading-multiple-model-configuration">Multiple Model Configuration</h2>
<p>Real applications often need multiple AI models. Spring AI makes this elegant with <code>@Qualifier</code>:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Configuration</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ChatClientConfig</span> </span>{

    <span class="hljs-meta">@Bean</span>
    <span class="hljs-meta">@Qualifier("openai")</span>
    <span class="hljs-function">ChatClient <span class="hljs-title">openAiClient</span><span class="hljs-params">(ChatModel openAiModel)</span> </span>{
        <span class="hljs-keyword">return</span> ChatClient.builder(openAiModel)
            .defaultSystem(<span class="hljs-string">"You are an expert coder"</span>)
            .build();
    }

    <span class="hljs-meta">@Bean</span>
    <span class="hljs-meta">@Qualifier("anthropic")</span>
    <span class="hljs-function">ChatClient <span class="hljs-title">anthropicClient</span><span class="hljs-params">(ChatModel anthropicModel)</span> </span>{
        <span class="hljs-keyword">return</span> ChatClient.builder(anthropicModel)
            .defaultSystem(<span class="hljs-string">"You are a creative writer"</span>)
            .build();
    }
}

<span class="hljs-comment">// Usage</span>
<span class="hljs-meta">@Service</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AIService</span> </span>{
    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-meta">@Qualifier("openai")</span>
    <span class="hljs-keyword">private</span> ChatClient openAiClient;

    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-meta">@Qualifier("anthropic")</span>
    <span class="hljs-keyword">private</span> ChatClient anthropicClient;
}
</code></pre>
<hr />
<h2 id="heading-production-tips">Production Tips</h2>
<h3 id="heading-1-default-system-prompts">1. Default System Prompts</h3>
<p>Set application-wide behavior in the builder:</p>
<pre><code class="lang-java"><span class="hljs-keyword">return</span> ChatClient.builder(chatModel)
    .defaultSystem(<span class="hljs-string">"You are a helpful assistant. Be concise."</span>)
    .defaultOptions(ChatOptions.builder()
        .temperature(<span class="hljs-number">0.7</span>)
        .build())
    .build();
</code></pre>
<h3 id="heading-2-requestresponse-logging">2. Request/Response Logging</h3>
<p>For debugging, intercept the ChatClient calls with an Advisor (covered in Lecture 4):</p>
<pre><code class="lang-java">chatClient.prompt()
    .advisors(<span class="hljs-keyword">new</span> LoggingAdvisor())
    .user(<span class="hljs-string">"Hello"</span>)
    .call();
</code></pre>
<h3 id="heading-3-error-handling">3. Error Handling</h3>
<p>Wrap calls in try-catch for model-specific exceptions:</p>
<pre><code class="lang-java"> <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">return</span> chatClient.prompt()
        .user(userInput)
        .call()
        .content();
} <span class="hljs-keyword">catch</span> (AiException e) {
    <span class="hljs-comment">// Handle rate limits, token limits, etc.</span>
    <span class="hljs-keyword">return</span> <span class="hljs-string">"Service temporarily unavailable"</span>;
}
</code></pre>
<hr />
<h2 id="heading-complete-rest-controller-example">Complete REST Controller Example</h2>
<p>Here's a production-ready controller with multiple model configs and streaming:</p>
<pre><code class="lang-java"><span class="hljs-meta">@RestController</span>
<span class="hljs-meta">@RequestMapping("/api/ai")</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AIController</span> </span>{

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> ChatClient defaultClient;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> ChatClient streamingClient;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">AIController</span><span class="hljs-params">(
            <span class="hljs-meta">@Qualifier("openai")</span> ChatClient defaultClient,
            <span class="hljs-meta">@Qualifier("groq")</span> ChatClient streamingClient)</span> </span>{
        <span class="hljs-keyword">this</span>.defaultClient = defaultClient;
        <span class="hljs-keyword">this</span>.streamingClient = streamingClient;
    }

    <span class="hljs-comment">// Sync endpoint for quick responses</span>
    <span class="hljs-meta">@GetMapping("/ask")</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> ResponseEntity&lt;String&gt; <span class="hljs-title">ask</span><span class="hljs-params">(<span class="hljs-meta">@RequestParam</span> String question)</span> </span>{
        String answer = defaultClient.prompt()
            .user(question)
            .call()
            .content();
        <span class="hljs-keyword">return</span> ResponseEntity.ok(answer);
    }

    <span class="hljs-comment">// Streaming endpoint for chat-like experience</span>
    <span class="hljs-meta">@GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> Flux&lt;String&gt; <span class="hljs-title">stream</span><span class="hljs-params">(<span class="hljs-meta">@RequestParam</span> String question)</span> </span>{
        <span class="hljs-keyword">return</span> streamingClient.prompt()
            .user(question)
            .stream()
            .content();
    }

    <span class="hljs-comment">// Entity mapping endpoint</span>
    <span class="hljs-meta">@PostMapping("/analyze")</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> ResponseEntity&lt;Analysis&gt; <span class="hljs-title">analyze</span><span class="hljs-params">(<span class="hljs-meta">@RequestBody</span> String text)</span> </span>{
        Analysis result = defaultClient.prompt()
            .user(<span class="hljs-string">"Analyze this text: "</span> + text)
            .call()
            .entity(Analysis.class);
        <span class="hljs-keyword">return</span> ResponseEntity.ok(result);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> record <span class="hljs-title">Analysis</span><span class="hljs-params">(String sentiment, List&lt;String&gt; keyPoints)</span> </span>{}
}
</code></pre>
<hr />
<h2 id="heading-whats-next">What's Next?</h2>
<p>Now that you understand the ChatClient API, the next lecture covers <strong>Working with Multiple AI Models</strong> — how to configure, compare, and combine different model providers in a single application.</p>
<hr />
<h2 id="heading-key-takeaways">Key Takeaways</h2>
<ol>
<li><strong>ChatClient.Builder</strong> gives you clean, configurable AI model access</li>
<li><strong>prompt() → call() → content()</strong> is your bread-and-butter chain</li>
<li>Use <strong>streaming</strong> for real-time UX, <strong>sync</strong> for quick operations</li>
<li><strong>Entity mapping</strong> eliminates boilerplate JSON parsing</li>
<li><strong>@Qualifier</strong> pattern enables multiple model configurations</li>
</ol>
<hr />
<p><em>Series: Spring AI Complete Course</em>
<em>Next: Lecture 3 — Working with Multiple AI Models</em>
<em>Code samples: [GitHub Repository Link]</em></p>
<p>#springai #java #springboot #ai #chatclient #llm #tutorial</p>
]]></content:encoded></item><item><title><![CDATA[What is Spring AI? — Why Java Developers Need This in 2026]]></title><description><![CDATA[Every AI tutorial you see is in Python. LangChain, LlamaIndex, OpenAI SDK — all Python. But here's the uncomfortable truth: 80% of enterprise backends run…]]></description><link>https://digitalyogi.hashnode.dev/what-is-spring-ai-why-java-developers-need-this-in-2026</link><guid isPermaLink="true">https://digitalyogi.hashnode.dev/what-is-spring-ai-why-java-developers-need-this-in-2026</guid><category><![CDATA[AI]]></category><category><![CDATA[Java]]></category><category><![CDATA[Spring]]></category><dc:creator><![CDATA[DigitalYogi]]></dc:creator><pubDate>Fri, 10 Apr 2026 08:50:10 GMT</pubDate><content:encoded><![CDATA[<h1 id="heading-what-is-spring-ai-why-java-developers-need-this-in-2026">What is Spring AI? — Why Java Developers Need This in 2026</h1>
<p>Every AI tutorial you see is in Python. LangChain, LlamaIndex, OpenAI SDK — all Python. But here's the uncomfortable truth: <strong>80% of enterprise backends run Java.</strong></p>
<p>So who's building AI into those systems? That's exactly what <strong>Spring AI</strong> solves.</p>
<hr />
<h2 id="heading-the-problem-javas-ai-gap">The Problem: Java's AI Gap</h2>
<p>If you're a Spring Boot developer, you've probably felt it:</p>
<ul>
<li>AI frameworks are Python-first</li>
<li>You can't rewrite your enterprise backend in Python</li>
<li>Each AI provider has its own SDK with different patterns</li>
<li>No portable abstraction exists in the Java ecosystem</li>
</ul>
<p>Until now.</p>
<h2 id="heading-what-is-spring-ai">What is Spring AI?</h2>
<p>Spring AI is the <strong>official Spring project</strong> for integrating artificial intelligence into Java applications. It's inspired by Python projects like LangChain and LlamaIndex — but it's not a port. It's built from the ground up for the Spring ecosystem.</p>
<h3 id="heading-the-key-insight">The Key Insight</h3>
<p>Spring AI addresses the fundamental challenge: <strong>connecting your enterprise data and APIs with AI models</strong> — the Spring way.</p>
<h2 id="heading-6-core-abstractions">6 Core Abstractions</h2>
<p>Here's what Spring AI gives you:</p>
<h3 id="heading-1-chatclient-the-fluent-api">1. ChatClient — The Fluent API</h3>
<p>Think of it as <strong>WebClient, but for AI models</strong>. A fluent builder pattern for prompts, responses, and streaming.</p>
<h3 id="heading-2-advisors-middleware-for-ai">2. Advisors — Middleware for AI</h3>
<p>Like Spring Security filters, but for AI requests. Chain advisors to log, transform, filter, and enhance prompts and responses.</p>
<h3 id="heading-3-tool-calling-let-ai-invoke-your-methods">3. Tool Calling — Let AI Invoke Your Methods</h3>
<p>Annotate a method with <code>@Tool</code>, and the AI model can request it to be called. The model never gets direct access — your app controls execution.</p>
<h3 id="heading-4-vector-store-portable-vector-db-api">4. Vector Store — Portable Vector DB API</h3>
<p>One interface, 14+ database implementations. PGVector, Pinecone, Milvus, Redis, Elasticsearch — swap with zero code changes.</p>
<h3 id="heading-5-etl-pipeline-data-ingestion-for-rag">5. ETL Pipeline — Data Ingestion for RAG</h3>
<p>Read documents (PDF, JSON, HTML), split into chunks, generate embeddings, store in vector DB. The complete RAG ingestion pipeline.</p>
<h3 id="heading-6-structured-output-ai-responses-as-pojos">6. Structured Output — AI Responses as POJOs</h3>
<p>Map AI model output directly to Java objects. Type-safe, validated, production-ready.</p>
<h2 id="heading-your-first-spring-ai-application">Your First Spring AI Application</h2>
<p>Setting up is embarrassingly simple:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.ai<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-ai-openai-spring-boot-starter<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
</code></pre>
<pre><code class="lang-yaml"><span class="hljs-attr">spring:</span>
  <span class="hljs-attr">ai:</span>
    <span class="hljs-attr">openai:</span>
      <span class="hljs-attr">api-key:</span> <span class="hljs-string">${OPENAI_API_KEY}</span>
</code></pre>
<p>And your first AI endpoint:</p>
<pre><code class="lang-java"><span class="hljs-meta">@RestController</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AiController</span> </span>{

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> ChatClient chatClient;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">AiController</span><span class="hljs-params">(ChatClient.Builder builder)</span> </span>{
        <span class="hljs-keyword">this</span>.chatClient = builder.build();
    }

    <span class="hljs-meta">@GetMapping("/ai")</span>
    <span class="hljs-function">String <span class="hljs-title">ask</span><span class="hljs-params">(<span class="hljs-meta">@RequestParam</span> String question)</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.chatClient.prompt()
            .user(question)
            .call()
            .content();
    }
}
</code></pre>
<p><strong>Three lines of actual code.</strong> The <code>ChatClient.Builder</code> is auto-configured by Spring Boot. No boilerplate, no SDK initialization, no API client setup.</p>
<h2 id="heading-why-this-matters-for-enterprise-developers">Why This Matters for Enterprise Developers</h2>
<ol>
<li><strong>Portable across providers</strong> — OpenAI today, Anthropic tomorrow, zero code changes</li>
<li><strong>Spring patterns</strong> — DI, auto-config, fluent APIs, annotations — you already know this</li>
<li><strong>Enterprise-grade</strong> — Observability, testing, security — all built in</li>
<li><strong>Not Python</strong> — Your team doesn't need to learn a new language stack</li>
</ol>
<h2 id="heading-whats-next">What's Next</h2>
<p>This is Lecture 1 of a 12-part series taking you from zero to a <strong>production RAG application</strong> with Spring AI.</p>
<p>Next up: <strong>ChatClient API Deep Dive</strong> — the fluent API that makes talking to AI feel like writing a REST call.</p>
<hr />
<h2 id="heading-key-takeaways">Key Takeaways</h2>
<ul>
<li>Spring AI = AI integration for Java developers, done the Spring way</li>
<li>Portable API across all major AI providers</li>
<li>If you know Spring Boot, you already know 80% of Spring AI</li>
<li>Enterprise-ready from day one</li>
</ul>
<hr />
<p><em>This post is part of the "Spring AI Complete Course" series by Kumar Pallav.</em></p>
<p>#SpringAI #Java #SpringBoot #AI #RAG #SystemDesign #AIForDevelopers</p>
]]></content:encoded></item><item><title><![CDATA[Event-Driven Architecture with Spring Boot and Kafka]]></title><description><![CDATA[Event-driven architecture (EDA) is a powerful approach to building scalable, decoupled, and reactive applications. Unlike traditional request-response…]]></description><link>https://digitalyogi.hashnode.dev/event-driven-architecture-with-spring-boot-and-kafka</link><guid isPermaLink="true">https://digitalyogi.hashnode.dev/event-driven-architecture-with-spring-boot-and-kafka</guid><category><![CDATA[Java]]></category><category><![CDATA[events]]></category><category><![CDATA[event-driven-architecture]]></category><category><![CDATA[kafka]]></category><dc:creator><![CDATA[DigitalYogi]]></dc:creator><pubDate>Mon, 17 Feb 2025 14:02:01 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/JVSgcV8_vb4/upload/045ec7ee9579f296473dcc09a01f5c2a.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction"><strong>Introduction</strong></h2>
<p>Event-driven architecture (EDA) is a powerful approach to building scalable, decoupled, and reactive applications. Unlike traditional request-response models, EDA revolves around events that propagate through the system asynchronously, enabling real-time processing and high availability.</p>
<p>In this article, we'll explore EDA using <strong>Spring Boot and Apache Kafka</strong>, leveraging a real-world example of an <strong>Order and Commerce API</strong>. We'll also compare it with traditional architectures, discuss benefits like event replayability, and highlight key challenges.</p>
<p>Below is the introduction video on same.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.youtube.com/watch?v=iMlBA6Gn1eg">https://www.youtube.com/watch?v=iMlBA6Gn1eg</a></div>
<p> </p>
<h2 id="heading-understanding-event-driven-architecture"><strong>Understanding Event-Driven Architecture</strong></h2>
<p>EDA consists of three core components:</p>
<ul>
<li><p><strong>Event Producers</strong>: Generate events (e.g., order placed, payment processed).</p>
</li>
<li><p><strong>Event Brokers</strong>: Store and distribute events (e.g., Apache Kafka).</p>
</li>
<li><p><strong>Event Consumers</strong>: Process events asynchronously (e.g., notification service, inventory update service).</p>
</li>
</ul>
<p>Instead of synchronous communication (e.g., REST APIs), events are published and processed independently by different microservices.</p>
<h2 id="heading-traditional-vs-event-driven-approach"><strong>Traditional vs. Event-Driven Approach</strong></h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739800412560/4eaf1d5a-a3e7-4540-925e-6c5630519ca4.png" alt class="image--center mx-auto" /></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Feature</td><td>Traditional Approach</td><td>Event-Driven Approach</td></tr>
</thead>
<tbody>
<tr>
<td>Communication</td><td>Synchronous (REST, RPC)</td><td>Asynchronous (events)</td></tr>
<tr>
<td>Coupling</td><td>Tightly coupled</td><td>Loosely coupled</td></tr>
<tr>
<td>Scalability</td><td>Limited</td><td>Highly scalable</td></tr>
<tr>
<td>Data Flow</td><td>Request-response</td><td>Event propagation</td></tr>
<tr>
<td>Resilience</td><td>Single point of failure</td><td>Fault-tolerant</td></tr>
<tr>
<td>Replayability</td><td>No event history</td><td>Events can be replayed</td></tr>
</tbody>
</table>
</div><h2 id="heading-building-an-event-driven-order-and-commerce-api"><strong>Building an Event-Driven Order and Commerce API</strong></h2>
<p>We'll build a system where users place orders, and multiple services (e.g., payment, inventory, notification) react asynchronously.</p>
<h3 id="heading-step-1-set-up-kafka-using-docker"><strong>Step 1: Set Up Kafka Using Docker</strong></h3>
<p>To avoid manual setup, we will use Docker to set up Kafka and Zookeeper.</p>
<h4 id="heading-docker-compose-file"><strong>Docker Compose File</strong></h4>
<p>Create a <code>docker-compose.yml</code> file:</p>
<pre><code class="lang-java">version: <span class="hljs-string">'2'</span>
services:
  zookeeper:
    image: confluentinc/cp-zookeeper:latest
    environment:
      ZOOKEEPER_CLIENT_PORT: <span class="hljs-number">2181</span>
  kafka:
    image: confluentinc/cp-kafka:latest
    depends_on:
      - zookeeper
    environment:
      KAFKA_BROKER_ID: <span class="hljs-number">1</span>
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:<span class="hljs-number">2181</span>
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT:<span class="hljs-comment">//localhost:9092</span>
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: <span class="hljs-number">1</span>
</code></pre>
<p>Start Kafka and Zookeeper:</p>
<pre><code class="lang-java">docker-compose up -d
</code></pre>
<h3 id="heading-step-2-define-an-order-event"><strong>Step 2: Define an Order Event</strong></h3>
<p>Create a Java class representing an order event:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Data</span>
<span class="hljs-meta">@AllArgsConstructor</span>
<span class="hljs-meta">@NoArgsConstructor</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">OrderEvent</span> </span>{
    <span class="hljs-keyword">private</span> String orderId;
    <span class="hljs-keyword">private</span> String status; <span class="hljs-comment">// CREATED, PAYMENT_SUCCESS, PAYMENT_FAILED</span>
    <span class="hljs-keyword">private</span> Instant timestamp;
}
</code></pre>
<h3 id="heading-step-3-implement-the-order-producer"><strong>Step 3: Implement the Order Producer</strong></h3>
<p>Use KafkaTemplate to publish order events.</p>
<pre><code class="lang-java"><span class="hljs-meta">@RestController</span>
<span class="hljs-meta">@RequestMapping("/orders")</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">OrderController</span> </span>{
    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-keyword">private</span> KafkaTemplate&lt;String, OrderEvent&gt; kafkaTemplate;

    <span class="hljs-meta">@PostMapping</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> ResponseEntity&lt;String&gt; <span class="hljs-title">placeOrder</span><span class="hljs-params">(<span class="hljs-meta">@RequestBody</span> Order order)</span> </span>{
        OrderEvent event = <span class="hljs-keyword">new</span> OrderEvent(order.getId(), <span class="hljs-string">"CREATED"</span>, Instant.now());
        kafkaTemplate.send(<span class="hljs-string">"order-events"</span>, event);
        <span class="hljs-keyword">return</span> ResponseEntity.ok(<span class="hljs-string">"Order placed!"</span>);
    }
}
</code></pre>
<h3 id="heading-step-4-implement-the-order-consumer"><strong>Step 4: Implement the Order Consumer</strong></h3>
<p>Consume order events asynchronously.</p>
<pre><code class="lang-java"><span class="hljs-meta">@Component</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">OrderEventConsumer</span> </span>{
    <span class="hljs-meta">@KafkaListener(topics = "order-events", groupId = "order-group")</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">consume</span><span class="hljs-params">(OrderEvent event)</span> </span>{
        System.out.println(<span class="hljs-string">"Received Order Event: "</span> + event);
    }
}
</code></pre>
<h3 id="heading-step-5-running-the-application-in-docker"><strong>Step 5: Running the Application in Docker</strong></h3>
<p>To containerize our Spring Boot services, create a <code>Dockerfile</code>:</p>
<pre><code class="lang-java">FROM openjdk:<span class="hljs-number">17</span>-jdk-slim
VOLUME /tmp
COPY target/order-service.jar order-service.jar
ENTRYPOINT [<span class="hljs-string">"java"</span>, <span class="hljs-string">"-jar"</span>, <span class="hljs-string">"/order-service.jar"</span>]
</code></pre>
<p>Build and run the container:</p>
<pre><code class="lang-java">mvn clean <span class="hljs-keyword">package</span> -DskipTests
docker build -t order-service .
docker run -p <span class="hljs-number">8080</span>:<span class="hljs-number">8080</span> order-service
</code></pre>
<h2 id="heading-benefits-of-event-replayability"><strong>Benefits of Event Replayability</strong></h2>
<p>One major advantage of Kafka-based EDA is the ability to <strong>replay events</strong>. This is crucial for:</p>
<ul>
<li><p><strong>Data recovery</strong>: If a service fails, it can reprocess past events.</p>
</li>
<li><p><strong>Audit logging</strong>: Maintaining a history of system actions.</p>
</li>
<li><p><strong>Machine learning</strong>: Training models based on past events.</p>
</li>
</ul>
<h2 id="heading-challenges-of-event-driven-systems"><strong>Challenges of Event-Driven Systems</strong></h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739800715769/89b664de-6e9a-4785-8a8f-fac52bbe2dca.png" alt class="image--center mx-auto" /></p>
<p>While EDA is powerful, it comes with challenges:</p>
<ol>
<li><p><strong>Event Ordering</strong>: Kafka guarantees ordering per partition, but cross-partition ordering needs extra handling.</p>
</li>
<li><p><strong>Idempotency</strong>: Consumers must handle duplicate events gracefully.</p>
</li>
<li><p><strong>Schema Evolution</strong>: Changing event structures requires backward compatibility.</p>
</li>
<li><p><strong>Debugging Complexity</strong>: Tracing issues in an asynchronous system is harder than in monolithic architectures.</p>
</li>
</ol>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>Event-driven architecture, powered by <strong>Spring Boot and Kafka</strong>, enables highly scalable, decoupled applications. By using <strong>event replayability</strong>, services can recover from failures and derive insights from historical data.</p>
<p>Would you like to see an alternative use case, such as <strong>real-time ride-sharing</strong> or <strong>stock market trade processing</strong>? Let me know your thoughts!</p>
]]></content:encoded></item><item><title><![CDATA[3Sum Closest - Step-by-Step with Java]]></title><description><![CDATA[The problem asks us to find three numbers in an array whose sum is closest to a given target value. Example Input: nums = [-1, 2, 1, -4], **target = 1…]]></description><link>https://digitalyogi.hashnode.dev/3sum-closest-step-by-step-with-java</link><guid isPermaLink="true">https://digitalyogi.hashnode.dev/3sum-closest-step-by-step-with-java</guid><category><![CDATA[two pointers]]></category><category><![CDATA[DSA]]></category><dc:creator><![CDATA[DigitalYogi]]></dc:creator><pubDate>Thu, 19 Dec 2024 17:57:54 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/s9CC2SKySJM/upload/645df89d7ce609980dac80de739c54bc.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-problem-statement">Problem Statement</h3>
<p>The problem asks us to find three numbers in an array whose sum is closest to a given target value.</p>
<p><strong>Example Input</strong>: <code>nums = [-1, 2, 1, -4]</code>, **target = 1 <code>**Expected Output**:</code>2`</p>
<hr />
<h2 id="heading-approach"><strong>Approach</strong></h2>
<p>We can solve the problem using the <strong>Two Pointer Technique</strong> with a sorted array. Here's a high-level summary of the solution:</p>
<ol>
<li><p><strong>Sort the array</strong> to prepare for the two-pointer method.</p>
</li>
<li><p>Iterate through each number in the array. For each number:</p>
<ul>
<li><p>Fix the number as the first number (<code>nums[start]</code>).</p>
</li>
<li><p>Use two pointers, <code>left</code> and <code>right</code>, to explore the remaining numbers.</p>
</li>
</ul>
</li>
<li><p>Calculate the sum of the three numbers.</p>
</li>
<li><p>Update the closest sum whenever the new sum is closer to the target than the previous closest value.</p>
</li>
<li><p>Adjust the pointers (<code>left++</code> or <code>right--</code>) based on the comparison between <code>sum</code> and <code>target</code>.</p>
</li>
</ol>
<hr />
<h2 id="heading-code"><strong>Code</strong></h2>
<p>Here is the final Java solution:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.Arrays;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">threeSumClosest</span><span class="hljs-params">(<span class="hljs-keyword">int</span>[] nums, <span class="hljs-keyword">int</span> target)</span> </span>{
        Arrays.sort(nums);  <span class="hljs-comment">// Step 1: Sort the array</span>
        <span class="hljs-keyword">int</span> closest = Integer.MAX_VALUE;  <span class="hljs-comment">// Closest sum initialized to max value</span>

        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; nums.length; i++) {
            <span class="hljs-keyword">int</span> start = i;  <span class="hljs-comment">// Fix the current number</span>
            <span class="hljs-keyword">int</span> left = i + <span class="hljs-number">1</span>;  <span class="hljs-comment">// Left pointer</span>
            <span class="hljs-keyword">int</span> right = nums.length - <span class="hljs-number">1</span>;  <span class="hljs-comment">// Right pointer</span>

            <span class="hljs-keyword">while</span> (left &lt; right) {  <span class="hljs-comment">// Step 2: Two-pointer approach</span>
                <span class="hljs-keyword">int</span> sum = nums[start] + nums[left] + nums[right];

                <span class="hljs-comment">// Step 3: Update closest sum</span>
                <span class="hljs-keyword">if</span> (Math.abs(sum - target) &lt; Math.abs(closest - target)) {
                    closest = sum;
                }

                <span class="hljs-keyword">if</span> (sum == target) <span class="hljs-keyword">return</span> sum;  <span class="hljs-comment">// Perfect match</span>

                <span class="hljs-comment">// Move pointers</span>
                <span class="hljs-keyword">if</span> (sum &lt; target) {
                    left++;  <span class="hljs-comment">// Increase the sum</span>
                } <span class="hljs-keyword">else</span> {
                    right--;  <span class="hljs-comment">// Decrease the sum</span>
                }
            }
        }
        <span class="hljs-keyword">return</span> closest;  <span class="hljs-comment">// Return the closest sum</span>
    }
}
</code></pre>
<hr />
<h2 id="heading-step-by-step-execution"><strong>Step-by-Step Execution</strong></h2>
<p>We will use the input <code>nums = [-1, 2, 1, -4]</code> and <code>target = 1</code>.</p>
<h3 id="heading-step-1-sort-the-array"><strong>Step 1: Sort the Array</strong></h3>
<p>The input array becomes:</p>
<pre><code class="lang-plaintext">cssCopy codeSorted nums = [-4, -1, 1, 2]
</code></pre>
<p>You can use a diagram to visualize this:</p>
<p><strong>Image 1: Array before and after sorting</strong></p>
<pre><code class="lang-plaintext">Original: [-1, 2, 1, -4]
Sorted:   [-4, -1, 1, 2]
</code></pre>
<hr />
<h3 id="heading-step-2-initialize-pointers"><strong>Step 2: Initialize Pointers</strong></h3>
<p>We loop through the array, starting with <code>i = 0</code>:</p>
<ul>
<li><p><code>start = i = 0</code> → <code>nums[start] = -4</code></p>
</li>
<li><p><code>left = 1</code> → <code>nums[left] = -1</code></p>
</li>
<li><p><code>right = 3</code> → <code>nums[right] = 2</code></p>
</li>
</ul>
<p><strong>Initial pointers:</strong></p>
<pre><code class="lang-plaintext">codenums = [-4, -1, 1, 2]
            ↑    ↑    ↑
          start left right
</code></pre>
<hr />
<h3 id="heading-step-3-calculate-the-first-sum"><strong>Step 3: Calculate the First Sum</strong></h3>
<ul>
<li><p>First sum = <code>nums[start] + nums[left] + nums[right] = -4 + (-1) + 2 = -3</code></p>
</li>
<li><p>Compare <code>|target - sum|</code>:</p>
<ul>
<li><p><code>target = 1</code></p>
</li>
<li><p><code>difference = |1 - (-3)| = 4</code></p>
</li>
</ul>
</li>
<li><p>Update <code>closest</code> to <code>-3</code> because it's the first valid sum.</p>
</li>
</ul>
<p><strong>Image 2: State after the first calculation</strong></p>
<pre><code class="lang-plaintext">codeSum = -3
Closest = -3
</code></pre>
<hr />
<h3 id="heading-step-4-move-pointers"><strong>Step 4: Move Pointers</strong></h3>
<p>Since <code>sum &lt; target</code>, we increment <code>left</code>:</p>
<ul>
<li><code>left = 2</code> → <code>nums[left] = 1</code></li>
</ul>
<p><strong>New pointers:</strong></p>
<pre><code class="lang-plaintext">codenums = [-4, -1, 1, 2]
             ↑       ↑  ↑
           start   left right
</code></pre>
<hr />
<h3 id="heading-step-5-calculate-the-new-sum"><strong>Step 5: Calculate the New Sum</strong></h3>
<ul>
<li><p>New sum = <code>-4 + 1 + 2 = -1</code></p>
</li>
<li><p>Compare <code>|target - sum|</code>:</p>
<ul>
<li><code>difference = |1 - (-1)| = 2</code></li>
</ul>
</li>
<li><p>Update <code>closest</code> to <code>-1</code> because it's closer to the target than <code>-3</code>.</p>
</li>
</ul>
<p><strong>Image 3: State after the second calculation</strong></p>
<pre><code class="lang-plaintext">Sum = -1
Closest = -1
</code></pre>
<hr />
<h3 id="heading-step-6-move-pointers-again"><strong>Step 6: Move Pointers Again</strong></h3>
<p>Since <code>sum &lt; target</code>, increment <code>left</code>:</p>
<ul>
<li><code>left = 3</code> → Now <code>left</code> equals <code>right</code>, so the while loop ends.</li>
</ul>
<hr />
<h3 id="heading-step-7-move-to-the-next-start"><strong>Step 7: Move to the Next Start</strong></h3>
<p>Now, <code>i = 1</code>:</p>
<ul>
<li><p><code>start = 1</code> → <code>nums[start] = -1</code></p>
</li>
<li><p><code>left = 2</code> → <code>nums[left] = 1</code></p>
</li>
<li><p><code>right = 3</code> → <code>nums[right] = 2</code></p>
</li>
</ul>
<p><strong>New pointers:</strong></p>
<pre><code class="lang-plaintext">nums = [-4, -1, 1, 2]
            ↑   ↑  ↑
          start left right
</code></pre>
<hr />
<h3 id="heading-step-8-calculate-the-sum"><strong>Step 8: Calculate the Sum</strong></h3>
<ul>
<li><p>Sum = <code>-1 + 1 + 2 = 2</code></p>
</li>
<li><p>Compare <code>|target - sum|</code>:</p>
<ul>
<li><code>difference = |1 - 2| = 1</code></li>
</ul>
</li>
<li><p>Update <code>closest</code> to <code>2</code> because it's closer than <code>-1</code>.</p>
</li>
</ul>
<p><strong>Image 4: State after final calculation</strong></p>
<pre><code class="lang-plaintext">codeSum = 2
Closest = 2
</code></pre>
<hr />
<h3 id="heading-step-9-end-of-iteration"><strong>Step 9: End of Iteration</strong></h3>
<p>The loop ends, and the closest sum is returned as <strong>2</strong>.</p>
<hr />
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>With clear visuals and diagrams at each step, you can demonstrate how the pointers move and how the closest sum is updated. Here’s a summary of the pointer movements and sums:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Iteration</td><td><code>start</code></td><td><code>left</code></td><td><code>right</code></td><td>Sum</td><td>Closest</td></tr>
</thead>
<tbody>
<tr>
<td>1</td><td>-4</td><td>-1</td><td>2</td><td>-3</td><td>-3</td></tr>
<tr>
<td>2</td><td>-4</td><td>1</td><td>2</td><td>-1</td><td>-1</td></tr>
<tr>
<td>3</td><td>-1</td><td>1</td><td>2</td><td>2</td><td>2</td></tr>
</tbody>
</table>
</div><h3 id="heading-final-output">Final Output:</h3>
<pre><code class="lang-plaintext">Closest Sum = 2
</code></pre>
]]></content:encoded></item><item><title><![CDATA[52-Weeks 52 - Blogs + Vlogs]]></title><description><![CDATA[#365DaysofBlogging]]></description><link>https://digitalyogi.hashnode.dev/52-weeks-52-blogs-vlogs</link><guid isPermaLink="true">https://digitalyogi.hashnode.dev/52-weeks-52-blogs-vlogs</guid><dc:creator><![CDATA[DigitalYogi]]></dc:creator><pubDate>Thu, 23 Feb 2023 17:19:31 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/RLw-UC03Gwc/upload/0ee478f48f3f6ed08c0da4f747e9524a.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I have been very much interested in blogs and vlogs. I believe it gives me a chance to learn as well as give back to the community. While I have always loved the idea, I have never been consistent.</p>
<p>In the past few months, I have realized that I have been a lot more consistent if set a goal, and deadline and commit it publically. Many feel it's a way to show off but It personally has paid me good results. I took a personal fitness goal and lost 10 KG by running and eating healthy with my 100DaysOfTransformation journey.</p>
<p>This has given me the confidence to explore further and push to my limits. So I am creating a year plan to revive my learning path. I would like to learn new things, revisit ones to reinforce my knowledge and keep it consistent for a year. Writing blogs and creating youtube videos will be a part of it.</p>
<p>52 weeks is a long time. I believe the target is that the longer the time, slowly motivation dies. The action fuels motivation and smaller success will give me a lot more motivation to keep me on track for this long journey. I will try to break this into 3 months period. Each of these 3 months should accomplish one subject in detail. Along with core subjects like Java, Spring, Quarkus and Micronaut, I would also like to work on Data Structure and Algorithms and System design. This journey for these two will be all over the year. For DS and Algo, I will try to create weekly plans in another post.</p>
<p>Let's create a plan for 52 weeks, 52 blogs along with 52 vlogs.</p>
<p>Starting with initial plans of few weeks , I will update as I go further</p>
<p><strong>Week 1: February 20, 2024</strong></p>
]]></content:encoded></item><item><title><![CDATA[Azure Spring Cloud -  PostGres Database]]></title><description><![CDATA[PostgreSQL is a powerful, open-source object-relational database system that is widely used for storing and managing data. It is known for its reliability…]]></description><link>https://digitalyogi.hashnode.dev/azure-spring-cloud-postgres-database</link><guid isPermaLink="true">https://digitalyogi.hashnode.dev/azure-spring-cloud-postgres-database</guid><category><![CDATA[Spring]]></category><category><![CDATA[Azure]]></category><category><![CDATA[Springboot]]></category><category><![CDATA[PostgreSQL]]></category><dc:creator><![CDATA[DigitalYogi]]></dc:creator><pubDate>Mon, 23 Jan 2023 12:49:41 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/npxXWgQ33ZQ/upload/a4c07f0b49608fff5fecc6e05dd04748.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>PostgreSQL is a powerful, open-source object-relational database system that is widely used for storing and managing data. It is known for its reliability, flexibility, and performance, making it a popular choice for a variety of applications.</p>
<p>Spring Azure Apps is a framework for building cloud-native Java applications that are designed to run on Microsoft Azure. It provides a range of tools and features for developing, deploying, and managing applications on Azure, including support for various database technologies.</p>
<h2 id="heading-agenda">Agenda</h2>
<p>In this article, we will explore how to use PostgreSQL with Spring Azure Apps to build and deploy cloud-native applications. We will cover the following topics:</p>
<ul>
<li><p><strong>Setting up a PostgreSQL database on Azure</strong></p>
</li>
<li><p><strong>Connecting to the PostgreSQL database from a Spring Azure App</strong></p>
</li>
<li><p><strong>Using PostgreSQL with the Spring Data JPA module</strong></p>
</li>
<li><p><strong>Deploying a Spring Azure App with PostgreSQL to Azure</strong></p>
</li>
</ul>
<h3 id="heading-setting-up-a-postgresql-database-on-azure">Setting up a PostgreSQL database on Azure</h3>
<p>To use PostgreSQL with a Spring Azure App, you will first need to set up a PostgreSQL database on Azure. There are a few different options for hosting a PostgreSQL database on Azure, including:</p>
<ul>
<li><p><strong>Azure Database for PostgreSQL</strong>: This is a fully-managed PostgreSQL database service that is built on Azure infrastructure. It is easy to set up and manage and includes features like high availability, automatic backups, and security.</p>
</li>
<li><p><strong>Azure Virtual Machines</strong>: You can also set up a PostgreSQL database on an Azure Virtual Machine (VM). This allows you to have more control over the configuration and management of the database, but requires more work to set up and maintain.</p>
</li>
</ul>
<p>In this article, we will focus on using <strong><em>Azure Database for PostgreSQL</em></strong>, as it is the easiest option for getting started.</p>
<h2 id="heading-using-azure-portal">Using Azure Portal</h2>
<p>To create an Azure Database for PostgreSQL instance, follow these steps:</p>
<ol>
<li><p>Go to the Azure portal and sign in with your Azure account.</p>
</li>
<li><p>Click the "Create a resource" button in the top left corner of the portal.</p>
</li>
<li><p>In the search box, type "Azure Database for PostgreSQL" and press enter.</p>
</li>
<li><p>Click on the "Azure Database for PostgreSQL" option that appears in the search results.</p>
</li>
<li><p>Click the "Create" button to start the creation process.</p>
</li>
<li><p>Fill out the form with the necessary information for your database, including the server name, resource group, and location. Make sure to choose "Flexible Server" as the deployment option.</p>
</li>
<li><p>Click the "Create" button to create the database.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672903878508/bc49cad7-36d9-4db0-89eb-485b941d07f4.png" alt class="image--center mx-auto" /></p>
<p> Once done click on create the below picture will appear</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672904146068/54ca93ad-1e8c-409e-9f58-543bd90bd2aa.png" alt class="image--center mx-auto" /></p>
</li>
</ol>
<p>It may take a few minutes for the database to be created. Once it is ready, you will see it listed in the Azure portal under the "All resources" section.</p>
<h2 id="heading-using-azure-cli">Using Azure CLI</h2>
<pre><code class="lang-bash"><span class="hljs-built_in">export</span> AZ_RESOURCE_GROUP=codingsaint
<span class="hljs-built_in">export</span> AZ_DATABASE_SERVER_NAME=codingsaintdb
<span class="hljs-built_in">export</span> AZ_DATABASE_NAME=superhero
<span class="hljs-built_in">export</span> AZ_LOCATION=eastus
<span class="hljs-built_in">export</span> AZ_POSTGRESQL_AD_NON_ADMIN_USERNAME=codingsaint
<span class="hljs-built_in">export</span> AZ_LOCAL_IP_ADDRESS=&lt;YOUR_IP_ADDRESS&gt;
<span class="hljs-built_in">export</span> CURRENT_USERNAME=$(az ad signed-in-user show --query userPrincipalName -o tsv)
</code></pre>
<p>Now, Let's add create the DB server</p>
<pre><code class="lang-bash">az postgres flexible-server create --resource-group <span class="hljs-variable">$AZ_RESOURCE_GROUP</span> --name <span class="hljs-variable">$AZ_DATABASE_SERVER_NAME</span> --location <span class="hljs-variable">$AZ_LOCATION</span> --yes --output tsv
</code></pre>
<p>This will give the output as below , it contains userid and password for database, do note it.</p>
<pre><code class="lang-bash">Checking the existence of the resource group <span class="hljs-string">'codingsaint'</span>...
Resource group <span class="hljs-string">'codingsaint'</span> exists ? : True 
Detected current client IP : 101.0.63.192
Creating PostgreSQL Server <span class="hljs-string">'codingsaintdb'</span> <span class="hljs-keyword">in</span> group <span class="hljs-string">'codingsaint'</span>...
Your server <span class="hljs-string">'codingsaintdb'</span> is using sku <span class="hljs-string">'Standard_D2s_v3'</span> (Paid Tier). Please refer to https://aka.ms/postgres-pricing <span class="hljs-keyword">for</span> pricing details
Configuring server firewall rule to accept connections from <span class="hljs-string">'101.0.63.192'</span>...
Creating PostgreSQL database <span class="hljs-string">'flexibleserverdb'</span>...
Make a note of your password. If you forget, you would have to reset your password with <span class="hljs-string">"az postgres flexible-server update -n codingsaintdb -g codingsaint -p &lt;new-password&gt;"</span>.
Try using <span class="hljs-string">'az postgres flexible-server connect'</span> <span class="hljs-built_in">command</span> to <span class="hljs-built_in">test</span> out connection.
postgresql://puzzledpie9:Yv9GFa2gVPXXHTvQ1nyJfA@codingsaintdb.postgres.database.azure.com/postgres?sslmode=require    flexibleserverdb    FirewallIPAddress_2023-1-23_7-6-2    codingsaintdb.postgres.database.azure.com    /subscriptions/29f6fde1-6736-4a36-b820-c879ba4868d1/resourceGroups/codingsaint/providers/Microsoft.DBforPostgreSQL/flexibleServers/codingsaintdb    East US    Yv9GFa2gVPXXHTvQ1nyJfA    codingsaint    Standard_D2s_v3        puzzledpie9    13
</code></pre>
<p>Once Server is created let's create a database on the server. As we have added the export commands in the previous step, we will create a database name superhero for our application</p>
<pre><code class="lang-bash">az postgres flexible-server db create  --resource-group <span class="hljs-variable">$AZ_RESOURCE_GROUP</span> --database-name <span class="hljs-variable">$AZ_DATABASE_NAME</span> --server-name <span class="hljs-variable">$AZ_DATABASE_SERVER_NAME</span> --output tsv
</code></pre>
<p>This will create a database for our application. Now we need to provide network access to the database. The command below will help us to create it.</p>
<h3 id="heading-using-postgresql-with-the-spring-data-jpa-module"><strong>Using PostgreSQL with the Spring Data JPA module</strong></h3>
<p>Connecting to the PostgreSQL database from a Spring Azure App</p>
<p>Now that you have a PostgreSQL database on Azure, you can start building a Spring Azure App that connects to it.</p>
<p>To connect to the PostgreSQL database from a Spring Azure App, you will need to do the following:</p>
<ol>
<li>Add the PostgreSQL JDBC driver dependency to your project. You can do this by adding the following dependency to your <code>pom.xml</code> file:</li>
</ol>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-starter-data-jdbc<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-starter-data-jpa<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>com.azure.spring<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-cloud-azure-starter-jdbc-postgresql<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.postgresql<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>postgresql<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">scope</span>&gt;</span>runtime<span class="hljs-tag">&lt;/<span class="hljs-name">scope</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>com.azure.spring<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-cloud-azure-starter<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
</code></pre>
<p>Update application.properties with parameters recieved while creating DB</p>
<pre><code class="lang-plaintext">logging.level.org.springframework.jdbc.core=DEBUG

spring.datasource.url=jdbc:postgresql://codingsaintdb.postgres.database.azure.com/postgres?sslmode=require

spring.datasource.username=puzzledpie9
spring.datasource.password=Yv9GFa2gVPXXHTvQ1nyJfA
#spring.datasource.azure.passwordless-enabled=true
spring.jpa.show-sql=true
spring.sql.init.mode=always
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect

# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = create-drop
</code></pre>
<p>Lets create an entity for superhero</p>
<h2 id="heading-entity">Entity</h2>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> com.kp.superhero;

<span class="hljs-keyword">import</span> lombok.AllArgsConstructor;
<span class="hljs-keyword">import</span> lombok.Data;
<span class="hljs-keyword">import</span> lombok.NoArgsConstructor;

<span class="hljs-keyword">import</span> javax.persistence.Entity;
<span class="hljs-keyword">import</span> javax.persistence.Id;

<span class="hljs-meta">@Entity</span>
<span class="hljs-meta">@AllArgsConstructor</span>
<span class="hljs-meta">@NoArgsConstructor</span>
<span class="hljs-meta">@Data</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Superhero</span> </span>{

    <span class="hljs-meta">@Id</span>
    <span class="hljs-keyword">private</span> String id;
    <span class="hljs-keyword">private</span> String name;
    <span class="hljs-keyword">private</span> String power;
}
</code></pre>
<h2 id="heading-repository">Repository</h2>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> com.kp.superhero;

<span class="hljs-keyword">import</span> org.springframework.data.repository.CrudRepository;
<span class="hljs-keyword">import</span> org.springframework.stereotype.Repository;

<span class="hljs-meta">@Repository</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">SuperheroRepository</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">CrudRepository</span>&lt; <span class="hljs-title">Superhero</span>,<span class="hljs-title">String</span>&gt; </span>{
}
</code></pre>
<h3 id="heading-controller">Controller</h3>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> com.kp.superhero;

<span class="hljs-keyword">import</span> org.springframework.http.HttpStatus;
<span class="hljs-keyword">import</span> org.springframework.http.ResponseEntity;
<span class="hljs-keyword">import</span> org.springframework.web.bind.annotation.*;

<span class="hljs-meta">@RestController</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SuperheroController</span> </span>{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> SuperheroRepository superheroRepository;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">SuperheroController</span><span class="hljs-params">(SuperheroRepository superheroRepository)</span> </span>{
        <span class="hljs-keyword">this</span>.superheroRepository = superheroRepository;
    }

    <span class="hljs-meta">@PostMapping("/superhero")</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> ResponseEntity&lt;Superhero&gt; <span class="hljs-title">add</span><span class="hljs-params">(<span class="hljs-meta">@RequestBody</span> Superhero superhero)</span></span>{
        <span class="hljs-keyword">var</span> sh= superheroRepository.save(superhero);
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> ResponseEntity&lt;&gt;(sh, HttpStatus.CREATED);
    }
    <span class="hljs-meta">@GetMapping("superhero/{id}")</span>
    <span class="hljs-function"><span class="hljs-keyword">private</span> Superhero <span class="hljs-title">getSuperhero</span><span class="hljs-params">(<span class="hljs-meta">@PathVariable("id")</span> String id)</span></span>{
        <span class="hljs-keyword">return</span> superheroRepository.findById(id).get();
    }
}
</code></pre>
<p>Now we can start the server and check if everything works</p>
<p>Once server is started use postman or curl to validate</p>
<pre><code class="lang-bash">curl --location --request POST <span class="hljs-string">'localhost:8080/superhero'</span> \
--header <span class="hljs-string">'Content-Type: application/json'</span> \
--data-raw <span class="hljs-string">'{
    "id":"01",
    "name": "codingsaint",
    "power": "Bug Killer"
}'</span>
{<span class="hljs-string">"id"</span>:<span class="hljs-string">"01"</span>,<span class="hljs-string">"name"</span>:<span class="hljs-string">"codingsaint"</span>,<span class="hljs-string">"power"</span>:<span class="hljs-string">"Bug Killer"</span>}
</code></pre>
<p>This will return the inserted Superhero to Azure DB. We can use the get URL to retrieve it to validate the insert .</p>
<pre><code class="lang-bash">curl --location --request GET <span class="hljs-string">'localhost:8080/superhero/01'</span>
{<span class="hljs-string">"id"</span>:<span class="hljs-string">"01"</span>,<span class="hljs-string">"name"</span>:<span class="hljs-string">"codingsaint"</span>,<span class="hljs-string">"power"</span>:<span class="hljs-string">"Bug Killer"</span>}
</code></pre>
<h3 id="heading-deploying-a-spring-azure-app-with-postgresql-to-azure"><strong>Deploying a Spring Azure App with PostgreSQL to Azure</strong></h3>
<p>Create a superhero app exactly as we did in last article using web console and enable</p>
<p>URL by assigning endpoint https://blog.pallav.dev/first-spring-boot-app-at-azure-spring-app-and-github-action</p>
<p>To deploy we will use the below command from the target directory where the jar file is located after the maven build.</p>
<pre><code class="lang-bash">az spring app deploy -n superhero -g codingsaint -s codingsaintsvc --artifact-path superhero-0.0.1-SNAPSHOT.jar
</code></pre>
<p>Once done we can check via POSTMAN</p>
]]></content:encoded></item><item><title><![CDATA[1962. Remove Stones to Minimize the Total]]></title><description><![CDATA[To solve the question you can visit the following link The question is asking us to do one operation at a time, the operation is simply to reduce the…]]></description><link>https://digitalyogi.hashnode.dev/1962-remove-stones-to-minimize-the-total</link><guid isPermaLink="true">https://digitalyogi.hashnode.dev/1962-remove-stones-to-minimize-the-total</guid><category><![CDATA[leetcode]]></category><category><![CDATA[leetcodedaily]]></category><category><![CDATA[leetcode-solution]]></category><category><![CDATA[DSA]]></category><dc:creator><![CDATA[DigitalYogi]]></dc:creator><pubDate>Wed, 28 Dec 2022 07:13:18 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/4e0edfced11b84d0ae5d5bd7d031ef56.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>To solve the question you can visit the following link</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://leetcode.com/problems/remove-stones-to-minimize-the-total/">https://leetcode.com/problems/remove-stones-to-minimize-the-total/</a></div>
<p> </p>
<h2 id="heading-explanation">Explanation</h2>
<p>The question is asking us to do one operation at a time, the operation is simply to reduce the number of piles to half. We can do at most K operations. We wan't to operate in a way that we minimize the number of piles after K operation.</p>
<p>We need to remove the maximum number of possible stones from the pipes which also means we need to operate on the maximum number of stones at any pile at any given time. The piles are kept in an unordered way which should be sorted but the problem with sorting the pile is that after removing the half, the pile will again become unsorted. So after each removal, we need to know which Pile has the maximum number of stones present.</p>
<p>The Data structure which can keep the max element always at the top is Max Heap. Let's look at the approach to solving it using Max Heap</p>
<h2 id="heading-approach">Approach</h2>
<p>We will put the elements (piles) on a Max Heap. At top of the max heap, we will have the pile with most of the elements. We will remove half of the pile, We will add half of the pile back to Max Heap.</p>
<p>We will keep doing the operation K times, whatever is left on the queue, the sum of it is our answer.</p>
<h2 id="heading-code">Code</h2>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">minStoneSum</span><span class="hljs-params">(<span class="hljs-keyword">int</span>[] piles, <span class="hljs-keyword">int</span> k)</span> </span>{
<span class="hljs-comment">//Create a PriorityQueue</span>
    PriorityQueue&lt;Integer&gt; pq = <span class="hljs-keyword">new</span> PriorityQueue&lt;Integer&gt;((a, b) -&gt; b - a);
<span class="hljs-comment">// Add all elements to PriorityQueue</span>
         <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> num: piles)
            pq.add(num);        
     <span class="hljs-comment">//Iterate for K times and half the number of piles at top    </span>
        <span class="hljs-keyword">while</span>(k!=<span class="hljs-number">0</span>){
             <span class="hljs-keyword">int</span> top= pq.poll();
            pq.add((<span class="hljs-keyword">int</span>) Math.ceil((<span class="hljs-keyword">float</span>)top/<span class="hljs-number">2</span> ));
            k--;
        }
        <span class="hljs-keyword">int</span> result=<span class="hljs-number">0</span>;
<span class="hljs-comment">// Sum of remaining is our answer.</span>
        <span class="hljs-keyword">while</span>(!pq.isEmpty()){
            result+=pq.remove();
        }
    <span class="hljs-keyword">return</span> result;
    }
}
</code></pre>
]]></content:encoded></item><item><title><![CDATA[First Spring Boot App at Azure Spring App and GitHub Action]]></title><description><![CDATA[In this tutorial, we will look at deploying our app at Spring Azure app. Spring Azure App is an Azure offering to seamlessly deploy Spring boot…]]></description><link>https://digitalyogi.hashnode.dev/first-spring-boot-app-at-azure-spring-app-and-github-action</link><guid isPermaLink="true">https://digitalyogi.hashnode.dev/first-spring-boot-app-at-azure-spring-app-and-github-action</guid><category><![CDATA[Azure]]></category><category><![CDATA[Springboot]]></category><category><![CDATA[GitHub]]></category><dc:creator><![CDATA[DigitalYogi]]></dc:creator><pubDate>Fri, 23 Dec 2022 15:46:31 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1671810313747/d323aaaf-a524-4b84-b930-34eea54e410f.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this tutorial, we will look at deploying our app at Spring Azure app. Spring Azure App is an Azure offering to seamlessly deploy Spring boot microservices at Azure. For this article, we hope you have an active Azure subscription. At the time of writing this article, Azure provides a one-year subscription free of cost.</p>
<h1 id="heading-agenda">Agenda</h1>
<ul>
<li><p>Create a spring boot app and add a hello endpoint</p>
</li>
<li><p>Create Resource Group, Service and App at Azure Portal</p>
</li>
<li><p>Deploy Application at Azure using Command Line (Azure cli)</p>
</li>
<li><p>Use GitHub Action to deploy on Azure</p>
</li>
</ul>
<p>If you want to follow the video tutorial of the app you can use it at Youtube below.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.youtube.com/watch?v=uliQ37J8jU4">https://www.youtube.com/watch?v=uliQ37J8jU4</a></div>
<p> </p>
<h3 id="heading-create-a-spring-boot-app-and-add-a-hello-endpoint">Create a spring boot app and add a hello endpoint</h3>
<p>We will use <a target="_blank" href="https://start.spring.io">https://start.spring.io</a> . We are using maven as the build tool and 2.7.6 as version . We will use Java 17 as our Java version. Add web dependency and hit download.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1671804920603/9e68acdb-b822-4073-9a44-67aa3a0f7572.png" alt class="image--center mx-auto" /></p>
<p>Open the project in your favourite IDE, We are using IntelliJ. Add the Hello endpoint and run the project.</p>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> com.kp.springdemo;

<span class="hljs-keyword">import</span> org.springframework.boot.SpringApplication;
<span class="hljs-keyword">import</span> org.springframework.boot.autoconfigure.SpringBootApplication;
<span class="hljs-keyword">import</span> org.springframework.web.bind.annotation.GetMapping;
<span class="hljs-keyword">import</span> org.springframework.web.bind.annotation.PathVariable;
<span class="hljs-keyword">import</span> org.springframework.web.bind.annotation.RestController;

<span class="hljs-meta">@SpringBootApplication</span>
<span class="hljs-meta">@RestController</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SpringdemoApplication</span> </span>{

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        SpringApplication.run(SpringdemoApplication.class, args);
    }
    <span class="hljs-meta">@GetMapping("hello/{name}")</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span>  String <span class="hljs-title">hello</span><span class="hljs-params">(<span class="hljs-meta">@PathVariable</span> (<span class="hljs-string">"name"</span>)</span>  String name)</span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Hello "</span>+name +<span class="hljs-string">" from Azure"</span>;
    }
}
</code></pre>
<p>Now we can run the project and verify if everything is working as expected. We can check with http://localhost:8080/hello/Kumar in browser , it should return <code>Hello Kumar from Azure</code></p>
<p>Build the project using <code>mvn clean package</code> , and it will keep generate the war file at the target folder inside your project.</p>
<h2 id="heading-create-resource-group-service-and-app-at-azure-portal">Create Resource Group, Service and App at Azure Portal</h2>
<p>Login to the azure portal and click on resource group, add a resource group.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1671805568130/1223fbed-0e1b-41d7-920b-81c060e3abbf.png" alt class="image--center mx-auto" /></p>
<p>If you wish you can use Azure cli to do same . Use the following command.</p>
<pre><code class="lang-bash">az group create --resource-group &lt;YOUR_RESOURCE_GROUP_NAME&gt;  --location eastus
</code></pre>
<p>Once created we will add Spring Azure Service inside this resource group so that we can create Spring application inside the service.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1671805845945/5d501afc-7e6c-42a8-9c58-d38e6d677568.png" alt class="image--center mx-auto" /></p>
<p>Alternatively following command can be used at Azure cli.</p>
<pre><code class="lang-bash">az spring spring create   --resource-group  &lt;YOUR_RESOURCE_GROUP_NAME&gt;  --name &lt;YOUR_SPRING_AZURE_SERVICE_NAME&gt;
</code></pre>
<p>Now we can create a Spring App inside the service. Azure will deploy a sample Spring app. We will replace the app with thw one we have coded.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1671806386691/a7ba4f73-3598-4d88-a028-a92d91c6f2d2.png" alt class="image--center mx-auto" /></p>
<p>Once deployment is complete it will have a app as shown in picture</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1671808704360/5cd45681-e8ab-434d-a18c-9fe88012eec8.png" alt class="image--center mx-auto" /></p>
<p>Alternatively, we can create this all using Azure CLI.</p>
<pre><code class="lang-bash">az spring app create &lt;YOUR_RESOURCE_GROUP_NAME&gt;  --name &lt;YOUR_SPRING_AZURE_SERVICE_NAME&gt;  --name &lt;YOUR_SPRING_AAPP_NAME&gt;  --assign-endpoint <span class="hljs-literal">true</span>
</code></pre>
<h2 id="heading-deploy-application-at-azure-using-command-line-azure-cli">Deploy Application at Azure using Command Line (Azure cli)</h2>
<p>Now let us go to the target folder where our jar file is created while building via maven. We will run the following command to deploy the app. It will deploy our app rather the sample spring azure app.</p>
<pre><code class="lang-bash">az spring app deploy -n springdemo -g codingsaint -s codingsaintsvc --artifact-path springdemo-0.0.1-SNAPSHOT.jar
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1671809116479/1e989fb7-f449-4125-af96-1bfaa0b6f7ef.png" alt class="image--center mx-auto" /></p>
<p>We can go to the assigned endpoint and check the deployed app. At present the URL (if assigned , you can see "Assign URL" link when you login to Azure and check your app) gets created as https://YOUR_SERVICENAME-YOUR_APPNAME.azuremicroservices.io .</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1671809166025/41b0c323-dc7f-425f-90f1-0ce304d3cfba.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-use-github-action-to-deploy-on-azure">Use GitHub Action to deploy on Azure</h2>
<p>It is not ideal to run deploy command every time we deploy. Let's use Github Action to deploy</p>
<p>Create .github folder inside source code , inside this folder create a workflow folder. Add Azure deployment yaml inside it.</p>
<pre><code class="lang-yaml"><span class="hljs-attr">name:</span> <span class="hljs-string">AZSpringDemo</span>
<span class="hljs-attr">on:</span> <span class="hljs-string">push</span>
<span class="hljs-attr">env:</span>
  <span class="hljs-attr">ASC_PACKAGE_PATH:</span> <span class="hljs-string">${{</span> <span class="hljs-string">github.workspace</span> <span class="hljs-string">}}</span>
  <span class="hljs-attr">JAVA_VERSION:</span> <span class="hljs-number">17</span>
  <span class="hljs-attr">AZURE_SUBSCRIPTION:</span> <span class="hljs-string">29f6fde1-6736-4a36-b820-c879ba4868d1</span>

<span class="hljs-attr">jobs:</span>
  <span class="hljs-attr">deploy_to_production:</span>
    <span class="hljs-attr">runs-on:</span> <span class="hljs-string">ubuntu-latest</span>
    <span class="hljs-attr">name:</span> <span class="hljs-string">deploy</span> <span class="hljs-string">to</span> <span class="hljs-string">production</span> <span class="hljs-string">with</span> <span class="hljs-string">artifact</span>
    <span class="hljs-attr">steps:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Checkout</span> <span class="hljs-string">Github</span> <span class="hljs-string">Action</span>
        <span class="hljs-attr">uses:</span> <span class="hljs-string">actions/checkout@v2</span>

      <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Set</span> <span class="hljs-string">up</span> <span class="hljs-string">JDK</span> <span class="hljs-string">${{</span> <span class="hljs-string">env.JAVA_VERSION</span> <span class="hljs-string">}}</span>
        <span class="hljs-attr">uses:</span> <span class="hljs-string">actions/setup-java@v1</span>
        <span class="hljs-attr">with:</span>
          <span class="hljs-attr">java-version:</span> <span class="hljs-string">${{</span> <span class="hljs-string">env.JAVA_VERSION</span> <span class="hljs-string">}}</span>

      <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">maven</span> <span class="hljs-string">build,</span> <span class="hljs-string">clean</span>
        <span class="hljs-attr">run:</span> <span class="hljs-string">|
          mvn clean package -DskipTests
</span>      <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Login</span> <span class="hljs-string">via</span> <span class="hljs-string">Azure</span> <span class="hljs-string">CLI</span>
        <span class="hljs-attr">uses:</span> <span class="hljs-string">azure/login@v1</span>
        <span class="hljs-attr">with:</span>
          <span class="hljs-attr">creds:</span> <span class="hljs-string">${{</span> <span class="hljs-string">secrets.AZURE_CREDENTIALS</span> <span class="hljs-string">}}</span>

      <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">deploy</span> <span class="hljs-string">to</span> <span class="hljs-string">production</span> <span class="hljs-string">with</span> <span class="hljs-string">artifact</span>
        <span class="hljs-attr">uses:</span> <span class="hljs-string">azure/spring-cloud-deploy@v1</span>
        <span class="hljs-attr">with:</span>
          <span class="hljs-attr">azure-subscription:</span> <span class="hljs-string">${{</span> <span class="hljs-string">env.AZURE_SUBSCRIPTION</span> <span class="hljs-string">}}</span>
          <span class="hljs-attr">action:</span> <span class="hljs-string">Deploy</span>
          <span class="hljs-attr">service-name:</span> <span class="hljs-string">codingsaintsvc</span>
          <span class="hljs-attr">app-name:</span> <span class="hljs-string">springdemo</span>
          <span class="hljs-attr">use-staging-deployment:</span> <span class="hljs-literal">false</span>
          <span class="hljs-attr">package:</span> <span class="hljs-string">${{</span> <span class="hljs-string">env.ASC_PACKAGE_PATH</span> <span class="hljs-string">}}/**/*.jar</span>
</code></pre>
<p>The YAML has name of the app and the service under which it is deployed. It also has a command under <code>run</code> to build the application. We need to add AZURE_CREDENTIAL so that whenever we push code to git, it logs in to the Azure portal and deploys our app.</p>
<p>Run the following command at azure cli to create Authentication to be used for github.  </p>
<pre><code class="lang-bash">az ad sp create-for-rbac --name <span class="hljs-string">"CICD"</span> --role contributor \ --scopes /subscriptions/{SUBSCRIPTION_ID/resourceGroups/{YOUR_RESOURCE_GROUP_NAME} \ --sdk-auth
</code></pre>
<p>This will generate the JSON. Copy it.</p>
<p>Log in to Github , and create a repository to push our code. Go to Setting Tab. Under Settings go to secret and Add AZURE_CREDENTIAL inside it.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1671809859340/5d88eb7c-dbd4-4715-aaf4-b795554433f1.png" alt class="image--center mx-auto" /></p>
<p>Now we can save to JSON generated while running the command. Now we can commit our code to it. As the YAML for pipeline suggest it should trigger the build for you.</p>
<p>You can verify the build under Action tab.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1671810046139/00e10c7d-d4f3-4410-9205-6699b2fd310d.png" alt class="image--center mx-auto" /></p>
<p>If everything goes fine it will deploy the app at azure.</p>
]]></content:encoded></item><item><title><![CDATA[378. Kth Smallest Element in a Sorted Matrix]]></title><description><![CDATA[Let's discuss today the problem 378. Kth Smallest Element in a Sorted Matrix at leetcode. Problem link]]></description><link>https://digitalyogi.hashnode.dev/378-kth-smallest-element-in-a-sorted-matrix</link><guid isPermaLink="true">https://digitalyogi.hashnode.dev/378-kth-smallest-element-in-a-sorted-matrix</guid><category><![CDATA[leetcode]]></category><category><![CDATA[algorithms]]></category><category><![CDATA[data structures]]></category><category><![CDATA[Binary Search Algorithm]]></category><dc:creator><![CDATA[DigitalYogi]]></dc:creator><pubDate>Tue, 16 Aug 2022 18:40:56 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/xG8IQMqMITM/upload/v1660675186289/q47I4309gE.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Let's discuss today the problem <em>378. Kth Smallest Element in a Sorted Matrix</em> at leetcode. 
Problem link <a target="_blank" href="https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/">https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/</a></p>
<p>The example in question has following</p>
<pre><code><span class="hljs-attr">Input:</span> <span class="hljs-string">matrix</span> <span class="hljs-string">=</span> [
[<span class="hljs-number">1</span>,<span class="hljs-number">5</span>,<span class="hljs-number">9</span>]
[<span class="hljs-number">10</span>,<span class="hljs-number">11</span>,<span class="hljs-number">13</span>]
[<span class="hljs-number">12</span>,<span class="hljs-number">13</span>,<span class="hljs-number">15</span>]
]<span class="hljs-string">,</span> <span class="hljs-string">k</span> <span class="hljs-string">=</span> <span class="hljs-number">8</span>
<span class="hljs-attr">Output:</span> <span class="hljs-number">13</span>
</code></pre><p>Explanation: The elements in the matrix are [1,5,9,10,11,12,13,13,15], and the 8th smallest number is 13</p>
<blockquote>
<p>With a simple observation we can understand that the first element will be the smallest number (low) in the matrix and the last number say , high (matrix[n-1][n-1] , n bring length of matrix) will be the highest.</p>
<p>It is clear that question wan't has to find the number before which there are k-1 lower number.  Since the matrix is sorted row and column wise, we need to find how many numbers in each row are bigger than K .</p>
<p> If we find the sum of numbers lower than k in each row we can get the answer.</p>
<p>In any row the smallest is at 0th column and largest element is at n-1 column.</p>
<p>In any column smallest is at 0th row and largest element is at n-1 row.</p>
<p>Number of elements lesser than current element at any place  in the matrix in a row is column number -1 ;</p>
</blockquote>
<p>Since, array is sorted , can we try Binary Search ? Let's see</p>
<p>If the find the mid of high and low , by <code>mid=low+(high-low)/2</code> , it can be present or not present in the matrix, but we can try to see how many are lower than mid. 
If there are lesser number which are smaller than mid, we need to increase lower bound to find more numbers or else decrease the higher bound to remove few numbers. </p>
<p>If we keep finding mid with our binary search , we will find k numbers which are lower than mid.
The position of the mid is the position on required answer, as it will be nothing but the number from the grid.</p>
<pre><code>class Solution {
    <span class="hljs-keyword">int</span>[][] matrix<span class="hljs-operator">=</span>null;
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> kthSmallest(<span class="hljs-keyword">int</span>[][] matrix, <span class="hljs-keyword">int</span> k) {
        <span class="hljs-built_in">this</span>.matrix=matrix;
        <span class="hljs-keyword">int</span> n <span class="hljs-operator">=</span> matrix.<span class="hljs-built_in">length</span>;
        <span class="hljs-keyword">int</span> low <span class="hljs-operator">=</span> matrix[<span class="hljs-number">0</span>][<span class="hljs-number">0</span>];
        <span class="hljs-keyword">int</span> high <span class="hljs-operator">=</span> matrix[n<span class="hljs-number">-1</span>][n<span class="hljs-number">-1</span>];

        <span class="hljs-keyword">while</span>(low<span class="hljs-operator">&lt;</span>high){
            <span class="hljs-keyword">int</span> mid<span class="hljs-operator">=</span>low<span class="hljs-operator">+</span>(high<span class="hljs-operator">-</span>low)<span class="hljs-operator">/</span><span class="hljs-number">2</span>;
            <span class="hljs-keyword">if</span>(lowerThanMid(mid)<span class="hljs-operator">&lt;</span>k){
                low<span class="hljs-operator">=</span>mid<span class="hljs-operator">+</span><span class="hljs-number">1</span>;
            }<span class="hljs-keyword">else</span>{
                high <span class="hljs-operator">=</span>mid;
            }
        }
        <span class="hljs-keyword">return</span> low;
    }

    <span class="hljs-keyword">int</span> lowerThanMid(<span class="hljs-keyword">int</span> target){
        <span class="hljs-keyword">int</span> n<span class="hljs-operator">=</span> matrix.<span class="hljs-built_in">length</span>;
        <span class="hljs-keyword">int</span> i<span class="hljs-operator">=</span>matrix.<span class="hljs-built_in">length</span>-<span class="hljs-number">1</span>;
        <span class="hljs-keyword">int</span> j<span class="hljs-operator">=</span><span class="hljs-number">0</span>;
        <span class="hljs-keyword">int</span> lower<span class="hljs-operator">=</span><span class="hljs-number">0</span>;
        <span class="hljs-keyword">while</span>(i<span class="hljs-operator">&gt;</span><span class="hljs-operator">=</span><span class="hljs-number">0</span> <span class="hljs-operator">&amp;</span><span class="hljs-operator">&amp;</span> j<span class="hljs-operator">&lt;</span>n){
            <span class="hljs-keyword">if</span>(matrix[i][j] <span class="hljs-operator">&gt;</span> target){
                i<span class="hljs-operator">-</span><span class="hljs-operator">-</span>;
            }<span class="hljs-keyword">else</span>{
                j<span class="hljs-operator">+</span><span class="hljs-operator">+</span>;
                lower<span class="hljs-operator">+</span><span class="hljs-operator">=</span>i<span class="hljs-operator">+</span><span class="hljs-number">1</span>;
            }
        }
        <span class="hljs-keyword">return</span> lower;
    }

}
</code></pre>]]></content:encoded></item><item><title><![CDATA[235. Lowest Common Ancestor of a Binary Search Tree]]></title><description><![CDATA[Let's discuss problem no 235 at leetcode i.e 235. Lowest Common Ancestor of a Binary Search Tree. Problem Link:]]></description><link>https://digitalyogi.hashnode.dev/235-lowest-common-ancestor-of-a-binary-search-tree</link><guid isPermaLink="true">https://digitalyogi.hashnode.dev/235-lowest-common-ancestor-of-a-binary-search-tree</guid><category><![CDATA[leetcode]]></category><category><![CDATA[bst]]></category><category><![CDATA[binary search]]></category><category><![CDATA[algorithms]]></category><dc:creator><![CDATA[DigitalYogi]]></dc:creator><pubDate>Fri, 12 Aug 2022 13:37:07 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/FHnnjk1Yj7Y/upload/v1660311526053/NCZztJ2br.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Let's discuss problem no 235 at leetcode i.e 235. Lowest Common Ancestor of a Binary Search Tree.
Problem Link: https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1660311380372/PAHDfbnjn.png" alt="BST.png" />
Here we are supposed to find the lowest common ancestor in a binary search tree. The lowest common ancestor is the node which is the first common ancestor of any given node.</p>
<p>If we look closely there are the following cases.</p>
<ol>
<li>One of the given nodes itself is the common ancestor.</li>
<li>Since it's a BST, all the elements lower to the current node will be on the left side and all the elements higher will be on the right side. which means 
&gt;<ul>
<li>If the current  node value is lesser than both elements, our common ancestor will be on the right side</li>
<li>If the current  node value is greater than both elements, our common ancestor will be on the left side   </li>
<li>If one of the values is higher and another is lower than the current element, it is the ancestor of both elements,  actually this is the lowest common ancestor.</li>
</ul>
</li>
</ol>
<p>Let's check the code for it. </p>
<pre><code>class Solution {
    <span class="hljs-keyword">public</span> TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {

        <span class="hljs-keyword">if</span>(root.val&gt;p.val <span class="hljs-operator">&amp;</span><span class="hljs-operator">&amp;</span> root.val&gt;q.val) 
            <span class="hljs-keyword">return</span> lowestCommonAncestor( root.left , p, q);
        <span class="hljs-keyword">if</span>(root.val&lt;p.val <span class="hljs-operator">&amp;</span><span class="hljs-operator">&amp;</span> root.val&lt;q.val) 
            <span class="hljs-keyword">return</span> lowestCommonAncestor( root.right , p, q);

       <span class="hljs-keyword">return</span> root;


    }
}
</code></pre>]]></content:encoded></item><item><title><![CDATA[Quarkus - Demo Application]]></title><description><![CDATA[Let's create an App which will recommend random quotes from a database. To start , let us generate an app using maven CLI . To run the above project we can…]]></description><link>https://digitalyogi.hashnode.dev/quarkus-demo-application</link><guid isPermaLink="true">https://digitalyogi.hashnode.dev/quarkus-demo-application</guid><category><![CDATA[quarkus]]></category><dc:creator><![CDATA[DigitalYogi]]></dc:creator><pubDate>Thu, 30 Jun 2022 03:22:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/95YRwf6CNw8/upload/v1656559213542/Qrb72k0MS.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-quarkus-demo-application">Quarkus - Demo Application</h1>
<h2 id="heading-creating-first-quarkus-app">Creating first Quarkus app</h2>
<p>Let's create an App which will recommend random quotes from a database. To start , let us generate an app using maven CLI . </p>
<pre><code>mvn io.quarkus.platform:quarkus<span class="hljs-operator">-</span>maven<span class="hljs-operator">-</span>plugin:<span class="hljs-number">2.10</span><span class="hljs-number">.0</span>.Final:create \
    <span class="hljs-operator">-</span>DprojectGroupId<span class="hljs-operator">=</span>dev.pallav \
    <span class="hljs-operator">-</span>DprojectArtifactId<span class="hljs-operator">=</span>quotes\
    <span class="hljs-operator">-</span>Dextensions<span class="hljs-operator">=</span><span class="hljs-string">"resteasy-reactive"</span>
cd quotes
</code></pre><p>To run the above project we can run the simple command and it will start the server at <code>8080</code> port. </p>
<pre><code>
./mvnw quarkus:dev
</code></pre><p>The above step has generated a GreetingResource as default which has an endpoint <code>/hello</code>
GreetingController has below code .</p>
<pre><code><span class="hljs-meta">@Path(<span class="hljs-meta-string">"/hello"</span>)</span>  
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">GreetingResource</span> </span>{  

  <span class="hljs-meta">@GET</span>  
 <span class="hljs-meta">@Produces(MediaType.TEXT_PLAIN)</span>  
  <span class="hljs-keyword">public</span> String hello() {  
  <span class="hljs-keyword">return</span> <span class="hljs-string">"Hello from RESTEasy Reactive"</span>;  
    }  
}
</code></pre><ul>
<li>@Path is annotation for for describing URL path</li>
<li>@GET - invokes the GET endpoint</li>
<li>@Produces - Response type, here its a plain text, other example could be JSON or XML</li>
</ul>
<p>We can use postman or curl to access the endpoint and validate if it works.</p>
<pre><code>[codingsaint@fedora ~]$ curl <span class="hljs-symbol">http:</span>/<span class="hljs-regexp">/localhost:8080/hello</span>
Hello from RESTEasy Reactive
</code></pre><p>This showed how easy was it to create a working project with Quarkus.</p>
<h2 id="heading-injection-of-the-service">Injection of the service</h2>
<p>Let us add more details. We will create QuotesResource will generate random quotes , to start with we will have 5 quotes and let it be picked randomly. We will evolve our system to learn event driven microservices.
Our Quote object will be a simple record with author and quote</p>
<pre><code>package dev.pallav.models;  

<span class="hljs-built_in">public</span> <span class="hljs-type">record</span> <span class="hljs-keyword">Quote</span>(String author, String <span class="hljs-keyword">quote</span>) {  
}
</code></pre><p>Let's create QuoteService </p>
<pre><code>package dev.pallav.service;  

<span class="hljs-keyword">import</span> <span class="hljs-title">dev</span>.<span class="hljs-title">pallav</span>.<span class="hljs-title">models</span>.<span class="hljs-title">Quote</span>;  

<span class="hljs-keyword">import</span> <span class="hljs-title">javax</span>.<span class="hljs-title">enterprise</span>.<span class="hljs-title">context</span>.<span class="hljs-title">ApplicationScoped</span>;  
<span class="hljs-keyword">import</span> <span class="hljs-title">java</span>.<span class="hljs-title">util</span>.<span class="hljs-title">ArrayList</span>;  
<span class="hljs-keyword">import</span> <span class="hljs-title">java</span>.<span class="hljs-title">util</span>.<span class="hljs-title">List</span>;  
<span class="hljs-keyword">import</span> <span class="hljs-title">java</span>.<span class="hljs-title">util</span>.<span class="hljs-title">Random</span>;  

@ApplicationScoped  
<span class="hljs-keyword">public</span> class QuoteService {  
  <span class="hljs-keyword">private</span> List<span class="hljs-operator">&lt;</span>Quote<span class="hljs-operator">&gt;</span> quotes<span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> ArrayList<span class="hljs-operator">&lt;</span><span class="hljs-operator">&gt;</span>();  

    <span class="hljs-keyword">public</span> QuoteService(){  
  Quote q1<span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> Quote(<span class="hljs-string">"Yoda"</span>, <span class="hljs-string">"Do, or do not. There is no try"</span>);  
        Quote q2<span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> Quote(<span class="hljs-string">"Ralph Waldo Emerson"</span>, <span class="hljs-string">"Happiness is a perfume you cannot pour on others without getting a few drops on yourself"</span>);  
        Quote q3<span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> Quote(<span class="hljs-string">"Oliver Holmes"</span>, <span class="hljs-string">"A man may fulfil the object of his existence by asking a question he cannot answer, and attempting a task he cannot achieve."</span>);  
        Quote q4<span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> Quote(<span class="hljs-string">"Napoleon Hill"</span>, <span class="hljs-string">"Opportunity often comes disguised in the form of misfortune, or temporary defeat"</span>);  
        Quote q5<span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> Quote(<span class="hljs-string">"Mahatma Gandhi"</span>, <span class="hljs-string">"Our greatness lies not so much in being able to remake the world as being able to remake ourselves"</span>);  
        quotes.addAll(List.of(q1,q2,q3,q4,q5));  
    }  

  <span class="hljs-keyword">public</span> Quote quote(){  
  Random random<span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> Random();  
        <span class="hljs-keyword">return</span> quotes.get(random.nextInt(quotes.size()));  
    }  

}
</code></pre><ul>
<li><code>@ApplicationScoped</code> - Let container know that bean is application scoped</li>
<li><code>QuoteService</code> constructor - initialize List of Quotes acting as  temporary database</li>
<li><code>quote</code> method pick a random quote
Since we want a RESTful endpoint with json output , let's add jackson support with dependency in pom.xml . </li>
</ul>
<pre><code><span class="hljs-operator">&lt;</span><span class="hljs-operator">!</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span> Jackson <span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">&gt;</span>  
<span class="hljs-operator">&lt;</span>dependency<span class="hljs-operator">&gt;</span>  
 <span class="hljs-operator">&lt;</span>groupId<span class="hljs-operator">&gt;</span>io.quarkus&lt;<span class="hljs-operator">/</span>groupId<span class="hljs-operator">&gt;</span>  
 <span class="hljs-operator">&lt;</span>artifactId<span class="hljs-operator">&gt;</span>quarkus<span class="hljs-operator">-</span>resteasy<span class="hljs-operator">-</span>reactive<span class="hljs-operator">-</span>jackson<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>artifactId<span class="hljs-operator">&gt;</span>  
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>dependency<span class="hljs-operator">&gt;</span>
</code></pre><p>Not we can create the endpoint and invoke <code>QuoteService</code> to get a random quote.</p>
<pre><code>package dev.pallav;  

<span class="hljs-keyword">import</span> <span class="hljs-title">dev</span>.<span class="hljs-title">pallav</span>.<span class="hljs-title">models</span>.<span class="hljs-title">Quote</span>;  
<span class="hljs-keyword">import</span> <span class="hljs-title">dev</span>.<span class="hljs-title">pallav</span>.<span class="hljs-title">service</span>.<span class="hljs-title">QuoteService</span>;  

<span class="hljs-keyword">import</span> <span class="hljs-title">javax</span>.<span class="hljs-title">print</span>.<span class="hljs-title">attribute</span>.<span class="hljs-title">standard</span>.<span class="hljs-title">Media</span>;  
<span class="hljs-keyword">import</span> <span class="hljs-title">javax</span>.<span class="hljs-title">ws</span>.<span class="hljs-title">rs</span>.<span class="hljs-title">GET</span>;  
<span class="hljs-keyword">import</span> <span class="hljs-title">javax</span>.<span class="hljs-title">ws</span>.<span class="hljs-title">rs</span>.<span class="hljs-title">Path</span>;  
<span class="hljs-keyword">import</span> <span class="hljs-title">javax</span>.<span class="hljs-title">ws</span>.<span class="hljs-title">rs</span>.<span class="hljs-title">Produces</span>;  
<span class="hljs-keyword">import</span> <span class="hljs-title">javax</span>.<span class="hljs-title">ws</span>.<span class="hljs-title">rs</span>.<span class="hljs-title">core</span>.<span class="hljs-title">MediaType</span>;  

@Path(<span class="hljs-string">"quote"</span>)  
<span class="hljs-keyword">public</span> class QuoteResource {  

  <span class="hljs-keyword">private</span> final QuoteService quoteService;  

    <span class="hljs-keyword">public</span> QuoteResource(QuoteService quoteService) {  
  <span class="hljs-built_in">this</span>.quoteService <span class="hljs-operator">=</span> quoteService;  
    }  

  @GET  
 @Produces(MediaType.APPLICATION_JSON)  
  <span class="hljs-keyword">public</span> Quote quote(){  
  <span class="hljs-keyword">return</span> quoteService.quote();  
    }  
}
</code></pre><ul>
<li>You can see the <code>MediaType.APPLICATION_JSON</code> with <code>@Produces</code> annotation to let endpoint produce a JSON response
Let's run the application and validate  our service, We can curl to validate or use any client as postman<pre><code>curl http://localhost:<span class="hljs-number">8080</span>/<span class="hljs-keyword">quote</span>
{"author":"Ralph Waldo Emerson","quote":"Happiness is a perfume you cannot pour on others without getting a few drops on yourself"}
</code></pre></li>
</ul>
<p>In this article we created a Sample Quarkus Application and learn how to inject (Constructor Injection) a service . In next article we will add a database support and a POST endpoint to add quotes at database.</p>
]]></content:encoded></item><item><title><![CDATA[Why & How I automated Wordle]]></title><description><![CDATA[Wordle has taken over the world trend. I feel the simple interface and no extra advertisement have made it successful. Without advertisements, you can…]]></description><link>https://digitalyogi.hashnode.dev/why-and-how-i-automated-wordle</link><guid isPermaLink="true">https://digitalyogi.hashnode.dev/why-and-how-i-automated-wordle</guid><category><![CDATA[Java]]></category><category><![CDATA[automation]]></category><dc:creator><![CDATA[DigitalYogi]]></dc:creator><pubDate>Sun, 06 Feb 2022 13:27:27 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1644154039491/DBBAFc_3r.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Wordle has taken over the world trend. I feel the simple interface and no extra advertisement have made it successful. Without advertisements, you can focus on the problem, and each answer you give acts as a clue for the next one.</p>
<p> More than being an interesting game it is unique problem as a programmer. The problem has already been solved over the years but yet a good exercise to practice filters.  If you are not aware of the wordle game let’s look at its rules and understand the game first.</p>
<h2 id="heading-what-is-wordle">What is Wordle</h2>
<p>A simple game, where you have to guess 5 letter words in 6 attempts. Once you enter the first guess word, there are two possibility </p>
<ul>
<li>You guessed the correct word.</li>
<li>You guessed the wrong word.</li>
</ul>
<p>If you guessed the correct one, the game is over for the day. You can come again the next day and try a new word to guess.</p>
<p>If you guessed wrong, there are 3 possibilities again</p>
<ul>
<li>Character in present and at the <strong>correct</strong> place</li>
<li>Character is <strong>present</strong> but in the wrong place</li>
<li>Character is not <strong>absent</strong> in the word</li>
</ul>
<p>The above three are the clue for you to guess the next word. You can play the game at <a target="_blank" href="https://www.powerlanguage.co.uk/wordle/">https://www.powerlanguage.co.uk/wordle/</a></p>
<p>Below is a working video of my code </p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://youtu.be/Q1omD5VPLPY">https://youtu.be/Q1omD5VPLPY</a></div>
<p>If you just want to use it, you can go to https://github.com/CODINGSAINT/wordle-solver,  and clone the repo</p>
<p>It requires</p>
<ul>
<li>Java 17</li>
<li>maven</li>
</ul>
<h3 id="heading-run-it">run it</h3>
<p>With Java 17+ and maven installed, run the following commands for magic</p>
<pre><code>mvn clean install 

java <span class="hljs-operator">-</span>jar .\target\wordle<span class="hljs-number">-1.0</span><span class="hljs-operator">-</span>SNAPSHOT<span class="hljs-operator">-</span>jar<span class="hljs-operator">-</span>with<span class="hljs-operator">-</span>dependencies.jar
</code></pre><h2 id="heading-how-to-solve-it">How to solve it</h2>
<p>We require the list of 5 letter words as database. Now if we see the pseudo code , it should be as following</p>
<pre><code class="lang-powershell">1. while (correct word is found){
2.  pick a random word from database
3. evaluate word
4.    if not correct 
        5.     filter words 
                5.a    - remove all of the words whose character are not present in database
                5.b    - pick all words has the present character from current word
                5.c    - pick those whose character are at correct place
                5.d    - update words database
            go to step 2
        if word is correct exit            

}
</code></pre>
<p>I wanted to solve it , so I looked at my go-to language, java - You can use any language of your choice, all you require is a framework that can open a web browser and key in for your tests. I have used Microsoft <code>Playwright</code>. </p>
<p>Let's create 3 important buckets for keeping present characters, absent characters, and a map for position and characters at a place</p>
<pre><code class="lang-java"><span class="hljs-keyword">static</span> List&lt;Character&gt; notPresent =newArrayList&lt;&gt;();
<span class="hljs-keyword">static</span> List&lt;Character&gt; present =newArrayList&lt;&gt;();
<span class="hljs-keyword">static</span> Map&lt;Integer, Character&gt; atPos =newHashMap&lt;&gt;();
</code></pre>
<p>Let’s look at the  most important filter logic below</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">static</span> Predicate&lt;String&gt; <span class="hljs-title">filter</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">//Remove all present fom notPresent and contails - Because of double letter words</span>
        notPresent.removeAll(present);
        notPresent.removeAll(atPos.values());
    <span class="hljs-keyword">return</span> s -&gt; {
            <span class="hljs-keyword">boolean</span> np = notPresent.stream().allMatch(character -&gt; s.indexOf(character) &lt; <span class="hljs-number">0</span>);
            <span class="hljs-keyword">if</span> (!np) <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;
            <span class="hljs-keyword">boolean</span> p = present.stream().allMatch(character -&gt; s.indexOf(character) &gt;= <span class="hljs-number">0</span>);
            <span class="hljs-keyword">if</span> (!p) <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;
            Boolean positionVerified = <span class="hljs-keyword">true</span>;
            Set&lt;Integer&gt; set = atPos.keySet();
            <span class="hljs-keyword">for</span> (Integer pos : set) {
                <span class="hljs-keyword">if</span> (s.charAt(pos) != atPos.get(pos)) {
                    <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;
                }
            }
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">true</span>;
        };
    }
</code></pre>
<p>We need to evaluate each word from the list of words and update our Lists of notPresent, present, and map of position and character. </p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">static</span> Integer <span class="hljs-title">evaluate</span><span class="hljs-params">(Page page, String word, <span class="hljs-keyword">int</span> row)</span> </span>{

        <span class="hljs-keyword">var</span> elements = page.querySelectorAll(<span class="hljs-string">"#board game-row:nth-child("</span> + (row) + <span class="hljs-string">") game-tile"</span>);
        <span class="hljs-keyword">var</span> results = elements
                .stream().map(e -&gt; e.getAttribute(<span class="hljs-string">"evaluation"</span>)).toList();
        <span class="hljs-keyword">if</span> (results.size() == <span class="hljs-number">0</span>)
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>;

        Integer exactMatch = <span class="hljs-number">0</span>;

        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; results.size(); i++) {
            String currentResult = results.get(i);
            <span class="hljs-keyword">if</span> (currentResult == <span class="hljs-keyword">null</span>) <span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>;
            <span class="hljs-keyword">switch</span> (currentResult) {

                <span class="hljs-keyword">case</span> <span class="hljs-string">"present"</span> -&gt; present.add(word.charAt(i));
                <span class="hljs-keyword">case</span> <span class="hljs-string">"absent"</span> -&gt; notPresent.add(word.charAt(i));
                <span class="hljs-keyword">case</span> <span class="hljs-string">"correct"</span> -&gt; {
                    exactMatch++;
                    atPos.put(i, word.charAt(i));
                }

            }
        }

        <span class="hljs-keyword">return</span> exactMatch;
    }
</code></pre>
<p>This method will return 5 if all of the evaluated characters are correct.</p>
<p>If you are interested in the full program, check it at <a target="_blank" href="https://github.com/CODINGSAINT/wordle-solver/blob/main/src/main/java/Main.java">https://github.com/CODINGSAINT/wordle-solver/blob/main/src/main/java/Main.java</a></p>
]]></content:encoded></item><item><title><![CDATA[Kubernetes and Spring Boot]]></title><description><![CDATA[Kubernetes (k8s) is an open-source system for automatic management, scaling, and deployment of containerized applications. With the rise of microservices…]]></description><link>https://digitalyogi.hashnode.dev/kubernetes-and-spring-boot</link><guid isPermaLink="true">https://digitalyogi.hashnode.dev/kubernetes-and-spring-boot</guid><category><![CDATA[Spring]]></category><category><![CDATA[Springboot]]></category><category><![CDATA[Kubernetes]]></category><dc:creator><![CDATA[DigitalYogi]]></dc:creator><pubDate>Sat, 29 Jan 2022 09:15:31 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1643447675554/i7tyodEPi.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-kubernetes-with-spring-tutorial">Kubernetes with Spring Tutorial</h1>
<h2 id="heading-introduction-to-kubernetes">Introduction to Kubernetes</h2>
<p>Kubernetes (k8s) is an open-source system for automatic management, scaling, and deployment of containerized applications. </p>
<p>With the rise of microservices, we required a tool to deploy these independent applications. Containers like docker were the perfect fit for it. They provided a working environment for delivering microservices. </p>
<p>As the Microservices increased, so increases the number of containers. It becomes difficult to manage these containers with scripts. This problem has led to the creation of the container orchestration tool. Kubernetes is the answer to such a need. </p>
<h2 id="heading-component-of-kubernetes">Component of Kubernetes</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1643447535441/9XTNJV7d-.png" alt="ComponentOfKubernates.png" /></p>
<h3 id="heading-nodes">Nodes</h3>
<p>Kubernetes is a solution for containerized applications. One of the containers could be a docker but there are many other container solutions available. In order to manage these containers, we require an abstraction layer that talks with different vendors seamlessly. </p>
<p>The pod can be considered as a working unit for Kubernetes. A pod can have one or more containers.</p>
<h3 id="heading-service">Service</h3>
<p>Each node on Kubernetes is assigned an IP.  While pods in nodes can talk with each other using IP, <strong>nodes are ephemeral.</strong> They can die at any moment. Whenever a node dies, Kubernetes will create another one in its place to keep the desired state.  <em>**</em>The new pod will have a new IP assigned. This will create a problem while the pods interact via IP. </p>
<p>To solve this Kubernetes creates a service assigned to pods and they will interact using service rather than IP. Service will remain the same even if the ip attached changes.</p>
<h3 id="heading-control-plane">Control Plane</h3>
<p>As we know Kubernetes is all about container management, to manage it we require some components. These components which help to manage the containers effectively, if grouped together will be known as the control plane.</p>
<p>Let’s look at the components that make the control plane.</p>
<h3 id="heading-api-gateway">API Gateway</h3>
<p>As the name suggests it provides the gateway to interact with all nodes and its port to the outside world. Any communication to the pods from outside the cluster can happen via the API gateway. </p>
<h3 id="heading-scheduler">Scheduler</h3>
<p>To manage the desired state whenever a pod dies, we require a mechanism that can check the state on the cluster and can schedule the new pods if required. This is the work of the scheduler running from the control plane.</p>
<h3 id="heading-control-manager">Control Manager</h3>
<p>All of the components in the control plane is managed by controller processes. There are different controllers like Node, Jobs, Endpoints, Service, and Token controllers. All of them combined together are known as Control Manager.</p>
<h3 id="heading-etcd">etcd</h3>
<p>To manage effectively we require some sort of memory. etcd acts as a database for all of the config maps and secrets. </p>
<h3 id="heading-deployment">Deployment</h3>
<p>To deploy anything on Kubernetes, we create a deployment object which is a YAML file.  It has all of the information related to container images, its location, and the metadata corresponding to pods</p>
<h3 id="heading-service">Service</h3>
<p>Service is another YAML file that holds the configuration of protocols that is required for nodes to communicate and serve.</p>
<h3 id="heading-configmap">ConfigMap</h3>
<p>Applications deployed via pods require many configurations, if we keep them inside pod we will have to build images for every change </p>
<h3 id="heading-secrets">Secrets</h3>
<p>Many of the configurations are secrets, like database passwords, we can’t reveal them. We can save them as secrets rather than plain text. Kubernetes doesn’t control the encryption mechanism but these secrets are kept as encrypted text in etcd database.</p>
<h1 id="heading-deploying-sample-spring-boot-app-to-kubernetes">Deploying Sample Spring Boot App to Kubernetes</h1>
<h2 id="heading-deploying-sample-spring-boot-app-to-kubernetes">Deploying Sample Spring Boot App to Kubernetes</h2>
<p>Now with the understanding of Kubernetes basic building blocks, let us try our hand in creating an application and deploying it on Kubernetes. To start we will go to <a target="_blank" href="https://start.sprting.oio">https://start.sprting.</a>io and create a simple application which one endpoint. We will only select reactive web as a dependency. </p>
<p>We will create a with a get endpoint, The endpoint will take a String via query String and will welcome the user.                                                                            </p>
<pre><code class="lang-java"><span class="hljs-meta">@RestController</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SpringK8SDemoController</span> </span>{

    <span class="hljs-meta">@GetMapping("/welcome")</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> Mono&lt;String&gt; <span class="hljs-title">welcome</span> <span class="hljs-params">(<span class="hljs-meta">@RequestParam("name")</span> String param)</span></span>{
        <span class="hljs-keyword">return</span>  Mono.just(<span class="hljs-string">"Welcome "</span>+ param);
    }
}
</code></pre>
<p>Before we create the containerize the docker file, let’s the final jar file at pom.xml
<strong>k8s-demo</strong></p>
<pre><code class="lang-docker">&lt;build&gt;
        &lt;plugins&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
                &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
            &lt;/plugin&gt;
        &lt;/plugins&gt;
        **&lt;finalName&gt;k8s-demo&lt;/finalName&gt;**
    &lt;/build&gt;
</code></pre>
<p>Now we need to containerize the application. We will use a docker container. Let us add a file named <strong>Dockerfile.</strong> We will add it to the root directory of the project. </p>
<pre><code class="lang-docker">FROM openjdk:17-jdk-alpine
EXPOSE 8080
ARG JAR_FILE=target/k8s-demo.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-jar","/app.jar"]
</code></pre>
<p>The file is self-explanatory, it adds OpenJDK 17 to the container and uses 8080 port for exposing. It just copies the file to the target directory and names it app.jar. In the end, it starts with command as an entry point that’s java -jar app.jar.</p>
<p>Let’s build the docker image and run it to verify. </p>
<pre><code class="lang-bash">mvn clean install
<span class="hljs-built_in">cd</span> target
docker build -t codingsaint/k8s-demo
docker run -p 9090:8080 k8s-demo
</code></pre>
<p>The app should run and if you send HTTP request <a target="_blank" href="http://localhost:9090/welcome?name=Pallav">http://localhost:9090/welcome?name=Pallav</a> , it should respond as <strong>welcome Pallav</strong></p>
<h2 id="heading-spring-boot-deployment-using-deployment-object">Spring Boot Deployment using Deployment Object</h2>
<p>In Kubernetes, we deploy using a configuration file in YAML format. The standard file of configuration is called deployment. Let’s create a deployment file as below and we will discuss its content.</p>
<p>Let’s create a <strong>deployment.yam</strong>l file at the root of the spring boot project. </p>
<pre><code class="lang-yaml"><span class="hljs-attr">apiVersion:</span> <span class="hljs-string">apps/v1</span>
<span class="hljs-attr">kind:</span> <span class="hljs-string">Deployment</span>
<span class="hljs-attr">metadata:</span>
  <span class="hljs-attr">name:</span> <span class="hljs-string">k8s-demo</span>

<span class="hljs-attr">spec:</span>
  <span class="hljs-attr">selector:</span>
    <span class="hljs-attr">matchLabels:</span>
      <span class="hljs-attr">app:</span> <span class="hljs-string">k8s-demo</span>
  <span class="hljs-attr">replicas:</span> <span class="hljs-number">3</span>
  <span class="hljs-attr">template:</span>
    <span class="hljs-attr">metadata:</span>
      <span class="hljs-attr">labels:</span>
        <span class="hljs-attr">app:</span> <span class="hljs-string">k8s-demo</span>
    <span class="hljs-attr">spec:</span>
      <span class="hljs-attr">containers:</span>
        <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">k8s-demo</span>
          <span class="hljs-attr">image:</span> <span class="hljs-string">k8s-demo:0.0.1-SNAPSHOT</span>
          <span class="hljs-attr">imagePullPolicy:</span> <span class="hljs-string">IfNotPresent</span>
          <span class="hljs-attr">ports:</span>
            <span class="hljs-bullet">-</span> <span class="hljs-attr">containerPort:</span> <span class="hljs-number">8080</span>
</code></pre>
<p>In the above file, we are creating an object of kind deployment, named k8s-demo using metadata.name. At the spec level, we are defining that the app k8s-demo should have 3 replica</p>
<p>At spec.selector.spec.container we are defining the container properties. With imagePullPolicy as IfNotPresent it will look at local docker images first then at the remote.</p>
<h2 id="heading-service-object">Service Object</h2>
<p>As we discussed the communication of pods, We need services that are attached to the pods. Service Object in Kubernetes can be created using YAML file. Let’s review the content of the service file. We are creating this file at root directory , let’s name it <strong>k8s-demo-svc.yaml</strong></p>
<pre><code class="lang-yaml"><span class="hljs-attr">apiVersion:</span> <span class="hljs-string">v1</span>
<span class="hljs-attr">kind:</span> <span class="hljs-string">Service</span>
<span class="hljs-attr">metadata:</span>
  <span class="hljs-attr">name:</span> <span class="hljs-string">k8s-demo-svc</span>
<span class="hljs-attr">spec:</span>
  <span class="hljs-attr">selector:</span>
    <span class="hljs-attr">app:</span> <span class="hljs-string">k8s-demo</span>
  <span class="hljs-attr">ports:</span>
    <span class="hljs-bullet">-</span> <span class="hljs-attr">protocol:</span> <span class="hljs-string">TCP</span>
      <span class="hljs-attr">port:</span> <span class="hljs-number">8080</span>
      <span class="hljs-attr">targetPort:</span> <span class="hljs-number">8080</span>
  <span class="hljs-attr">type:</span> <span class="hljs-string">NodePort</span>
</code></pre>
<p>If you see spec , it clearly says to select  (selector) the app k8s-demo. It also tells that the protocol is TCP. </p>
<h1 id="heading-deploying-to-kubernetes-cluster">Deploying to Kubernetes Cluster</h1>
<h2 id="heading-start-minikube">Start Minikube</h2>
<pre><code class="lang-powershell">minikube start
</code></pre>
<p>You should be getting an output like below</p>
<pre><code class="lang-powershell">PS C:\Users\07pal\development\tutorial\k8s\k8s-demo&gt; minikube start
😄  minikube v1.25.1 on Microsoft Windows 11 Home Single Language 10.0.22000 Build 22000
✨  Using the docker driver based on existing profile
👍  Starting control plane node minikube in cluster minikube
🚜  Pulling base image ...
🔄  Restarting existing docker container for "minikube" ...
🐳  Preparing Kubernetes v1.23.1 on Docker 20.10.12 ...
    ▪ kubelet.housekeeping-interval=5m
    ▪ Generating certificates and keys ...
    ▪ Booting up control plane ...
    ▪ Configuring RBAC rules ...
🔎  Verifying Kubernetes components...
    ▪ Using image gcr.io/k8s-minikube/storage-provisioner:v5
🌟  Enabled addons: storage-provisioner, default-storageclass
🏄  Done! kubectl is now configured to use "minikube" cluster and "default" namespace by default
</code></pre>
<h2 id="heading-build-docker-image">Build docker image</h2>
<p>Before we deploy it to cluster we  need Kubernetes and Docker images’ to be in sync . If you are on windows use below command</p>
<pre><code class="lang-powershell">minikube docker-env | Invoke-Expression
</code></pre>
<p>If you are on Mac , use following</p>
<pre><code class="lang-powershell">eval $(minikube docker-env)
</code></pre>
<p>Now we will build the docker image from the Dockerfile we created </p>
<pre><code class="lang-powershell">docker build -t k8s-demo:0.0.1-SNAPSHOT .
</code></pre>
<p>This will create a Docker Image and we will deploy using our deployment object. The output of above command should be like </p>
<pre><code class="lang-powershell">[+] Building 3.4s (8/8) FINISHED
 =&gt; [internal] load build definition from Dockerfile                                                               0.0s
 =&gt; =&gt; transferring dockerfile: 32B                                                                                0.0s
 =&gt; [internal] load .dockerignore                                                                                  0.0s
 =&gt; =&gt; transferring context: 2B                                                                                    0.0s
 =&gt; [internal] load metadata for docker.io/library/openjdk:17-jdk-alpine                                           3.3s
 =&gt; [auth] library/openjdk:pull token for registry-1.docker.io                                                     0.0s
 =&gt; [internal] load build context                                                                                  0.0s
 =&gt; =&gt; transferring context: 69B                                                                                   0.0s
 =&gt; [1/2] FROM docker.io/library/openjdk:17-jdk-alpine@sha256:4b6abae565492dbe9e7a894137c966a7485154238902f2f25e9  0.0s
 =&gt; CACHED [2/2] COPY target/k8s-demo.jar app.jar                                                                  0.0s
 =&gt; exporting to image                                                                                             0.0s
 =&gt; =&gt; exporting layers                                                                                            0.0s
 =&gt; =&gt; writing image sha256:714ae55f7105935be0267470795b5dc890d17c1773b194d5bfda9a45fa2d8b8c                       0.0s
 =&gt; =&gt; naming to docker.io/library/k8s-demo:0.0.1-SNAPSHOT                                                         0.0s
</code></pre>
<p>You can verify the images at local docker repo using command </p>
<p><strong>docker images</strong></p>
<p>It should give output like </p>
<pre><code class="lang-powershell">REPOSITORY                    TAG              IMAGE ID       CREATED         SIZE
**k8s-demo                      0.0.1-SNAPSHOT   714ae55f7105   5 days ago      346MB**
gcr.io/k8s-minikube/kicbase   v0.0.29          64d09634c60d   5 weeks ago     1.14GB
mysql                         latest           ecac195d15af   3 months ago    516MB
mongo                         latest           fefd78e9381a   3 months ago    699MB
jaegertracing/all-in-one      latest           9844aed41d42   4 months ago    59MB
docker101tutorial             latest           c492a391575a   4 months ago    28.3MB
postgres                      12               91d892a67245   4 months ago    314MB
consul                        latest           b74a0a01afc4   5 months ago    116MB
alpine/git                    latest           b8f176fa3f0d   8 months ago    25.1MB
testcontainers/ryuk           0.3.1            ee7515743e6f   13 months ago   12MB
postgres                      11.5-alpine      da01ecfbabe1   2 years ago     71.8MB
openjdk                       8-jdk-alpine     a3562aa0b991   2 years ago     105MB
</code></pre>
<h2 id="heading-deploy-on-kubernetes">Deploy on Kubernetes</h2>
<p>Let’s deploy it on Kubernetes using the deployment object that we created .</p>
<pre><code class="lang-powershell">kubectl apply -f .\deployment.yaml
</code></pre>
<p>The above command will put out image from docker to kubernetes cluster and deploy as it is stated in deployment.yaml. The output should be looking something like</p>
<pre><code class="lang-powershell">PS C:\Users\07pal\development\tutorial\k8s\k8s-demo&gt; kubectl apply -f .\deployment.yaml
**deployment.apps/k8s-demo created**
</code></pre>
<p>We can verify our pods are up and running using </p>
<pre><code class="lang-powershell">kubectl get pods
</code></pre>
<p>You will see pods name as output </p>
<pre><code class="lang-powershell">PS C:\Users\07pal\development\tutorial\k8s\k8s-demo&gt; kubectl get pods
NAME                        READY   STATUS    RESTARTS   AGE
k8s-demo-675766fff7-92kxk   1/1     Running   0          102s
k8s-demo-675766fff7-grsdm   1/1     Running   0          102s
k8s-demo-675766fff7-z6z4s   1/1     Running   0          102s
</code></pre>
<p>If you want to check logs of individual pod , you can use kubectl logs   as </p>
<pre><code class="lang-powershell">kubectl logs  k8s-demo-675766fff7-92kxk
</code></pre>
<p>We can see the spring boot app running at cluster. The below output can be taken as proof</p>
<pre><code class="lang-powershell">.   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.6.3)

2022-01-29 08:23:38.136  INFO 1 --- [           main] c.c.k8sdemo.K8sDemoApplication           : Starting K8sDemoApplication v0.0.1-SNAPSHOT using Java 17-ea on k8s-demo-675766fff7-92kxk with PID 1 (/app.jar started by root in /)
2022-01-29 08:23:38.138  INFO 1 --- [           main] c.c.k8sdemo.K8sDemoApplication           : No active profile set, falling back to default profiles: default
2022-01-29 08:23:42.756  INFO 1 --- [           main] o.s.b.web.embedded.netty.NettyWebServer  : Netty started on port 8080
2022-01-29 08:23:42.824  INFO 1 --- [           main] c.c.k8sdemo.K8sDemoApplication           : Started K8sDemoApplication in 6.006 seconds (JVM running for 7.407)
</code></pre>
<h2 id="heading-creating-service">Creating Service</h2>
<p>It’s running at a cluster we will not be able to access it directly so let us create a service . We will use the service file we created above to create the service</p>
<pre><code class="lang-powershell">kubectl apply -f .\k8s-demo-svc.yaml
</code></pre>
<p>You can verify your service via <strong><em>kubectl get svc</em></strong> or <strong><em>kubectl get service</em></strong></p>
<pre><code class="lang-powershell">kubectl get svc
NAME           TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)          AGE
k8s-demo-svc   NodePort    10.99.108.29   &lt;none&gt;        8080:31019/TCP   2m15s
kubernetes     ClusterIP   10.96.0.1      &lt;none&gt;        443/TCP          22m
</code></pre>
<p>Since we are on windows and even Kubernetes is running inside docker ,we need proxy to access pod , otherwise on linux we could have used cluster IP and the port 31019 (as shown above, for your case it will be different) . </p>
<p>Let’s hit the pod using below command. It will open your browser with proxy </p>
<pre><code class="lang-powershell">minikube service k8s-demo-svc
</code></pre>
<p>It will also give following output</p>
<pre><code class="lang-powershell">PS C:\Users\07pal\development\tutorial\k8s\k8s-demo&gt; minikube service k8s-demo-svc
|-----------|--------------|-------------|---------------------------|
| NAMESPACE |     NAME     | TARGET PORT |            URL            |
|-----------|--------------|-------------|---------------------------|
| default   | k8s-demo-svc |        8080 | http://192.168.49.2:31019 |
|-----------|--------------|-------------|---------------------------|
🏃  Starting tunnel for service k8s-demo-svc.
|-----------|--------------|-------------|------------------------|
| NAMESPACE |     NAME     | TARGET PORT |          URL           |
|-----------|--------------|-------------|------------------------|
| default   | k8s-demo-svc |             | **http://127.0.0.1:52260** |
|-----------|--------------|-------------|------------------------|
🎉  Opening service default/k8s-demo-svc in default browser...
❗  Because you are using a Docker driver on windows, the terminal needs to be open to run it.
</code></pre>
<p>Here  <strong><a target="_blank" href="http://127.0.0.1:52260">http://127.0.0.1:52260</a> is the URL where you can access your deployed pods. so you can check it via</strong>  <a target="_blank" href="http://127.0.0.1:52260/welcome?name=Pallav">http://127.0.0.1:52260/welcome?message=Pallav</a></p>
<p>It will be giving you proper output.</p>
]]></content:encoded></item><item><title><![CDATA[Micronaut  - Discovery Client and Client-side load balancing with Consul]]></title><description><![CDATA[Micronaut - Discovery Client and Client-side load balancing with Consul]]></description><link>https://digitalyogi.hashnode.dev/micronaut-discovery-client-and-client-side-load-balancing-with-consul</link><guid isPermaLink="true">https://digitalyogi.hashnode.dev/micronaut-discovery-client-and-client-side-load-balancing-with-consul</guid><category><![CDATA[Java]]></category><dc:creator><![CDATA[DigitalYogi]]></dc:creator><pubDate>Tue, 28 Sep 2021 00:12:55 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1632787854520/X0csFWTCW.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="introduction">Introduction</h3>
<p>In any microservice architecture, we need multiple instances of the services. Our superhero API is no different. While we have been running only one instance of superhero API and command center, it is far from reality.</p>
<p> In the real world, the load on servers is expected to increase. We need to establish efficient communication to talk between services. </p>
<p>Suppose, there is a surge in load,  we need to increase the instances of superhero API, how will the command-center know the new instances URLs. How will it call them and balance the load on servers? Till now, we hardcoded it with the <code>@Client</code> annotation and value as URL. </p>
<p>Can we solve this problem if we have another service that can keep track of all the services deployed? If it can know all the instances of any service and can give us the URLs. How good it could be if we distribute the load among all available instances. </p>
<p>In this section we will solve this using Consul Service discovery and client-side load balancing. </p>
<h3 id="approach">Approach</h3>
<ul>
<li><h4 id="add-the-discovery-dependency-to-command-center-and-superhero-api">Add the discovery dependency to command-center and superhero api.</h4>
</li>
<li><h4 id="run-consul">Run consul</h4>
</li>
<li><h4 id="update-the-client-annotation-to-use-id-of-the-service-rather-urls">Update the <code>@Client</code> annotation to use <code>id</code> of the service rather URLs</h4>
</li>
</ul>
<h4 id="add-the-discovery-dependency-to-command-center-and-superhero-api">Add the discovery dependency to command-center and superhero api.</h4>
<p>When we add this dependency and let client know that they have to register at consul service discovery, client will sent HTTP request at startup. it keeps sending the request at regular interval to let the consul service discovery app know that its up and running.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632763989300/1F3qLg-y2.png" alt="superhero API.png" /></p>
<p>Add the below dependency to the superhero API and command center poms</p>
<pre><code>  <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>io.micronaut.discovery<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>micronaut-discovery-client<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">scope</span>&gt;</span>compile<span class="hljs-tag">&lt;/<span class="hljs-name">scope</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
</code></pre><p>Once it is added, we will tell apps the address of the consul server so that they can register themselves. </p>
<p>Add the below in superhero and command-center application.yml</p>
<pre><code><span class="hljs-attr">consul:</span>
  <span class="hljs-attr">client:</span>
    <span class="hljs-attr">registration:</span>
      <span class="hljs-attr">enabled:</span> <span class="hljs-literal">true</span>
    <span class="hljs-attr">defaultZone:</span> <span class="hljs-string">"${CONSUL_HOST:localhost}:${CONSUL_PORT:8500}"</span>
</code></pre><p>This will tell the application about the address of the consul server. At the start of microservices, they will hit the server on this port to let it know about their availability.</p>
<h4 id="run-consul">Run consul</h4>
<p>There are many ways to run consul, let us keep simple with docker, run below docker command to run it</p>
<pre><code><span class="hljs-attribute">docker</span> run -p <span class="hljs-number">8500</span>:<span class="hljs-number">8500</span> consul
</code></pre><p>This will sun consul app and expose to 8500 port. </p>
<h4 id="update-the-client-annotation-to-use-id-of-the-service-rather-urls">Update the <code>@Client</code> annotation to use <code>id</code> of the service rather URLs</h4>
<p>Till now we have used hardcoded <code>@Client</code> value , let us use id rather than URL now. Ids are the same as Micronaut's  application name . 
We will update the declarative client used in the last section with id.</p>
<p>Below is the code </p>
<pre><code>
<span class="hljs-variable">@Client</span>(id = <span class="hljs-string">"superHeroes"</span>)
<span class="hljs-variable">@Header</span>(name = <span class="hljs-string">"Accept"</span>, value = HEADER_ACCEPT)
public interface SuperheroClient {
    <span class="hljs-variable">@Get</span>(<span class="hljs-string">"/rx/superheroes"</span>)
    Flux&lt;Superhero&gt; superheroes();

    <span class="hljs-variable">@Get</span>(<span class="hljs-string">"/rx/superhero/{id}"</span>)
    Mono&lt;Superhero&gt; superheroesById(Long id);

    <span class="hljs-variable">@Post</span>(<span class="hljs-string">"/rx/superhero"</span>)
    Publisher&lt;Superhero&gt; create( <span class="hljs-variable">@Body</span>  Superhero superhero);

    <span class="hljs-variable">@Put</span>(<span class="hljs-string">"/rx/superhero"</span>)
    Publisher&lt;Superhero&gt; update( Superhero superhero);

    <span class="hljs-variable">@Delete</span>(<span class="hljs-string">"/rx/superhero/{id}"</span>)
    Publisher&lt;HttpResponse&lt;Long&gt;&gt; delete(Long id);
}
</code></pre><p>If you observe we have updated <code>@Client</code> with id of superhero API.  Whenever a call to superhero API is made, it can select one of the instances that have registered itself at consul. </p>
<h4 id="test-the-setup">Test The Setup</h4>
<p>Once it is all done , it's time to test the setup. To do that let us start multiple instance on superhero API. We can start them by directly invoking jar in the <code>target</code> folder and passing <code>micronaut.server.port={PORT_NO}</code> as parameter. </p>
<p>Open two terminals and navingate to project. Change directory to target folder and run the command</p>
<pre><code> <span class="hljs-attribute">java</span> -jar .\super-heroes-<span class="hljs-number">0</span>.<span class="hljs-number">1</span>.jar --micronaut.server.port=<span class="hljs-number">8082</span>
</code></pre><pre><code> <span class="hljs-attribute">java</span> -jar .\super-heroes-<span class="hljs-number">0</span>.<span class="hljs-number">1</span>.jar --micronaut.server.port=<span class="hljs-number">8081</span>
</code></pre><p>The above commands will start two instances of superhero API at 8081 and 8082 port. You will notice the application will register itself with consul and log it.</p>
<h4 id="superhero-api-registered-at-consul-at-port-8081">Superhero API Registered at consul at port 8081</h4>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632786784055/ctcALHOUp.png" alt="RegisterATConsul0.PNG" /></p>
<h4 id="superhero-api-registered-at-consul-at-port-8082">Superhero API Registered at consul at port 8082</h4>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632786865515/JG9ltVPXy.png" alt="RegisterATConsul1.PNG" /></p>
<h4 id="start-command-center-app-and-test-the-sever">Start command-center App and Test the sever</h4>
<p>Once command-center all is up and you can see it registered to consul, you can verify all of them are at consul UI too. visit <code>http://localhost:8500</code> where docker is running the consul </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632787241444/fnWHIlcHB.png" alt="consulAppunnig.PNG" /></p>
<p>If you hit the API via command-center, You can see logs are different console widows of superhero API.</p>
<p>This shows the working load balancing of HttpClient with consul.</p>
]]></content:encoded></item><item><title><![CDATA[Micronaut - HttpClient, Declarative Client and Filters]]></title><description><![CDATA[Call Superheroes via Command Center]]></description><link>https://digitalyogi.hashnode.dev/micronaut-and-httpclient-micronaut-declarative-client-and-filters</link><guid isPermaLink="true">https://digitalyogi.hashnode.dev/micronaut-and-httpclient-micronaut-declarative-client-and-filters</guid><category><![CDATA[Java]]></category><category><![CDATA[Microservices]]></category><dc:creator><![CDATA[DigitalYogi]]></dc:creator><pubDate>Fri, 24 Sep 2021 17:48:49 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1632531442900/fMU8VEiN8.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="introduction">Introduction</h3>
<p>In Microservices we will always have more than one service interacting with each other. One of the most popular ways for inter-service communication is REST API. While we are using POSTMAN to check our services as of now , in an actual service we require an agent to make REST calls for us. This is done by HttpClient in Micronaut.</p>
<h3 id="requirement">Requirement</h3>
<p>If you are following the series, you must be aware that we have created the API for Superheroes and added the reactive version of API as well. We also checked at <code>TestContainers</code> to write efficient tests. In this section, we will look at calling the API from another service, let us call it command-center. </p>
<p>It will be the job of the command center to make calls to the services. It will help us to understand how API communication happens between two microservices. We will also add a Filter to add custom headers and track id as the header. In the end, we will update superhero API to check if the client who is making the request is valid using another HTTP Filter. </p>
<h3 id="git-repository">Git Repository</h3>
<p>You can find the code of the article at </p>
<ul>
<li>command-center: https://github.com/CODINGSAINT/command-center/tree/06HttpClient</li>
<li>Superhero API : https://github.com/CODINGSAINT/super-heroes/tree/06HttpClient</li>
</ul>
<h2 id="approach">Approach</h2>
<ul>
<li><h3 id="creating-a-new-micronaut-project-command-center">Creating a new Micronaut project <code>command-center</code></h3>
</li>
<li><h3 id="adding-the-pojo-controller-and-service-layer">Adding the POJO , controller &amp; service layer</h3>
</li>
<li><h3 id="call-endpoints-from-service-layer">Call endpoints from service layer</h3>
</li>
<li><h3 id="call-superhero-api">Call superhero API</h3>
</li>
<li><h3 id="add-http-filter-to-add-headers-to-all-outgoing-api-calls">Add HTTP Filter to add Headers to all outgoing API calls</h3>
</li>
<li><h3 id="add-a-filter-in-superhero-api-to-validate-the-incoming-headers">Add a Filter in superhero API to validate the incoming headers</h3>
</li>
</ul>
<h3 id="creating-a-new-micronaut-project-command-center">Creating a new Micronaut project <code>command-center</code></h3>
<ul>
<li>In order to create the micronaut project we will vising 
<a target="_blank" href="https://micronaut.io/launch">https://micronaut.io/launch</a> . We will launch a new project with the dependency of HTTP Client added to it.  </li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1632266854769/Td9-sTI8-.png" alt="2021-09-22.png" /></p>
<ul>
<li><p>We have changed the name as <code>command-center</code>, Build Tool as <code>maven</code>, Java version as 16 and the base package as <code>com.codingsaint</code></p>
</li>
<li><p>Generate the new project and import it into your IDE (IntelliJ, eclipse)</p>
</li>
</ul>
<h3 id="adding-the-pojo-controller-and-service-layer">Adding the POJO , controller &amp; service layer</h3>
<p>Once our new project is imported into IDE we can add Superhero POJO (it's same as we did in superhero project) a Controller and a Service layer to our new project. </p>
<p>We will also create a class for keeping constant , let us name it <code>CommandCenterConstants</code> </p>
<pre><code>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CommandCenterConstants</span> </span>{
    <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">String</span> SUPERHERO_URL= <span class="hljs-string">"http://localhost:8080/"</span>;
    <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">String</span> USER_AGENT= <span class="hljs-string">"Coding Saint Command Center Client"</span>;
    <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">String</span> HEADER_ACCEPT= <span class="hljs-string">"application/json"</span>;


}
</code></pre><h4 id="commandcenterservicejava">CommandCenterService.java</h4>
<pre><code>
<span class="hljs-meta">@Singleton</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CommandCenterService</span> </span>{
    <span class="hljs-keyword">private</span> static <span class="hljs-keyword">final</span> Logger logger = LoggerFactory.getLogger(CommandCenterService.<span class="hljs-keyword">class</span>);

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> HttpClient client;

    <span class="hljs-keyword">public</span> CommandCenterService(<span class="hljs-meta">@Client(SUPERHERO_URL)</span> HttpClient client) {
        <span class="hljs-keyword">this</span>.client = client;
    }
}
</code></pre><ul>
<li>Here you can see we have injected <code>HttpClient</code> to the Service layer. It will help us to do the Rest Calls to the Superhero API</li>
<li><code>@Client</code> annotation is has a value <code>SUPERHERO_URL</code> which is a constant from <code>CommandCenterConstants</code> and has a value <code>http://localhost:8080/</code>. </li>
<li>The URL of the <code>Client</code> annotation will let the HTTP client to connect to it while making a call.</li>
</ul>
<h4 id="commandcentercontrollerjava">CommandCenterController.java</h4>
<pre><code>
<span class="hljs-meta">@Controller</span>
<span class="hljs-meta">@ExecuteOn(TaskExecutors.IO)</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CommandCenterController</span> </span>{
    <span class="hljs-keyword">private</span> static <span class="hljs-keyword">final</span> Logger logger = LoggerFactory.getLogger(CommandCenterController.<span class="hljs-keyword">class</span>);

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> CommandCenterService service;

    <span class="hljs-keyword">public</span> CommandCenterController(CommandCenterService commandCenterService) {
        <span class="hljs-keyword">this</span>.service = commandCenterService;
    }
</code></pre><ul>
<li>The Controller has <code>CommandCenterService</code> injected into it. </li>
</ul>
<h3 id="call-endpoints-from-the-service-layer">Call endpoints from the service layer</h3>
<p> Let us call the endpoints of our Superhero through the service layer. </p>
<pre><code> <span class="hljs-built_in">public</span> Publisher&lt;Superhero&gt; <span class="hljs-keyword">create</span>(Superhero superhero) {
        logger.<span class="hljs-keyword">info</span>("Adding a new saviour {} ", superhero);
       var uri= UriBuilder.<span class="hljs-keyword">of</span>("superhero").build();
        HttpRequest req = HttpRequest.POST(uri, superhero)
                 .<span class="hljs-keyword">header</span>("ACCEPT", "application/json");
        var created = Mono.<span class="hljs-keyword">from</span>( client.retrieve(req));
        <span class="hljs-keyword">return</span> created;
    }

    <span class="hljs-built_in">public</span> Publisher&lt;Superhero&gt; <span class="hljs-keyword">update</span>(Superhero superhero) {
        logger.<span class="hljs-keyword">info</span>("Updating the old saviour {} ", superhero);

        var uri= UriBuilder.<span class="hljs-keyword">of</span>("superhero").build();
        HttpRequest req = HttpRequest.PUT(uri, superhero)
                .<span class="hljs-keyword">header</span>("ACCEPT", "application/json");
        var updated = Mono.<span class="hljs-keyword">from</span>( client.retrieve(req));

        <span class="hljs-keyword">return</span> updated;
    }

    <span class="hljs-built_in">public</span> Publisher&lt;Long&gt; <span class="hljs-keyword">delete</span>(Long id) {
        logger.<span class="hljs-keyword">info</span>("Purging the saviour {} ", id);
        var uri= UriBuilder.<span class="hljs-keyword">of</span>("superhero").path(String.valueOf(id)).build();
        HttpRequest req = HttpRequest.<span class="hljs-keyword">DELETE</span>(uri.toString())
                 .<span class="hljs-keyword">header</span>("ACCEPT", "application/json");
        <span class="hljs-keyword">return</span> Mono.<span class="hljs-keyword">from</span>( client.exchange(req));

    }
</code></pre><ul>
<li>Here you can note that we can add ``path<code>variables and headers as required by the endpoint. Do note that the header is just to show that it can be added while invoking the</code>URLs```  via HTTP client. We can also configure common Headers like Content-Type and even Authorization headers via Http Filter which we will add later.</li>
</ul>
<h3 id="call-superhero-api">Call superhero API</h3>
<p>Now we will not directly call Superhero API but via command center. We will add endpoints to command center Controller , which will talk to Superhero via REST API using injected service layer. </p>
<p>Let us add methods for Controller as below</p>
<pre><code> <span class="hljs-meta">@Get(<span class="hljs-meta-string">"superhero/{id}"</span>)</span>
    <span class="hljs-keyword">public</span> Mono&lt;Superhero&gt; superheroesById(<span class="hljs-built_in">Long</span> id) {

        <span class="hljs-keyword">return</span> service.superheroesById(id);

    }

    <span class="hljs-meta">@Post(<span class="hljs-meta-string">"/superhero"</span>)</span>
    Mono&lt;Superhero&gt; create(<span class="hljs-meta">@Valid</span> Superhero superhero) {
        logger.info(<span class="hljs-string">"Call to add a new saviour {} "</span>, superhero);
        <span class="hljs-keyword">return</span> Mono.from(service.create(superhero));
    }

    <span class="hljs-meta">@Put(<span class="hljs-meta-string">"superhero"</span>)</span>
    Mono&lt;Superhero&gt; update(<span class="hljs-meta">@Valid</span> Superhero superhero) {
        <span class="hljs-keyword">return</span> Mono.from(service.update(superhero));
    }

    <span class="hljs-meta">@Delete(<span class="hljs-meta-string">"superhero/{id}"</span>)</span>
    Mono&lt;HttpResponse&lt;?&gt;&gt; delete(<span class="hljs-meta">@NotNull</span> <span class="hljs-built_in">Long</span> id) {
        <span class="hljs-keyword">return</span> Mono
                .from(service.delete(id))
                .map(deleted -&gt; deleted &gt; <span class="hljs-number">0</span> ? HttpResponse.noContent() : HttpResponse.notFound());
    }
</code></pre><p>If you restart your server it will work. But I would like to show you HTTP request and response filters as well to control the API misuse and let only valid clients call Superhero API. While we will only show it as demo , you can enhance it to use production-ready service adding Authorization headers, or any other heder of your need.</p>
<h3 id="add-http-filter-to-add-headers-to-all-outgoing-api-calls">Add HTTP Filter to add Headers to all outgoing API calls</h3>
<p>Let us add the HTTP Request Filter in the command-center config. </p>
<pre><code>
@<span class="hljs-keyword">Filter</span>( "/**")
<span class="hljs-built_in">public</span> <span class="hljs-keyword">class</span> SuperheroHttpClientFilter implements HttpClientFilter {
    private static final Logger logger= LoggerFactory.getLogger(SuperheroHttpClientFilter.<span class="hljs-keyword">class</span>);
    @Override
    <span class="hljs-built_in">public</span> Publisher&lt;? extends HttpResponse&lt;?&gt;&gt; doFilter(MutableHttpRequest&lt;?&gt; request, ClientFilterChain chain) {
        var <span class="hljs-keyword">header</span>= request.getHeaders();
        logger.<span class="hljs-keyword">debug</span>("Adding HTTP Headers to client ");
        <span class="hljs-keyword">header</span>.<span class="hljs-keyword">add</span>("User-Agent", "Coding Saint HTTP Client") ;
        <span class="hljs-keyword">header</span>.<span class="hljs-keyword">add</span>("ACCEPT", "application/json");
        String GUID= <span class="hljs-type">UUID</span>.randomUUID().toString();
        <span class="hljs-keyword">header</span>.<span class="hljs-keyword">add</span>("TRACKING_ID", GUID);
        logger.<span class="hljs-keyword">info</span>("Request with id {} , url {} , body {} to superheroes API ", GUID, request.getUri(), request.getBody());

        <span class="hljs-keyword">return</span> chain.proceed(request);
    }
}
</code></pre><ul>
<li><code>@Filter</code> itself is telling them it's valid for all outgoing HTTP request with <code>**</code></li>
<li><code>doFilter</code> method is adding <code>User-Agent</code> and a custom <code>TRACKING-ID</code> to the header of all outgoing requests.
``` We are logging the tracking id and URL to record the outgoing HTTP requests.</li>
</ul>
<p>We will start the command-center App at 8083. Let is update application.yml accordingly</p>
<pre><code><span class="hljs-attr">micronaut:</span>
  <span class="hljs-attr">application:</span>
    <span class="hljs-attr">name:</span> <span class="hljs-string">commandCenter</span>
  <span class="hljs-attr">server:</span>
    <span class="hljs-attr">port:</span> <span class="hljs-number">8083</span>
</code></pre><h3 id="add-a-filter-in-superhero-api-to-validate-the-incoming-headers">Add a Filter in superhero API to validate the incoming headers</h3>
<p>Since we are adding it for all of the outgoing requests from command-center to Superhero API, let us add another filter to check if it's well-received or not. In case User-Agent and TRACKING_ID are not present in the header, let us simulate it as a bad request</p>
<p>We will add the following class at Superhero API</p>
<pre><code>
<span class="hljs-meta">@Filter</span>(<span class="hljs-string">"/**"</span>)
public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SuperheroServerFilter</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">HttpServerFilter</span> </span>{
    private <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> Logger logger = LoggerFactory.getLogger(SuperheroServerFilter.<span class="hljs-keyword">class</span>);

    <span class="hljs-meta">@Override</span>
    public Publisher&lt;MutableHttpResponse&lt;?&gt;&gt; doFilter(HttpRequest&lt;?&gt; request, ServerFilterChain chain) {
        <span class="hljs-built_in">String</span> userAgent = request.getHeaders().<span class="hljs-keyword">get</span>(<span class="hljs-string">"User-Agent"</span>);
        <span class="hljs-built_in">String</span> trackingId = request.getHeaders().<span class="hljs-keyword">get</span>(<span class="hljs-string">"TRACKING_ID"</span>);
        logger.info(<span class="hljs-string">"Received requests from {} and Tracking id   {} "</span>, userAgent, trackingId);
        <span class="hljs-keyword">if</span> (StringUtils.isEmpty(userAgent) || StringUtils.isEmpty(trackingId)) {
            <span class="hljs-keyword">var</span> map = <span class="hljs-keyword">new</span> HashMap&lt;<span class="hljs-built_in">String</span>, <span class="hljs-built_in">String</span>&gt;();
            map.put(<span class="hljs-string">"id"</span>, <span class="hljs-string">"Please provide a valid tracking id and user agent "</span>);
            <span class="hljs-keyword">return</span> Publishers.just(HttpResponse.ok(map)
                    .status(HttpStatus.FORBIDDEN)
                    .contentType(MediaType.APPLICATION_JSON_TYPE));
        }


        <span class="hljs-keyword">return</span> chain.proceed(request);
    }
</code></pre><ul>
<li>Her as dummy check we have rejected requests who don't have User-Agent and TRACKING-ID in the header and returning Forbidden status. We are also adding a meaningful message as a response (Please provide a valid tracking id and user agent ).
Now we have done all of the hard work, it's showtime. Let us run both of the App and check that flow is working.</li>
</ul>
<pre><code>curl <span class="hljs-comment">--location --request POST 'localhost:8080/superhero' \</span>
<span class="hljs-comment">--header 'User-Agent: Postman' \</span>
<span class="hljs-comment">--header 'TRACKING_ID: TEST_01' \</span>
<span class="hljs-comment">--header 'Content-Type: application/json' \</span>
<span class="hljs-comment">--data-raw '{</span>
    "name": "Bug Killer",
    "prefix": "Miss",
    "suffix": "Bomber",
    "power": "Bomb All the bugs in code"
}<span class="hljs-string">'</span>
</code></pre><p>The response to the above request </p>
<pre><code>{
    <span class="hljs-attr">"id"</span>: <span class="hljs-number">1</span>,
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Bug Killer"</span>,
    <span class="hljs-attr">"prefix"</span>: <span class="hljs-string">"Miss"</span>,
    <span class="hljs-attr">"suffix"</span>: <span class="hljs-string">"Bomber"</span>,
    <span class="hljs-attr">"power"</span>: <span class="hljs-string">"Bomb All the bugs in code"</span>
}
</code></pre><p>Do note that I have only shown POST endpoint . You can check all others similarly. </p>
<p>If you observe the logs , you can see that Filter logs are added in each request at the command-center app which is making an HTTP request and also is intercepted by API and validated. </p>
<h5 id="logs-at-command-center-app">Logs at command-center App</h5>
<pre><code>
06:08:24.857 [main] INFO  io.micronaut.runtime.Micronaut - Startup completed in 892ms. Server Running: http://localhost:8083
06:08:34.869 [io-executor-thread-2] INFO  c.c.CommandCenterController - <span class="hljs-keyword">Call</span> <span class="hljs-keyword">to</span> <span class="hljs-keyword">add</span> a <span class="hljs-keyword">new</span> saviour Superhero[<span class="hljs-keyword">id</span>=<span class="hljs-literal">null</span>, <span class="hljs-keyword">name</span>=Bug Killer, prefix=Miss, suffix=Bomber, <span class="hljs-keyword">power</span>=Bomb <span class="hljs-keyword">All</span> the bugs <span class="hljs-keyword">in</span> code] 
<span class="hljs-number">06</span>:<span class="hljs-number">08</span>:<span class="hljs-number">34.891</span> [io-executor-<span class="hljs-keyword">thread</span><span class="hljs-number">-2</span>] INFO  c.c.c.SuperheroHttpClientFilter - Request <span class="hljs-keyword">with</span> <span class="hljs-keyword">id</span> ee8c9d5e-d5b9<span class="hljs-number">-49</span>df-be6b-b63c4bd9e9fe , <span class="hljs-keyword">url</span> <span class="hljs-keyword">http</span>://localhost:<span class="hljs-number">8080</span>/superhero , <span class="hljs-keyword">body</span> Optional[Superhero[<span class="hljs-keyword">id</span>=<span class="hljs-literal">null</span>, <span class="hljs-keyword">name</span>=Bug Killer, prefix=Miss, suffix=Bomber, <span class="hljs-keyword">power</span>=Bomb <span class="hljs-keyword">All</span> the bugs <span class="hljs-keyword">in</span> code]] <span class="hljs-keyword">to</span> superheroes API
</code></pre><h5 id="logs-at-superhero-api">Logs at Superhero API</h5>
<pre><code>06<span class="hljs-selector-pseudo">:14</span><span class="hljs-selector-pseudo">:32.524</span> <span class="hljs-selector-attr">[default-nioEventLoopGroup-1-2]</span> <span class="hljs-selector-tag">INFO</span>  <span class="hljs-selector-tag">c</span><span class="hljs-selector-class">.c</span><span class="hljs-selector-class">.configs</span><span class="hljs-selector-class">.SuperheroServerFilter</span> <span class="hljs-selector-tag">-</span> <span class="hljs-selector-tag">Received</span> <span class="hljs-selector-tag">requests</span> <span class="hljs-selector-tag">from</span> <span class="hljs-selector-tag">Coding</span> <span class="hljs-selector-tag">Saint</span> <span class="hljs-selector-tag">HTTP</span> <span class="hljs-selector-tag">Client</span> <span class="hljs-selector-tag">and</span> <span class="hljs-selector-tag">Tracking</span> <span class="hljs-selector-tag">id</span>   599<span class="hljs-selector-tag">cc7f7-781d-476f-9d5b-5c4c433b1905</span> 
06<span class="hljs-selector-pseudo">:14</span><span class="hljs-selector-pseudo">:32.830</span> <span class="hljs-selector-attr">[io-executor-thread-2]</span> <span class="hljs-selector-tag">INFO</span>  <span class="hljs-selector-tag">com</span><span class="hljs-selector-class">.codingsaint</span><span class="hljs-selector-class">.SuperHeroController</span> <span class="hljs-selector-tag">-</span> <span class="hljs-selector-tag">Saving</span> <span class="hljs-selector-tag">new</span> <span class="hljs-selector-tag">Superhero</span> <span class="hljs-selector-tag">Superhero</span><span class="hljs-selector-attr">[id=null, name=Bug Killer, prefix=Miss, suffix=Bomber, power=Bomb All the bugs in code]</span>
</code></pre><h3 id="declarative-client-to-call-http-requests-at-other-server">Declarative Client to call HTTP Requests at other Server</h3>
<p>We have written a low-level client with <code>CommandCenterService</code>, it gives us control before calling to Superhero API , but there are chances where you will not be interested in writing the full REST API calls. 
We can use a declarative client which will be an interface. It will call the Superhero API as needed.  Let us create <code>SuperheroClient</code> in the service layer.
Below is the code for the Declarative REST client with Micronaut. </p>
<pre><code>
<span class="hljs-variable">@Client</span>(SUPERHERO_URL)
<span class="hljs-variable">@Header</span>(name = <span class="hljs-string">"Accept"</span>, value = HEADER_ACCEPT)
public interface SuperheroClient {
    <span class="hljs-variable">@Get</span>(<span class="hljs-string">"/rx/superheroes"</span>)
    Flux&lt;Superhero&gt; superheroes();

    <span class="hljs-variable">@Get</span>(<span class="hljs-string">"/rx/superhero/{id}"</span>)
    Mono&lt;Superhero&gt; superheroesById(Long id);

    <span class="hljs-variable">@Post</span>(<span class="hljs-string">"/rx/superhero"</span>)
    Publisher&lt;Superhero&gt; create( <span class="hljs-variable">@Body</span>  Superhero superhero);

    <span class="hljs-variable">@Put</span>(<span class="hljs-string">"/rx/superhero"</span>)
    Publisher&lt;Superhero&gt; update( Superhero superhero);

    <span class="hljs-variable">@Delete</span>(<span class="hljs-string">"/rx/superhero/{id}"</span>)
    Publisher&lt;HttpResponse&lt;Long&gt;&gt; delete(Long id);
</code></pre><p>We can update the Controller and use any of the two i.e. <code>CommandCenterService</code> the low-level client or the SuperheroClient the declarative one.</p>
<h4 id="updated-controller-to-use-declarative-client">Updated Controller to use Declarative Client</h4>
<pre><code> <span class="hljs-meta">@Get(<span class="hljs-meta-string">"superhero/{id}"</span>)</span>
    <span class="hljs-keyword">public</span> Mono&lt;Superhero&gt; superheroesById(<span class="hljs-built_in">Long</span> id) {
        <span class="hljs-comment">/* return service.superheroesById(id);*/</span>
        <span class="hljs-keyword">return</span> client.superheroesById(id);

    }

    <span class="hljs-meta">@Post(<span class="hljs-meta-string">"/superhero"</span>)</span>
    Mono&lt;Superhero&gt; create(<span class="hljs-meta">@Valid</span> Superhero superhero) {
        logger.info(<span class="hljs-string">"Call to add a new saviour {} "</span>, superhero);
      <span class="hljs-comment">/* return Mono.from(service.create(superhero));*/</span>
        <span class="hljs-keyword">return</span> Mono.from(client.create(superhero));
    }

    <span class="hljs-meta">@Put(<span class="hljs-meta-string">"superhero"</span>)</span>
    Mono&lt;Superhero&gt; update(<span class="hljs-meta">@Valid</span> Superhero superhero) {
       <span class="hljs-comment">/* return Mono.from(service.update(superhero));*/</span>
        <span class="hljs-keyword">return</span> Mono.from(client.update(superhero));
    }

    <span class="hljs-meta">@Delete(<span class="hljs-meta-string">"superhero/{id}"</span>)</span>
    Mono&lt;HttpResponse&lt;?&gt;&gt; delete(<span class="hljs-meta">@NotNull</span> <span class="hljs-built_in">Long</span> id) {
       <span class="hljs-comment">/* return Mono
                .from(service.delete(id))
                .map(deleted -&gt; deleted &gt; 0 ? HttpResponse.noContent() : HttpResponse.notFound());*/</span>

         <span class="hljs-keyword">return</span> Mono
                .from(client.delete(id));
    }
</code></pre><ul>
<li>Do note that the service layer is commented , you can use any of them. </li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Caching with Micronaut: Superheroes superquick]]></title><description><![CDATA[Caching with Micronaut]]></description><link>https://digitalyogi.hashnode.dev/caching-with-micronaut</link><guid isPermaLink="true">https://digitalyogi.hashnode.dev/caching-with-micronaut</guid><category><![CDATA[Microservices]]></category><category><![CDATA[Java]]></category><dc:creator><![CDATA[DigitalYogi]]></dc:creator><pubDate>Wed, 08 Sep 2021 19:24:25 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1631128911874/Mi3B5ab9w.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="introduction">Introduction</h3>
<p>Any framework needs to be fast enough to deliver content , Micronaut is no different. In order to deliver content faster, we depend on <strong><em>caching</em></strong>. Micronaut has inbuild support for caching with diffferent cache provider such as Redis, EhCache , Hazelcast etc. Here, we will explore caching implementation with Micronaut. 
 If you wan't the full source code , you can find it below. </p>
<h4 id="source-code-httpsgithubcomcodingsaintsuper-heroestree05cachewithmicronauthttpsgithubcomcodingsaintsuper-heroes">Source code :  <a target="_blank" href="https://github.com/CODINGSAINT/super-heroes">https://github.com/CODINGSAINT/super-heroes/tree/05CacheWithMicronaut</a></h4>
<p>Let's explore micronaut caching. </p>
<h2 id="table-of-content">Table of Content</h2>
<ul>
<li><a class="post-section-overview" href="#goal">Goal</a></li>
<li><a class="post-section-overview" href="#prerequisite">Prerequisite</a></li>
<li><p><a class="post-section-overview" href="#approach">Approach</a></p>
<ul>
<li><a class="post-section-overview" href="#cahceDependecy">Adding the cache dependencies of micronaut</a></li>
<li><p><a class="post-section-overview" href="#properties">Adding the cache properties to yml</a></p>
</li>
<li><p><a class="post-section-overview" href="#serviceLayer">Creating Service layer for cache Database (postgres) and Cache</a></p>
</li>
<li><a class="post-section-overview" href="#controller">Injecting Service layer to controller </a></li>
<li><a class="post-section-overview" href="#running">Running the project</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#conclusion">Conclusion</a>
</p><div id="id-goal"><p></p>
<h3 id="goal">Goal</h3>
<p>The goal of this article is simple. We need a service that demonstrates caching capabilities.</p>
</div></li>
<li>System must cache the superheroes whenever they are called.</li>
<li>Every next call to the service should not be hitting the database but our caches.</li>
<li>Every update on superhero API should also update the cache object. </li>
<li>Once any superhero is deleted cache should be invalidated and next time any call to superhero GET API should fetch from the database again.</li>
</ul>
<p></p><div id="id-prerequisite"><p></p>
<h3 id="prerequisite">Prerequisite</h3>
<p>We have created the application with a reactive database (postgres) . We will use same for adding caching capabilities to our projects.
You can check the previous where we added testcontains at  <a target="_blank" href="https://blog.pallav.dev/realtime-testing-micronaut-postgres-and-testcontainer">https://blog.pallav.dev/realtime-testing-micronaut-postgres-and-testcontainer</a> 
You can also check the entire series at  <a target="_blank" href="https://blog.pallav.dev/series/micronaut">https://blog.pallav.dev/series/micronaut</a> </p>
<p></p><div id="id-approach"><p></p>
<h3 id="approach">Approach</h3>
<p></p><div id="id-cahceDependecy"><p></p>
<h4 id="adding-the-cache-dependencies-of-micronaut">Adding the cache dependencies of micronaut</h4>
<p>Add below dependencies to <code>pom.xml</code></p>
<pre><code><span class="hljs-comment">&lt;!-- 05 Cache Configs --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>io.micronaut.cache<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>micronaut-cache-caffeine<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">scope</span>&gt;</span>compile<span class="hljs-tag">&lt;/<span class="hljs-name">scope</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>

      <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>io.micronaut.cache<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>micronaut-cache-management<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>

    <span class="hljs-comment">&lt;!-- 05 cache Configs ends--&gt;</span>
</code></pre><p></p><div id="id-properties"><p></p>
<h4 id="adding-the-cache-properties-to-yml">Adding the cache properties to yml</h4>
<p>Let us add the properties to application yml ,which will tell the caches the system will configure</p>
<pre><code> <span class="hljs-comment">#cache related</span>
<span class="hljs-attr">micronaut:</span>
  <span class="hljs-attr">caches:</span>
    <span class="hljs-attr">superheroes:</span>
      <span class="hljs-attr">charset:</span> <span class="hljs-string">'UTF-8'</span>
    <span class="hljs-attr">superhero:</span>
      <span class="hljs-attr">charset:</span> <span class="hljs-string">'UTF-8'</span>
<span class="hljs-attr">endpoints:</span>
  <span class="hljs-attr">caches:</span>
    <span class="hljs-attr">enabled:</span> <span class="hljs-literal">true</span>
    <span class="hljs-attr">sensitive:</span> <span class="hljs-literal">false</span>
</code></pre><div id="id-serviceLayer">

<h4 id="creating-service-layer-for-cache-database-postgres-and-cache">Creating Service layer for cache Database (postgres) and Cache</h4>
<p>Till now we have been injecting DAO to controller , now it's a good use case to create a service layer which will do the talking to cache &amp; db . It act as bridge between controllers and others.
Let us add the service layer . Create a Service class as following with Repository and Cache Injected to it</p>
<pre><code><span class="hljs-meta">@Singleton</span>
<span class="hljs-meta">@CacheConfig(<span class="hljs-meta-string">"superheroes"</span>)</span><span class="hljs-comment">//1</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SuperheroService</span> </span>{
    <span class="hljs-keyword">private</span> static <span class="hljs-keyword">final</span> Logger logger = LoggerFactory.getLogger(SuperheroService.<span class="hljs-keyword">class</span>);
    <span class="hljs-keyword">protected</span> ReactiveSuperheroRepository reactiveSuperheroRepository;
    @Inject
    <span class="hljs-keyword">private</span> CacheManager cacheManager;
    SuperheroService(ReactiveSuperheroRepository superheroRepository) {
        this.reactiveSuperheroRepository = superheroRepository;

    }


    <span class="hljs-keyword">public</span> Flux&lt;Superhero&gt; superheroes() {
        logger.info(<span class="hljs-string">"Fetching all of the superheroes in universe "</span>);
        <span class="hljs-keyword">return</span> reactiveSuperheroRepository.findAll();
    }


    <span class="hljs-meta">@Cacheable( cacheNames = {<span class="hljs-meta-string">"superheroes"</span>}, parameters ={<span class="hljs-meta-string">"id"</span>}  )</span><span class="hljs-comment">//1</span>
    <span class="hljs-keyword">public</span> Mono&lt;Superhero&gt; superheroesById(<span class="hljs-built_in">Long</span> id) {
        logger.info(<span class="hljs-string">"Finding the saviour  id {} "</span>, id);
        <span class="hljs-keyword">return</span> reactiveSuperheroRepository.findById(id);

    }

    <span class="hljs-keyword">public</span> Publisher&lt;Superhero&gt; create(Superhero superhero) {
        logger.info(<span class="hljs-string">"Adding a new saviour {} "</span>, superhero);
        <span class="hljs-keyword">var</span> created = reactiveSuperheroRepository.save(superhero);
        <span class="hljs-keyword">return</span> created;
    }

    <span class="hljs-meta">@CachePut( cacheNames = <span class="hljs-meta-string">"superheroes"</span>, parameters = <span class="hljs-meta-string">"id"</span>)</span><span class="hljs-comment">//2</span>
    <span class="hljs-keyword">public</span> Publisher&lt;Superhero&gt; update(Superhero superhero, <span class="hljs-built_in">Long</span> id) {
        logger.info(<span class="hljs-string">"Updating the old saviour {} "</span>, superhero);
        <span class="hljs-keyword">var</span> updated=reactiveSuperheroRepository.update(superhero);

        <span class="hljs-keyword">return</span> updated;
    }

    <span class="hljs-meta">@CacheInvalidate(cacheNames = {<span class="hljs-meta-string">"superheroes"</span>},parameters = <span class="hljs-meta-string">"id"</span> ,async = true)</span><span class="hljs-comment">//4</span>
    <span class="hljs-keyword">public</span> Publisher&lt;<span class="hljs-built_in">Long</span>&gt; delete(<span class="hljs-built_in">Long</span> id) {
        <span class="hljs-keyword">var</span> deleted= reactiveSuperheroRepository.deleteById(id);

        <span class="hljs-keyword">return</span> deleted;
    }


}
</code></pre><ol>
<li><code>CacheConfig</code>: It is optional to add if we use <code>@Cacheable</code> but added as just to show</li>
<li><code>@Cacheable</code>:  As the name suggests, tells that this method can be cached <code>cacheName</code> stores names of the caches and <code>parameters</code> tells the id with which cache will be created. If the method has only one parameter, it can be avoided.  POST method will add the superhero and once it will be retrieved from the database on <code>GET</code>. As the method is annotated with <code>Cachaeable</code>, next time whenever the same superhero will be called it will be given from cache rather than DB </li>
<li><code>CachePut</code>: Will update the cache with the given <code>parameter</code> (key), It will help us when there is a change in superhero properties. It will automatically cache the newer version with the same key. </li>
<li><code>CacheInvalidate</code>: removes the cache all together with <code>parameter</code> (key). This will invalidate the superhero so when it will be asked to give the same superhero again, we will not be getting the value from cache and a DB hit will happen.</li>
</ol>
<p></p><div id="id-controller"><p></p>
<h4 id="injecting-service-layer-to-controller">Injecting Service layer to controller</h4>
<p>Till now we have been calling the database from Controller but now we will call the Service layer, so we will inject the same and remove the repository (which is moved to service)</p>
<pre><code><span class="hljs-meta">@Controller(<span class="hljs-meta-string">"rx/"</span>)</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ReactiveSuperHeroController</span> </span>{
    <span class="hljs-keyword">private</span> static <span class="hljs-keyword">final</span> Logger logger = LoggerFactory.getLogger(SuperHeroController.<span class="hljs-keyword">class</span>);

    <span class="hljs-keyword">private</span> SuperheroService service;

    <span class="hljs-keyword">public</span> ReactiveSuperHeroController(SuperheroService service) {
        this.service = service;
    }

    @Get(<span class="hljs-string">"superheroes"</span>)
    <span class="hljs-keyword">public</span> Flux&lt;Superhero&gt; superheroes() {
        <span class="hljs-keyword">return</span> service.superheroes();
    }

    <span class="hljs-meta">@Get(<span class="hljs-meta-string">"superhero/{id}"</span>)</span>
    <span class="hljs-keyword">public</span> Mono&lt;Superhero&gt; superheroesById(<span class="hljs-built_in">Long</span> id) {

        <span class="hljs-keyword">return</span> service.superheroesById(id);

    }

    <span class="hljs-meta">@Post(<span class="hljs-meta-string">"/superhero"</span>)</span>
    Single&lt;Superhero&gt; create(<span class="hljs-meta">@Valid</span> Superhero superhero) {
        logger.info(<span class="hljs-string">"Call to add a new saviour {} "</span>, superhero);
        <span class="hljs-keyword">return</span> Single.fromPublisher(service.create(superhero));
    }

    <span class="hljs-meta">@Put(<span class="hljs-meta-string">"superhero"</span>)</span>
    Single&lt;Superhero&gt; update( <span class="hljs-meta">@Valid</span> Superhero superhero) {
        <span class="hljs-keyword">return</span> Single.fromPublisher(service.update(superhero, superhero.id()));
    }
    <span class="hljs-meta">@Delete(<span class="hljs-meta-string">"superhero/{id}"</span>)</span>
    Single&lt;HttpResponse&lt;?&gt;&gt; delete(<span class="hljs-meta">@NotNull</span> <span class="hljs-built_in">Long</span> id) {
        <span class="hljs-keyword">return</span> Single
                .fromPublisher(service.delete(id))
                .map(deleted-&gt;deleted&gt;<span class="hljs-number">0</span>?HttpResponse.noContent():HttpResponse.notFound());
    }
}
</code></pre><p></p><div id="id-running"><p></p>
<h3 id="running-the-project">Running the project</h3>
<p>Now we can run the project and Create few Superheroes and do CRUD operations. We will keep an eye on logs to see if the method (GET) is being called multiple times. It is expected that the Cachable method will be called only when the call for the superhero is for the first time.</p>
<p>Below is the CURL request to create  (POST)</p>
<pre><code>curl <span class="hljs-comment">--location --request POST 'http://localhost:8080/rx/superhero' \</span>
<span class="hljs-comment">--header 'Content-Type: application/json' \</span>
<span class="hljs-comment">--data-raw '{</span>
    "name": "Justice Hammer",
    "prefix": "Captain",
    "suffix": "Walker",
    "power": "Lightening Thunder"
}<span class="hljs-string">'</span>
</code></pre><p>Now we will hit GET multiple times but logs will print only once from the service layer</p>
<pre><code><span class="hljs-attribute">curl</span> --location --request GET 'http://localhost:<span class="hljs-number">8080</span>/rx/superhero/<span class="hljs-number">1</span>'
<span class="hljs-attribute">curl</span> --location --request GET 'http://localhost:<span class="hljs-number">8080</span>/rx/superhero/<span class="hljs-number">1</span>'
<span class="hljs-attribute">curl</span> --location --request GET 'http://localhost:<span class="hljs-number">8080</span>/rx/superhero/<span class="hljs-number">1</span>'
</code></pre><p>We can see in the logs below that the service layer is called once, post that it is not called as the values have been returned from the cache.</p>
<p>We can also update and check still, the GET log will not print as an update on the same hero will be also updated in the cache.  Once deleted it will try again to check from DB as the cache is invalidated.</p>
<p>The logs of the above operation will be </p>
<pre><code><span class="hljs-selector-tag">our</span> <span class="hljs-selector-tag">Superhero</span><span class="hljs-selector-attr">[id=null, name=Justice Hammer, prefix=Captain, suffix=Walker, power=Lightening Thunder]</span> 
00<span class="hljs-selector-pseudo">:42</span><span class="hljs-selector-pseudo">:06.300</span> <span class="hljs-selector-attr">[default-nioEventLoopGroup-1-3]</span> <span class="hljs-selector-tag">INFO</span>  <span class="hljs-selector-tag">c</span><span class="hljs-selector-class">.c</span><span class="hljs-selector-class">.service</span><span class="hljs-selector-class">.SuperheroService</span> <span class="hljs-selector-tag">-</span> <span class="hljs-selector-tag">Adding</span> <span class="hljs-selector-tag">a</span> <span class="hljs-selector-tag">new</span> <span class="hljs-selector-tag">saviour</span> <span class="hljs-selector-tag">Superhero</span><span class="hljs-selector-attr">[id=null, name=Justice Hammer, prefix=Captain, suffix=Walker, power=Lightening Thunder]</span> 
00<span class="hljs-selector-pseudo">:44</span><span class="hljs-selector-pseudo">:44.132</span> <span class="hljs-selector-attr">[default-nioEventLoopGroup-1-3]</span> <span class="hljs-selector-tag">INFO</span>  <span class="hljs-selector-tag">c</span><span class="hljs-selector-class">.c</span><span class="hljs-selector-class">.service</span><span class="hljs-selector-class">.SuperheroService</span> <span class="hljs-selector-tag">-</span> <span class="hljs-selector-tag">Finding</span> <span class="hljs-selector-tag">the</span> <span class="hljs-selector-tag">saviour</span>  <span class="hljs-selector-tag">id</span> 1
</code></pre><p></p><div id="id-conclusion"><p></p>
<h3 id="conclusion">Conclusion</h3>
<p>We saw that caching has reduced the load on DB and significantly improved performance. If you have not noticed performance benefits, check time taken with the first call and the subsequent (<code>Cacheable</code>) method calls </p>
</div></div></div></div></div></div></div></div>]]></content:encoded></item></channel></rss>