前言:在上一篇文章中我们介绍了关于负载轮询算法的原理以及看了源代码,而本章节内容则是着重于我们自己手写一个负载轮询算法
1、分别编写provider-payment8001、provider-payment8002这两个子项目的PaymentController类,增加一个/payment/lb接口
provider-payment8001
package com.ken.springcloud.controller;import com.ken.springcloud.entities.CommonResult;
import com.ken.springcloud.entities.Payment;
import com.ken.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;import javax.annotation.Resource;
import java.util.List;@RestController
@Slf4j
public class PaymentController {@Resourceprivate PaymentService paymentService;@Value("${server.port}")private String serverPort;@Resourceprivate DiscoveryClient discoveryClient;@PostMapping("/payment/insert")public CommonResult insert(@RequestBody Payment payment) {int result = paymentService.insert(payment);log.info("插入结果{}",result);if(result > 0) {return new CommonResult(200,"插入数据库成功,提供服务的端口号为" + serverPort,result);}else {return new CommonResult(500,"插入数据库失败",result);}}@GetMapping("/payment/get/{id}")public CommonResult insert(@PathVariable("id") Long id) {Payment payment = paymentService.getPaymentById(id);log.info("查询结果{}",payment);if(payment != null) {return new CommonResult(200,"查询成功,提供服务的端口号为" + serverPort,payment);}else {return new CommonResult(500,"没有对应的数据,查询失败,查询id" + id,payment);}}@GetMapping("/payment/discovery")public Object discovery() {//获取eureka内的服务List<String> services = discoveryClient.getServices();for (String service : services) {log.info("***service:" + service);}//获取服务名为CLOUD-PAYMENT-SERVICE下的实例List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");for (ServiceInstance instance : instances) {log.info(instance.getServiceId()+"\t"+instance.getHost()+"\t"+instance.getPort()+"\t"+instance.getUri());}return this.discoveryClient;}@GetMapping("/payment/lb")public String getPaymentLB() {//返回当前服务的端口号return serverPort;}}
provider-payment8002
package com.ken.springcloud.controller;import com.ken.springcloud.entities.CommonResult;
import com.ken.springcloud.entities.Payment;
import com.ken.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;import javax.annotation.Resource;@RestController
@Slf4j
public class PaymentController {@Resourceprivate PaymentService paymentService;@Value("${server.port}")private String serverPort;@PostMapping("/payment/insert")public CommonResult insert(@RequestBody Payment payment) {int result = paymentService.insert(payment);log.info("插入结果{}",result);if(result > 0) {return new CommonResult(200,"插入数据库成功,提供服务的端口号为" + serverPort,result);}else {return new CommonResult(500,"插入数据库失败",result);}}@GetMapping("/payment/get/{id}")public CommonResult insert(@PathVariable("id") Long id) {Payment payment = paymentService.getPaymentById(id);log.info("查询结果{}",payment);if(payment != null) {return new CommonResult(200,"查询成功,提供服务的端口号为" + serverPort,payment);}else {return new CommonResult(500,"没有对应的数据,查询失败,查询id" + id,payment);}}@GetMapping("/payment/lb")public String getPaymentLB() {//返回当前服务的端口号return serverPort;}}
2、在com.ken.springcloud包下新建名为lb的包,用于存储负载均衡相关的代码
效果图:
3、在lb包下新建一个名为LoadBalancer的接口类
效果图:
4、编写LoadBalancer接口类
package com.ken.springcloud.lb;import org.springframework.cloud.client.ServiceInstance;import java.util.List;public interface LoadBalancer {ServiceInstance instances(List<ServiceInstance> sserviceINstances);}
5、在lb包下新建一个名为MyBL的类
效果图:
6、编写MyLB类,使其实现LoadBalancer接口类
package com.ken.springcloud.lb;import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;@Component
public class MyLB implements LoadBalancer{private AtomicInteger atomicInteger = new AtomicInteger(0);/*** 获取当前是第几次的请求* @return*/public final int getAndIncrement() {//atomicInteger的期望值int current;int next;do {current = this.atomicInteger.get();next = current >= Integer.MAX_VALUE ? 0 : current + 1;}while (!this.atomicInteger.compareAndSet(current,next));//比较atomicInteger对象当前的值和期望值current,如果atomicInteger对象当前的值和期望值current相同,则把atomicInteger对象当前的值修改为next,并返回trueSystem.out.println("next:" + next);return next;}@Overridepublic ServiceInstance instances(List<ServiceInstance> serviceInstances) {//通过请求数模以提供服务的服务数获取需要提供服务的服务实例下标int index = getAndIncrement() % serviceInstances.size();//返回提供服务的服务实例return serviceInstances.get(index);}
}
7、编写consumer-order80这个子项目的OrderController类,增加一个/payment/lb接口
package com.ken.springcloud.controller;import com.ken.springcloud.entities.CommonResult;
import com.ken.springcloud.entities.Payment;
import com.ken.springcloud.lb.LoadBalancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;import javax.annotation.Resource;
import java.net.URI;
import java.util.List;@RestController
@Slf4j
public class OrderController {//public static final String PAYMENT_URL = "http://localhost:8001";public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";@Resourceprivate RestTemplate restTemplate;@Resourceprivate LoadBalancer loadBalancer;@Resourceprivate DiscoveryClient discoveryClient;@PostMapping("/consumer/insert")public CommonResult<Payment> insert(Payment payment) {log.info("payment:{}",payment);return restTemplate.postForObject(PAYMENT_URL + "/payment/insert",payment,CommonResult.class);}/*** 返回对象为响应体中数据转化成的对象,基本上可以理解为Json* @param id* @return*/@GetMapping("/consumer/get/{id}")public CommonResult<Payment> getPayment(@PathVariable("id") Long id) {return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id,CommonResult.class);}/*** 返回对象为ResponseEntity对象,包含了响应中的一些重要信息,比如响应头、响应状态码、响应体等* @param id* @return*/@GetMapping("/consumer/getForEntity/{id}")public CommonResult<Payment> getPayment2(@PathVariable("id") Long id) {ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id,CommonResult.class);if(entity.getStatusCode().is2xxSuccessful()) {return entity.getBody();}else {return new CommonResult<>(500,"异常");}}@GetMapping("/consumer/payment/lb")public String getPaymentLB() {//获取服务名为CLOUD-PAYMENT-SERVICE下的实例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);}}
8、分别启动eureka-server7001、eureka-server7002、provider-payment8001、provider-payment8002、consumer-order80,然后在浏览器地址栏输入
http://localhost/consumer/payment/lb 并回车调用接口,可以看到接口调用成功,并会按照预想的那样轮询地分别访问provider-payment8001和provider-payment8002服务
效果图: