Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

章节5.2.1 Ribbon自定义全局负载均衡策略的疑问 #13

Closed
zxcvbnmzsedr opened this issue Oct 13, 2018 · 2 comments
Closed

章节5.2.1 Ribbon自定义全局负载均衡策略的疑问 #13

zxcvbnmzsedr opened this issue Oct 13, 2018 · 2 comments

Comments

@zxcvbnmzsedr
Copy link

我曾经在项目中使用书中说的方法去配置全局负载均衡策略的时候发现这种配置方式无法得到预期的效果。

自定义的负载均衡服务继承AvailabilityFilteringRule去重写了选择服务器的方法

@Bean
public IRule rule() {
    return new RibbonRule();
}

public class RibbonRule extends AvailabilityFilteringRule {
@Override
public Server choose(Object key) {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    // Get the actual ip address
    key = RequestUtils.getIpAddress(request);
    ILoadBalancer lb = getLoadBalancer();
    Server returnServer = null;
    List<Server> server = getPredicate().getEligibleServers(lb.getAllServers(), String.valueOf(key));
    for (Server s : server) {
        if (StringUtils.contains(s.getHost(), String.valueOf(key))) {
            returnServer = s;
        }
    }
    if (returnServer == null) {
        returnServer = super.choose(key);
    }
    return returnServer;    }}

这种配置方式在只请求第一次的场景下不会有任何问题,但是在第二次请求的时候ILoadBalancer没有办法获取到正确的服务器导致请求失败

我在init方法中同时去请求了a-center和b-center两个微服务,第一次没问题,第二次请求a-center的feign获取到的是b-center的IP地址

public void init() {
   //a-center
   a.getA();
   //b-center
    b.getB();
}

Ribbon的文档给的案例上配置全局负载均衡是通过@RibbonClients这个注解的defaultConfiguration属性来实现的

@RibbonClients(defaultConfiguration = RibbonRule.class)
public class RibbonClientConfiguration {

}

所以~~~~我想知道是哪里的问题

@SoftwareKing
Copy link
Member

@zxcvbnmzsedr 加我微信Software_King进群答疑

@mojie126
Copy link

我也遇到这个问题了...请问是怎么解决的啊...?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants