<?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" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Antony Christopher on Medium]]></title>
        <description><![CDATA[Stories by Antony Christopher on Medium]]></description>
        <link>https://medium.com/@antoblog?source=rss-f4f0186b13fb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fKmZ0UNQ7ztP6zgrGHvOOA.jpeg</url>
            <title>Stories by Antony Christopher on Medium</title>
            <link>https://medium.com/@antoblog?source=rss-f4f0186b13fb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 04:03:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@antoblog/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Stop Wasting Tokens: How Graphify Gives Claude Code a Persistent Memory]]></title>
            <link>https://antoblog.medium.com/stop-wasting-tokens-how-graphify-gives-claude-code-a-persistent-memory-c2a450c535a4?source=rss-f4f0186b13fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2a450c535a4</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[claude-code]]></category>
            <dc:creator><![CDATA[Antony Christopher]]></dc:creator>
            <pubDate>Wed, 13 May 2026 06:18:39 GMT</pubDate>
            <atom:updated>2026-05-13T06:18:39.005Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*Ij7xrgqCDdfmyo1TDHSlUw.png" /></figure><p>If you’ve spent any serious time working with Claude Code, you’ve probably felt the friction: every new session, Claude re-reads your project files from scratch. It doesn’t remember what it learned yesterday. It burns tokens rediscovering the same functions, the same architecture, the same documentation — over and over again.</p><p><strong>Graphify</strong> is a free, open-source tool designed to solve exactly this problem. Instead of letting Claude Code relearn your project every session, Graphify maps your entire codebase into a structured knowledge graph — once — and makes it available automatically at the start of every future session.</p><h3>The Core Problem: Claude Code Starts Blind Every Time</h3><p>Claude Code is powerful, but it has no persistent memory between sessions. Each time you open a new chat, it re-reads your files, re-processes your documentation, and reconstructs its understanding of your project from scratch. For large or complex projects, this isn’t just inefficient — it’s expensive in both time and tokens.</p><p>The diagram below makes the contrast clear:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*pxpoaqePy1N1keEKLP6wOg.png" /></figure><h3>What Graphify Actually Does</h3><p>Graphify builds a <strong>knowledge graph</strong> of your project: a structured map of nodes (functions, classes, documents, concepts) connected by edges (relationships like calls, imports, references). Think of it as a permanent, navigable summary of everything in your project folder.</p><p>Once built, this graph is injected automatically at the start of every Claude Code session via a <strong>PreToolUse hook</strong> — replacing dozens of file reads with a single structured map. Claude reads the graph instead of your files, arriving at each session already oriented.</p><p>And it works on more than just code. Graphify handles any folder — research papers, meeting notes, strategy documents, content vaults. If it’s text, it can be graphed.</p><h3>The Architecture: Three Passes, Minimal Token Cost</h3><p><strong>Pass 1 — Code Parsing (Zero token cost)</strong><br>This runs entirely on your local machine. It parses your code files, extracts functions and classes, and maps their relationships — without touching Claude’s API at all.</p><p><strong>Pass 2 — Structure Mapping</strong><br>Dependencies, imports, and cross-file relationships are resolved and organized into neighborhoods within the graph.</p><p><strong>Pass 3 — Documentation Extraction (One-time API cost)</strong><br>This is the only pass that calls Claude’s API, and it only runs once. It extracts concepts and summaries from your documentation and markdown files, enriching the graph with human-readable context.</p><p>After the initial build, updates to the graph are incremental. You’re not paying a full rebuild cost every time you modify a file.</p><h3>The Real Token Savings: What the Numbers Actually Mean</h3><p>Graphify’s marketing cites a <strong>71.5x token reduction</strong> benchmark — technically true in a very specific scenario: comparing against pasting your entire codebase directly into context at once. Almost nobody actually works that way.</p><p>In a realistic test — 10 questions across two identical Claude Code sessions on the browser-use project — the numbers looked like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*20NpHsAicZlZsZCxgqhSpQ.png" /></figure><h3>How to Set It Up (Step by Step)</h3><p>Getting started takes under five minutes:</p><pre># Step 1: Install Graphify<br># ⚠️  Double &quot;y&quot; — graphifyy — the single-y package on PyPI is unrelated<br>pip install graphifyy\<br><br># Step 2: Register the always-on PreToolUse hook<br>graphify install<br><br># Step 3: Claude Code<br>graphify claude install <br><br># Step 4: Build your graph inside a Claude Code session<br>/graphify</pre><p>Once the graph is built, Claude Code reads it automatically at the start of every subsequent session. Update it at any time by running /graphify again.</p><h3>Keeping Your Graph Fresh</h3><p>Two commands handle everything after the initial setup:</p><pre># Incrementally rebuild after codebase changes<br># Only reprocesses modified files — cheap and fast<br>graphify --update<br><br># Wire the auto-inject hook into Claude Code (one-time)<br># Makes Claude read the graph at the start of every session automatically<br>graphify hook install</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*TaSkfn979dlrysxmiM3dHQ.png" /></figure><h3>Beyond Code: Graphify for Research and Business Folders</h3><p>Because Pass 1 (code parsing) is simply skipped when there’s no code to parse, Graphify works just as well on non-code folders:</p><ul><li><strong>Research folders</strong> — papers, notes, bibliographies</li><li><strong>Content vaults</strong> — blog drafts, strategy docs, brand guidelines</li><li><strong>Business folders</strong> — meeting recordings, project briefs, process documentation</li></ul><p>The ability to drop Claude into a folder of PDFs and markdown files — and have it arrive already aware of the structure and key concepts — changes how you can work with AI assistants on long-running projects.</p><h3>When Graphify Makes Sense (and When It Doesn’t)</h3><p>Graphify is worth the setup if you’re working on a mid-to-large codebase across multiple sessions, your project mixes code and documentation, you run long sessions with many questions, or you manage non-code knowledge bases you want Claude to navigate efficiently.</p><p>It may not be worth it if you’re running short one-off sessions on small projects, your codebase changes so rapidly that graph updates become frequent overhead, or you’re primarily pasting small snippets rather than navigating a full project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*ihRrW0YfukgH3DZEy1YJKg.png" /></figure><p>Graphify on Github : <a href="https://github.com/safishamsi/graphify">github.com/safishamsi/graphify</a></p><p>Graphify reference docs: <a href="https://graphify.net/index.html">https://graphify.net/index.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2a450c535a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Circuit Breaker with Spring Boot]]></title>
            <link>https://antoblog.medium.com/circuit-breaker-with-spring-boot-e080ac9a53d9?source=rss-f4f0186b13fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/e080ac9a53d9</guid>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-training]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Antony Christopher]]></dc:creator>
            <pubDate>Tue, 18 Feb 2025 04:51:49 GMT</pubDate>
            <atom:updated>2025-02-18T04:51:49.916Z</atom:updated>
            <content:encoded><![CDATA[<p>In the microservices design pattern, the circuit breaker plays a vital role in the distribution system. It handles the faults while calling the remote services. The purpose of the circuit breaker is to avoid cascading failure and provide a fallback mechanism when service is unavailable or experiencing issues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bm-8nq7hGqrIpXwTSujOpg.png" /></figure><h4><strong>What is a circuit breaker pattern?</strong></h4><p>We may come across the circuit breaker in the electronics, which is designed to prevent electrical overload. Similarly, in a software circuit breaker monitor the calls to a remote service.</p><p><strong>How the pattern works?</strong></p><p>If the number of failures exceeds the threshold value, the circuit breaker turns to an ‘Open’ state. This means any subsequent calls to remote service fall to the default fallback mechanism. such as returning a cached response or providing a default value.</p><p>This prevents the additional load on failing service and allows to recover it without disrupting the system.</p><p>Here’s how the circuit breaker pattern typically works in a microservices architecture:</p><p><strong>1. Closed State:</strong></p><ul><li>Initially, the circuit breaker is in a “closed” state, allowing calls to the remote service to proceed as normal.</li><li>During this state, the circuit breaker monitors the calls to the remote service. If the call succeeds, it resets the failure count. If the call fails, it increments the failure count.</li></ul><p><strong>2. Open State:</strong></p><ul><li>If the number of failures within a specified time window exceeds a predefined threshold, the circuit breaker transitions to an “open” state.</li><li>In the open state, subsequent calls to the remote service are intercepted, and the circuit breaker immediately returns a predefined fallback response without attempting to call the remote service.</li><li>This prevents additional calls from overwhelming the failing service and allows it time to recover.</li></ul><h4>3. Half-Open State:</h4><ul><li>After a certain period of time, the circuit breaker enters a “half-open” state, where it allows a limited number of calls to the remote service to test if it has recovered.</li><li>If these test calls succeed, the circuit breaker transitions back to the closed state, allowing normal operation to resume.</li><li>If the test calls continue to fail, the circuit breaker remains in the open state, and the process repeats.</li></ul><p>To implement the circuit breaker in the Spring Boot microservices. We are using the <strong>Resilience4j</strong> library for implementation.</p><p><strong>Resilience4j </strong>is a lightweight fault-tolerance library for Java applications, inspired by Netflix Hystrix. It provides various features.</p><ol><li><strong>Circuit Breaker</strong>: Prevents cascading failures by opening a circuit when a service consistently fails.</li><li><strong>Retry</strong>: Automatically retries failed operations with customizable backoff strategies.</li><li><strong>Rate Limiter</strong>: Limits the number of calls to a resource in a given timeframe.</li><li><strong>Bulkhead</strong>: Limits the number of concurrent calls to prevent resource exhaustion.</li><li><strong>TimeLimiter</strong>: Sets timeouts for operations to avoid indefinite waiting.</li><li><strong>Cache</strong>: Caches responses to reduce load on external services.</li></ol><p>Let’s start implementing the circuit breaker using Spring Boot.</p><p>Create two microservices services namely department &amp; employee services. Each service runs independently in a separate Tomcat instance.</p><p>From the employee service need to call the department service to know the department details for an employee.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iciAfLBt7L4SHfAmoyTBkw.png" /></figure><p>We need to include the <strong>Resilience4</strong>j dependency for the employee project</p><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-cloud-starter-circuitbreaker-resilience4j&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>In addition to that we need to configure the properties on the employee-service.</p><ul><li><strong>failureRateThreshold</strong> — Expected percentage of the failure threshold.<br>I have set it as 50%. It means, when total failed remote calls % is equal or greater than 50%, breaker will be active to stop furthermore requests.</li><li><strong>minimumNumberOfCalls</strong> — Minimum number of total API calls to decide failure percentage to enable the breaker.<br>I have set it as 5. Let’s say 3 API calls are failing from the the first 5 API calls. It means failureRateThreshold = (3/5) * 100 = 60%.</li><li><strong>automaticTransitionFromOpenToHalfOpenEnabled</strong> — I have set this as true. It will automatically transfer OPEN state to HALF OPEN state when it comes the right time for that transition.</li><li><strong>waitDurationInOpenState</strong> — Timeout period before going to HALF OPEN state from OPEN state. After 5 seconds, breaker will change the state, here.</li><li><strong>permittedNumberOfCallsInHalfOpenState</strong> — Number of LIMITED API calls that should be sent while in HALF OPEN state. I have set it as 3. So, after 3 API calls, if they are failed, then breaker will again go to OPEN state. Otherwise breaker will be CLOSED since rate-service is UP.</li><li><strong>slidingWindowType</strong>: Here I have set the type to keep the circuit breaker behavior based on the requests counts.</li></ul><pre><br># Circuit Breaker configuration<br>resilience4j.circuitbreaker.instances.EMPLOYEE-SERVICE.registerHealthIndicator=true <br>resilience4j.circuitbreaker.instances.EMPLOYEE-SERVICE.failureRateThreshold=50<br>resilience4j.circuitbreaker.instances.EMPLOYEE-SERVICE.minimumNumberOfCalls=5<br>resilience4j.circuitbreaker.instances.EMPLOYEE-SERVICE.automaticTransitionFromOpenToHalfOpenEnabled=true<br>resilience4j.circuitbreaker.instances.EMPLOYEE-SERVICE.waitDurationInOpenState=5s<br>resilience4j.circuitbreaker.instances.EMPLOYEE-SERVICE.permittedNumberOfCallsInHalfOpenState=3<br>resilience4j.circuitbreaker.instances.EMPLOYEE-SERVICE.slidingWindowSize=10<br>resilience4j.circuitbreaker.instances.EMPLOYEE-SERVICE.slidingWindowType=COUNT_BASED<br><br># Retry configuration<br>resilience4j.retry.instances.EMPLOYEE-SERVICE.registerHealthIndicator=true<br>resilience4j.retry.instances.EMPLOYEE-SERVICE.maxAttempts=5<br>resilience4j.retry.instances.EMPLOYEE-SERVICE.waitDuration=2s</pre><p>On the code implementation need to add the fallback mechanism by applying the annotation of</p><p><strong>@Retry(name=”${spring.application.name}”, fallbackMethod = “getDefaultDepartment”)</strong></p><p>The @Retry annotation in Resilience4j is used to automatically retry a failed operation before falling back to a default method.</p><p>If the method fails after retries, it falls back to getDefaultDepartment.</p><pre><br>@Retry(name=&quot;${spring.application.name}&quot;, fallbackMethod = &quot;getDefaultDepartment&quot;)<br>@Override<br>public APIResponseDto getEmployeeById(Long employeeId) throws ResourceNotFoundException {<br><br>      LOGGER.info(&quot;Get employee by Id:&quot;);<br><br>      Employee employee = employeeRepository.findById(employeeId).orElseThrow(<br>                () -&gt; new ResourceNotFoundException(&quot;Employee&quot;, &quot;Id&quot;, employeeId)<br>        );<br><br>     // Calling another microservices using webClient<br>      DepartmentDto webClntResponse  = webclient.get()<br>                .uri(&quot;http://localhost:8080/api/departments/&quot; + employee.getDepartmentCode())<br>                .retrieve()<br>                .bodyToMono(DepartmentDto.class)<br>                .block();<br><br><br>     EmployeeDto employeeDtoMapStruct = AutoUserMapper.MAPPER.mapToEmployee(employee);<br><br>        APIResponseDto apiResponseDto = new APIResponseDto();<br>        apiResponseDto.setEmployee(employeeDtoMapStruct);<br>        apiResponseDto.setDepartment(webClntResponse);<br>        return apiResponseDto;<br>    }<br><br></pre><p>Creating the fallback method as below.</p><pre> public APIResponseDto getDefaultDepartment(Long employeeId, Exception exception){<br><br>       LOGGER.info(&quot;Inside the defalut department mthd() &quot;);<br><br>       Employee employee = employeeRepository.findById(employeeId).get();<br><br>       DepartmentDto departmentDto = new DepartmentDto();<br>       departmentDto.setDepartmentName(&quot;R&amp;D Department&quot;);<br>       departmentDto.setDepartmentCode(&quot;RD001&quot;);<br>       departmentDto.setDepartmentDescription(&quot;Research and Development Department&quot;);<br><br>       EmployeeDto employeeDto = new EmployeeDto(<br>               employee.getId(),<br>               employee.getFirstName(),<br>               employee.getLastName(),<br>               employee.getEmail(),<br>               employee.getDepartmentCode(),<br>               employee.getOrganizationCode()<br>       );<br><br>        APIResponseDto apiResponseDto = new APIResponseDto();<br>        apiResponseDto.setEmployee(employeeDto);<br>        apiResponseDto.setDepartment(departmentDto);<br><br>        return apiResponseDto;<br>    }</pre><p><strong>Start</strong> both services. Now go to the Employee service actuator URL and see how the circuit breaker is shown here: <a href="http://localhost:8081/actuator/health">http://localhost:8081/actuator/health</a>.</p><pre> &quot;circuitBreakers&quot;: {<br>      &quot;status&quot;: &quot;UP&quot;,<br>      &quot;details&quot;: {<br>        &quot;EMPLOYEE-SERVICE&quot;: {<br>          &quot;status&quot;: &quot;UP&quot;,<br>          &quot;details&quot;: {<br>            &quot;failureRate&quot;: &quot;-1.0%&quot;,<br>            &quot;failureRateThreshold&quot;: &quot;50.0%&quot;,<br>            &quot;slowCallRate&quot;: &quot;-1.0%&quot;,<br>            &quot;slowCallRateThreshold&quot;: &quot;100.0%&quot;,<br>            &quot;bufferedCalls&quot;: 0,<br>            &quot;slowCalls&quot;: 0,<br>            &quot;slowFailedCalls&quot;: 0,<br>            &quot;failedCalls&quot;: 0,<br>            &quot;notPermittedCalls&quot;: 0,<br>            &quot;state&quot;: &quot;CLOSED&quot;<br>          }<br>        }<br>      }<br>    }</pre><p>Now, call the API <a href="http://localhost:8081/api/employees/2">http://localhost:8081/api/employees/2</a> to get the department details along with the employee. Verify the circuit breaker actuator. The bufferedCalls updated the count to 1. The count get increment on each API call from the employee service.</p><pre>&quot;circuitBreakers&quot;: {<br>      &quot;status&quot;: &quot;UP&quot;,<br>      &quot;details&quot;: {<br>        &quot;EMPLOYEE-SERVICE&quot;: {<br>          &quot;status&quot;: &quot;UP&quot;,<br>          &quot;details&quot;: {<br>            &quot;failureRate&quot;: &quot;-1.0%&quot;,<br>            &quot;failureRateThreshold&quot;: &quot;50.0%&quot;,<br>            &quot;slowCallRate&quot;: &quot;-1.0%&quot;,<br>            &quot;slowCallRateThreshold&quot;: &quot;100.0%&quot;,<br>            &quot;bufferedCalls&quot;: 1,<br>            &quot;slowCalls&quot;: 0,<br>            &quot;slowFailedCalls&quot;: 0,<br>            &quot;failedCalls&quot;: 0,<br>            &quot;notPermittedCalls&quot;: 0,<br>            &quot;state&quot;: &quot;CLOSED&quot;<br>          }<br>        }<br>      }<br>    }</pre><p>Stop the department service, now hit the API-URL 4 times. This will lead buffered calls to count to 5. The failedCalls count applied to 4 out of 5. Now the failure rate could be (4/5*100), then 80% exceeds the threshold value. Then the status changed to ‘Open’</p><pre> &quot;circuitBreakers&quot;: {<br>      &quot;status&quot;: &quot;UNKNOWN&quot;,<br>      &quot;details&quot;: {<br>        &quot;EMPLOYEE-SERVICE&quot;: {<br>          &quot;status&quot;: &quot;CIRCUIT_OPEN&quot;,<br>          &quot;details&quot;: {<br>            &quot;failureRate&quot;: &quot;80.0%&quot;,<br>            &quot;failureRateThreshold&quot;: &quot;50.0%&quot;,<br>            &quot;slowCallRate&quot;: &quot;0.0%&quot;,<br>            &quot;slowCallRateThreshold&quot;: &quot;100.0%&quot;,<br>            &quot;bufferedCalls&quot;: 5,<br>            &quot;slowCalls&quot;: 0,<br>            &quot;slowFailedCalls&quot;: 0,<br>            &quot;failedCalls&quot;: 4,<br>            &quot;notPermittedCalls&quot;: 0,<br>            &quot;state&quot;: &quot;OPEN&quot;<br>          }<br>        }<br>      }<br>    }</pre><p>Then wait for 5s seconds, and the status changed to ‘HAF-OPEN’. As per our configuration, we have set <strong>waitDurationInOpenState to 5s</strong>…</p><pre>&quot;circuitBreakers&quot;: {<br>      &quot;status&quot;: &quot;UNKNOWN&quot;,<br>      &quot;details&quot;: {<br>        &quot;EMPLOYEE-SERVICE&quot;: {<br>          &quot;status&quot;: &quot;CIRCUIT_HALF_OPEN&quot;,<br>          &quot;details&quot;: {<br>            &quot;failureRate&quot;: &quot;-1.0%&quot;,<br>            &quot;failureRateThreshold&quot;: &quot;50.0%&quot;,<br>            &quot;slowCallRate&quot;: &quot;-1.0%&quot;,<br>            &quot;slowCallRateThreshold&quot;: &quot;100.0%&quot;,<br>            &quot;bufferedCalls&quot;: 0,<br>            &quot;slowCalls&quot;: 0,<br>            &quot;slowFailedCalls&quot;: 0,<br>            &quot;failedCalls&quot;: 0,<br>            &quot;notPermittedCalls&quot;: 0,<br>            &quot;state&quot;: &quot;HALF_OPEN&quot;<br>          }<br>        }<br>      }<br>    }</pre><p>Within HALF OPEN state, <strong>limited number of requests will be allowed</strong> to pass. In our case it is 3 in the configs the relevant value has been set as permittedNumberOfCallsInHalfOpenState: 3.<br>Since still department-serice is down, just try API 3 times again! All 3 calls failed! Then <strong>failureRate is 100%</strong>. Again our circuit breaker will be opened.</p><pre> &quot;circuitBreakers&quot;: {<br>      &quot;status&quot;: &quot;UNKNOWN&quot;,<br>      &quot;details&quot;: {<br>        &quot;EMPLOYEE-SERVICE&quot;: {<br>          &quot;status&quot;: &quot;CIRCUIT_OPEN&quot;,<br>          &quot;details&quot;: {<br>            &quot;failureRate&quot;: &quot;100.0%&quot;,<br>            &quot;failureRateThreshold&quot;: &quot;50.0%&quot;,<br>            &quot;slowCallRate&quot;: &quot;0.0%&quot;,<br>            &quot;slowCallRateThreshold&quot;: &quot;100.0%&quot;,<br>            &quot;bufferedCalls&quot;: 3,<br>            &quot;slowCalls&quot;: 0,<br>            &quot;slowFailedCalls&quot;: 0,<br>            &quot;failedCalls&quot;: 3,<br>            &quot;notPermittedCalls&quot;: 0,<br>            &quot;state&quot;: &quot;OPEN&quot;<br>          }<br>        }<br>      }<br>    }</pre><p>Now start the department service, Call the API 3 times and the response is getting the expected one. The circuit breaker status changed to an Open state. Because the expected limited API call count is successfully executed.</p><pre> &quot;circuitBreakers&quot;: {<br>      &quot;status&quot;: &quot;UP&quot;,<br>      &quot;details&quot;: {<br>        &quot;EMPLOYEE-SERVICE&quot;: {<br>          &quot;status&quot;: &quot;UP&quot;,<br>          &quot;details&quot;: {<br>            &quot;failureRate&quot;: &quot;-1.0%&quot;,<br>            &quot;failureRateThreshold&quot;: &quot;50.0%&quot;,<br>            &quot;slowCallRate&quot;: &quot;-1.0%&quot;,<br>            &quot;slowCallRateThreshold&quot;: &quot;100.0%&quot;,<br>            &quot;bufferedCalls&quot;: 0,<br>            &quot;slowCalls&quot;: 0,<br>            &quot;slowFailedCalls&quot;: 0,<br>            &quot;failedCalls&quot;: 0,<br>            &quot;notPermittedCalls&quot;: 0,<br>            &quot;state&quot;: &quot;CLOSED&quot;<br>          }<br>        }<br>      }<br>    }</pre><p>Now we practically saw how the breaker is behaving right? Isn’t amazing?? 😎 It is working as expected guys!!!</p><p>When choosing a circuit breaker implementation for your Spring Boot application, consider factors such as ease of integration, performance, features, and community support. Additionally, it’s essential to configure circuit breakers appropriately based on the characteristics of your application and its dependencies to achieve optimal resilience and fault tolerance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e080ac9a53d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Cloud Bus]]></title>
            <link>https://antoblog.medium.com/spring-cloud-bus-2b2cebb29272?source=rss-f4f0186b13fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b2cebb29272</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <dc:creator><![CDATA[Antony Christopher]]></dc:creator>
            <pubDate>Fri, 14 Feb 2025 04:42:04 GMT</pubDate>
            <atom:updated>2025-02-14T04:43:14.068Z</atom:updated>
            <content:encoded><![CDATA[<p>Spring Cloud Bus is a messaging system that connects distributed applications with lightweight messaging brokers like <strong>RabbitMQ</strong> or <strong>Kafka</strong>. It allows microservices to communicate efficiently, enabling features like configuration refresh, event propagation, and distributed state management.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o5cM5n_82SzLb9mA80MWMw.png" /></figure><p><strong>Spring Cloud Config Server</strong></p><ul><li>Fetches configuration properties from <strong>GitHub</strong>.</li><li>Serves configuration to <strong>Employee Service</strong> and <strong>Department Service</strong>.</li><li>Acts as a <strong>centralized configuration server</strong>.</li></ul><p><strong>Microservices (Employee &amp; Department)</strong></p><ul><li>Both services <strong>register as config clients</strong> with Spring Cloud Config.</li><li>Retrieve configurations from the <strong>Config Server</strong>.</li></ul><p><strong>RabbitMQ as a Message Broker</strong></p><ul><li>Used by <strong>Spring Cloud Bus</strong> for event-driven communication.</li><li>Both microservices <strong>subscribe to RabbitMQ</strong> to receive configuration updates.</li></ul><h4>Workflow</h4><ol><li>Config changes are pushed to <strong>GitHub</strong>.</li><li><strong>Spring Cloud Config Server</strong> detects changes.</li><li>A <strong>bus-refresh event</strong> is triggered via RabbitMQ.</li><li><strong>Employee &amp; Department services</strong> receive updates automatically.</li></ol><h4>Benefits</h4><p>✔ Centralized <strong>configuration management</strong><br>✔ <strong>Real-time configuration updates</strong> using RabbitMQ<br>✔ <strong>Scalability &amp; decoupling</strong> between services</p><p>Let’s see in detail how to implement it.</p><p>We need to include the dependency to use the Spring Cloud Bus feature.</p><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-cloud-starter-bus-amqp&lt;/artifactId&gt;<br>  &lt;/dependency&gt;</pre><p>Here, we use the Docker desktop for running the RabbitMQ service. The RabbitMQ is used in distributed systems. It helps to communicate asynchronously by sending and receiving messages through queues.</p><p>Once the rabbitMQ image is pulled in docker,</p><pre>docker pull rabbitmq:3.11.0</pre><p>we are set to go running the instance.</p><pre>docker run -it --rm --name rabbitmq -p 5672:5672 rabbitmq:3.11.0</pre><p>Verified the instance running</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U7mpg1yepDS53Ubf8ISqbw.png" /></figure><p>Coming to our microservices project, configured the rabbitMQ across departments/employees services.</p><pre><br>spring.rabbitmq.host=localhost<br>spring.rabbitmq.port=5672<br>spring.rabbitmq.username=guest<br>spring.rabbitmq.password=guest</pre><p>Update the properties file in the GitHub repository for both services as below.</p><pre><br>(On department config file)<br>spring.boot.message=Hello department!!<br><br>(On employee config file)<br>spring.boot.message=Hello employee!!</pre><p>On verifying the GET requests call for both services.</p><pre>C:\Users\AJohnbritto&gt;curl http://localhost:8081/users/message<br>Hello employee!!<br>C:\Users\AJohnbritto&gt;curl http://localhost:8080/message<br>Hello department!!</pre><p>We need to update the config files in GitHub without restarting the services.</p><pre>(On department config file)<br>spring.boot.message=Hello department!! Welcome to rabbitMQ !<br><br>(On employee config file)<br>spring.boot.message=Hello employee!! Welcome to rabbitMQ !</pre><p>Refresh the config by calling the API <a href="http://localhost:8080/actuator/busrefresh">http://localhost:8080/actuator/bus-refresh</a> to trigger a refresh across <strong>all microservices.</strong></p><p>Once the URL is hit in RabbitMQ internally about the refresh event, all subscribed instances will update their configuration as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e32mbJDQKn-gtVblbs_4eg.png" /></figure><p>Check the updated properties.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*XGzya8qdM_qc7ZDMbAFwBg.png" /></figure><p>Now we can see that with one refresh event only, the configuration values were updated for all instances.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b2cebb29272" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Cloud Config]]></title>
            <link>https://antoblog.medium.com/spring-cloud-config-7f732822bd3c?source=rss-f4f0186b13fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f732822bd3c</guid>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[spring-cloud-config]]></category>
            <dc:creator><![CDATA[Antony Christopher]]></dc:creator>
            <pubDate>Thu, 13 Feb 2025 03:32:48 GMT</pubDate>
            <atom:updated>2025-02-14T04:35:42.873Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iHEQQdvHU5hZ9g5F.png" /></figure><p>Spring Cloud Config is a framework that provides <strong>centralized configuration management</strong> for distributed applications. It allows you to store and serve configuration properties from a <strong>central repository</strong> (e.g., Git, database, or file system), making it easier to manage application settings across multiple environments (dev, test, prod, etc.).</p><p>Consider our example project configuring Department, Employee &amp; Organization services properties in the GitHub repository.</p><p>We can make use of the properties file from GitHub and run the respective services. The dependencies are to be added in pom.xml as</p><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-cloud-starter-config&lt;/artifactId&gt;<br>  &lt;/dependency&gt;</pre><p>Next step, create the configuration files in the GitHub repository as below.</p><p>For each microservice, the configuration needs to be maintained across such as database URL, databaseName, service Registry, port….</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CJH4fasr5RT_e7OxIVYQRg.png" /></figure><p>In the Next step, we need to create a separate Spring boot project for the Spring cloud-config. Applying the configuration to be fetched from the GitHub repository. Add the dependency for the cloud-config as above. Configure the properties as below on the startup of the project the configuration can be loaded.</p><pre>spring.application.name=CONFIG-SERVER<br>eureka.instance.client.serverUrl.defaultZone=http://localhost:8761/eureka/<br>server.port=8888<br>spring.cloud.config.server.git.uri=https://github.com/Anto-87/config-server-repo<br>spring.cloud.config.server.git.clone-on-start=true <br>spring.cloud.config.server.git.default-label=main</pre><p>You have to mark the annotation of the SpringBoot main class as @EnableConfigServer.</p><pre>@EnableConfigServer<br>public class ConfigServerApplication {<br> public static void main(String[] args) {<br>  SpringApplication.run(ConfigServerApplication.class, args);<br> }<br>}</pre><p>From the microservices modules, need to add the properties that tell us to pick the configuration from the GitHub repository. For each service need to map accordingly.</p><p>Let’s see for organization service, the very first property tells the name of the microservice. By using the naming reference create the config file in GitHub. Say for Org service, It will be organization-service.properties in the repository. The next property illustrates fetching the config files from the config-server project URL as <a href="http://localhost:8888/">http://localhost:8888</a></p><pre>spring.application.name=organization-service<br>spring.config.import=optional:configserver:http://localhost:8888</pre><p>From the above config-server properties, we used to map the GitHub repository. That will load the org-service properties from the repository.</p><p>Another widely used scenario in microservices is if we need to update the properties file without restarting the services. This can be achieved in Spring Cloud Config. Let’s see find detail, How to implement it?</p><p>Create a separate property to be dynamically updated and loaded from the repository.</p><pre>spring.boot.message=Hello department, welcome to spring cloud bus config using autuator/busrefersh with dynamic updation....</pre><p>Create a class to get the property from the repository as below. The @RefreshScope annotation in <strong>Spring Cloud Config</strong> allows you to update application properties <strong>without restarting the service</strong>.</p><pre>@RefreshScope<br>@RestController<br>public class MessageController {<br>    @Value(&quot;${spring.boot.message}&quot;)<br>    private String message;<br>    @GetMapping(&quot;message&quot;)<br>    public String getMessage(){<br>        return message;<br>    }<br>}</pre><p>The @Value declaration property name is on the config file. By Get call the values are fetched as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tGYGqxR0jV5RabbN9bpJ5w.png" /></figure><p>Consider another scenario, by updating the property value and verifying the results without restating the services.</p><pre>spring.boot.message=Hello department !!</pre><p>Once the update is done, need to trigger a refresh of the config across each microservices. The URL is <a href="http://localhost:8080/actuator/refresh">http://localhost:8080/actuator/refresh</a> update the config from GitHub.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uXyDhOh3gtSvexMiJUIEag.png" /></figure><p>The response provides the property of the configuration been updated. After that call the /message service to display the latest property value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3wcr_DPIl3MP8QdgCB5Fyg.png" /></figure><p>If the project holds 100 microservices we do update the property file on each service. We need to trigger the refresh on each microservices. This could be time-consuming and an obstacle to dynamic updation. To resolve this the <strong>Spring Cloud Bus</strong> comes into the picture.</p><p>By calling the API <a href="http://localhost:8080/actuator/busrefresh">http://localhost:8080/actuator/busrefresh</a> to trigger a refresh across <strong>all microservices</strong>. We will see the next section in detail.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f732822bd3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Cloud Gateway]]></title>
            <link>https://antoblog.medium.com/spring-cloud-gateway-c0494d20caba?source=rss-f4f0186b13fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0494d20caba</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spring-cloud-gateway]]></category>
            <dc:creator><![CDATA[Antony Christopher]]></dc:creator>
            <pubDate>Thu, 13 Feb 2025 03:30:07 GMT</pubDate>
            <atom:updated>2025-02-13T03:30:07.364Z</atom:updated>
            <content:encoded><![CDATA[<p>Why do we need of API gateway?</p><p>Is it mandatory to have the gateway rather than access the microservices directly via URL parameters?</p><p>Those questions can be grasped in our minds. To answer this, Let me start with the working architecture of the API gateway.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J583C82hL7VdbSwN" /></figure><p>Consider the above diagram, where the user can access the microservices via mobile, web &amp; desktop. <strong>API Gateway acts as a single entry point to access services</strong>. It provides a centralized point for managing, monitoring, load balancing and securing APIs exposed by these services to external clients.</p><p>The user wants to access the microservices 1/2/3 no need to know the port &amp; context URL for each service. Rather this will be taken care of in the API gateway itself.</p><p>Once the client requests to API gateway, it will redirect the request to the respective microservices.</p><p>Let’s see an example.</p><p>Microservice 1 access by <a href="http://http//localhost:8080/app1">http://localhost:8080/app1</a></p><p>Microservice 2 access by <a href="http://http//localhost:8080/app1">http://localhost:8080/app</a>2</p><p>Microservice3 access by <a href="http://http//localhost:8080/app1">http://localhost:8080/app</a>3</p><p>Without using api-gateway we can directly access the above URL. The reality we need to know the single context URL through which it can access the microservices.</p><p>The API gateway did some configuration mapping across the microservices. Here we can implement the gateway mapping for microservice 1.</p><pre>spring.application.name=API-GATEWAY<br>server.port=9191<br>eureka.instance.client.serverUrl.defaultZone=http://localhost:8761/eureka/<br>eureka.instance.hostname=localhost<br>spring.cloud.gateway.routes[0].id=MicroService1<br>spring.cloud.gateway.routes[0].uri=lb://MicroService1<br>spring.cloud.gateway.routes[0].predicates[0]=Path=/api/miroservice1/**</pre><p>To access the Microserivce1 using API-Gateway</p><p><a href="http://localhost:9191/api/microservice1/4">h<em>ttp://localhost:9191/api/microservice1/4</em></a></p><p>For Microservice2</p><p><a href="http://localhost:9191/api/microservice1/4">h<em>ttp://localhost:9191/api/microservice2/4</em></a></p><p><strong>API-Gateway Implementation</strong></p><ol><li>We have to register the API-client gateway project as a service registry.</li><li>Include the dependencies for the API gateway project as below.</li></ol><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-cloud-starter-gateway&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-cloud-starter-netflix-eureka-client&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>3. Configure the properties file for microservices id/URL/predicates mapping info.</p><p>Consider our microservices the mapping info for the gateway as</p><pre>server.port=9191<br>eureka.instance.client.serverUrl.defaultZone=http://localhost:8761/eureka/<br>eureka.instance.hostname=localhost<br><br>## Routes for employee service<br>spring.cloud.gateway.routes[0].id=EMPLOYEE-SERVICE<br>spring.cloud.gateway.routes[0].uri=lb://EMPLOYEE-SERVICE<br>spring.cloud.gateway.routes[0].predicates[0]=Path=/api/employees/**<br><br>## Routes for department service<br>spring.cloud.gateway.routes[1].id=DEPARTMENT-SERVICE<br>spring.cloud.gateway.routes[1].uri=lb://DEPARTMENT-SERVICE<br>spring.cloud.gateway.routes[1].predicates[0]=Path=/api/departments/**<br><br>## Routes for organization service<br>spring.cloud.gateway.routes[2].id=ORGANIZATION-SERVICE<br>spring.cloud.gateway.routes[2].uri=lb://ORGANIZATION-SERVICE<br>spring.cloud.gateway.routes[2].predicates[0]=Path=/api/organizations/**</pre><p>Test our results in PostMan, the URL as <a href="http://localhost:9191/api/employees/1">http://localhost:9191/api/employees/1</a></p><p>Here port 9191 applies for the API gateway and api/employees call the employee Microservice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yqcZvryluyN3vNNUhxUF7g.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0494d20caba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Service Registry]]></title>
            <link>https://antoblog.medium.com/spring-service-registry-acd89c0da2c3?source=rss-f4f0186b13fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/acd89c0da2c3</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[service-registry]]></category>
            <dc:creator><![CDATA[Antony Christopher]]></dc:creator>
            <pubDate>Thu, 13 Feb 2025 03:27:55 GMT</pubDate>
            <atom:updated>2025-02-13T03:27:55.239Z</atom:updated>
            <content:encoded><![CDATA[<p>Created a Spring boot project for the service registry implementation. Creating the main class by annotating @EnableEurekaServer illustrates the services can be registered from multiple microservices.</p><pre>@SpringBootApplication<br>@EnableEurekaServer<br>public class ServiceRegistryApplication {<br> public static void main(String[] args) {<br>  SpringApplication.run(ServiceRegistryApplication.class, args);<br> }<br>}</pre><p>In the properties file for Department/Employee/Organization/API-Gateway/ConfigServer need to configure the service registry. To make sure the service is registered with the Eureka server.</p><pre>eureka.instance.client.serverUrl.defaultZone=http://localhost:8761/eureka/<br>eureka.instance.hostname=localhost</pre><p>After running the project, we can verify the service registry console below. There, you can see the list of services that are registered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*vuORY3aOq2meBaLcYFn9ag.png" /></figure><p>The dependencies to be included across the microservices</p><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-cloud-starter-netflix-eureka-client&lt;/artifactId&gt;<br>  &lt;/dependency&gt;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acd89c0da2c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Sample MicroService Implementation]]></title>
            <link>https://antoblog.medium.com/a-sample-microservice-implementation-4c9b7b93f884?source=rss-f4f0186b13fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c9b7b93f884</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Antony Christopher]]></dc:creator>
            <pubDate>Thu, 13 Feb 2025 03:26:05 GMT</pubDate>
            <atom:updated>2025-02-13T03:26:05.467Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s start implementing the sample microservices using Spring Cloud architecture. Here we defined three types of microservices Department, Employee &amp; Organization. Each has a separate database &amp; spring boot configuration project. Each API runs independently in a separate server.</p><p>Let’s see in detail about this. Please find the architecture diagram below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uUcDXYI4GDJZlHyOLfmOdQ.png" /></figure><p><strong>MicroServices Modules</strong></p><p>Here we inherited three modules such as <strong>Employee /Department/Organization.</strong></p><p>Employee -&gt; Used to save the employee details &amp; fetch the data with employee ID along with department &amp; organization details. This module is calling other microservices as well. We will be using the WebClient library for invoking another service. Let’s see this in detail in further discussion.</p><p>Department -&gt; Used to save the department details &amp; fetch the details with the department code.</p><p>Organization -&gt; Save &amp; fetch the organization details.</p><p><strong>Inter-Service Communication</strong></p><p>In a real-time scenario, there will be a necessity to know the details from the other service too. we can accomplish this by using the WebClient library.</p><pre>@SpringBootApplication<br>public class EmployeeServiceApplication {<br><br> @Bean<br> public WebClient webClient(){<br>  return WebClient.builder().build();<br> }<br><br> public static void main(String[] args) {<br>  SpringApplication.run(EmployeeServiceApplication.class, args);<br> }<br>}</pre><p>We added a separate bean to get the reference for WebClient.Need to use the reference to call another service.</p><p>From the code snippet, the webClient reference is initialized. Using that reference invokes other services using URL parameters and converts the received data to the DTO class.</p><p>Here we call two services one from the Organization and another being Department services. Each service runs in a separate tomcat. Hence, we need to put the respective URL to invoke their getService call and to get the response data in DTO format.</p><pre>try {<br>    OrganizationDto webClntOrgResponse = webClient.get()<br>        .uri(uriBuilder -&gt; uriBuilder<br>            .scheme(&quot;http&quot;)<br>            .host(&quot;localhost&quot;)<br>            .port(8083)<br>            .path(&quot;/api/organizations/{code}&quot;)<br>            .build(employee.getOrganizationCode()))<br>        .retrieve()<br>        .bodyToMono(OrganizationDto.class)<br>        .block(Duration.ofSeconds(5)); <br> <br>} catch (Exception e) {<br>    // Handle error gracefully<br>    log.error(&quot;Failed to fetch OrganizationDto&quot;, e);<br>}<br><br>try{<br>DepartmentDto webClntDeptResponse = webClient.get()<br>        .uri(uriBuilder -&gt; uriBuilder<br>            .scheme(&quot;http&quot;)<br>            .host(&quot;localhost&quot;)<br>            .port(8083)<br>            .path(&quot;/api/departments/{code}&quot;)<br>            .build(employee.getDepartmentCode()))<br>        .retrieve()<br>        .bodyToMono(DepartmentDto.class)<br>        .block(Duration.ofSeconds(5)); <br>} catch(Exception err){<br>  // Handle error gracefully<br>    log.error(&quot;Failed to fetch departmentDto&quot;, err);<br>}</pre><p>Once all the response is received. Create the reference for the DTO class which inherits all the responses of the Employee/Department/Organization dtos.</p><p>Verified the results in JSON format.</p><pre>{<br>    &quot;employee&quot;: {<br>        &quot;id&quot;: 2,<br>        &quot;firstName&quot;: &quot;Brand Cooper&quot;,<br>        &quot;lastName&quot;: &quot;Smith&quot;,<br>        &quot;email&quot;: &quot;EEE76@univ.ac.in&quot;,<br>        &quot;departmentCode&quot;: &quot;EEE-076&quot;,<br>        &quot;organizationCode&quot;: &quot;ABC7891&quot;<br>    },<br>    &quot;department&quot;: {<br>        &quot;id&quot;: 2,<br>        &quot;departmentName&quot;: &quot;E.E.E&quot;,<br>        &quot;departmentDescription&quot;: &quot;Engineering in Electricals.&quot;,<br>        &quot;departmentCode&quot;: &quot;EEE-076&quot;<br>    },<br>    &quot;organization&quot;: {<br>        &quot;id&quot;: 2,<br>        &quot;organizationName&quot;: &quot;Test1&quot;,<br>        &quot;organizationDescription&quot;: &quot;Test organization description1&quot;,<br>        &quot;organizationCode&quot;: &quot;ABC7891&quot;,<br>        &quot;createdDate&quot;: &quot;2025-01-29T11:56:40.563259&quot;<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c9b7b93f884" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Cloud Architecture]]></title>
            <link>https://antoblog.medium.com/spring-cloud-architecture-f71eb1ce562f?source=rss-f4f0186b13fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/f71eb1ce562f</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Antony Christopher]]></dc:creator>
            <pubDate>Thu, 13 Feb 2025 03:11:44 GMT</pubDate>
            <atom:updated>2025-02-13T03:11:44.016Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*HhbqmmhAnN-lisLd.png" /><figcaption>Representation of a microservices architecture on a cloud platform (<a href="https://spring.io/microservices">ref. off. docs</a>)</figcaption></figure><p><strong>API Gateway</strong></p><p>In microservices, there will be N number of modules that can be used in a project. For each microservices, we used to call via the context along with a port number. We should be aware of the port config for each microservice. To resolve this, The API Gateway acts as a single entry point for all client requests, handling routing, authentication, load balancing, rate limiting, and more.</p><p><strong>Service Registry</strong></p><p>The services registry is used to register the microservices, and that helps in service discovery, allowing microservices to dynamically register themselves and discover other services.</p><p>On using Spring Cloud Netflix provides a separate URL can see the list of services registry &amp; status.</p><p><strong>Config Server</strong></p><p>Spring Cloud Config Server is used to centralize configuration management for multiple microservices. It allows services to fetch their configuration dynamically from a Git repository, file system, or database.</p><p><strong>Circuit Breaker Dashboard</strong></p><p>A Circuit Breaker prevents cascading failures in microservices by stopping repeated requests to failing services. In microservices, some of the API calls tend to fail again and again. In such cases, we can avoid the retry request.</p><p>The circuit breaker maintained the status as Closed/Open/Half-open.</p><p>When the API initiates the call to another microservice, If the other service is down and we maintain a threshold value of 3 calls failure consequently moved to Open status(failure rate &gt; threshold).</p><p>Suppose the timeout expires in the Open and moves to Half-open. Allow only a few calls based on the configuration. If any of the calls are successful, then move them to Closed or else move them to Open status.</p><p><strong>Spring Cloud Sleuth</strong></p><p>Spring Cloud Sleuth is a distributed tracing solution for Spring Boot microservices. It adds trace IDs and span IDs to logs, allowing developers to track requests across multiple services.</p><p><strong>Spring Cloud Bus</strong></p><p>Spring Cloud Bus broadcasts configuration changes across microservices in a distributed system using Apache Kafka or RabbitMQ.</p><p><strong>Without Spring Cloud Bus</strong> → Each microservice must manually refresh configs after changes in the Spring Cloud Config Server.<br><strong>With Spring Cloud Bus</strong> → Changes are automatically pushed to all services in real time. Call /actuator/bus-refresh on any service to reflect the config changes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f71eb1ce562f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Overview Of MicroServices]]></title>
            <link>https://antoblog.medium.com/an-overview-of-microservices-using-spring-cloud-93fa08fc6b56?source=rss-f4f0186b13fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/93fa08fc6b56</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Antony Christopher]]></dc:creator>
            <pubDate>Wed, 12 Feb 2025 03:22:13 GMT</pubDate>
            <atom:updated>2025-02-13T02:23:09.888Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TX4XTwTThUC6MRaU.jpg" /></figure><p>This article gives you an idea of how the microservices part is implemented using Spring Cloud. Well, in today’s modern world apps make our daily activities much easier. Also, big tech giants developing apps having a microservice architecture. This architecture comes in handy for smaller apps each have it’s database. The user doesn’t even hesitate to change the individual apps based on the database/logic and doesn’t affect the other microservices. Let’s dive into it. Have a detailed exploration of how microservices architecture plays a crucial role today.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qIbn_U436NXVISAK.png" /></figure><p><strong>Monolithic Architecture</strong></p><p>The monolithic architecture is a traditional approach to application development. It involves constructing an application as a single, indivisible unit. Typically, such a solution encompasses a client-side user interface, a server-side application, and a database, all integrated into a unified structure where all functions are managed and served from a single location.</p><p>For any modification done on a product, it should be aware that other logic shouldn’t be broken. Also, customization and load balancing are not very easy. The difficult part, If any changes are required by the client, it should be changing other modules as well. Each module should share the same database. Any change / altering field definition will lead to a change in the entire module.</p><p>In monolithic applications, there is usually one large codebase lacking modularity. Developers needing to update or modify something must access this single codebase, resulting in changes being made across the entire stack simultaneously.</p><p><strong>Microservices Architecture</strong></p><p>In microservices, each module is shared with a unique database and Each module can be developed individually without depending on the other modules. we can call one microservices to another also. We can scale each product individually and robust code modification can be made without any hesitation of other modules. The load balance and performance tuning can be done individually on each module. Each module says microservices running on a separate port. We can communicate through third-party APIs for streaming and data services.</p><p>We can have multiple tech stacks to develop the microservices. Consider the case that App1 was developed using NodeJs and another App2 can be developed using Java Spring Boot.</p><p>We can develop based on the needs of the user and customer. How much scalable the application is needed based on it, we can change the tech stack accordingly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93fa08fc6b56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A newbie journey for SpringBoot Part II]]></title>
            <link>https://antoblog.medium.com/a-newbie-journey-for-springboot-part-ii-735291ff910e?source=rss-f4f0186b13fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/735291ff910e</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[crud]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Antony Christopher]]></dc:creator>
            <pubDate>Mon, 23 Dec 2024 15:23:22 GMT</pubDate>
            <atom:updated>2024-12-27T17:24:47.808Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*HCygoj_wrLdg6IL_.png" /></figure><p>In our previous section, we discussed the Spring Boot project skeleton structure, which shows the essentials and their functionality. Let’s deep divide and create the CRUD operation on a specific table.</p><p>Let’s start with the database. here we use MySql Server for creating a sample database.</p><p>From MySql user_management new database has been created as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*SBTNkBGwnVTs0GyZY-BJ3w.png" /></figure><p>Don’t need to worry about creating a table structure the spring boot will take care of creating the table dynamically while startup.</p><p>The below configuration is used to connect the MySql database server using spring boot.</p><pre>spring.application.name=springboot-restful-webservices<br>spring.datasource.url=jdbc:mysql://localhost:3316/user_management<br>spring.datasource.username=root<br>spring.datasource.password=testUser<br><br>spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect<br>spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false<br><br>spring.jpa.hibernate.ddl-auto=update<br>spring.sql.init.mode=never</pre><p><strong>spring.jpa.hibernate.ddl-auto=update</strong> it will create the table automatically in the database on the startup. The table structure is created based on the entity specification of the java class. The POJO class is defined as a getter/ setter with a mapping configuration. Let’s see in detail below.</p><p><strong>Entity Definition</strong></p><p>The below code snippet is used to create an entity class as ‘User’. On top of it, we have the annotations in place to avoid boilerplate code.</p><p>Getter — used to generate the getter property for the variables in the class</p><p>Setter — used to generate the setter property for the variables in the class</p><p>NoArgsConstructor — used to create the default constructor for the user class as User()</p><p>AllArgsConstructor — used to create a parameter constructor for the user based on the variables declared User(firstName, lastName, email)</p><pre>@Getter<br>@Setter<br>@NoArgsConstructor<br>@AllArgsConstructor<br>@Entity<br>@Table(name=&quot;users&quot;)<br>public class User {<br><br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    @Column(nullable = false)<br>    private String firstName;<br><br>    @Column(nullable = false)<br>    private String lastName;<br><br>    @Column(nullable = false, unique = true)<br>    private String email;<br>}</pre><p>Entity — represents a persistent object in the database. It is a class that maps to a database table, and each instance of the entity corresponds to a row in that table.</p><p>Table(name=” users”) — specifies the name reference for the table gonna be created in run time.</p><p><strong>Table creation at run-time</strong></p><p>After running the application the users table is created as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*DavqUh6LR_HvrcgbcjtNkg.png" /></figure><p>Next, we are going to create the repository for the user_managment database</p><p><strong>DTO</strong></p><p><strong>A</strong>n object that carries data between processes. It is used to transfer data between layers or systems (e.g., from the controller to the service layer, or between a Spring-based backend and a client in the case of REST APIs). DTOs are typically used to encapsulate data in a manner that is optimized for communication, avoiding over-fetching or under-fetching of data.</p><pre><br>@Schema(<br>        description = &quot;UserDTO model information&quot;<br>)<br>@Setter<br>@Getter<br>@AllArgsConstructor<br>@NoArgsConstructor<br>public class UserDto {<br><br>    private Long id;<br><br>    @Schema(<br>            description = &quot;First Name&quot;<br>    )<br>    @NotEmpty(message = &quot;User first name should not be null or empty&quot;)<br>    private String firstName;<br><br>    @Schema(<br>            description = &quot;Last Name&quot;<br>    )<br>    @NotEmpty(message = &quot;User last name should not be null or empty&quot;)<br>    private String lastName;<br><br>    @Schema(<br>            description = &quot;User Email Address&quot;<br>    )<br>    @NotEmpty(message = &quot;User email should not be null or empty&quot;)<br>    @Email(message = &quot;Email address should be valid&quot;)<br>    private String email;<br><br><br>}</pre><p><strong>Repository definition</strong></p><p>Here the annotation @Repository stands for defining the repository. Which extends JpaRepository&lt;tableName, &lt;&lt;uniqueType&gt;&gt;&gt;.</p><p>This JpaRepository is a part of the <strong>Spring Data JPA</strong> framework. It extends the PagingAndSortingRepository and, in turn, the CrudRepository, providing a rich layer of functionalities for working with databases using the Java Persistence API (JPA).</p><pre>@Repository<br>public interface UserRepository  extends JpaRepository&lt;User, Long&gt; {<br><br>    Optional&lt;User&gt; findByEmail(String email);<br><br>}</pre><p><strong>Service Layer</strong></p><p>This is the layer we used to create the interface, where we are about to implement the method against the entity definition.</p><pre>public interface UserService {<br><br>    UserDto createUser(UserDto user) throws EmailAlreadyExistException;<br>    UserDto getByUserId(Long id) throws ResourceNotFoundException;<br>    List&lt;UserDto&gt; getAllUsers() throws ResourceNotFoundException;<br>    UserDto updateUser(UserDto user) throws ResourceNotFoundException;<br>    void deleteUser(Long id) throws ResourceNotFoundException;<br>}</pre><p><strong>Service Implementation</strong></p><p>This class is used to define the business logic for each method implementation defined in the UserService class.</p><p>The basic CRUD operation is implemented here and customized fetch operations such as fetchByUserId() / getAllusers() are also applied.</p><pre>@Service<br>@AllArgsConstructor<br>public class UserServiceImpl implements UserService {<br><br>    private UserRepository userRepository;<br><br>    private ModelMapper modelMapper;<br><br>    @Override<br>    public UserDto createUser(UserDto userDto) throws EmailAlreadyExistException {<br><br>       <br>        Optional&lt;User&gt; optionalUser = userRepository.findByEmail(userDto.getEmail());<br><br>        if(optionalUser.isPresent()){<br>            throw new EmailAlreadyExistException(&quot;Email Already Exists for User&quot;);<br>        }<br><br>        User user = AutoUserMapper.MAPPER.mapToUser(userDto);<br>        User savedUser = userRepository.save(user);<br>          <br>        UserDto savedUserDto = AutoUserMapper.MAPPER.maptoUserDto(savedUser);<br><br>        return savedUserDto;<br>    }<br><br>    @Override<br>    public UserDto getByUserId(Long id) throws ResourceNotFoundException {<br>        User user= userRepository.findById(id).orElseThrow(<br>                () -&gt; new ResourceNotFoundException(&quot;User&quot;, &quot;id&quot;, id)<br>        );<br><br>        <br>        return AutoUserMapper.MAPPER.maptoUserDto(user);<br>    }<br><br>    @Override<br>    public List&lt;UserDto&gt; getAllUsers() {<br>        List&lt;User&gt; userDatas =  userRepository.findAll();<br><br>        // Map Struct<br>        return userDatas.stream().map(<br>                  (users) -&gt; AutoUserMapper.MAPPER.maptoUserDto(users))<br>                 .collect(Collectors.toList());<br>    }<br><br>    @Override<br>    public UserDto updateUser(UserDto user) throws ResourceNotFoundException {<br><br>        User userData = userRepository.findById(user.getId()).orElseThrow(<br>                () -&gt; new ResourceNotFoundException(&quot;User&quot;, &quot;id&quot;, user.getId())<br>        );<br>        userData.setFirstName(user.getFirstName());<br>        userData.setLastName(user.getLastName());<br>        userData.setEmail(user.getEmail());<br>        userRepository.save(userData);<br>       <br>        return AutoUserMapper.MAPPER.maptoUserDto(userData);<br>    }<br><br>    @Override<br>    public void deleteUser(Long id) throws ResourceNotFoundException {<br>        User existingUser = userRepository.findById(id).orElseThrow(<br>                () -&gt; new ResourceNotFoundException(&quot;User&quot;, &quot;id&quot;, id)<br>        );<br>        userRepository.deleteById(id);<br>    }<br>}</pre><p><strong>Controller</strong></p><p>A <strong>Spring Controller</strong> is typically used to handle incoming HTTP requests in a web application. It’s part of the <strong>Spring MVC (Model-View-Controller)</strong> architecture, where controllers handle the user requests, process them (with the help of models), and return an appropriate response (view).</p><p>In Spring, you can define controllers as Java classes annotated with @Controller or @RestController, depending on whether you&#39;re building a traditional web app with views (HTML, JSP, etc.) or a RESTful API that returns data (usually JSON or XML).</p><pre><br>@Tag(<br>        name=&quot;CRUD Rest APIs for User Resource&quot;,<br>        description = &quot;Create, update, delete, Get All, Get User details&quot;<br>        )<br>@RestController<br>@AllArgsConstructor<br>@RequestMapping(&quot;api/users&quot;)<br>public class UserController {<br><br>    private UserService userService;<br><br>    @Operation(<br>        summary = &quot;Create User REST API&quot;,<br>        description = &quot;Create User REST Api is used to save user in a database&quot;<br>    )<br>    @ApiResponse(<br>            responseCode = &quot;201&quot;,<br>            description = &quot;HTTP Status 201 CREATED&quot;<br>    )<br>    @PostMapping<br>    public ResponseEntity&lt;UserDto&gt; createUser(@Valid @RequestBody UserDto user) throws EmailAlreadyExistException {<br>        UserDto savedUser = userService.createUser(user);<br>        return new ResponseEntity&lt;&gt;(savedUser, HttpStatus.CREATED);<br>    }<br><br>    @Operation(<br>            summary = &quot;Get User By Id REST API&quot;,<br>            description = &quot;Get User By Id used to get the single user details from the database&quot;<br>    )<br>    @ApiResponse(<br>            responseCode = &quot;200&quot;,<br>            description = &quot;HTTP Status 200 SUCCESS&quot;<br>    )<br>    @GetMapping(&quot;{id}&quot;)<br>    public ResponseEntity&lt;UserDto&gt; getUserById(@PathVariable(&quot;id&quot;)  Long userID) throws ResourceNotFoundException {<br>        UserDto user = userService.getByUserId(userID);<br>        return new ResponseEntity&lt;&gt;(user, HttpStatus.OK);<br>    }<br><br>    @Operation(<br>            summary = &quot;Get All Users By Id REST API&quot;,<br>            description = &quot;Get All Users used to get the all users from the database&quot;<br>    )<br>    @ApiResponse(<br>            responseCode = &quot;200&quot;,<br>            description = &quot;HTTP Status 200 SUCCESS&quot;<br>    )<br>    @GetMapping<br>    public ResponseEntity&lt;List&lt;UserDto&gt;&gt; getAllUsers() throws ResourceNotFoundException {<br>        List&lt;UserDto&gt; users = userService.getAllUsers();<br>        return new ResponseEntity&lt;&gt;(users, HttpStatus.OK);<br>    }<br><br>    @Operation(<br>            summary = &quot;Update User By Id REST API&quot;,<br>            description = &quot;Update User By Id used to update the user data from the database&quot;<br>    )<br>    @ApiResponse(<br>            responseCode = &quot;200&quot;,<br>            description = &quot;HTTP Status 200 SUCCESS&quot;<br>    )<br>    @PutMapping(&quot;{id}&quot;)<br>    public ResponseEntity&lt;UserDto&gt; updateUserById(@PathVariable Long id, @RequestBody @Valid UserDto user) throws ResourceNotFoundException {<br>       user.setId(id);<br>       UserDto updatedUser =  userService.updateUser(user);<br>       return new ResponseEntity&lt;&gt;(updatedUser, HttpStatus.OK);<br>    }<br><br>    @Operation(<br>            summary = &quot;Delete User By Id REST API&quot;,<br>            description = &quot;Delete User By Id used to delete the user from the database&quot;<br>    )<br>    @ApiResponse(<br>            responseCode = &quot;200&quot;,<br>            description = &quot;HTTP Status 200 SUCCESS&quot;<br>    )<br>    @DeleteMapping(&quot;{id}&quot;)<br>    public ResponseEntity&lt;String&gt; deleteByUserID(@PathVariable Long id) throws ResourceNotFoundException {<br>        userService.deleteUser(id);<br>        return new ResponseEntity&lt;&gt;(&quot;User successfully deleted!&quot;, HttpStatus.OK);<br>    }</pre><p><strong>Mapper</strong></p><p>The <strong>AutoUserMapper</strong> or <strong>automatic user mapping</strong> in the context of DTOs, entities, or mapping libraries in Spring, you may be asking about how to automatically map User entities to UserDTO objects without writing repetitive mapping code manually. In this case, you can use tools like <strong>MapStruct</strong> or <strong>ModelMapper</strong> to automate the conversion process.</p><p>In this section, we used the MapStruct tool. Let’s see in detail.</p><h4>Step 1: Add MapStruct Dependency</h4><p>If you’re using Maven, include the following dependencies in your pom.xml.</p><pre>&lt;dependencies&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.mapstruct&lt;/groupId&gt;<br>        &lt;artifactId&gt;mapstruct&lt;/artifactId&gt;<br>        &lt;version&gt;1.5.3.Final&lt;/version&gt;<br>    &lt;/dependency&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.mapstruct&lt;/groupId&gt;<br>        &lt;artifactId&gt;mapstruct-processor&lt;/artifactId&gt;<br>        &lt;version&gt;1.5.3.Final&lt;/version&gt;<br>        &lt;scope&gt;provided&lt;/scope&gt;<br>    &lt;/dependency&gt;<br>&lt;/dependencies&gt;<br><br>&lt;build&gt;<br>    &lt;plugins&gt;<br>        &lt;plugin&gt;<br>            &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;<br>            &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;<br>            &lt;version&gt;3.8.1&lt;/version&gt;<br>            &lt;configuration&gt;<br>                &lt;source&gt;1.8&lt;/source&gt;<br>                &lt;target&gt;1.8&lt;/target&gt;<br>                &lt;annotationProcessorPaths&gt;<br>                    &lt;path&gt;<br>                        &lt;groupId&gt;org.mapstruct&lt;/groupId&gt;<br>                        &lt;artifactId&gt;mapstruct-processor&lt;/artifactId&gt;<br>                        &lt;version&gt;1.5.3.Final&lt;/version&gt;<br>                    &lt;/path&gt;<br>                &lt;/annotationProcessorPaths&gt;<br>            &lt;/configuration&gt;<br>        &lt;/plugin&gt;<br>    &lt;/plugins&gt;<br>&lt;/build&gt;</pre><h4>Step 2: Create the MapStruct Mapper</h4><p>MapStruct uses an interface to define the mapping rules. It generates the implementation of the mapping at compile time.</p><pre><br>@Mapper<br>public interface AutoUserMapper {<br><br>    AutoUserMapper MAPPER = Mappers.getMapper(AutoUserMapper.class);<br><br>    UserDto maptoUserDto(User user);<br><br>    User mapToUser(UserDto userDto);<br><br>}</pre><p>On implementing the mapper in the service implementation for saving the user operation as below.</p><p>Here the AutoUserMapper converts the DTO object to an entity object for saving the user details.</p><pre><br> public UserDto createUser(UserDto userDto){<br>    <br>    .....<br>    User user = AutoUserMapper.MAPPER.mapToUser(userDto);<br>    User savedUser = userRepository.save(user);<br><br>}</pre><p><strong>Exception Handling</strong></p><p>Consider the case when the user fetches the details based on the ID. If the user is present, fetch the info about the user. If the ID is not available in the table, it should show the user with valid information.</p><p>Here is the method to return the user details based on the ID.</p><pre><br> public UserDto getByUserId(Long id) throws ResourceNotFoundException {<br><br>        User user= userRepository.findById(id).orElseThrow(<br>                () -&gt; new ResourceNotFoundException(&quot;User&quot;, &quot;id&quot;, id)<br>        );<br><br>        <br>        return AutoUserMapper.MAPPER.maptoUserDto(user);<br>    }</pre><p>If the user details are not found, the info is displayed to the user as below.</p><pre><br>{<br>    &quot;timestamp&quot;: &quot;2024-12-23T20:30:51.09832&quot;,<br>    &quot;message&quot;: &quot;User not found with id : &#39;2&#39;&quot;,<br>    &quot;path&quot;: &quot;uri=/api/users/2&quot;,<br>    &quot;errorCode&quot;: &quot;USER_NOT_FOUND&quot;<br>}</pre><p><strong>Step 1</strong></p><p>Created the custom exception in the ResourceNotFoundException class. Initialize the exception message as <strong>String.format(“%s not found with %s : ‘%s’”, resourceName, fieldName, fieldValue). </strong>Those values are passed from the getUserById(), by throwing the ResourceNotFoundException.</p><pre>@ResponseStatus(value= HttpStatus.NOT_FOUND)<br>public class ResourceNotFoundException extends Exception {<br><br>    private String resourceName;<br>    private String fieldName;<br>    private Long fieldValue;<br><br>    public ResourceNotFoundException(String resourceName, String fieldName, Long fieldValue){<br>        super(String.format(&quot;%s not found with %s : &#39;%s&#39;&quot;, resourceName, fieldName, fieldValue));<br>        this.resourceName = resourceName;<br>        this.fieldName = fieldName;<br>        this.fieldValue = fieldValue;<br>    }<br><br><br>}</pre><p><strong>Step 2</strong></p><p>The ControllerAdvice is a powerful annotation used for global exception handling, binding data, and applying other cross-cutting concerns to all controllers in your application. It allows you to handle exceptions across the whole application in one place, making it easier to centralize the logic for handling errors.</p><pre><br>@ControllerAdvice<br>public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {<br><br>    @ExceptionHandler(ResourceNotFoundException.class)<br>    public ResponseEntity&lt;ErrorDetails&gt; handleResourceNotFoundException(ResourceNotFoundException exception,<br>                                                                        WebRequest webRequest ){<br><br>        ErrorDetails errorDetails = new ErrorDetails(<br>                LocalDateTime.now(),<br>                exception.getMessage(),<br>                webRequest.getDescription(false),<br>                &quot;USER_NOT_FOUND&quot;<br><br>        );<br>        return new ResponseEntity&lt;&gt;(errorDetails, HttpStatus.NOT_FOUND);<br><br>    }<br><br>.....<br><br>}</pre><p>The error details are shown to the user. We can do the same for validation purposes also, such as if email already exists.</p><pre><br>@ExceptionHandler(EmailAlreadyExistException.class)<br>    public ResponseEntity&lt;ErrorDetails&gt; handleEmailAlreadyExistsException(EmailAlreadyExistException exception,<br>                                                                        WebRequest webRequest ){<br><br>        ErrorDetails errorDetails = new ErrorDetails(<br>                LocalDateTime.now(),<br>                exception.getMessage(),<br>                webRequest.getDescription(false),<br>                &quot;USER_EMAIL_ALREADY_EXISTS&quot;<br><br>        );<br>        return new ResponseEntity&lt;&gt;(errorDetails, HttpStatus.BAD_REQUEST);<br><br>    }<br><br>// Custom exception handler for EmailID<br><br>@ResponseStatus(value = HttpStatus.BAD_REQUEST)<br>public class EmailAlreadyExistException extends Exception {<br><br>    private String message;<br><br>    public EmailAlreadyExistException(String message){<br>        super(message);<br>    }<br><br>}</pre><p>Hope this article gives you a basic idea of implementing the CRUD operation with exception &amp; MapStruct.</p><p><a href="https://github.com/Anto-87/springboot-restful-webservices.git">GitHub - Anto-87/springboot-restful-webservices: A CRUD operation using MySQL server with exception &amp; MapStruct implementation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=735291ff910e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>