Ribbon是什么?
springcloud-consumer-dept-80向pom.xml中添加Ribbon和Eureka依赖
org.springframework.cloud spring-cloud-starter-ribbon 1.4.6.RELEASE org.springframework.cloud spring-cloud-starter-eureka 1.4.6.RELEASE
在application.yml文件中配置Eureka
# Eureka配置eureka: client: register-with-eureka: false # 不向 Eureka注册自己 service-url: # 从三个注册中心中随机取一个去访问 defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
主启动类加上@EnableEurekaClient注解,开启Eureka
//Ribbon 和 Eureka 整合以后,客户端可以直接调用,不用关心IP地址和端口号@SpringBootApplication@EnableEurekaClient //开启Eureka 客户端public class DeptConsumer_80 { public static void main(String[] args) { SpringApplication.run(DeptConsumer_80.class, args); }}
自定义Spring配置类:ConfigBean.java 配置负载均衡实现RestTemplate
@Configurationpublic class ConfigBean { //@Configuration -- spring applicationContext.xml @LoadBalanced //配置负载均衡实现RestTemplate @Bean public RestTemplate getRestTemplate() { return new RestTemplate(); }}
修改conroller:DeptConsumerController.java
//Ribbon:我们这里的地址,应该是一个变量,通过服务名来访问//private static final String REST_URL_PREFIX = "http://localhost:8001";private static final String REST_URL_PREFIX = "http://SPRINGCLOUD-PROVIDER-DEPT";
流程图:
1.新建两个服务提供者Moudle:springcloud-provider-dept-8003、springcloud-provider-dept-8002
2.参照springcloud-provider-dept-8001 依次为另外两个Moudle添加pom.xml依赖 、resourece下的mybatis和application.yml配置,Java代码
3.启动所有服务测试(根据自身电脑配置决定启动服务的个数),访问http://eureka7001.com:7002/查看结果
测试访问http://localhost/consumer/dept/list 这时候随机访问的是服务提供者8003
再次访问http://localhost/consumer/dept/list这时候随机的是服务提供者8001
以上这种每次访问http://localhost/consumer/dept/list随机访问集群中某个服务提供者,这种情况叫做轮询,轮询算法在SpringCloud中可以自定义。
如何切换或者自定义规则呢?
在springcloud-provider-dept-80模块下的ConfigBean中进行配置,切换使用不同的规则
@Configurationpublic class ConfigBean { //@Configuration -- spring applicationContext.xml /** * IRule: * RoundRobinRule 轮询策略 * RandomRule 随机策略 * AvailabilityFilteringRule : 会先过滤掉,跳闸,访问故障的服务~,对剩下的进行轮询~ * RetryRule : 会先按照轮询获取服务~,如果服务获取失败,则会在指定的时间内进行,重试 */ @Bean public IRule myRule() { return new RandomRule();//使用随机策略 //return new RoundRobinRule();//使用轮询策略 //return new AvailabilityFilteringRule();//使用轮询策略 //return new RetryRule();//使用轮询策略 }}
也可以自定义规则,在myRule包下自定义一个配置类MyRule.java,注意:该包不要和主启动类所在的包同级,要跟启动类所在包同级:
MyRule.java
/** * @Auther: csp1999 * @Date: 2020/05/19/11:58 * @Description: 自定义规则 */@Configurationpublic class MyRule { @Bean public IRule myRule(){ return new MyRandomRule();//默认是轮询RandomRule,现在自定义为自己的 }}
主启动类开启负载均衡并指定自定义的MyRule配置类
//Ribbon 和 Eureka 整合以后,客户端可以直接调用,不用关心IP地址和端口号@SpringBootApplication@EnableEurekaClient//在微服务启动的时候就能加载自定义的Ribbon类(自定义的规则会覆盖原有默认的规则)@RibbonClient(name = "SPRINGCLOUD-PROVIDER-DEPT",configuration = MyRule.class)//开启负载均衡,并指定自定义的规则public class DeptConsumer_80 { public static void main(String[] args) { SpringApplication.run(DeptConsumer_80.class, args); }}
自定义的规则(这里我们参考Ribbon中默认的规则代码自己稍微改动):MyRandomRule.java
public class MyRandomRule extends AbstractLoadBalancerRule { /** * 每个服务访问5次则换下一个服务(总共3个服务) * * total=0,默认=0,如果=5,指向下一个服务节点 * index=0,默认=0,如果total=5,index+1 */ private int total = 0;//被调用的次数 private int currentIndex = 0;//当前是谁在提供服务 //@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE") public Server choose(ILoadBalancer lb, Object key) { if (lb == null) { return null; } Server server = null; while (server == null) { if (Thread.interrupted()) { return null; } List upList = lb.getReachableServers();//获得当前活着的服务 List allList = lb.getAllServers();//获取所有的服务 int serverCount = allList.size(); if (serverCount == 0) { /* * No servers. End regardless of pass, because subsequent passes * only get more restrictive. */ return null; } //int index = chooseRandomInt(serverCount);//生成区间随机数 //server = upList.get(index);//从或活着的服务中,随机获取一个 //=====================自定义代码========================= if (total < 5) { server = upList.get(currentIndex); total++; } else { total = 0; currentIndex++; if (currentIndex > upList.size()) { currentIndex = 0; } server = upList.get(currentIndex);//从活着的服务中,获取指定的服务来进行操作 } //====================================================== if (server == null) { /* * The only time this should happen is if the server list were * somehow trimmed. This is a transient condition. Retry after * yielding. */ 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; } protected int chooseRandomInt(int serverCount) { return ThreadLocalRandom.current().nextInt(serverCount); } @Override public Server choose(Object key) { return choose(getLoadBalancer(), key); } @Override public void initWithNiwsConfig(IClientConfig clientConfig) { // TODO Auto-generated method stub }}