<?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 Rafael Megda on Medium]]></title>
        <description><![CDATA[Stories by Rafael Megda on Medium]]></description>
        <link>https://medium.com/@rafaelmisidoro?source=rss-83d15fada348------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*70J0A7cw3SkGIKn5zv7UOw.jpeg</url>
            <title>Stories by Rafael Megda on Medium</title>
            <link>https://medium.com/@rafaelmisidoro?source=rss-83d15fada348------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 10:34:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rafaelmisidoro/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[Aggregator Pattern em Microserviços — Como Combinar Respostas Assíncronas]]></title>
            <link>https://medium.com/code-coffee-tech/o-padr%C3%A3o-aggregator-em-microservi%C3%A7os-orquestrando-mensagens-ass%C3%ADncronas-para-decis%C3%B5es-de-neg%C3%B3cio-e67bb4b16c3f?source=rss-83d15fada348------2</link>
            <guid isPermaLink="false">https://medium.com/p/e67bb4b16c3f</guid>
            <dc:creator><![CDATA[Rafael Megda]]></dc:creator>
            <pubDate>Sat, 04 Oct 2025 19:34:38 GMT</pubDate>
            <atom:updated>2025-10-08T23:48:30.056Z</atom:updated>
            <content:encoded><![CDATA[<p>Em um sistema distribuído, decidir corretamente depende muito de combinar informações que chegam de formas e tempos distintos. O Aggregator Pattern é a ferramenta arquitetural que permite essa coordenação — com previsibilidade e tolerância a falhas.</p><p>Em arquiteturas de microserviços, a integração de dados provenientes de fontes distribuídas representa um desafio recorrente.</p><p>Recentemente, em um projeto real, deparei-me com a necessidade de processar duas mensagens externas assíncronas, cada uma contendo um status de aprovação ou rejeição para uma solicitação.</p><p>A regra de negócio exigia que a solicitação fosse considerada aprovada apenas se ambos os status fossem positivos. Para resolver isso, adotei o padrão Aggregator, persistindo os estados intermediários em um banco de dados para garantir resiliência e consistência.</p><p>Este artigo explora o padrão Aggregator em profundidade, destacando seus componentes técnicos, aplicações em microserviços e considerações práticas, com o objetivo de demonstrar expertise em sistemas distribuídos e auxiliar profissionais enfrentando problemas semelhantes.</p><h3>Conceitos Fundamentais do Padrão Aggregator</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*E0_VMQf71i8CkxsvwDyeYw.png" /><figcaption>Conceitos Fundamentais do Padrão Aggregator</figcaption></figure><p>O Aggregator Pattern, parte dos Enterprise Integration Patterns (EIP), atua como um filtro com estado que coordena fluxos de mensagens em sistemas distribuídos. Ele coleta mensagens individuais correlacionadas, armazena-as temporariamente e, ao atingir uma condição de completude, gera uma mensagem unificada para processamento downstream. Esse padrão é especialmente útil quando uma requisição inicial é dividida (via Splitter) ou enviada a múltiplos destinatários (via Recipient List ou Scatter-Gather), exigindo a recombinação de respostas.</p><p>Em contextos de microserviços, o Aggregator simplifica a comunicação assíncrona, permitindo que serviços independentes contribuam para uma resposta coesa sem acoplamento excessivo. Por exemplo, em um sistema de e-commerce, ele pode agregar dados de estoque, preços e carrinho de compras de serviços separados para formar uma visão unificada do pedido.</p><h4>Componentes Técnicos Essenciais</h4><p>A implementação eficaz de um Aggregator requer a definição precisa de três componentes principais:</p><p><strong>1. Correlação</strong><br>A correlação identifica mensagens pertencentes ao mesmo grupo, geralmente por meio de um Correlation Identifier — um cabeçalho padrão que rastreia sub-mensagens derivadas de uma requisição original. Em Java, por exemplo, isso pode ser implementado usando um identificador único (como UUID) propagado em headers de mensagens via frameworks como Spring Cloud ou Apache Camel.</p><p><strong>2. Condição de Completude</strong><br>Essa lógica determina quando o conjunto de mensagens está pronto para agregação. Estratégias comuns incluem:</p><ul><li><strong>Wait for All</strong>: Aguarda todas as respostas esperadas, com timeouts para detecção de erros. Ideal para cenários como o caso real mencionado, onde duas aprovações são obrigatórias, mas sensível a atrasos.</li><li><strong>Time Out:</strong> Processa mensagens recebidas dentro de um período fixo, útil em licitações onde a melhor oferta é selecionada.</li><li><strong>First Best</strong>: Agrega a primeira resposta recebida, priorizando velocidade em ambientes time-sensitive.</li><li><strong>External Event:</strong> Finaliza via um evento externo, como uma mensagem de controle, oferecendo flexibilidade em fluxos de negócio dinâmicos.</li></ul><p>No caso real, utilizei “Wait for All” com persistência em banco de dados para rastrear os dois status, garantindo que a regra de aprovação (ambos aprovados) fosse aplicada apenas ao receber ambas as mensagens.</p><p><strong>3. Algoritmo de Agregação</strong><br>Define como combinar payloads e headers em uma mensagem resultante. Em implementações simples, isso envolve mesclar dados em uma coleção; em cenários complexos, inclui cálculos como somas ou seleções condicionais. Por exemplo, em um aggregator para finanças, pode calcular patrimônio líquido agregando investimentos e dívidas.</p><h4>Aplicações em Arquiteturas de Microserviços</h4><p>Em microserviços, o Aggregator pode ser implementado como um serviço dedicado ou integrado a um API Gateway, reduzindo chamadas do cliente e melhorando a performance. Classificações incluem:</p><ul><li><strong>Aggregator Simples:</strong> Para combinações lineares, como compilar categorias de produtos.</li><li><strong>Aggregator Complexo:</strong> Para lógicas avançadas, como personalização em apps financeiros.</li></ul><p>Estratégias relacionadas abrangem Scatter-Gather para requisições paralelas, Chain para sequenciais e Branch para condicionais. Exemplos reais incluem o Loan Broker em AWS, usando Lambda e DynamoDB para agregar cotações de empréstimos com timeouts, ou em GCP com Cloud Functions e Datastore para gerenciamento de estado.</p><p>No contexto do caso real, a persistência em banco de dados permitiu resiliência, armazenando mensagens parciais e aplicando a regra de negócio ao atingir completude.</p><h4>Persistência e Integração com Domain-Driven Design (DDD)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*ArXHQsGINYRbmZZlCwqKEw.png" /></figure><p>Para tolerância a falhas em sistemas assíncronos, o Aggregator deve persistir estados intermediários. Bancos NoSQL, como key-value ou document stores, são ideais, tratando agregados como unidades atômicas de armazenamento. Isso alinha com o conceito de Aggregate no DDD, onde dados coesos são gerenciados juntos, facilitando sharding em clusters distribuídos.</p><p>Vantagens incluem otimização de desempenho, mas desafios surgem em consultas cruzadas, exigindo visões materializadas via Map-Reduce. No caso real, utilizei um banco relacional para simplicidade, mas recomendo NoSQL para escalabilidade em produções maiores.</p><h4>Desafios Operacionais e Estratégias de Mitigação</h4><p>Embora poderoso, o Aggregator introduz complexidades:</p><ul><li><strong>Ponto Único de Falha (SPOF):</strong> Mitigue com redundância e fail-over.</li><li><strong>Latência:</strong> Otimize com chamadas paralelas e caching.</li><li><strong>Resiliência:</strong> Implemente timeouts, retries e fallbacks para falhas em serviços subjacentes.</li><li><strong>Manutenção:</strong> Monitore escalabilidade à medida que serviços crescem, usando ferramentas como Prometheus.</li></ul><p>Em ambientes como Azure, o Gateway Aggregation Pattern complementa, agregando requisições para reduzir tráfego.</p><h3>Case prático de implementação</h3><p>Recentemente enfrentei um desafio prático: um fluxo que precisava receber <strong>duas mensagens externas</strong> (através de binds no RabbitMQ). Cada mensagem trazia um status (APROVADO / REJEITADO) associado à mesma solicitação. A regra de negócio era simples e severa: <strong>a solicitação só estaria aprovada se ambas as respostas fossem </strong><strong>APROVADO</strong>. As mensagens chegavam assincronamente e sem ordem garantida — então era necessário <strong>combinar</strong> esses dois eventos antes de tomar a decisão.</p><p>A solução arquitetural foi aplicar o <strong>Aggregator Pattern</strong>, persistindo estados parciais enquanto aguardávamos ambas as respostas. O resultado: uma decisão consistente, auditável e recuperável em caso de falhas.</p><p>Abaixo eu explico o raciocínio, o case, lições práticas e um código de estudo sanitizado para replicação (anexo).</p><p><strong>Por que usar o Aggregator neste cenário</strong></p><ul><li><strong>Assincronia natural</strong>: produtores diferentes e tempos de resposta variados.</li><li><strong>Decisão baseada no conjunto</strong>: condição APROVADO só válida se <em>todas</em> as respostas forem positivas.</li><li><strong>Necessidade de resiliência</strong>: crashes, retries e duplicatas não podem gerar decisões inconsistentes.</li><li><strong>Auditoria e rastreabilidade</strong>: preciso registrar quais inputs levaram à decisão final.</li></ul><p>O Aggregator trata o problema como um fluxo de coordenação: receber → correlacionar → persistir estado parcial → avaliar condição de completude → emitir resultado final.</p><p><strong>Decisões arquiteturais que tomei no case</strong></p><ol><li><strong>Correlação explícita</strong>: todas as mensagens carregavam requestId (correlation key) no header/payload. Sem isso, não havia como garantir que duas mensagens pertenciam à mesma solicitação.</li><li><strong>Condição de conclusão: Wait-for-All</strong>: neste negócio, só aceitamos APROVADO com as duas respostas positivas; portanto, esperei ambos os eventos, com timeout configurável.</li><li><strong>Persistência dos estados parciais</strong>: não confiei em memória; persisti o estado intermediário para tolerância a falhas e auditoria.</li><li><strong>Idempotência e deduplicação</strong>: mensagens externas podem ser reenviadas; tratei reenvios como esperados e idempotentes.</li><li><strong>Publicação segura do resultado</strong>: adotei o conceito de <em>transactional outbox</em> para evitar perda de eventos em caso de falha entre commit no banco e publicação no broker.</li><li><strong>Observability</strong>: traceId + métricas (PENDING, COMPLETED, TIMED_OUT), logs correlacionados e alertas sobre timeouts.</li></ol><h3>Como implementar o Aggregator usando Integration no Java</h3><p>AggregatorIntegrationConfig.java — configuração de filas/exchanges/bindings</p><pre>package com.example.aggregator.config;<br><br>import org.springframework.amqp.core.Binding;<br>import org.springframework.amqp.core.BindingBuilder;<br>import org.springframework.amqp.core.TopicExchange;<br>import org.springframework.amqp.core.Queue;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>/**<br> * Configuração mínima de RabbitMQ:<br> * - 1 Exchange (topic) que recebe eventos externos<br> * - 2 filas ligadas por routing keys (ex: responses.a e responses.b)<br> *<br> * Ajuste nomes e routing keys conforme sua topologia.<br> */<br>@Configuration<br>public class AggregatorIntegrationConfig {<br>    public static final String EXCHANGE_NAME = &quot;external.responses.exchange&quot;;<br>    public static final String QUEUE_A = &quot;external.responses.queue.a&quot;;<br>    public static final String QUEUE_B = &quot;external.responses.queue.b&quot;;<br>    public static final String ROUTING_KEY_A = &quot;response.serviceA&quot;;<br>    public static final String ROUTING_KEY_B = &quot;response.serviceB&quot;;<br>    @Bean<br>    public TopicExchange externalResponsesExchange() {<br>        return new TopicExchange(EXCHANGE_NAME, true, false);<br>    }<br>    @Bean<br>    public Queue queueA() {<br>        return new Queue(QUEUE_A, true);<br>    }<br>    @Bean<br>    public Queue queueB() {<br>        return new Queue(QUEUE_B, true);<br>    }<br>    @Bean<br>    public Binding bindingA(Queue queueA, TopicExchange externalResponsesExchange) {<br>        return BindingBuilder.bind(queueA).to(externalResponsesExchange).with(ROUTING_KEY_A);<br>    }<br>    @Bean<br>    public Binding bindingB(Queue queueB, TopicExchange externalResponsesExchange) {<br>        return BindingBuilder.bind(queueB).to(externalResponsesExchange).with(ROUTING_KEY_B);<br>    }<br>}</pre><p>AggregationMessage.java — contrato de mensagem (modelo simples)</p><pre>package com.example.aggregator.model;<br><br>import java.util.UUID;<br>/**<br> * Modelo simples que representa a mensagem recebida.<br> * Em produção, alinhe o contrato entre produtores e consumidores.<br> */<br>public class AggregationMessage {<br>    private UUID requestId;<br>    private String source;<br>    private String status; // &quot;APPROVED&quot; / &quot;REJECTED&quot;<br>    private String payload; // JSON string<br>    public AggregationMessage() {}<br>    public AggregationMessage(UUID requestId, String source, String status, String payload) {<br>        this.requestId = requestId;<br>        this.source = source;<br>        this.status = status;<br>        this.payload = payload;<br>    }<br>    // getters/setters<br>    public UUID getRequestId() { return requestId; }<br>    public void setRequestId(UUID requestId) { this.requestId = requestId; }<br>    public String getSource() { return source; }<br>    public void setSource(String source) { this.source = source; }<br>    public String getStatus() { return status; }<br>    public void setStatus(String status) { this.status = status; }<br>    public String getPayload() { return payload; }<br>    public void setPayload(String payload) { this.payload = payload; }<br>    @Override<br>    public String toString() {<br>        return &quot;AggregationMessage{&quot; +<br>            &quot;requestId=&quot; + requestId +<br>            &quot;, source=&#39;&quot; + source + &#39;\&#39;&#39; +<br>            &quot;, status=&#39;&quot; + status + &#39;\&#39;&#39; +<br>            &quot;, payload=&#39;&quot; + payload + &#39;\&#39;&#39; +<br>            &#39;}&#39;;<br>    }<br>}</pre><p>AggregationListeners.java — consumidores que extraiem correlação e delegam</p><p><em>Nota: os métodos </em><em>extractRequestIdFromBody e </em><em>extractStatusFromBody são placeholders — substitua por parsing JSON real (Jackson/Gson) conforme seu contrato de mensagens.</em></p><pre>package com.example.aggregator.listener;<br><br>import com.example.aggregator.model.AggregationMessage;<br>import com.example.aggregator.service.AggregationService;<br>import org.springframework.amqp.rabbit.annotation.RabbitListener;<br>import org.springframework.messaging.handler.annotation.Header;<br>import org.springframework.stereotype.Service;<br>import java.util.UUID;<br>/**<br> * Listeners das filas A e B.<br> * Extraem o requestId (correlation key) do header &quot;requestId&quot; ou do payload.<br> * Delegam ao AggregationService para coordenação.<br> */<br>@Service<br>public class AggregationListeners {<br>    private final AggregationService aggregationService;<br>    public AggregationListeners(AggregationService aggregationService) {<br>        this.aggregationService = aggregationService;<br>    }<br>    @RabbitListener(queues = &quot;${aggregator.queue.a:external.responses.queue.a}&quot;)<br>    public void onMessageFromA(String body, @Header(value = &quot;requestId&quot;, required = false) String requestIdHeader) {<br>        handleIncoming(&quot;SERVICE_A&quot;, body, requestIdHeader);<br>    }<br>    @RabbitListener(queues = &quot;${aggregator.queue.b:external.responses.queue.b}&quot;)<br>    public void onMessageFromB(String body, @Header(value = &quot;requestId&quot;, required = false) String requestIdHeader) {<br>        handleIncoming(&quot;SERVICE_B&quot;, body, requestIdHeader);<br>    }<br>    private void handleIncoming(String source, String body, String requestIdHeader) {<br>        // EXEMPLO: extrair do body se header ausente; aqui simplificamos:<br>        UUID requestId = (requestIdHeader != null) ? UUID.fromString(requestIdHeader) : extractRequestIdFromBody(body);<br>        // parse do payload e extração do status (dependente do formato)<br>        // para exemplo, assumimos payload é JSON simples com campo &quot;status&quot;<br>        String status = extractStatusFromBody(body);<br>        AggregationMessage msg = new AggregationMessage(requestId, source, status, body);<br>        aggregationService.handleMessage(msg);<br>    }<br>    // métodos utilitários simplificados (substituir por parser JSON real)<br>    private UUID extractRequestIdFromBody(String body) {<br>        // placeholder: em produção, parse JSON e pegar requestId<br>        // aqui geramos um UUID temporário para evitar NPE em demo<br>        return UUID.randomUUID();<br>    }<br>    private String extractStatusFromBody(String body) {<br>        // placeholder: parse do JSON; aqui simulamos &quot;APPROVED&quot; por default<br>        return &quot;APPROVED&quot;;<br>    }<br>}</pre><p>AggregationService.java — interface de coordenação (contrato)</p><pre>package com.example.aggregator.service;<br><br>import com.example.aggregator.model.AggregationMessage;<br>/**<br> * Contrato do serviço de agregação.<br> * Implementações podem persistir em DB, usar outbox, etc.<br> */<br>public interface AggregationService {<br>    void handleMessage(AggregationMessage message);<br>}</pre><p>InMemoryAggregationService.java — implementação didática (demo)</p><pre>package com.example.aggregator.service.impl;<br><br>---<br><br>import com.example.aggregator.model.AggregationMessage;<br>import com.example.aggregator.service.AggregationService;<br>import org.springframework.stereotype.Service;<br>import java.time.Instant;<br>import java.util.*;<br>import java.util.concurrent.ConcurrentHashMap;<br>/**<br> * Implementação simples em memória para demonstrar fluxo:<br> * - armazena estados parciais em ConcurrentHashMap<br> * - aplica &quot;wait-for-all&quot; para expectedCount = 2<br> * - compute: se todos APPROVED =&gt; APPROVED; se algum REJECTED =&gt; REJECTED<br> *<br> * Em produção:<br> * - substituir por persistência (Postgres/Mongo/Redis)<br> * - adicionar locking/optimistic versioning<br> * - usar transactional outbox para publicar evento final<br> */<br>@Service<br>public class InMemoryAggregationService implements AggregationService {<br>    private static final int EXPECTED_COUNT = 2;<br>    private static class State {<br>        UUID requestId;<br>        List&lt;String&gt; statuses = new ArrayList&lt;&gt;();<br>        List&lt;String&gt; payloads = new ArrayList&lt;&gt;();<br>        Instant updatedAt = Instant.now();<br>    }<br>    private final Map&lt;UUID, State&gt; store = new ConcurrentHashMap&lt;&gt;();<br>    @Override<br>    public void handleMessage(AggregationMessage message) {<br>        UUID requestId = message.getRequestId();<br>        State s = store.computeIfAbsent(requestId, id -&gt; {<br>            State ns = new State();<br>            ns.requestId = id;<br>            return ns;<br>        });<br>        synchronized (s) { // sincronização por key (simplificada para demo)<br>            s.statuses.add(message.getStatus());<br>            s.payloads.add(message.getPayload());<br>            s.updatedAt = Instant.now();<br>            if (s.statuses.size() &gt;= EXPECTED_COUNT) {<br>                String finalStatus = computeFinalStatus(s.statuses);<br>                finalizeAggregation(requestId, finalStatus, s.payloads);<br>                store.remove(requestId); // cleanup; em produção, atualizar state para COMPLETED<br>            } else {<br>                // Ainda aguardando: log / métricas<br>                System.out.printf(&quot;Aggregation pending for %s: received %d/%d%n&quot;,<br>                        requestId, s.statuses.size(), EXPECTED_COUNT);<br>            }<br>        }<br>    }<br>    private String computeFinalStatus(List&lt;String&gt; statuses) {<br>        boolean anyRejected = statuses.stream().anyMatch(s -&gt; &quot;REJECTED&quot;.equalsIgnoreCase(s));<br>        boolean allApproved = !statuses.isEmpty() &amp;&amp; statuses.stream().allMatch(s -&gt; &quot;APPROVED&quot;.equalsIgnoreCase(s));<br>        if (anyRejected) return &quot;REJECTED&quot;;<br>        if (allApproved) return &quot;APPROVED&quot;;<br>        return &quot;PENDING&quot;;<br>    }<br>    private void finalizeAggregation(UUID requestId, String finalStatus, List&lt;String&gt; payloads) {<br>        // Em produção, aqui:<br>        // 1) gravar estado final no DB (aggregation_state)<br>        // 2) gravar evento no outbox na mesma tx<br>        // 3) publicar resultado de forma confiável<br>        System.out.printf(&quot;Finalized aggregation %s -&gt; %s. payloads=%s%n&quot;, requestId, finalStatus, payloads);<br>    }<br>}</pre><p><strong>Fontes:</strong></p><ul><li><a href="https://www.enterpriseintegrationpatterns.com/patterns/messaging/Aggregator.html">Aggregator - Enterprise Integration Patterns</a></li><li><a href="https://java-design-patterns.com/patterns/microservices-aggregrator/">Microservices Aggregator Pattern in Java: Building Efficient Composite Services in Java</a></li><li><a href="https://martinfowler.com/bliki/AggregateOrientedDatabase.html">bliki: Aggregate Oriented Database</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e67bb4b16c3f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/code-coffee-tech/o-padr%C3%A3o-aggregator-em-microservi%C3%A7os-orquestrando-mensagens-ass%C3%ADncronas-para-decis%C3%B5es-de-neg%C3%B3cio-e67bb4b16c3f">Aggregator Pattern em Microserviços — Como Combinar Respostas Assíncronas</a> was originally published in <a href="https://medium.com/code-coffee-tech">Code &amp; Coffee Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GraphQL: O Que é, Como Funciona e Como Implementar com Python e MySQL]]></title>
            <link>https://medium.com/code-coffee-tech/graphql-o-que-%C3%A9-como-funciona-e-como-implementar-com-python-e-mysql-db81ebfac9e5?source=rss-83d15fada348------2</link>
            <guid isPermaLink="false">https://medium.com/p/db81ebfac9e5</guid>
            <dc:creator><![CDATA[Rafael Megda]]></dc:creator>
            <pubDate>Fri, 21 Mar 2025 02:04:16 GMT</pubDate>
            <atom:updated>2025-09-08T17:32:59.242Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9K6r7iGo4f_zGQXSOGqoRQ.jpeg" /></figure><p>Se você já trabalhou com APIs REST, provavelmente já enfrentou situações onde precisou fazer várias requisições para obter dados de diferentes endpoints. Ou pior: recebeu mais dados do que realmente precisava.</p><p>Se isso soa familiar, você pode se beneficiar do <strong>GraphQL</strong>.</p><h3>O que é GraphQL?</h3><p>GraphQL é uma linguagem de consulta para APIs e um runtime que permite obter <strong>exatamente</strong> os dados que você precisa, sem desperdícios ou chamadas desnecessárias.</p><p>Diferente do REST, onde os dados são acessados por meio de vários endpoints fixos, no GraphQL temos <strong>uma única URL</strong> que recebe queries dinâmicas e retorna apenas as informações solicitadas.</p><h3>Por que usar GraphQL ao invés de REST?</h3><p>Vamos comparar os dois modelos com um exemplo.</p><h3>API REST: Dados fixos e pouca flexibilidade</h3><p>No REST, os endpoints retornam dados pré-definidos. Se você fizer uma requisição para buscar um usuário, a API pode retornar um objeto com todas as informações disponíveis, mesmo que você só precise de algumas.</p><p>Exemplo de requisição REST:</p><pre>GET /users/1</pre><p>Exemplo de resposta REST:</p><pre>{<br>  &quot;id&quot;: 1,<br>  &quot;name&quot;: &quot;João Silva&quot;,<br>  &quot;email&quot;: &quot;joao@email.com&quot;,<br>  &quot;birth_date&quot;: &quot;1990-05-20&quot;,<br>  &quot;address&quot;: {<br>    &quot;street&quot;: &quot;Rua das Flores&quot;,<br>    &quot;city&quot;: &quot;São Paulo&quot;,<br>    &quot;state&quot;: &quot;SP&quot;<br>  }<br>}</pre><p>Agora imagine que você só precisa do nome e e-mail. Com REST, não há como solicitar apenas esses campos — você recebe todo o payload definido na rota.</p><h3>API GraphQL: Flexibilidade total</h3><p>Com GraphQL, você pode definir <strong>exatamente</strong> quais informações deseja receber.</p><p>Exemplo de requisição GraphQL:</p><pre>query {<br>  user(id: 1) {<br>    name<br>    email<br>  }<br>}</pre><p>Exemplo de resposta GraphQL:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;user&quot;: {<br>      &quot;name&quot;: &quot;João Silva&quot;,<br>      &quot;email&quot;: &quot;joao@email.com&quot;<br>    }<br>  }<br>}</pre><p>✅ <strong>Menos tráfego de dados</strong><br> ✅ <strong>Maior eficiência</strong><br> ✅ <strong>Melhor escalabilidade</strong></p><p>Agora, se quisermos incluir os pedidos do usuário na mesma requisição, basta modificar a query:</p><pre>query {<br>  user(id: 1) {<br>    name<br>    email<br>    orders {<br>      id<br>      total<br>    }<br>  }<br>}</pre><p>Isso elimina a necessidade de múltiplas requisições, como no REST, onde precisaríamos de um endpoint separado para buscar pedidos (GET /orders?userId=1).</p><h3>Implementando um Servidor GraphQL com Python e MySQL</h3><p>Aqui está um exemplo simples usando <strong>FastAPI</strong> e <strong>SQLAlchemy</strong> para um sistema de pedidos.</p><h3>Passo 1: Instalar dependências</h3><pre>pip install fastapi graphene sqlalchemy databases mysql-connector-python uvicorn</pre><h3>Passo 2: Criar o banco de dados MySQL</h3><pre>CREATE DATABASE ecommerce;<br><br>CREATE TABLE users (<br>    id INT PRIMARY KEY AUTO_INCREMENT,<br>    name VARCHAR(100),<br>    email VARCHAR(100)<br>);<br><br>CREATE TABLE orders (<br>    id INT PRIMARY KEY AUTO_INCREMENT,<br>    user_id INT,<br>    total DECIMAL(10,2),<br>    FOREIGN KEY (user_id) REFERENCES users(id)<br>);</pre><h4>Passo 3: Configurar SQLAlchemy e conectar ao MySQL</h4><pre>from sqlalchemy import create_engine, Column, Integer, String, ForeignKey, DECIMAL<br>from sqlalchemy.ext.declarative import declarative_base<br>from sqlalchemy.orm import sessionmaker, relationship<br><br>DATABASE_URL = &quot;mysql+mysqlconnector://user:password@localhost/ecommerce&quot;<br>engine = create_engine(DATABASE_URL)<br>SessionLocal = sessionmaker(bind=engine)<br>Base = declarative_base()<br><br>class User(Base):<br>    __tablename__ = &quot;users&quot;<br>    id = Column(Integer, primary_key=True)<br>    name = Column(String)<br>    email = Column(String)<br>    orders = relationship(&quot;Order&quot;, back_populates=&quot;user&quot;)<br><br>class Order(Base):<br>    __tablename__ = &quot;orders&quot;<br>    id = Column(Integer, primary_key=True)<br>    user_id = Column(Integer, ForeignKey(&quot;users.id&quot;))<br>    total = Column(DECIMAL(10, 2))<br>    user = relationship(&quot;User&quot;, back_populates=&quot;orders&quot;)</pre><h4>Passo 4: Criar a API GraphQL</h4><pre>import graphene<br>from graphene_sqlalchemy import SQLAlchemyObjectType<br>from fastapi import FastAPI<br>from starlette.graphql import GraphQLApp<br><br>class UserType(SQLAlchemyObjectType):<br>    class Meta:<br>        model = User<br><br>class OrderType(SQLAlchemyObjectType):<br>    class Meta:<br>        model = Order<br><br>class Query(graphene.ObjectType):<br>    users = graphene.List(UserType)<br>    user = graphene.Field(UserType, id=graphene.Int())<br><br>    def resolve_users(self, info):<br>        session = SessionLocal()<br>        return session.query(User).all()<br><br>    def resolve_user(self, info, id):<br>        session = SessionLocal()<br>        return session.query(User).filter(User.id == id).first()<br><br>schema = graphene.Schema(query=Query)<br>app = FastAPI()<br>app.add_route(&quot;/graphql&quot;, GraphQLApp(schema=schema))</pre><h3>Passo 4: Executar a API</h3><pre>uvicorn main:app --reload</pre><p>Agora, você pode acessar http://127.0.0.1:8000/graphql e fazer queries no seu servidor GraphQL.</p><h3>Sugestões de Leitura 📚</h3><p>Para se aprofundar no assunto, confira esses artigos no Medium:</p><h3>GraphQL e API Gateway</h3><ul><li>🔗 <a href="https://medium.com/algum-link-graphql">Como usar GraphQL em ambientes com API Gateway</a></li><li>🔗 <a href="https://medium.com/algum-link-graphql-vs-rest">GraphQL vs REST: Qual escolher?</a></li></ul><h3>API REST e Boas Práticas</h3><ul><li>🔗 <a href="https://medium.com/algum-link-rest">Como projetar APIs REST de forma eficiente</a></li><li>🔗 <a href="https://medium.com/algum-link-versionamento-api">Versionamento de APIs: Estratégias para escalar</a></li></ul><p>Se você quer melhorar seu design de APIs, vale a pena dar uma olhada! 🚀</p><h3>Dicas Rápidas de Carreira 🎯</h3><p>Baseadas em livros que ajudam a desenvolver soft skills e inteligência profissional:</p><p>📌 <strong>“O Jogo Infinito” — Simon Sinek</strong><br> ➡ O sucesso não é um ponto final, mas um processo contínuo. Pense a longo prazo.</p><p>📌 <strong>“Como Fazer Amigos e Influenciar Pessoas” — Dale Carnegie</strong><br> ➡ O impacto que você causa depende mais de como você escuta do que do que você fala.</p><p>📌 <strong>“A Regra dos 5 Segundos” — Mel Robbins</strong><br> ➡ Se algo te assusta, conte até 5 e faça mesmo assim. A ação elimina a hesitação.</p><p>📌 <strong>“Mindset” — Carol Dweck</strong><br> ➡ O crescimento vem da adaptação. Falhar faz parte do jogo, continuar é o que diferencia os melhores.</p><p>📌 <strong>“Antifrágil” — Nassim Taleb</strong><br> ➡ Não busque estabilidade absoluta, mas a capacidade de se fortalecer com o caos.</p><p>Se você quer crescer na carreira, comece ajustando seu mindset! 🔥</p><h3>🚀 Quer receber conteúdos exclusivos? Assine a Newsletter Code &amp; Coffee!</h3><p>Se você curtiu esse artigo e quer receber mais conteúdos sobre <strong>backend, arquitetura de software, APIs e carreira em tecnologia</strong>, assine minha newsletter <strong>Code &amp; Coffee</strong> no LinkedIn.</p><p>Toda semana, trago <strong>insights práticos, tutoriais e discussões técnicas</strong> para você se manter atualizado e evoluir como desenvolvedor.</p><p>🔗 <a href="https://www.linkedin.com/newsletter/code-coffee"><strong>Assine grátis aqui!</strong></a></p><p>Te vejo na próxima edição! ☕🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db81ebfac9e5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/code-coffee-tech/graphql-o-que-%C3%A9-como-funciona-e-como-implementar-com-python-e-mysql-db81ebfac9e5">GraphQL: O Que é, Como Funciona e Como Implementar com Python e MySQL</a> was originally published in <a href="https://medium.com/code-coffee-tech">Code &amp; Coffee Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing AWS Lambda Memory Usage: Monitoring and Visualization with CloudWatch, Grafana, and…]]></title>
            <link>https://medium.com/@rafaelmisidoro/optimizing-aws-lambda-memory-usage-monitoring-and-visualization-with-cloudwatch-grafana-and-25e06519ac4f?source=rss-83d15fada348------2</link>
            <guid isPermaLink="false">https://medium.com/p/25e06519ac4f</guid>
            <dc:creator><![CDATA[Rafael Megda]]></dc:creator>
            <pubDate>Fri, 28 Feb 2025 17:44:45 GMT</pubDate>
            <atom:updated>2025-02-28T17:44:45.454Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Optimizing AWS Lambda Memory Usage: Monitoring and Visualization with CloudWatch, Grafana, and Datadog</strong></h3><h4>Enhancing Performance and Cost Efficiency through Effective Memory Management and Real-time Monitoring in Serverless Architectures 🌐📊</h4><h3>Introduction</h3><p>Microservices have revolutionized our approach to architecture, and cloud computing has brought significant benefits. However, with great power comes great responsibility, especially regarding cost management. Often, when creating a new component in the cloud, such as on AWS, we tend to focus on functionality without adequately considering cost implications. While we usually make a preliminary cost estimate using tools like the AWS Pricing Calculator, it is crucial to delve deeper to ensure an efficient, robust, and scalable system while minimizing costs.</p><h3>AWS Lambda Memory Configuration</h3><p>AWS Lambda allows you to configure memory allocation, ranging from 128 MB to 10,240 MB in 1 MB increments. The default memory size is 128 MB.</p><h4>How to Configure Memory</h4><ul><li>Open the Functions page of the Lambda console.</li><li>Choose a function.</li><li>Select the Configuration tab and then choose General configuration.</li><li>Under General configuration, click Edit.</li><li>For Memory, set a value between 128 MB and 10,240 MB.</li><li>Click Save.</li></ul><h4>How Memory Affects Performance</h4><ul><li>Increasing memory can improve execution speed, especially for compute-intensive tasks.</li><li>However, higher memory allocations can lead to unnecessary costs.</li><li>The right balance depends on your function’s requirements and behavior.</li></ul><h4>How to Optimize Memory</h4><ul><li>Use tools like AWS Lambda Power Tuning to test your function at different memory settings.</li><li>Monitor performance metrics such as execution duration, memory usage, and CPU utilization.</li><li>Set alarms to identify memory-bound functions.</li></ul><h3>CloudWatch Queries for AWS Lambda with Grafana and Datadog</h3><p>Monitoring memory usage and performance of AWS Lambda functions is crucial for optimizing resources and reducing costs. This tutorial provides a step-by-step guide to creating monitoring dashboards in Grafana and Datadog using CloudWatch queries.</p><h4>Prerequisites</h4><ul><li>AWS Account: Access to an AWS account with permissions to view CloudWatch logs.</li><li>Grafana: A configured Grafana instance with access to the CloudWatch data plugin.</li><li>Datadog: An active Datadog account with AWS integration configured.</li></ul><h3>Creating Dashboards in Grafana</h3><h4>Step 1: Configure the CloudWatch Data Source</h4><ul><li>Access Grafana and go to Configuration &gt; Data Sources.</li><li>Click Add data source and select CloudWatch.</li><li>Enter AWS credentials (Access Key and Secret Key) or configure IAM Role for access.</li><li>Test the connection to ensure Grafana can access CloudWatch data.</li></ul><h4>Step 2: Create a Monitoring Panel</h4><ul><li>Go to Create &gt; Dashboard and click Add new panel.</li><li>In the query editor, select the configured CloudWatch data source.</li><li>Enter the query to monitor memory consumption: plaintext filter @type = &quot;REPORT&quot; | stats max(@memorySize / 1000 / 1000) as provisionedMemoryMB, min(@maxMemoryUsed / 1000 / 1000) as smallestMemoryRequestMB, avg(@maxMemoryUsed / 1000 / 1000) as avgMemoryUsedMB, max(@maxMemoryUsed / 1000 / 1000) as maxMemoryUsedMB, provisionedMemoryMB - maxMemoryUsedMB as overProvisionedMB</li><li>Configure the graph to display the desired metrics, such as lines or bars.</li><li>Save the panel and add it to the dashboard.</li></ul><h3>Creating Dashboards in Datadog</h3><h4>Step 1: Configure AWS Integration</h4><ul><li>In Datadog, go to Integrations &gt; Amazon Web Services.</li><li>Configure the integration with the necessary permissions to access CloudWatch logs.</li></ul><h4>Step 2: Create a Dashboard</h4><ul><li>Access Dashboards and click New Dashboard.</li><li>Add a new widget and select Timeseries or Query Value.</li><li>Enter the query to monitor execution duration: plaintext fields @timestamp, @message | filter @message like /REPORT/ | parse @message /Duration: (?&lt;duration&gt;\d+\.\d+) ms/ | stats avg(duration) as avgDuration, max(duration) as maxDuration, min(duration) as minDuration by bin(5m) | sort @timestamp desc</li><li>Configure the widget to display metrics clearly and informatively.</li><li>Save the widget and add it to the dashboard.</li></ul><h3>Conclusion</h3><p>Creating monitoring dashboards in Grafana and Datadog using CloudWatch queries allows for effective visualization of AWS Lambda functions’ performance and resource usage. This facilitates pattern identification and resource optimization, contributing to more efficient and cost-effective management.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25e06519ac4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[️ Microserviços na Prática: Como Fazer a Transição Sem Complicar Seu Sistema]]></title>
            <link>https://medium.com/code-coffee-tech/%EF%B8%8F-microservi%C3%A7os-na-pr%C3%A1tica-como-fazer-a-transi%C3%A7%C3%A3o-sem-complicar-seu-sistema-5f4194c00814?source=rss-83d15fada348------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f4194c00814</guid>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Rafael Megda]]></dc:creator>
            <pubDate>Mon, 24 Feb 2025 11:48:14 GMT</pubDate>
            <atom:updated>2025-09-08T17:37:59.295Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HZDgBvIiQ5QtNg82vospCw.jpeg" /></figure><p>Eaee galera, tudo bem? Dando sequência ao conteúdo de arquitetura que temos visto nas últimas edições, dessa vez vamos explorar abordagens técnicas sólidas para essa transição, citando livros e artigos renomados, além de trazer exemplos práticos para guiar essa jornada.</p><p>Não deixe de ler até o final e se curtir o conteúdo compartilhe, comente no post os desafios já encontrados, compartilhe também sua experiência para que outros possam absorver, afinal uma boa forma de aprender é compartilhar seu conhecimento.</p><p>Bora pra leitura?</p><h3>🔍 O Problema da Arquitetura Monolítica</h3><p>Muitos sistemas legados foram construídos de forma monolítica, onde todas as funcionalidades estão interligadas em uma única base de código. Isso pode trazer problemas como:</p><ul><li>🚀 <strong>Baixa escalabilidade</strong> — Todo o sistema precisa ser escalado junto, mesmo que apenas uma funcionalidade demande mais recursos.</li><li>🐞 <strong>Manutenção difícil</strong> — Pequenas mudanças podem gerar efeitos colaterais inesperados.</li><li>⏳ <strong>Deploys demorados</strong> — Qualquer alteração exige a reconstrução e o redeploy do sistema inteiro.</li></ul><p>📖 <strong>Referência:</strong> Fowler, M. (2019). “Microservices: A Definition”. <a href="http://martinfowler.com/">MartinFowler.com</a>.</p><h3>🔄 Como Planejar a Transição</h3><p>A transição de um monolito para microserviços precisa de uma estratégia bem definida. Alguns modelos sugeridos por especialistas incluem:</p><h3>🔹 1. Estrangulamento do Monólito (Strangler Pattern)</h3><p>Este padrão, descrito por Martin Fowler, consiste em dividir partes do sistema aos poucos, migrando funcionalidades para novos serviços independentes sem interromper o funcionamento do monólito.</p><p><strong>Passo a passo:</strong></p><ol><li><strong>Identifique os Domínios</strong> — Quebre o sistema em módulos independentes (DDD pode ajudar aqui).</li><li><strong>Crie APIs Facade</strong> — Redirecione chamadas para novas implementações aos poucos.</li><li><strong>Migre Funcionalidades Críticas</strong> — Comece pelos módulos de menor dependência.</li></ol><p>📖 <strong>Referência:</strong> Fowler, M. (2019). “The Strangler Fig Application”. <a href="http://martinfowler.com/">MartinFowler.com</a>.</p><h3>🔹 2. Modularização Progressiva</h3><p>Nesse modelo, ao invés de quebrar o monólito de uma vez, refatora-se internamente, criando camadas de abstração até que os módulos possam ser extraídos como serviços independentes.</p><p><strong>Principais benefícios:</strong> ✅ Menos impacto imediato ✅ Código mais organizado ✅ Melhor adaptação dos times</p><p>📖 <strong>Referência:</strong> Newman, S. (2015). “Building Microservices”. O’Reilly Media.</p><h3>🛠️ Implementação Técnica: Exemplo Prático</h3><p>Vamos ilustrar a transição usando um sistema fictício de gestão de pedidos.</p><p><strong>Antes (Monolito):</strong></p><pre>public class PedidoService {<br>    public void processarPedido(Pedido pedido) {<br>        EstoqueService.atualizarEstoque(pedido);<br>        PagamentoService.processarPagamento(pedido);<br>        NotificacaoService.enviarEmail(pedido);<br>    }<br>}</pre><p><strong>Após a migração para microserviços:</strong></p><p>✅ Criamos serviços independentes para Estoque, Pagamento e Notificação. ✅ Utilizamos comunicação assíncrona via <strong>eventos</strong>.</p><pre>public class PedidoService {<br>    public void processarPedido(Pedido pedido) {<br>        eventBus.publish(new PedidoCriadoEvent(pedido));<br>    }<br>}</pre><p>Cada serviço agora escuta e processa apenas eventos relevantes. Isso reduz acoplamento e melhora escalabilidade.</p><p>📖 <strong>Referência:</strong> Richardson, C. (2017). “Microservices Patterns”. Manning Publications.</p><h3>📢 Conclusão</h3><p>Migrar de um monolito para microserviços não é apenas uma mudança técnica, mas organizacional. Estratégias como <strong>Strangler Pattern</strong> e <strong>Modularização Progressiva</strong> ajudam a evitar riscos e garantir uma transição suave.</p><h3>📚 Sugestões de Leitura</h3><p>📘 <em>“Building Microservices” — Sam Newman</em></p><p>📘 <em>“Designing Data-Intensive Applications” — Martin Kleppmann</em></p><p>📘 <em>“Microservices Patterns” — Chris Richardson</em></p><h3>📰 Notícias da Semana</h3><p>🔥 AWS lança nova ferramenta para observabilidade em microsserviços</p><p>🔥 Kubernetes 1.30 traz melhorias de segurança</p><p>🔥 Netflix compartilha case sobre transição de monólito para microsserviços</p><p>Sabia que agora também estamos no Substack? Ao assinar, irá ganhar grátis, na hora, um template do Notion especial, feito para te ajudar a organizar seus estudos e projetos.</p><p><strong>Quer mais conteúdos técnicos aprofundados?</strong> 🔗 Assine a <strong>Code &amp; Coffee</strong> no Substack ou no Linkedin e receba toda semana insights como este!</p><p>👉 <a href="https://rafaelmegda.substack.com/">Assinar a Newsletter Substack</a></p><p>👉 <a href="https://www.linkedin.com/newsletters/7057736334987141121/">Assinar a Newsletter Linkedin</a></p><p>👉 <a href="https://www.instagram.com/megdarafael">Instagram</a></p><p>👉 <a href="https://medium.com/@rafaelmisidoro">Assinar o Medium grátis</a></p><p>📩 <strong>Gostou deste conteúdo? Compartilhe com sua rede! Comente no post quais seus desafios e aprendizados com migração de micro-serviços.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f4194c00814" width="1" height="1" alt=""><hr><p><a href="https://medium.com/code-coffee-tech/%EF%B8%8F-microservi%C3%A7os-na-pr%C3%A1tica-como-fazer-a-transi%C3%A7%C3%A3o-sem-complicar-seu-sistema-5f4194c00814">🏗️ Microserviços na Prática: Como Fazer a Transição Sem Complicar Seu Sistema</a> was originally published in <a href="https://medium.com/code-coffee-tech">Code &amp; Coffee Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boas práticas usando GIT. Aprenda comandos do básico ao avançado]]></title>
            <link>https://medium.com/code-coffee-tech/boas-pr%C3%A1ticas-usando-git-aprenda-comandos-do-b%C3%A1sico-ao-avan%C3%A7ado-52dfb65a4c1e?source=rss-83d15fada348------2</link>
            <guid isPermaLink="false">https://medium.com/p/52dfb65a4c1e</guid>
            <category><![CDATA[fundamentos]]></category>
            <dc:creator><![CDATA[Rafael Megda]]></dc:creator>
            <pubDate>Wed, 17 Jul 2024 02:03:27 GMT</pubDate>
            <atom:updated>2025-09-08T17:33:57.969Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n9g3u2RQ2L0duv9pXFyGGw.jpeg" /></figure><p>Faaallaa, Devs, blz? 👋</p><p>Nesta edição, vamos mergulhar fundo no Git para dar um panorama do básico ao avançado e com boas praticas do Git. Se você está começando na área de programação ou já é um desenvolvedor experiente, este artigo está repleto de dicas e truques para aprimorar suas habilidades com Git. Vamos explorar alguns comandos e estratégias avançadas para tornar seu fluxo de trabalho mais eficiente e produtivo.</p><h3>📚Manual de Boas Práticas com Git</h3><p>Para começarmos, trago alguns pontos que considero serem de boas praticas ao trabalhar com o Git. Versionar o código corretamente é essencial para o projeto que tenha mais pessoas alterando a mesma aplicação.</p><p>Então, vamos la, anota ae algumas dicas de boas práticas:</p><h3>1. Commite com Frequência</h3><p>Realize commits frequentemente para garantir que as mudanças sejam pequenas e fáceis de gerenciar. Isso facilita o rastreamento de bugs e a revisão de código.</p><h3>2. Use Mensagens de Commit Descritivas</h3><p>As mensagens de commit devem ser claras e descritivas. Uma boa prática é usar a estrutura:</p><pre>Resumo do commit<br>Descrição detalhada (se necessário)</pre><h3>3. Trabalhe em Branches</h3><p>Sempre crie um branch para novas features ou correções de bugs. Isso mantém o branch main (ou master) limpo e estável. Veja a possibilidade de criar convensões para padronizar os nomes das branchs como bug/nome-projeto ou feature/nome-projeto.</p><h3>4. Use mensagens para descrever Pull Request</h3><p>Ao fazer o PR da sua branch para outra, coloque uma mensagem descritiva do que se trata a entrega, quais foram as alterações. Isso auxilia ao pesquisar os PRs e o que foi implantado em determinado ambiente.</p><h3>5. Faça Revisões de Código</h3><p>O famoso Code Review. O github por exemplo oferece ferramentas interessantes para revisar o código. O importante é que você revise o código dos seus colegas e peça para que revisem o seu. A revisão de código ajuda a identificar problemas e melhorar a qualidade do código.</p><p>Este ponto já nos gera nos conteúdos sobre Code Review, o importante aqui é criar a cultura de revisão.</p><h3>5. Sincronize com Frequência</h3><p>Cuidado com os merges, não deixe acumlar código que gera um Merge complexo depois. Mantenha sua branch atualizada com o branch principal para evitar conflitos de merge. Use git pull ou git fetch seguido de git rebase.</p><h3>6. Use .gitignore de Forma Eficiente</h3><p>Configure seu .gitignore para evitar adicionar arquivos desnecessários ao repositório.</p><h3>7. Backup e Recuperação</h3><p>Sempre tenha um backup de seus repositórios remotos e saiba como recuperar dados usando git reflog e git reset.</p><p>Agora que já passamos pelas boas práticas, vamos conhecer alguns comandos do básico ao avançado.</p><h3>🌱 Para os Iniciantes: O Básico do Git</h3><p>Vamos começar do básico para formarmos o conceito até o avançado. Tenho certeza que conhecimento a mais é sempre bem vindo!</p><h3>O Que é Git?</h3><p>De forma prática e resumida: Git é um sistema de controle de versão distribuído que ajuda você a gerenciar mudanças no código-fonte ao longo do tempo. Ele permite que você colabore com outros desenvolvedores de forma eficiente.</p><h3>Comandos Básicos do Git</h3><p>Isso aqui é importante você ter anotado nas suas notas adesivas. Com certeza ira usar praticamente todos os dias e logo já tera decorado.</p><p>São comandos básicos para versionamento do seu código:</p><ul><li>git init**:** Inicializa um novo repositório Git.</li><li>git clone [URL]<strong>:</strong> Clona um repositório existente.</li><li>git add [arquivo]: Adiciona arquivos ao próximo commit.</li><li>git commit -m “mensagem”: Cria um novo commit com uma mensagem descritiva.</li><li>git push: Envia commits para um repositório remoto.</li></ul><p><strong>Para um guia completo para iniciantes, confira </strong><a href="https://www.freecodecamp.org/news/how-to-use-git-best-practices-for-beginners/"><strong>este artigo</strong></a><strong> do freeCodeCamp, vai te ajudar a instalar e dar os primeiros passos com o Git.</strong></p><h3>🚀 Para os Devs Avançados: Explorando Git Avançado</h3><p>Agora que já vimos as boas praticas, os comandos básicos, intalações e como usar o Git, vamos dar um passo a mais e conhecer alguns comandos avançados do Git.</p><p>É claro, existem inumeros outros comandos, o objetivo é listarmos alguns dos mais utilizados e que são importantes conhecermos. Então, vamos la!!</p><h3>Reescrevendo Histórico com git rebase</h3><p>O git rebase é uma ferramenta poderosa para reescrever o histórico de commits. Ele é especialmente útil para manter um histórico de commits limpo e linear.</p><pre>git rebase -i HEAD~3</pre><p>Este comando abre um editor de texto com os últimos três commits. Você pode escolher reordenar, combinar (squash) ou editar commits.</p><h3>Manipulando Commits com git cherry-pick</h3><p>O git cherry-pick permite aplicar commits específicos de um branch em outra branch.</p><pre>git cherry-pick abc123</pre><p>Isso aplica o commit identificado por abc123 ao branch atual.</p><h3>Stashing com git stash</h3><p>O git stash é útil quando você precisa salvar temporariamente mudanças que ainda não estão prontas para serem commitadas.</p><pre>git stash</pre><p>Isso salva suas mudanças e limpa seu diretório de trabalho. Para recuperar suas mudanças, use:</p><pre>git stash pop</pre><h3>Trabalhando com Branches Remotos</h3><p>Quando colaboramos com outros desenvolvedores, é comum trabalhar com branches remotos.</p><pre>git fetch origin<br>git checkout -b featureX origin/featureX</pre><p>Isso busca as últimas mudanças do repositório remoto e cria um novo branch local baseado no branch remoto featureX.</p><h3>🌟 Dicas para Todos os Níveis</h3><p>E para fecharmos, separei algumas dicas gerais para utilizarmos com o Git.</p><h3>Configuração Global do Git</h3><p>Defina seu nome de usuário e e-mail globalmente para todos os seus projetos Git:</p><pre>git config --global user.name &quot;Seu Nome&quot;<br>git config --global user.email &quot;seu.email@exemplo.com&quot;</pre><h3>Ignorando Arquivos com .gitignore</h3><p>Crie um arquivo .gitignore para especificar quais arquivos ou diretórios o Git deve ignorar.</p><pre>node_modules/<br>.env<br>.DS_Store</pre><h3>Verificando o Histórico de Commits</h3><p>Use git log para visualizar o histórico de commits:</p><pre>git log --oneline --graph --decorate --all</pre><p>Isso exibe um log gráfico compacto e decorado de todos os branches.</p><h3>Criação de Alias para Comandos Comuns</h3><p>Gosta de atalhos? Eu curto agilizar o trabalho. Com os alias são atalhos para comandos que você usa frequentemente, tornando seu trabalho com Git mais rápido.</p><pre>git config --global alias.co checkout<br>git config --global alias.br branch<br>git config --global alias.ci commit<br>git config --global alias.st status</pre><p>Agora você pode usar “git co” em vez de “git checkout”, “git br” em vez de “git branch”, e assim por diante, o céu é o limite</p><h3>Revertendo Commits</h3><p>Às vezes, é necessário desfazer mudanças feitas em commits anteriores. Use git revert para criar um novo commit que inverte as mudanças de um commit específico.</p><pre>git revert abc123</pre><p>Isso reverterá as mudanças do commit abc123 e criará um novo commit com essa reversão.</p><h3>Visualizando Diferentes de Código com git diff</h3><p>O git diff permite comparar mudanças entre commits, branches e o estado de trabalho atual.</p><pre>git diff HEAD~1</pre><p>Isso mostra as mudanças entre o último commit e o estado de trabalho atual.</p><h3>Combinando Commits com git squash</h3><p>Combinar (ou “squash”) commits pode ajudar a limpar o histórico de commits antes de mesclar um branch.</p><pre>git rebase -i HEAD~3</pre><p>No editor que aparece, substitua pick por squash ou s nos commits que deseja combinar. Salve e saia do editor para concluir.</p><h3>Navegando e Recuperando Commits com git reflog</h3><p>O git reflog permite visualizar todas as mudanças locais feitas no repositório, mesmo aquelas que não são visíveis no log normal.</p><pre>git reflog</pre><p>Isso lista todas as ações recentes feitas no repositório, permitindo que você recupere estados anteriores.</p><h3>Mesclando Branches com git merge</h3><p>Mesclar branches permite integrar mudanças de diferentes branches. Use git merge para unir o conteúdo de um branch ao branch atual.</p><pre>git checkout main git merge feature-branch</pre><p>Isso mescla feature-branch ao branch main.</p><h3>Rastreando Arquivos Removidos</h3><p>Às vezes, você pode querer ver os arquivos que foram removidos do repositório.</p><pre>git log --diff-filter=D --summary</pre><p>Isso lista todos os arquivos que foram deletados no histórico do repositório.</p><h3>Cancelando git add Antes do Commit</h3><p>Se você adicionou arquivos acidentalmente e deseja removê-los do próximo commit, use git reset.</p><pre>git add . git reset HEAD arquivo-que-nao-quero.txt</pre><p>Isso remove arquivo-que-nao-quero.txt da lista de arquivos a serem commitados.</p><h3>Rastreando Branches Remotos</h3><p>Para manter-se atualizado com os branches remotos e saber quais estão disponíveis, use git branch -r.</p><pre>git branch -r</pre><p>Isso lista todos os branches remotos que estão disponíveis no repositório remoto.</p><h3>Conclusão</h3><p>Espero que de alguma forma possa contribuir com seu dia a dia. São comandos comuns, mas não são todos, fique tranquilo, existem muitos outras mais avançados e alguns outros nem tão avançados, mas que não são usuais no nosso dia a dia.</p><p>Obrigado por ler nossa edição de Junho da <strong>News</strong>! Esperamos que essas dicas ajudem você a dominar o Git e a melhorar seu fluxo de trabalho.</p><p>Ah comente o que você achou, traga sugestões, novos comandos!</p><p>Compatilhe com sua rede!!</p><p>Até a próxima!</p><p><strong>Quer mais conteúdos técnicos aprofundados?</strong> 🔗 Assine a <strong>Code &amp; Coffee</strong> no Substack ou no Linkedin e receba toda semana insights como este!</p><p>👉 <a href="https://rafaelmegda.substack.com/">Assinar a Newsletter Substack</a></p><p>👉 <a href="https://www.linkedin.com/newsletters/7057736334987141121/">Assinar a Newsletter Linkedin</a></p><p>👉 <a href="https://www.instagram.com/megdarafael">Instagram</a></p><p>👉 <a href="https://medium.com/@rafaelmisidoro">Assinar o Medium grátis</a></p><p>📩 <strong>Gostou deste conteúdo? Compartilhe com sua rede! Comente no post quais seus desafios e aprendizados com migração de micro-serviços.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52dfb65a4c1e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/code-coffee-tech/boas-pr%C3%A1ticas-usando-git-aprenda-comandos-do-b%C3%A1sico-ao-avan%C3%A7ado-52dfb65a4c1e">Boas práticas usando GIT. Aprenda comandos do básico ao avançado</a> was originally published in <a href="https://medium.com/code-coffee-tech">Code &amp; Coffee Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How use Exception Handling in Spring Boot using @ControllerAdvice and @ExceptionHandler to Rest API…]]></title>
            <link>https://medium.com/code-coffee-tech/how-use-exception-handling-in-spring-boot-using-controlleradvice-and-exceptionhandler-to-rest-api-f60d10650e02?source=rss-83d15fada348------2</link>
            <guid isPermaLink="false">https://medium.com/p/f60d10650e02</guid>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Rafael Megda]]></dc:creator>
            <pubDate>Wed, 29 May 2024 12:22:06 GMT</pubDate>
            <atom:updated>2025-09-04T15:12:59.295Z</atom:updated>
            <content:encoded><![CDATA[<h3>How use Exception Handling in Spring Boot using @ControllerAdvice and @ExceptionHandler to Rest API (Examples)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*f15mug4UJfAUuZReY8VcyQ.png" /></figure><p>Developing an API requires a design pattern that helps not only maintain your code, but also consume your API. An important part of the design pattern of a Rest API are exceptions. The API Consumer must receive the correct Status Code in the call.</p><p>To do this, we will see in this article how to use Exception Handling in Spring Boot using the <a href="http://twitter.com/ControllerAdviice">@ControllerAdvice</a> and <a href="http://twitter.com/ExceptionHandler">@ExceptionHandler</a> annotations.</p><p>When you use global exception handling using <a href="http://twitter.com/ControllerAdvice">@ControllerAdvice</a>, your code defines global exception handlers that will apply to all controllers.</p><h4><strong>ResponseEntityExceptionHandler</strong></h4><p>For this you need creat a Class <strong>GlobalExceptionHandler</strong></p><pre>@ControllerAdvice<br>public class GlobalExceptionHandler {<br><br>  @ExceptionHandler(value = ExceptionRequestBadRequests.class)<br>  public ResponseEntity&lt;ErrorResponse&gt; badRequestCustomException(ExceptionRequestBadRequests ex) {<br>    ErrorResponse errorResponse = new ErrorResponse(ex.getMessage(), HttpStatus.BAD_REQUEST.value());<br>    return new ResponseEntity&lt;&gt;(errorResponse, HttpStatus.BAD_REQUEST);<br> }<br><br>  @ExceptionHandler(value = ExceptionRequestInternalError.class)<br>  public ResponseEntity&lt;ErrorResponse&gt; internalErrorCustomException(ExceptionRequestInternalError ex) {<br>    ErrorResponse errorResponse = new ErrorResponse(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR.value());<br>    return new ResponseEntity&lt;&gt;(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);<br> }<br>}</pre><p>In this example class, have two methods badRequestCustomException and internalErrorCustomException (named whatever you prefer).</p><p>The ExceptionHandler annotation is used to define a method that handles Exception-type approaches. It returns a custom error message and HTTP status code.</p><h4><strong>Custom Exception Classes</strong></h4><p>Create custom exception classes to represent different types of exceptions in your application. This improves code readability and maintainability.</p><p>To do this, you need to implement the class for your specific exceptions, in this example: <strong>ExceptionRequestBadRequests </strong>and <strong>ExceptionRequestInternalError</strong></p><pre>public class ExceptionRequestBadRequests extends RuntimeException {<br><br>    public ExceptionRequestBadRequests(String mensagem) {super(mensagem);}<br><br>    public ExceptionRequestBadRequests(Throwable causa) {<br>        super(causa);<br>    }<br><br>    public ExceptionRequestBadRequests(String mensagem, Throwable causa) {<br>        super(mensagem, causa);<br>    }<br>}</pre><pre>public class ExceptionRequestInternalError extends RuntimeException {<br><br>    public ExceptionRequestInternalError(String mensagem) {<br>        super(mensagem);<br>    }<br><br>    public ExceptionRequestInternalError(Throwable causa) {<br>        super(causa);<br>    }<br><br>    public ExceptionRequestInternalError(String mensagem, Throwable causa) {<br>        super(mensagem, causa);<br>    }<br>}</pre><h4>Response Error</h4><p>Now that we have a custom Exception, let’s return the caught error to the Rest API using ErrorResponse</p><pre>public class ErrorResponse {<br><br>   private Integer statusCode;<br><br>   private String message;<br><br>   public ErrorResponse(String message) {<br>    this.message = message;<br>   }<br><br>   public ErrorResponse(String message, int value) {<br>    this.message = message;<br>    this.statusCode = value;<br>   }<br>}</pre><h4>How use my exception Custom in Rest API</h4><p>With the exceptions created and the return to the API defined, you can use the custom method in your API to catch the exceptions and return the correct error code status to your consumer.</p><pre>public Interger testUsingExceptionCustom() {<br>    try {<br>        Interger value = null;<br>        Interger valueTwo = 1;<br>        Interger sum = value + valueTwo;<br>        <br>        return sum;<br><br>    } catch (Exception e) {<br>        throw new ExceptionRequestInternalError(&quot;Your message of error&quot;, e);<br>    }<br>}</pre><p>Alright, now your Rest API has a custom exception to return the correct status code, and you have a Rest API using a good design patterns parameter for Rest API.</p><p>Follow me: <a href="https://www.instagram.com/">https://www.instagram.com/</a>megdarafael</p><p>My Newsletter: <a href="https://www.linkedin.com/newsletters/code-coffee-7057736334987141121/">https://www.linkedin.com/newsletters/code-coffee-7057736334987141121/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f60d10650e02" width="1" height="1" alt=""><hr><p><a href="https://medium.com/code-coffee-tech/how-use-exception-handling-in-spring-boot-using-controlleradvice-and-exceptionhandler-to-rest-api-f60d10650e02">How use Exception Handling in Spring Boot using @ControllerAdvice and @ExceptionHandler to Rest API…</a> was originally published in <a href="https://medium.com/code-coffee-tech">Code &amp; Coffee Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How return in one only list using CompletableFuture for java]]></title>
            <link>https://medium.com/code-coffee-tech/how-return-in-one-only-list-using-completablefuture-for-java-1b2c2a452763?source=rss-83d15fada348------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b2c2a452763</guid>
            <dc:creator><![CDATA[Rafael Megda]]></dc:creator>
            <pubDate>Fri, 22 Sep 2023 15:04:27 GMT</pubDate>
            <atom:updated>2025-09-04T15:10:44.589Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*2Ruupo-vr1ocGDegR1pU3A.png" /></figure><p>To return a single List containing the results of multiple CompletableFuture&lt;List&gt; objects, you can use the CompletableFuture.allOf() method to wait for all the CompletableFuture objects to complete, and then combine their results into a single List. Here&#39;s an example:</p><pre>import java.util.ArrayList;<br>import java.util.List;<br>import java.util.concurrent.CompletableFuture;<br><br>public class Main {<br>    public static void main(String[] args) throws Exception {<br>        CompletableFuture&lt;List&lt;Integer&gt;&gt; futureList1 = CompletableFuture.supplyAsync(() -&gt; {<br>            List&lt;Integer&gt; list = new ArrayList&lt;&gt;();<br>            list.add(1);<br>            list.add(2);<br>            list.add(3);<br>            return list;<br>        });<br><br>        CompletableFuture&lt;List&lt;Integer&gt;&gt; futureList2 = CompletableFuture.supplyAsync(() -&gt; {<br>            List&lt;Integer&gt; list = new ArrayList&lt;&gt;();<br>            list.add(4);<br>            list.add(5);<br>            list.add(6);<br>            return list;<br>        });<br><br>        CompletableFuture&lt;List&lt;Integer&gt;&gt; futureList3 = CompletableFuture.supplyAsync(() -&gt; {<br>            List&lt;Integer&gt; list = new ArrayList&lt;&gt;();<br>            list.add(7);<br>            list.add(8);<br>            list.add(9);<br>            return list;<br>        });<br><br>        CompletableFuture&lt;Void&gt; allFutures = CompletableFuture.allOf(futureList1, futureList2, futureList3);<br><br>        CompletableFuture&lt;List&lt;Integer&gt;&gt; combinedFuture = allFutures.thenApply(v -&gt; {<br>            List&lt;Integer&gt; result = new ArrayList&lt;&gt;();<br>            result.addAll(futureList1.join());<br>            result.addAll(futureList2.join());<br>            result.addAll(futureList3.join());<br>            return result;<br>        });<br><br>        List&lt;Integer&gt; result = combinedFuture.get();<br>        System.out.println(result);<br>    }<br>}</pre><p>In this example, we create three CompletableFuture&lt;List&lt;Integer&gt;&gt; objects that each return a List&lt;Integer&gt; of results. We then use the CompletableFuture.allOf() method to wait for all three CompletableFuture objects to complete.</p><p>We then create a new CompletableFuture&lt;List&lt;Integer&gt;&gt; using the thenApply() method, which takes a Function&lt;T, U&gt; as an argument. The Function takes the result of the previous CompletableFuture objects and returns a new result. In this case, we combine the results of the three CompletableFuture objects into a single List&lt;Integer&gt;.</p><p>Finally, we call the get() method on the CompletableFuture to wait for the computation to complete and retrieve the result.</p><p>I need close my threads? Yes, you can use CompletableFuture.allOf() to wait for all the CompletableFuture objects to complete and then close the thread.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b2c2a452763" width="1" height="1" alt=""><hr><p><a href="https://medium.com/code-coffee-tech/how-return-in-one-only-list-using-completablefuture-for-java-1b2c2a452763">How return in one only list using CompletableFuture for java</a> was originally published in <a href="https://medium.com/code-coffee-tech">Code &amp; Coffee Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How call many methods using Callable and returning one only list]]></title>
            <link>https://medium.com/code-coffee-tech/how-call-many-methods-using-callable-and-returning-one-only-list-dde0afdd978b?source=rss-83d15fada348------2</link>
            <guid isPermaLink="false">https://medium.com/p/dde0afdd978b</guid>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Rafael Megda]]></dc:creator>
            <pubDate>Fri, 22 Sep 2023 13:24:39 GMT</pubDate>
            <atom:updated>2025-09-08T17:44:30.867Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IuiwP8zs_WaY0qNJIuNT_g.jpeg" /></figure><p>Java Callable and Future are used a lot in multithreaded programming. Different of threads, sometimes we wish that a thread could return some value that we can use. Java 5 introduced java.util.concurrent.Callable interface in concurrency package that is similar to Runnable interface but it can return any Object and able to throw Exception.</p><p>The Callable interface in Java is a part of the java.util.concurrent package and is used to define a task that can be executed asynchronously and return a result. It is similar to the Runnable interface, but with the added ability to return a result and throw an exception.</p><p>The Callable interface has a single method called call() that takes no arguments and returns a result of type V. The call() method can throw an exception of type Exception or any of its subclasses.</p><p>The Callable interface is often used in conjunction with the ExecutorService interface to execute tasks asynchronously. The ExecutorService interface provides methods for submitting Callable objects for execution and returning Future objects that represent the result of the Callable execution.</p><p>In Java, a Future is an interface in the java.util.concurrent package that represents the result of an asynchronous computation. It provides a way to check if the computation is complete, retrieve the result of the computation, and cancel the computation if necessary.</p><p>The Future interface has several methods, including:</p><p>isDone(): Returns true if the computation is complete, otherwise returns false.<br>get(): Waits for the computation to complete and returns the result of the computation. If the computation threw an exception, this method will throw an ExecutionException with the original exception as its cause.<br>get(long timeout, TimeUnit unit): Waits for the computation to complete for the specified amount of time and returns the result of the computation. If the computation did not complete within the specified time, this method will throw a TimeoutException.<br>cancel(boolean mayInterruptIfRunning): Attempts to cancel the computation. If the computation has not started yet, it will be cancelled. If the computation is already running and mayInterruptIfRunning is true, it will be interrupted. If the computation is already running and mayInterruptIfRunning is false, it will not be interrupted.<br>Future objects are often returned by methods that perform asynchronous computations, such as ExecutorService.submit(Callable) or CompletionService.submit(Callable). They can be used to retrieve the result of the computation or cancel the computation if necessary.</p><h3>Using Callable with many methods</h3><p>Now, is practic time!!</p><p>If you need call many methods using Callable and return in one only list, this soluction can help you.</p><p>To unify the results of multiple Callable objects that return a List, you can use a List&lt;Future&lt;List&lt;T&gt;&gt;&gt; to store the results of each Callable. Here’s an example:</p><pre>import java.util.ArrayList;<br>import java.util.List;<br>import java.util.concurrent.*;<br><br>public class Main {<br>    public static void main(String[] args) throws Exception {<br>        ExecutorService executorService = Executors.newFixedThreadPool(5);<br><br>        List&lt;Callable&lt;List&lt;Integer&gt;&gt;&gt; callables = new ArrayList&lt;&gt;();<br>        callables.add(new ListOperations(List.of(1, 2, 3)));<br>        callables.add(new ListOperations(List.of(4, 5, 6)));<br>        callables.add(new ListOperations(List.of(7, 8, 9)));<br><br>        List&lt;Future&lt;List&lt;Integer&gt;&gt;&gt; futures = executorService.invokeAll(callables);<br><br>        List&lt;Integer&gt; results = new ArrayList&lt;&gt;();<br>        for (Future&lt;List&lt;Integer&gt;&gt; future : futures) {<br>            results.addAll(future.get());<br>        }<br><br>        System.out.println(results);<br><br>        executorService.shutdown();<br>    }<br>}</pre><p>In this example, we create a List of Callable objects (ListOperations in this case) and pass it to the invokeAll() method of an ExecutorService. This returns a List of Future objects that represent the results of each Callable. We then iterate over the Future objects and add their results to a single List (results in this case). Finally, we print the results and shut down the ExecutorService.</p><h3>Using Callable with many methods and returning in one only list</h3><p>This solution is about how can you use in generic case, but, now i want show how you can call many methods and return in one list.</p><p>For example, if you need to call many queries in your database using Threads and need using different for each query methods for and returned in one only list, you can make this:</p><pre>import java.util.ArrayList;<br>import java.util.List;<br>import java.util.concurrent.*;<br><br>    public class ExemploCopilot {<br>        public static void main(String[] args) throws Exception {<br>            ExecutorService executorService = Executors.newFixedThreadPool(5);<br><br>            Callable&lt;List&lt;Integer&gt;&gt; callableA = new Callable&lt;List&lt;Integer&gt;&gt;() {<br>                @Override<br>                public List&lt;Integer&gt; call() throws Exception {<br>                    return getA();<br>                }<br>            };<br>            Callable&lt;List&lt;Integer&gt;&gt; callableB = new Callable&lt;List&lt;Integer&gt;&gt;() {<br>                @Override<br>                public List&lt;Integer&gt; call() throws Exception {<br>                    return getB();<br>                }<br>            };<br><br>            List&lt;Callable&lt;List&lt;Integer&gt;&gt;&gt; callables = new ArrayList&lt;&gt;();<br>            callables.add(callableA);<br>            callables.add(callableB);<br><br>            List&lt;Future&lt;List&lt;Integer&gt;&gt;&gt; futures = executorService.invokeAll(callables);<br><br>            List&lt;Integer&gt; results = new ArrayList&lt;&gt;();<br>            for (Future&lt;List&lt;Integer&gt;&gt; future : futures) {<br>                results.addAll(future.get());<br>            }<br><br>            System.out.println(results);<br><br>            executorService.shutdown();<br><br>        }<br><br>        private static List&lt;Integer&gt; getB() {<br>            //Write here your code, databases queries, or other codes, but return then in the same Object List as the others methods then you that using in your Callable<br>            List&lt;Integer&gt; interos = new ArrayList&lt;&gt;();<br>            interos.add(2);<br>            return interos;<br>        }<br><br>        private static List&lt;Integer&gt; getA() {<br>            //Write here your code, databases queries, or other codes, but return then in the same Object List as the others methods then you that using in your Callable<br>            List&lt;Integer&gt; interos = new ArrayList&lt;&gt;();<br>            interos.add(1);<br>            return interos;<br>        }<br>    }<br><br></pre><p>In this solution, the code use of Callable call two method for return one List&lt;Integer&gt; but, here, can return one List of your Object.</p><p>Wait that is can help you!</p><p>Follow me!</p><p>Instagram: <a href="https://www.instagram.com/megdarafael">@megdarafael</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dde0afdd978b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/code-coffee-tech/how-call-many-methods-using-callable-and-returning-one-only-list-dde0afdd978b">How call many methods using Callable and returning one only list</a> was originally published in <a href="https://medium.com/code-coffee-tech">Code &amp; Coffee Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practical solutions using Java]]></title>
            <link>https://medium.com/@rafaelmisidoro/practical-solutions-using-java-c8e3e5c0fda3?source=rss-83d15fada348------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8e3e5c0fda3</guid>
            <dc:creator><![CDATA[Rafael Megda]]></dc:creator>
            <pubDate>Fri, 01 Sep 2023 14:56:40 GMT</pubDate>
            <atom:updated>2023-09-01T14:56:40.100Z</atom:updated>
            <content:encoded><![CDATA[<p>The objective is to include a lot of solutions which you using to day of day to programmer using Java.</p><p>Exist many forms of a solution, this is a one of many solution which can help you.</p><h3>Split and trim String one shot creating a List String</h3><p>If you have a String with names and need cut with comma or semicolon, cut whitespace, but not between the names and at final create a String List, this solution can help you.</p><pre>yourString = &quot;testA, testB ; test c ,  testD&quot;<br>List&lt;String&gt; yourString = Arrays.stream(codigo.split(&quot;[,;]&quot;)).map(String::trim).collect(Collectors.toList());</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8e3e5c0fda3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Efficiently Swapping Subtrees in a Binary Tree: A Comprehensive Guide using Java]]></title>
            <link>https://medium.com/@rafaelmisidoro/arvore-bin%C3%A1ria-e997a69699ce?source=rss-83d15fada348------2</link>
            <guid isPermaLink="false">https://medium.com/p/e997a69699ce</guid>
            <dc:creator><![CDATA[Rafael Megda]]></dc:creator>
            <pubDate>Fri, 23 Sep 2022 11:42:25 GMT</pubDate>
            <atom:updated>2024-10-08T02:23:47.934Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction</h4><p>Binary trees are fundamental data structures in computer science, often used to represent hierarchical data. In this article, we will explore a specific problem involving binary trees: swapping subtrees at given depths and performing in-order traversals. We’ll walk through the problem statement, the solution approach, and the detailed implementation in Java.</p><h4>Problem Statement</h4><p>Given a binary tree and a series of swap operations, we need to perform the swaps and return the in-order traversal of the tree after each swap. The tree is defined by its node indexes, and the swaps are defined by their depths.</p><h4><strong>In-order Traversal</strong>:</h4><ol><li>Traverse the left subtree.</li><li>Visit the root node.</li><li>Traverse the right subtree.</li></ol><p><strong>Swap Operation</strong>: Swapping subtrees of a node means that if initially, the node has a left subtree L and a right subtree R, then after swapping, the left subtree will be R and the right subtree will be L.</p><h4>Solution Approach</h4><p>To solve this problem, we need to:</p><ol><li>Parse the input to construct the binary tree.</li><li>Perform the swap operations at the specified depths.</li><li>Perform in-order traversal after each swap operation and store the results.</li></ol><h4>Implementation</h4><p>Let’s dive into the implementation step by step.</p><h4>Node Class</h4><p>First, we define a class to represent each node in the tree.</p><pre>class Node {<br>    int value;<br>    Node left;<br>    Node right;<br><br>    Node(int value) {<br>        this.value = value;<br>        this.left = null;<br>        this.right = null;<br>    }<br>}</pre><h4>Building the Tree</h4><p>Next, we implement a function to build the tree from the given indexes.</p><pre>public static Node buildTree(List&lt;List&lt;Integer&gt;&gt; indexes) {<br>    Node root = new Node(1);<br>    Queue&lt;Node&gt; queue = new LinkedList&lt;&gt;();<br>    queue.add(root);<br>    <br>    for (List&lt;Integer&gt; index : indexes) {<br>        Node current = queue.poll();<br>        if (index.get(0) != -1) {<br>            current.left = new Node(index.get(0));<br>            queue.add(current.left);<br>        }<br>        if (index.get(1) != -1) {<br>            current.right = new Node(index.get(1));<br>            queue.add(current.right);<br>        }<br>    }<br>    return root;<br>}</pre><h4>Swapping Subtrees</h4><p>We then implement a function to swap subtrees at the specified depths.</p><pre>public static void swapSubTree(Node node, int k, int h) {<br>    if (node == null) return;<br>    <br>    if (h % k == 0) {<br>        Node temp = node.left;<br>        node.left = node.right;<br>        node.right = temp;<br>    }<br>    swapSubTree(node.left, k, h + 1);<br>    swapSubTree(node.right, k, h + 1);<br>}</pre><h4>In-order Traversal</h4><p>We also need a function to perform in-order traversal and collect the node values.</p><pre>public static void inOrderTraversal(Node node, List&lt;Integer&gt; result) {<br>    if (node == null) return;<br>    <br>    inOrderTraversal(node.left, result);<br>    result.add(node.value);<br>    inOrderTraversal(node.right, result);<br>}</pre><h4>Main Function</h4><p>Finally, we combine all the steps in the main function to handle the swap operations and collect the results.</p><pre>public static List&lt;List&lt;Integer&gt;&gt; swapNodes(List&lt;List&lt;Integer&gt;&gt; indexes, List&lt;Integer&gt; queries) {<br>    Node root = buildTree(indexes);<br>    List&lt;List&lt;Integer&gt;&gt; result = new ArrayList&lt;&gt;();<br>    <br>    for (int k : queries) {<br>        swapSubTree(root, k, 1);<br>        List&lt;Integer&gt; inOrder = new ArrayList&lt;&gt;();<br>        inOrderTraversal(root, inOrder);<br>        result.add(inOrder);<br>    }<br>    <br>    return result;<br>}</pre><h4>Putting It All Together</h4><p>Here is the complete code:</p><pre>import java.util.*;<br>import java.util.concurrent.*;<br>import java.util.function.*;<br>import java.util.regex.*;<br>import java.util.stream.*;<br>import static java.util.stream.Collectors.joining;<br>import static java.util.stream.Collectors.toList;<br><br>class Result {<br><br>    public static List&lt;List&lt;Integer&gt;&gt; swapNodes(List&lt;List&lt;Integer&gt;&gt; indexes, List&lt;Integer&gt; queries) {<br>        Node root = buildTree(indexes);<br>        List&lt;List&lt;Integer&gt;&gt; result = new ArrayList&lt;&gt;();<br>        <br>        for (int k : queries) {<br>            swapSubTree(root, k, 1);<br>            List&lt;Integer&gt; inOrder = new ArrayList&lt;&gt;();<br>            inOrderTraversal(root, inOrder);<br>            result.add(inOrder);<br>        }<br>        <br>        return result;<br>    }<br><br>    public static Node buildTree(List&lt;List&lt;Integer&gt;&gt; indexes) {<br>        Node root = new Node(1);<br>        Queue&lt;Node&gt; queue = new LinkedList&lt;&gt;();<br>        queue.add(root);<br>        <br>        for (List&lt;Integer&gt; index : indexes) {<br>            Node current = queue.poll();<br>            if (index.get(0) != -1) {<br>                current.left = new Node(index.get(0));<br>                queue.add(current.left);<br>            }<br>            if (index.get(1) != -1) {<br>                current.right = new Node(index.get(1));<br>                queue.add(current.right);<br>            }<br>        }<br>        return root;<br>    }<br><br>    public static void swapSubTree(Node node, int k, int h) {<br>        if (node == null) return;<br>        <br>        if (h % k == 0) {<br>            Node temp = node.left;<br>            node.left = node.right;<br>            node.right = temp;<br>        }<br>        swapSubTree(node.left, k, h + 1);<br>        swapSubTree(node.right, k, h + 1);<br>    }<br><br>    public static void inOrderTraversal(Node node, List&lt;Integer&gt; result) {<br>        if (node == null) return;<br>        <br>        inOrderTraversal(node.left, result);<br>        result.add(node.value);<br>        inOrderTraversal(node.right, result);<br>    }<br>}</pre><h3>Conclusion</h3><p>In this article, we explored how to efficiently swap subtrees in a binary tree at specified depths and perform in-order traversals. We walked through the problem statement, the solution approach, and the detailed implementation in Java. This solution can be adapted and extended to handle more complex tree operations and queries.</p><p>Feel free to leave your comments and questions below. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e997a69699ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>