1.替换负载均衡规则
新建一个包,一定不要被@SpringBootApplication扫描到(如果扫描到会出问题),在包里新建一个类
@Configuration
public class MySelfRule {
@Bean
public IRule myRule() {
return new RandomRule();//定义为随机
}
}
修改启动类
@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE", configuration = MySelfRule.class)
public class OrderMain80 {
public static void main(String[] args) {
SpringApplication.run(OrderMain80.class, args);
}
}
启动项目即可发现负载均衡规则变成了随机
2.手写轮询算法
在8001和8002的控制层都加入一下代码
@GetMapping("/payment/lb")
public String getPaymentLb() {
return serverPort;
}
然后在80服务下新建一个lb的包,加入一个接口和一个实现类
public interface LoadBalancer {
ServiceInstance instances(List<ServiceInstance> serviceInstanceList);
}
@Component
@Slf4j
public class MyLB implements LoadBalancer {
private AtomicInteger atomicInteger = new AtomicInteger(0);
public final int getAndIncreament() {
int current, next;
do {
current = this.atomicInteger.get();
next = current >= Integer.MAX_VALUE ? 0 : current + 1;
} while (!this.atomicInteger.compareAndSet(current, next));
log.info("*****第几次访问,访问次数next: " + next);
return next;
}
@Override
public ServiceInstance instances(List<ServiceInstance> serviceInstanceList) {
int index = getAndIncreament() % serviceInstanceList.size();
return serviceInstanceList.get(index);
}
}
在80的控制层加入以下代码
@Autowired
private LoadBalancer loadBalancer;
@Autowired
private DiscoveryClient discoveryClient;
@GetMapping("/consumer/payment/lb")
public String getPaymentLB() {
List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
if (instances == null || instances.size() <= 0) {
return null;
}
ServiceInstance serviceInstance = loadBalancer.instances(instances);
URI uri = serviceInstance.getUri();
return restTemplate.getForObject(uri + "/payment/lb", String.class);
}
启动项目即可发现自定义的负载均衡生效