Descoberta de Serviços e Gateways de API
Aprenda como os microsserviços Clojure se encontram dinamicamente e como um gateway de API fornece um único ponto de entrada seguro para o seu sistema.
Descoberta de Serviços e Gateways de API é uma aula grátis de Clojure Functional Programming & JVM Backend Development no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Clojure Functional Programming & JVM Backend Development, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Clojure Functional Programming & JVM Backend Development inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
The Discovery Problem
In a microservice system, instances start, stop, and move between hosts. Hardcoding IP addresses breaks quickly. Service discovery lets services locate each other dynamically.
Service Registries
A service registry is a database of available services and their network locations. Popular options include Consul, etcd, and Eureka.
Registering a Service
On startup, a service registers itself with the registry, including a health-check endpoint so the registry can drop it if it dies.
(defn register! [consul-url name host port]
(http/put (str consul-url "/v1/agent/service/register")
{:body (json/write-str
{:Name name :Address host :Port port
:Check {:HTTP (str "http://" host ":" port "/health")
:Interval "10s"}})}))Client-Side Discovery
In client-side discovery, the calling service queries the registry for healthy instances and picks one itself.
(defn lookup [consul-url name]
(-> (http/get (str consul-url "/v1/health/service/" name "?passing"))
:body
json/read-str))Server-Side Discovery
In server-side discovery, the client calls a load balancer or gateway, which consults the registry and forwards the request. The client stays simple.
What Is an API Gateway?
An API gateway is a single entry point that routes incoming requests to the right backend service. It hides internal topology from clients.
Gateway Responsibilities
Beyond routing, a gateway often handles cross-cutting concerns:
- Authentication and authorization
- Rate limiting
- Request/response transformation
- Aggregating multiple service calls
A Simple Gateway in Ring
You can build a basic gateway in Clojure by matching the path and proxying to the discovered service.
(defn gateway [request]
(let [service (route-for (:uri request))
target (lookup-instance service)]
(http/request
(assoc request :url (str target (:uri request))))))Authentication at the Edge
Centralizing auth at the gateway means individual services trust the gateway and avoid duplicating login logic.
(defn wrap-gateway-auth [handler]
(fn [request]
(if (valid-token? (get-in request [:headers "authorization"]))
(handler request)
{:status 401 :body "Unauthorized"})))Rate Limiting
The gateway is the natural place to throttle abusive clients before requests reach your services.
(defn wrap-rate-limit [handler limit]
(fn [request]
(if (under-limit? (client-id request) limit)
(handler request)
{:status 429 :body "Too Many Requests"})))Putting It Together
A production setup: services self-register in a registry with health checks, and a gateway discovers them, enforces auth and rate limits, then routes. This keeps clients decoupled from internal changes.
Quick Check
Test your discovery knowledge.
Recap
You learned how services discover each other and how a gateway unifies access.
- Registries like Consul track instances via health checks
- Discovery can be client-side or server-side
- Gateways centralize routing, auth, and rate limiting
Perguntas Frequentes
A aula “Descoberta de Serviços e Gateways de API” é grátis?
Sim — o texto completo de “Descoberta de Serviços e Gateways de API” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Clojure Functional Programming & JVM Backend Development, atualize para CoddyKit PRO. O curso de Clojure Functional Programming & JVM Backend Development inclui 4 aulas no total.
O que vou aprender em “Descoberta de Serviços e Gateways de API”?
Aprenda como os microsserviços Clojure se encontram dinamicamente e como um gateway de API fornece um único ponto de entrada seguro para o seu sistema. Você pratica Clojure Functional Programming & JVM Backend Development com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Clojure Functional Programming & JVM Backend Development?
Nenhuma experiência prévia é necessária. Clojure Functional Programming & JVM Backend Development no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Descoberta de Serviços e Gateways de API”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Clojure Functional Programming & JVM Backend Development?
Sim. Cada aula de Clojure Functional Programming & JVM Backend Development inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Projetando microsserviços Clojure
- Contêineres com Docker
- Implantação em plataformas de nuvem
- Descoberta de Serviços e Gateways de API