springcloud之ribbon初识篇-通过代码实现负载均衡

我们在代码中可以使用两种注解实现负载均衡:

  • @RibbonClients:配置所有服务的负载均衡
  • @RibbonClient:配置单个服务的负载均衡

@RibbonClients

@SpringBootApplication
//给每个服务指定不同的负载规则【PS:“name”指的是要调用的服务名称】
@RibbonClients(value = {
        @RibbonClient(name = "test1",configuration = RibbonConfiguration.class),
        @RibbonClient(name = "ribbon-java",configuration = RibbonConfiguration2.class)
})
public class TestDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestDemoApplication.class, args);
    }

}

-----------------------------------------------------------
@SpringBootApplication
//调用所有服务时使用统一的负载规则
@RibbonClients(defaultConfiguration = RibbonConfiguration.class)
public class TestDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestDemoApplication.class, args);
    }

}

@RibbonClient

我们可以单独写一个类用来定义某个服务的负载规则,也可以和@RibbonClients联合使用【联合使用看上面代码】

import com.example.springcloud.testdemo.ribbonConfig.RibbonConfiguration2;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.context.annotation.Configuration;


@Configuration
//指定test2使用RibbonConfiguration中定义的负载均衡策略
@RibbonClient(name = "test1",configuration = RibbonConfiguration.class)
public class CustomerRibbonConfiguration2 {
}

 

上述两种配置中我们使用的负载均衡配置类是自定义的,用默认的RibbonClientConfiguration调用时无法找到服务实例,暂时不知道是为什么。

RibbonConfiguration

//@Configuration
//PS:如果加上了这个配置那么项目加载扫描的时候就会扫描到这个类,会让所有服务都使用这个规则
public class RibbonConfiguration {

    @Bean
    public IRule ribbonRule(){
        return new MyRule();
    }
}

 

具体的负载均衡策略:MyRule

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;

/**
 * 2020/3/11
 */
public class MyRule extends AbstractLoadBalancerRule {
    public MyRule() {
        super();
    }

    public Server choose(ILoadBalancer lb, Object key){
        if (lb == null) {
            return null;
        }
        Server server = null;

        while (server == null) {
            if (Thread.interrupted()) {
                return null;
            }
            List<Server> upList = lb.getReachableServers();  //激活可用的服务
            List<Server> allList = lb.getAllServers();  //所有的服务

            int serverCount = allList.size();
            if (serverCount == 0) {
                return null;
            }
            //选自定义元数据的server,选择端口以2结尾的服务。
            for (int i = 0; i < upList.size(); i++) {
                server = upList.get(i);
                String port = server.getHostPort();
                if(port.endsWith("2") || port.endsWith("0")) {
                    break;
                }

            }


            if (server == null) {
                Thread.yield();
                continue;
            }

            if (server.isAlive()) {
                return (server);
            }

            // Shouldn't actually happen.. but must be transient or a bug.
            server = null;
            Thread.yield();
        }
        return server;
    }

    @Override
    public void setLoadBalancer(ILoadBalancer lb) {
        super.setLoadBalancer(lb);
    }

    @Override
    public ILoadBalancer getLoadBalancer() {
        return super.getLoadBalancer();
    }

    @Override
    public Server choose(Object o) {
        return choose(getLoadBalancer(),o);
    }

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }
}

调用代码:

@Configuration
public class RibbonComponent {

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

}

--------------------------------------------------------------

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;


@RestController
public class RibbonTest1Controller {
    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/ribbon/test1")
    public String queryTestRestTemplate(){
        String url = "http://test1/eureka-clinet1/ribbonTest";
        Map<String,String> map = new HashMap<String,String>(){{
            put("name","ribboon-test");
        }};

        ResponseEntity<String> result =restTemplate.postForEntity(url,map,String.class);
        System.err.println(result.getBody());
        return result.getBody();
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值