GO · 패턴
마이크로서비스 패턴
Go 마이크로서비스의 기본 구조. 서비스 디스커버리, 헬스 체크, 설정을 포함합니다.
패턴고급microserviceservicehealthhttp
핵심 설명
Go 마이크로서비스의 기본 구조. 서비스 디스커버리, 헬스 체크, 설정을 포함합니다.
Go code
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"time"
)
// 서비스 인터페이스
type Service interface {
Name() string
Start(ctx context.Context) error
Health() error
}
// 기본 마이크로서비스 구조
type Microservice struct {
name string
server *http.Server
mux *http.ServeMux
}
func NewMicroservice(name string, port int) *Microservice {
mux := http.NewServeMux()
ms := &Microservice{
name: name,
mux: mux,
server: &http.Server{
Addr: fmt.Sprintf(":%d", port),
Handler: mux,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
},
}
// 기본 엔드포인트
mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(map[string]string{
"service": name, "status": "healthy",
"time": time.Now().Format(time.RFC3339),
})
})
mux.HandleFunc("GET /info", func(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(map[string]string{
"name": name, "version": "1.0.0",
})
})
return ms
}
func (ms *Microservice) Name() string { return ms.name }
func (ms *Microservice) Health() error { return nil }
func (ms *Microservice) HandleFunc(pattern string, h http.HandlerFunc) {
ms.mux.HandleFunc(pattern, h)
}
func main() {
svc := NewMicroservice("user-service", 8080)
svc.HandleFunc("GET /api/users", func(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode([]map[string]string{{"name": "Gopher"}})
})
fmt.Printf("서비스 '%s' 준비 완료\n", svc.Name())
}학습 팁
모든 마이크로서비스에 /health와 /info 엔드포인트를 표준으로 제공하세요. 모니터링과 디버깅에 필수적입니다.
주의할 점
서비스 간 동기 호출이 많으면 결합도가 높아지고 장애가 전파됩니다. 이벤트 기반 비동기 통신을 고려하세요.
자주 묻는 질문
마이크로서비스 패턴란 무엇인가요?
Go 마이크로서비스의 기본 구조. 서비스 디스커버리, 헬스 체크, 설정을 포함합니다.
마이크로서비스 패턴 학습 시 주의할 점은 무엇인가요?
서비스 간 동기 호출이 많으면 결합도가 높아지고 장애가 전파됩니다. 이벤트 기반 비동기 통신을 고려하세요.