Closed JunHyungJang closed 1 day ago
import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; import org.springframework.cloud.gateway.filter.GatewayFilter; import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.LoadBalancerClientFilter; import org.springframework.cloud.gateway.route.Route; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.http.HttpCookie; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.stereotype.Component; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono;
import java.util.List;
@Component @Order(LoadBalancerClientFilter.LOAD_BALANCER_CLIENT_FILTER_ORDER) public class StickySessionLoadBalancerFilter extends LoadBalancerClientFilter {
public StickySessionLoadBalancerFilter(LoadBalancerClient loadBalancer) { super(loadBalancer); } @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR); ServerHttpRequest request = exchange.getRequest(); String userId = extractUserIdFromRequest(request); if (userId != null) { ServiceInstance instance = chooseInstance(route.getId(), userId); if (instance != null) { String uri = instance.getUri().toString(); ServerHttpRequest newRequest = request.mutate().uri(URI.create(uri)).build(); return chain.filter(exchange.mutate().request(newRequest).build()); } } return chain.filter(exchange); } private String extractUserIdFromRequest(ServerHttpRequest request) { HttpCookie userCookie = request.getCookies().getFirst("userId"); return userCookie != null ? userCookie.getValue() : null; } private ServiceInstance chooseInstance(String serviceId, String userId) { List<ServiceInstance> instances = loadBalancer.choose(serviceId); int index = Math.abs(userId.hashCode() % instances.size()); return instances.get(index); }
}
2. 사용자 식별자 추출 - 쿠키에서 userId 추출하기 3. Application.yaml 파일설정
spring: cloud: gateway: default-filters:
4. Eureka 설정
eureka: client: service-url: defaultZone: http://localhost:8761/eureka/ instance: prefer-ip-address: true
## 🏫 To-do - [ ] Custom LoadBalancer 생성 - [ ] userId 값을 기준으로 Routing
준형님~ 제가 작업 진행하면 될까요?
제가하겠슴다
📕 제목
📔 설명
import java.util.List;
@Component @Order(LoadBalancerClientFilter.LOAD_BALANCER_CLIENT_FILTER_ORDER) public class StickySessionLoadBalancerFilter extends LoadBalancerClientFilter {
}
spring: cloud: gateway: default-filters:
eureka: client: service-url: defaultZone: http://localhost:8761/eureka/ instance: prefer-ip-address: true