SpringCloud gateway自定义LB(负载均衡)规则

2024-08-28  本文已影响0人  饱饱想要灵感

一、概述

微服务开发时,通常在开发环境会有全套环境,包括nacos、gateway等。

当我们本地开发调试时,如果不想起全套环境,一般会直接接入开发环境的nacos。
那么路由规则只能通过调整负载均衡的权重来设置,如果把开发人员机器的权重调高,就会有很多多余请求进入本地服务。如果有多人同时调试时,那么权重就无法满足需求。

难道调试时只能本地也起全套服务吗,包括gateway、鉴权、登录、nacos、要调试的业务服务,要起这么多吗?

答案是不需要的,我们可以自定义负载均衡规则,灵活设置只有本地浏览器发起的请求会进入本地服务。

二、设计思路

本地浏览器请求时,多加一个请求头Prefer-Lb-IP,内容设为本地的IP地址,让gateway获取这个请求头。自定义负载均衡规则,当存在Prefer-Lb-IP设置的IP地址的服务时,直接选择该服务。

本地Chrome浏览器安装ModHeader插件添加请求头Prefer-Lb-IP, 设置优先选择的服务IP地址

ModHeader配置.png

三、自定义经过Gateway请求的LB路由规则

  1. 实现GlobalFilter接口获取request的请求头Prefer-Lb-IP, 保存到ThreadLocal中
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;


@Component
public class GatewayFilter implements GlobalFilter {

    public static ThreadLocal<String> PREFER_LB_IP = new ThreadLocal<>();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String method = request.getMethodValue();
        String url = request.getPath().value();
        String preferLbIP = request.getHeaders().getFirst(Const.PREFER_LB_IP);
        PREFER_LB_IP.set(ObjectUtils.isNotEmpty(preferLbIP) ? preferLbIP : "");
    }
}
  1. 自定义LB路由规则
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.RoundRobinRule;
import com.netflix.loadbalancer.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Primary;

import java.util.List;
import java.util.Objects;

@Primary
public class LBConfigRule extends NacosRule {

    @Override
    public Server choose(Object key) {
        ILoadBalancer lb = getLoadBalancer();
        if (lb == null) {
            return null;
        }

        String ip = GatewayFilter.PREFER_LB_IP.get();
        List<String> ipList = StringUtils.splitToList(ip);
        List<Server> upList = lb.getReachableServers();
        if (upList.size() > 1) {
            for (String ip : ipList) {
                for (Server server : serverList) {
                    if (Objects.equals(ip, server.getHost())) {
                        return server;
                    }
                }
            }
        }
        GatewayFilter.PREFER_LB_IP.remove();
        return super.choose(key);
    }
}

  1. 可以通过@RibbonClients为不同的服务设置不同的LB路由规则, 其中注解@RibbonClientname属性对应@FeignClientname
import com.alibaba.cloud.nacos.ribbon.NacosRule;
import com.netflix.loadbalancer.IRule;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.cloud.netflix.ribbon.RibbonClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@RibbonClients(
        value = {
                @RibbonClient(name = "authorization", configuration = LBConfigRule.class),
                @RibbonClient(name = "admin", configuration = LBConfigRule.class)
        },
        defaultConfiguration = LBConfig.class)
public class LBConfig {

    @Bean
    public IRule commonRule() {
        return new NacosRule();
    }
}

四、自定义微服务之间通过Feign请求的LB路由规则

  1. 实现Feign的RequestInterceptor接口, 在微服务之间调用时, 也添加请求头Prefer-Lb-IP
import feign.FeignException;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import feign.Response;
import feign.codec.Decoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.ResponseEntityDecoder;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class FeignConfig implements RequestInterceptor {

    @Bean
    public Decoder feignDecoder() {
        return new ResponseEntityDecoder(new FeignDecode(feignHttpMessageConverter()));
    }

    private ObjectFactory<HttpMessageConverters> feignHttpMessageConverter() {
        final HttpMessageConverters httpMessageConverters = new HttpMessageConverters(new GateWayMappingJackson2HttpMessageConverter());
        return () -> httpMessageConverters;
    }

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            requestTemplate.header("proxyHost", request.getHeader("proxyHost"));
            requestTemplate.header("Prefer-Lb-IP", request.getHeader("Prefer-Lb-IP"));
        }
    }

    private class GateWayMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {
        GateWayMappingJackson2HttpMessageConverter() {
            List<MediaType> mediaTypes = new ArrayList<>();
            mediaTypes.add(MediaType.APPLICATION_JSON);
            setSupportedMediaTypes(mediaTypes);
        }
    }

    public class FeignDecode extends SpringDecoder {
        FeignDecode(ObjectFactory<HttpMessageConverters> messageConverters) {
            super(messageConverters);
        }

        @Override
        public Object decode(Response response, Type type) throws FeignException, IOException, CrmException {
            Object data = super.decode(response, type);
            // 报错处理
            return data;
        }
    }
}

  1. 设置路由规则

import com.alibaba.cloud.nacos.ribbon.NacosRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Primary
public class LBConfigRule extends NacosRule {

    @Override
    public Server choose(Object key) {
        ServletRequestAttributes attributes = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
        List<String> ipList = new ArrayList<>();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            ipList = StringUtils.splitToList(request.getHeader("Prefer-Lb-IP"));
        }

        if (ObjectUtils.isEmpty(ipList)) {
            return super.choose(key);
        }
        ILoadBalancer lb = getLoadBalancer();
        if (lb == null) {
            return null;
        }
        List<Server> serverList = lb.getReachableServers();
        if (serverList.size() > 1) {
            for (String ip : ipList) {
                for (Server server : serverList) {
                    if (Objects.equals(ip, server.getHost())) {
                        return server;
                    }
                }
            }
        }
        return super.choose(key);

    }
}
  1. 同样通过@RibbonClients为不同的服务设置不同的LB路由规则
import com.alibaba.cloud.nacos.ribbon.NacosRule;
import com.netflix.loadbalancer.IRule;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.cloud.netflix.ribbon.RibbonClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@RibbonClients(
        value = {
                @RibbonClient(name = "admin", configuration = LBConfigRule.class)
        },
        defaultConfiguration = LBConfig.class)
public class LBConfig {

    @Bean
    public IRule commonRule() {
        return new NacosRule();
    }
}

上一篇下一篇

猜你喜欢

热点阅读