如何为Spring Cloud LoadBalancer同时配置多规则及替代粘性会话
Spring Cloud LoadBalancer多配置解决方案
多配置项启用方法
你无法同时启用两个配置的核心原因是spring.cloud.loadbalancer.configurations属性支持传入多值数组,你当前配置为单个字符串,只会生效最后写入的配置项。
正确的YAML配置有两种可选格式:
数组格式(推荐)
spring: cloud: loadbalancer: configurations: - health-check - same-instance-preference
逗号分隔格式
spring: cloud: loadbalancer: configurations: health-check,same-instance-preference
配置完成后两个规则会按顺序生效:首先会通过健康检查过滤掉不可用的实例,再从可用实例中优先选择之前复用过的实例。
配置组合替代sticky session的说明
health-check + same-instance-preference的组合无法完全替代sticky session负载均衡规则,二者的核心适用场景不同:
same-instance-preference的复用逻辑仅作用于单次请求上下文内的多次服务调用,跨请求时无法记忆之前选择的实例,没有会话级别的绑定能力- sticky session依赖
INSTANCE_IDCookie实现会话与实例的绑定,只要Cookie有效,同一个用户的所有跨请求都会路由到固定实例,除非该实例被健康检查判定为不可用
如果你的业务场景只需要单次请求内的多次服务调用复用同一个实例,该组合可以满足需求;如果需要用户整个会话周期内的所有请求都路由到同一个实例,建议保留你当前配置中的sticky-session.add-service-instance-cookie: true配置,三个规则可以同时生效,不会冲突。
完整可用配置示例
spring: application: name: sample cloud: discovery: client: health-indicator: enabled: false simple: instances: test-service: - uri: http://localhost:8082 - uri: http://localhost:8081 loadbalancer: configurations: - health-check - same-instance-preference sticky-session: add-service-instance-cookie: true cache: enabled: false health-check: path: default: /actuator/health interval: 10000 gateway: routes: - id: test_routing path: /user/* uri: lb://test-service predicates: - Method=GET,POST - Path=/user/** server: port: 45000
内容的提问来源于stack exchange,提问作者neelima john
相关产品推荐
相关产品推荐

