Especialização em Backend com Java & Spring Boot • Demonstrações Práticas Compiláveis


💻 Código de Exemplo 01 — Registro no Service Discovery com Eureka

package com.empresa.api;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient // registra a instância no Eureka/Consul na inicialização
public class PedidosServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(PedidosServiceApplication.class, args);
    }
}
# application.yml — pedidos-service
spring:
  application:
    name: pedidos-service # nome lógico usado por outros serviços via Feign/lb://
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka
  instance:
    lease-renewal-interval-in-seconds: 10 # frequência do heartbeat

💻 Código de Exemplo 02 — Cliente Declarativo Feign com Fallback

package com.empresa.api.client;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient(name = "estoque-service", fallback = EstoqueFeignClientFallback.class)
public interface EstoqueFeignClient {

    @GetMapping("/api/v1/estoque/{produtoId}")
    EstoqueDTO consultarEstoque(@PathVariable("produtoId") Long produtoId);
}
package com.empresa.api.client;

import org.springframework.stereotype.Component;

@Component
public class EstoqueFeignClientFallback implements EstoqueFeignClient {

    @Override
    public EstoqueDTO consultarEstoque(Long produtoId) {
        // Serviço de estoque indisponível: resposta degradada em vez de propagar exceção.
        return new EstoqueDTO(produtoId, 0, true);
    }
}

record EstoqueDTO(Long produtoId, int quantidadeDisponivel, boolean indisponivel) {}

💻 Código de Exemplo 03 — Configuração Dinâmica com Spring Cloud Config e @RefreshScope

package com.empresa.api.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

@Service
@RefreshScope // recarrega o valor abaixo após POST em /actuator/refresh, sem reiniciar a aplicação
public class TaxaJurosService {

    @Value("${taxa.juros.parcelamento:0.05}")
    private double taxaJuros;

    public double calcularValorComJuros(double valorBase, int parcelas) {
        return valorBase * (1 + taxaJuros * parcelas);
    }
}
# bootstrap.yml — aponta o serviço para o Config Server centralizado
spring:
  config:
    import: "configserver:http://localhost:8888"
  application:
    name: pedidos-service
management:
  endpoints:
    web:
      exposure:
        include: refresh # habilita o endpoint que dispara o @RefreshScope