MSA 프로젝트 1(초안)

이봐요이상해씨·2021년 11월 17일

마이크로서비스 연동을 위해 Discovery, ApiGateway, Config-service를 설정했다.

Discovery : Client로 부터 들어오는 요청 받기 및 Eureka 서버로서 작동.
ApiGateway : 로드밸런서 역할 및 마이크로서비스라우팅 역할
Config-Service : 각 마이크로서비스의 환경설정을 한 곳에서 설정하기 위해 외부 서비스로 빼냄

Discovery

의존성은 롬복과 유레카 서버만 등록 시켜 주었다

server:
  port: 8761

spring:
  application:
    name: discoveryservice

eureka:
  client:
    register-with-eureka: false
    fetch-registry: false

유레카 서버에 자기 자신을 등록할 것인지 확인하는 옵션이다. 서버로만 활용할 것임으로 false로 지정

package esanghaesee.discovery;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class DiscoveryApplication {

	public static void main(String[] args) {
		SpringApplication.run(DiscoveryApplication.class, args);
	}

}

유레카 서버로서 작동하기 위해 @EnableEurekaServer지정

ApiGateway

추후 Spring Security를 이용하여 user-service 유효성 검증을 할 것이다.

client -> user-service (회원가입) -> 로그인 -> JWT 발급 -> 요청 -> ApiGateway 에서 토큰 유효성 검사 -> 라우팅 순서로 진행

기본적으로 globalfilter를 지정해주고 해당 메시지 출력하게끔 yml 파일 작성
라우팅 정보를 routes: 하위에 작성

id : 라우팅할 service name
predicates : 조건
filters : 조건이 맞는다면 해당 필터를 거치게된다.
RewritePath : 일단 해당 서비스 내부로 요청이 들어가게 되면, 그 서비스 내부에서는 prefix부분을 제거하고 사용하게끔 하기 위해 선언해준다
즉 초기 요청이 -> /user-service/login 으로 들어온다면 user-service내부에서는 /login으로 해당 요청을 받아서 처리할 수 있음

server:
  port: 8000

eureka:
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://localhost:8761/eureka

spring:
  application:
    name: apigateway-service
  cloud:
    gateway:
      default-filters:
        - name: GlobalFilter
          args:
            baseMessage: GlobalFilter
            preLogger: true
            postLogger: true
      routes:
        - id: user-service
          uri: lb://USER-SERVICE
          predicates:
            - Path=/user-service/login
            - Method=POST
          filters:
            - RemoveRequestHeader=Cookie
            - RewritePath=/user-service/(?<segment>.*), /$\{segment}
            

라우팅 정보는 다음과 같이 지정할 것이다.
global filter는 모든 필터중에서 가장 먼저 호출되고 가장 마지막에 호출된다
현재 로그 출력만 작성했지만 추후 서비스 변경시 여기에 추가 내용을 작성할 예정이다

@Component
@Slf4j
public class GlobalFilter extends AbstractGatewayFilterFactory<GlobalFilter.Config> {

	public GlobalFilter() {
		super(Config.class);
	}

	@Data
	public static class Config {
		private String baseMessage;
		private boolean preLogger;
		private boolean postLogger;
	}

	@Override
	public GatewayFilter apply(Config config) {
		return ((exchange, chain) -> {
			ServerHttpRequest request = exchange.getRequest();
			ServerHttpResponse response = exchange.getResponse();

			if (config.isPreLogger()) {
				log.info("Global filter prelogger -> {}", request.getId());
			}
			return chain.filter(exchange).then(Mono.fromRunnable(()-> {
				if (config.isPreLogger()) {
					log.info("Global filter post -> {}", response.getStatusCode());
				}
			}));
		});
	}
}

Config Service

package esanghaesee.configservice;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;

@SpringBootApplication
@EnableConfigServer
public class ConfigServiceApplication {

	public static void main(String[] args) {
		SpringApplication.run(ConfigServiceApplication.class, args);
	}

}

Configuration 제공 서버로 이용하기 위해 @Configuration 어노테이션 추가

server:
  port: 8888

spring:
  application:
    name: config-service
  profiles:
    active: native
  cloud:
    config:
      server:
        native:
          search-locations: file:///Users/pupu/Desktop/study/java/msa-config

현재는 로컬파일에 설정한 값을 읽어오도록 지정했다. 추후 RabbitMq나 git으로 바꿀예정

0개의 댓글