代码结构
controller的代码
package com.demo.springcloud.controller; import com.demo.springcloud.pojo.Dept; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; import java.util.List; @RestController public class DeptConsumerController { @Autowired private RestTemplate restTemplate; // private static final String REST_URI_PREFIX = "http://localhost:8001"; private static final String REST_URI_PREFIX = "http://springcloud-provider-dept"; @GetMapping("/consumer/dept/queryAll") public List<Dept> queryAll(){ return restTemplate.getForObject(REST_URI_PREFIX+"/dept/queryAll", List.class); } }
springcloud-provider-dep是服务提供者的id:
自定义配置文件
自定义的规则:
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by FernFlower decompiler) // package com.demo.springcloud.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; /** * 自定义的规则: * 每个服务走5次,然后才切换到另一个服务上 */ public class HflRandomRule extends AbstractLoadBalancerRule { private int total; private int curentIndex; public HflRandomRule() { } // @SuppressWarnings({"RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE"}) public Server choose(ILoadBalancer lb, Object key) { if (lb == null) { return null; } else { 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; } if(total<5){ server = upList.get(curentIndex); }else{ total = 0; curentIndex ++; if(curentIndex > upList.size()){ curentIndex = 0; } server = upList.get(curentIndex); } total++; if (server == null) { Thread.yield(); } else { if (server.isAlive()) { return server; } server = null; Thread.yield(); } } return server; } } public Server choose(Object key) { return this.choose(this.getLoadBalancer(), key); } public void initWithNiwsConfig(IClientConfig clientConfig) { } }
application.yml
效果如下:
完