1.配置文件添加配置

management-pc-api:
  ribbon:
    NFLoadBalancerRuleClassName: com.hecr.FixedIpRule

网关添加拦截添加 lb
在这里插入图片描述

2.自定义均衡负载类,继承 AbstractLoadBalancerRule

package com.hecr;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;

public class FixedIpRule extends AbstractLoadBalancerRule {
    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }

    @Override
    public Server choose(Object o) {
        ILoadBalancer loadBalancer = getLoadBalancer();
        // 获取到当前调用的服务名(ms-provider)下的所有的服务
        List<Server> serverList = loadBalancer.getAllServers();

        // 没有服务可用
        if (null == serverList || serverList.size() == 0) {
            return null;
        }

        String myIp = "192.168.5.156";
        for (Server server : serverList) {
            if (myIp.equals(server.getHost())) {
                return server;
            }
        }

        return null;
    }
}
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐